com-lihaoyi / scalatags

ScalaTags is a small XML/HTML construction library for Scala.
https://com-lihaoyi.github.io/scalatags/
MIT License
758 stars 117 forks source link

class (cls) opeartor for setting classes in Element #136

Closed pawelpanasewicz closed 4 years ago

pawelpanasewicz commented 8 years ago

Given such construct:

div(cls:="C1", cls:= "C2")

When you render div it turns out, that second cls directive will override the first on. It will look like

<div class="C2" />

This is because cls is implemented as scalatags.generic.Attr.

Of course setting several classes can be implemented using string concatenation with extra space separator. This div(cls:="C1 C2") would generate <div class="C1 C2" />, no doubt.

How do you fill in terms of creating cls contruct as not Attr but dedicated mechanism for adding classes.

In such case above construct would generate:

<div class="C1 C2" />

More over a nice syntax would be introduced:

div(cls:= ("C1", "C2", "C3"))  //varying array of class names

This would yield

<div class="C1 C2 C3" />

What do you think?

pawelpanasewicz commented 8 years ago

Here is proof of concept in my project https://github.com/jawp/wicked-playground/commit/ed3097f6b3391ad68e8f3f7ec3f46d5f53b75fdd

I've tested it in real browsers and it works fine. Unfortunately in rhino and phantomjs it doesn't.

scalway commented 7 years ago

for Me, the new syntax isn't much nicer. It doesn't fix anything (and is a bit heavier due to vararg).

div(cls := Seq("C1","C2").mkString(" "))
div(cls := ("C1" + " C2"))
div(cls := (s"$c1 $c2"))

of corse your version is less verbose, but doesn't solve ANY problem.

What I personally propose is a new operator that'll not override existing value but rather append to it. something like:

div(cls:="C1", cls += " form-cog form-horizontal")

the only problem is what to do with trailing space in such constructs?

such operator could be used whenever you have helper objects with predefined classes:

val row = (cls:="row")
...
row(cls += " my-class")
//or to explicitly say that it'll be space separated 
row(cls +_= "my-class") //sorry +_= isn't valid scala name :(

this is wat I'm using a lot, and have own constructs that deals with it somehow!

scalway commented 7 years ago

oh... I see... := oerator will always append classes.

val row = (cls:="row")
row(cls := "my-class")
//<div class="row my-class"></div>

could be bad idea becouse we expect that it'll override them (it is true for every other place where we use :=). This'll be rather confusing and disallow to override current classes.

scalway commented 7 years ago

oh... it seems that for current 'scalatags.Text' this code appends classes! but for 'scalatags.JsDom' it overrides it! Weird.

import scalatags.Text.all._
val row = (cls:="row")
row(cls := "my-class").render
//<div class="row my-class"></div>

import scalatags.JsDom.all._
val row = (cls:="row")
row(cls := "my-class").render
//<div class="my-class"></div>