How to convert string's cases in LessCSS? - less

Is there a way to convert a given class name's case ?
The pseudo code would be :
&.#{lowercase(name)} {
...
}

There is a way
But it is questionable how useful it would be, and also not very straightforward to achieve. However, for the sake of showing it can be done using the inline javascript feature of LESS, there is this example:
LESS
#className1: SomeCamelCased;
#className2: ALL-UPPER-CASE;
.Some-Class-Already-Defined {
prop: no straight forward way here;
}
.lowerCaseIt(#className) {
#newClass: e(`'#{className}'.toLowerCase()`);
&.#{newClass} {
prop: a passed class name will work;
.setProps();
}
}
& {
.lowerCaseIt(#className1);
.setProps() {
property: that you set
}
}
& {
.lowerCaseIt(#className2);
.setProps() {
property: that you set;
another: that you set;
}
}
& {
.lowerCaseIt(Some-Class-Already-Defined);
.setProps() {
p1: that you set;
p2: that you set;
}
}
CSS Output
.Some-Class-Already-Defined {
prop: no straight forward way here;
}
.somecamelcased {
prop: a passed class name will work;
property: that you set;
}
.all-upper-case {
prop: a passed class name will work;
property: that you set;
another: that you set;
}
.some-class-already-defined {
prop: a passed class name will work;
p1: that you set;
p2: that you set;
}
You can see that it requires some extra layering of mixins to set properties to this new class. As well, any already existing class must be passed in as a keyword value as the third example does, which means some "repetition" (you cannot just "read" the class name from LESS and have it spit out a lower case version).

No, there is no way to do this.
CSS, CSS3 and LESS do not implement it.
There are several reasons why this would be a bad idea.
The main reason being that it could get confusing very quickly, and that it encourages bad naming conventions.

Related

How to avoid typecasting to subclass when using null object pattern

I have a Value interface with a method to show value as a string.
Usually the value is an integer so IntegerValue implements Value.
Sometimes value is unknown which I use null object pattern for so UnknownValue implements Value.
When the value is actually an integer, it's useful for the client to check whether the value is high enough (IntegerValue.isEnough). This affects how this value is displayed to the user later on. However, if the value is unknown, it doesn't make sense to check if it's high enough--the value is unknown. By the Interface Segregation Principle, UnknownValue should not have an isEnough method.
interface Value {
toString(): string;
}
class IntegerValue implements Value {
private value: number;
constructor(v: number) { this.value = v }
isEnough() { return this.value >= 30 }
toString() { return '' + this.value }
}
class UnknownValue implements Value {
toString() { return 'unknown' }
}
But the client accesses a Value and won't know whether it's an IntegerValue. So I'd have to check and then typecast it.
if(value.toString() !== 'unknown') {
handleInteger(value as IntegerValue) // <-- check if isEnough inside
} else {
handleUnknown(value)
}
I was wondering if there was a design pattern that could solve this with polymorphism, without typecasting.
I was considering the Visitor Pattern like so:
interface ValueVisitor {
handleInteger(v: IntegerValue): void;
handleUnknown(): void
}
class ViewValueVisitor implements ValueVisitor { ... }
class JsonSerializerValueVisitor implements ValueVisitor { ... }
interface Value {
toString(): string;
acceptVisitor(v: ValueVisitor): void;
}
class IntegerValue implements Value {
...
acceptVisitor(v) { v.handleInteger(this) }
}
class UnknownValue implements Value {
...
acceptVisitor(v) { v.handleUnknown() }
}
But the Visitor Pattern violates the Open Closed Principle. I was wondering if there is a better solution.
This answer is very contrived for the problem scope of the default behavior of some value object and its Interface Segregation Principle violation. We can usually afford to sin a little and just type-cast or check the class in the client with value instanceof IntegerValue or value.getType() === 'integervalue'.
But the inherent problem is not confined to only this problem scope. What happens when you have different classes implementing an interface that must be treated differently in the client. When there are more types involved, we may want to follow the SOLID principles to improve cohesion and encapsulation.
Also not sure if this answer is supported by languages other than typescript, but...
I think I got very close with my visitor pattern solution. Just needed one tweak so that the visitor pattern doesn't break the OCP. We can do that with the strategy pattern.
enum HandledTypes {
IntegerValue,
UnknownValue,
...
}
interface ValueHandler {
type: HandledType;
handle(value: Value): void;
}
class ValueVisitor {
handlers: Map<HandledTypes, ValueHandler>;
constructor(handlers: ValueHandler[]) { ... }
handle(key: HandledTypes, v: Value) {
const h = this.handlers.get(key)
h.handle(v);
}
}
// a handler would expect a more specific type
class ViewIntegerValueHandler implements ValueHandler {
readonly type = HandledTypes.IntegerValue;
handle(value: IntegerValue) { ... }
}
interface Value {
toString(): string;
acceptVisitor(v: ValueVisitor): void;
}
class IntegerValue implements Value {
...
acceptVisitor(v) { v.handle(HandledTypes.IntegerValue, this) }
}
class UnknownValue implements Value {
...
acceptVisitor(v) { v.handle(HandledTypes.UnknownValue, this) }
}
Now we can compose a ValueVisitor with all the types it needs to handle within the client.
function doSomething(value: Value) {
const viewValueVisitor = new ValueVisitor([
new ViewIntegerValueHandler(),
new ViewUnknownValueHandler(),
]);
value.acceptVisitor(viewValueVisitor);
}
One problem with this is that I don't see how TypeScript can warn you about providing the incorrect HandledTypes key to ValueVisitor.handle which may lead to a problem at runtime that may or may not throw an error.

Name Shadowing in kotlin

Recently, I face this warning in my IntelliJ Idea. But I don't have any solution for that...
Also, I don't want to use the #Suppress("NAME_SHADOWING").
I'll be grateful if you guide me.
This is my code:
fun add(
#Parameter id: Long?
): someClass {
myTable?.content?.firstOrNull { it.add }?.id?.let { id ->
db.products.readById(id)?.let { db.products.delete(it) }
}
return remove(id)
}
Name shadowing means that you are using variables with the same name in different scopes, making it more likely that you by accident refer to the wrong one. The solution is to rename them to be different. In your case it's the variable id. It is both the parameter of the function and it is also defined after the first let. So you could for example do this to remove the warning:
fun add(
#Parameter id: Long?
): someClass {
myTable?.content?.firstOrNull { it.add }?.id?.let { id2 ->
db.products.readById(id2)?.let { db.products.delete(it) }
}
return remove(id)
}
fun add(
#Parameter id: Long?
): someClass {
myTable?.content?.firstOrNull { it.add }?.id
?.let { id ->
// Here you have two variables named "id" (the other being the function parameter)
db.products.readById(id)?.let { db.products.delete(it) }
}
return remove(id)
}
Simply rename one of the parameters and the warning will go away.

Is it possible to create inheritance between two mobx stores?

I'm building two widgets with mobx/react, where all the logic sits inside the stores. Both share most of the design rules, so their stores are 95% identical.
Is there a smart way to handle this situation?
For example, is it possible to create inheritance such as this?
class Animal {
#observable name = "";
constructor(name) {
this.name = name;
}
#computed get sentence() {
console.log(this.name + ' makes a noise.');
}
}
class Dog extends Animal {
#observable isBarking = false;
#computed get bark() {
if (this.isBarking){
console.log('The dog is barking');
}
}
#action
setIsBarking(isBarking) {
this.isBarking = isBarking;
}
}
Yes you can, but you have to structure it like this, using the new Mobx pattern which does not use decorators:
(Using Typescript)
import {observable, action, computed, makeObservable} from "mobx";
const animalProps = {
name: observable,
sentence: computed
};
class abstract Animal {
name = "";
constructor(name) {
this.name = name;
}
get sentence() {
console.log(this.name + ' makes a noise.');
}
}
class Dog extends Animal {
isBarking = false;
constructor(){
makeObservable(this, {
...animalProps,
isBarking: observable,
bark: computed,
setIsBarking: action
});
}
get bark() {
if (this.isBarking){
console.log('The dog is barking');
}
}
setIsBarking(isBarking) {
this.isBarking = isBarking;
}
}
If you need an instance of Animal in your app, then Mobx-State-Tree is a better option. Because making a prop observable/actionable/computable twice (the parent class and the subclass) will throw an error.
I know this was asked a long time ago at this point, but per the docs here you can override as you wrote. There are limitations though:
Only action, computed, flow, action.bound defined on prototype can be overriden by subclass.
Field can't be re-annotated in subclass, except with override.
makeAutoObservable does not support subclassing.
Extending builtins (ObservableMap, ObservableArray, etc) is not supported.
You can't provide different options to makeObservable in subclass.
You can't mix annotations/decorators in single inheritance chain.
All their standard limitations apply as well which I won't list here.
This works with the non-annotation syntax as well (e.g., makeObservable).
Have you consider MobX State Tree (https://github.com/mobxjs/mobx-state-tree) for managing your two classes Animal and Dog ?
This will give you the powerfull compose functionality, that could be used instead of inheritance.
Here's the probably most useful part for you: "Simulate inheritance by using type composition" https://github.com/mobxjs/mobx-state-tree#simulate-inheritance-by-using-type-composition

TableView and Fragment to edit Details with tornadofx

I use kotlinx.serialization for my models.
I'd like the idea of them to not depend on JavaFX, so they do not expose properties.
Given a model, I want a tableview for a quick representation of a list of instances, and additionally a more detailed Fragment as an editor.
consider the following model:
#Serializable
data class Person(
var name: String,
var firstname: String,
var complex: Stuff)
the view containing the tableview contains
private val personlist = mutableListOf<Person>().observable()
with a tableview that opens an instance of PersonEditor for the selected row when Enter is pressed:
tableview(personlist) {
column("name", Person::name)
column("first name", Person::firstname)
setOnKeyPressed { ev ->
selectedItem?.apply {
when (ev.code) {
KeyCode.ENTER -> PersonEditor(this).openModal()
}
}
}
}
I followed this gitbook section (but do not want the modelview to be rebound on selection of another row within the tableview)
The editor looks about like this:
class PersonEditor(person: Person) : ItemFragment<Person>() {
val model: Model = Model()
override val root = form {
fieldset("Personal information") {
field("Name") {
textfield(model.name)
}
field("Vorname") {
textfield(model.firstname)
}
}
fieldset("complex stuff") {
//... more complex stuff here
}
fieldset {
button("Save") {
enableWhen(model.dirty)
action { model.commit() }
}
button("Reset") { action { model.rollback() } }
}
}
class Model : ItemViewModel<Person>() {
val name = bind(Person::name)
val firstname = bind(Person::firstname)
//... complex stuff
}
init {
itemProperty.value = mieter
model.bindTo(this)
}
}
When I save the edited values in the detail view, the tableview is not updated.
Whats the best practize to solve this?
Also I'm unsure, if what I'm doing can be considered good practize, so i'd be happy for some advice on that too.
The best practice in a JavaFX application is to use observable properties. Not doing so is an uphill battle. You can keep your lean domain objects, but add a JavaFX/TornadoFX specific version with observable properties. This object can know how to copy data to/from your "lean" domain objects.
With this approach, especially in combination with ItemViewModel wrappers will make sure that your data is always updated.
The setOnKeyPressed code you posted can be changed to:
setOnUserSelect {
PersonEditor(it).openModal()
}
Notice though, that you are not supposed to instantiate Views and Fragments directly, as doing so skips certain steps in the TornadoFX life cycle. Instead you should pass the person as a parameter, or create a new scope and inject a PersonModel into that scope before opening the editor in that scope:
setOnUserSelect {
find<PersonEditor>(Scope(PersonEditor(it)))
}

How do I mock an inherited method that has generics with JMockit

I have this abstract class:
public abstract class Accessor<T extends Id, U extends Value>
{
public U find(T id)
{
// let's say
return getHelper().find(id);
}
}
And an implementation:
public FooAccessor extends Accessor<FooId,Foo>
{
public Helper getHelper
{
// ...
return helper;
}
}
And I would like to mock the calls to FooAccessor.find.
This:
#MockClass(realClass=FooAccessor.class)
static class MockedFooAccessor
{
public Foo find (FooId id)
{
return new Foo("mocked!");
}
}
will fail with this error:
java.lang.IllegalArgumentException: Matching real methods not found for the following mocks of MockedFooAccessor:
Foo find (FooId)
and I understand why... but I don't see how else I could do it.
Note: yes, I could mock the getHelper method, and get what I want; but this is more a question to learn about JMockit and this particular case.
The only way around this I have found is to use fields
#Test
public void testMyFooMethodThatCallsFooFind(){
MyChildFooClass childFooClass = new ChildFooClass();
String expectedFooValue = "FakeFooValue";
new NonStrictExpectations(){{
setField(childFooClass, "fieldYouStoreYourFindResultIn", expectedFooValue);
}};
childFooClass.doSomethingThatCallsFind();
// if your method is protected or private you use Deencapsulation class
// instead of calling it directly like above
Deencapsulation.invoke(childFooClass, "nameOfFindMethod", argsIfNeededForFind);
// then to get it back out since you used a field you use Deencapsulation again to pull out the field
String actualFoo = Deencapsulation.getField(childFooClass, "nameOfFieldToRunAssertionsAgainst");
assertEquals(expectedFooValue ,actualFoo);
}
childFooClass doesn't need to be mocked nor do you need to mock the parent.
Without more knowledge of your specific case this strategy has been the best way for me to leverage jMockit Deencapsulation makes so many things possilbe to test without sacrificing visibility. I know this doesn't answer the direct question but I felt you should get something out of it. Feel free to downvote and chastise me community.
Honestly, I do not find it in any way different from mocking regular classes. One way to go is to tell JMockit to mock only the find method and use Expectations block to provide alternate implementation. Like this:
abstract class Base<T, U> {
public U find(T id) {
return null;
}
}
class Concrete extends Base<Integer, String> {
public String work() {
return find(1);
}
}
#RunWith(JMockit.class)
public class TestClass {
#Mocked(methods = "find")
private Concrete concrete;
#Test
public void doTest() {
new NonStrictExpectations() {{
concrete.find((Integer) withNotNull());
result = "Blah";
}}
assertEquals("Blah", concrete.work());
}
}
Hope it helps.