Everything is immutable in ScalaCSS
(except for the small scalacss.internal.mutable
package),
so any StyleS
,
StyleF
,
StyleC
can safely be used anywhere else.
StyleA
(applicable inline style) is immutable too but one of its properties
is a generated class name. If you're using inline stylesheet, class names are
generated by StyleSheet.Register
so sharing them is not a good idea. Instead what you want is a reusable style module.
It's often preferable to share a collection of named styles, a style module.
The definition of a style module is only slighty different from normal stylesheets
in that instead of defining an object
object MyStyles extends StyleSheet.Inline {
you create a class with an implicit register
class MyStyleModule(implicit r: StyleSheet.Register) extends StyleSheet.Inline()(r) {
Note: The ()(r)
syntax is weird because Scala has a rule that implicit arguments
always come second, even when there are no non-implicit arguments. That is the case
here which is why it forces us to specify an empty argument list before setting the
implicit one.
To use shared styles, you simply create an instance of them inside another stylesheet.
object MyStyles extends StyleSheet.Inline {
val shared = new MyStyleModule
}
That's all there is to it.
A shared module:
class SharedTheme(implicit r: StyleSheet.Register) extends StyleSheet.Inline()(r) {
import dsl._
val button = style(
padding(0.5 ex, 2 ex),
backgroundColor("#eee"),
border(1 px, solid, black)
)
val title = style(
fontSize(32 px)
)
}
Concrete styles in the app:
object MyAppStyles extends StyleSheet.Inline {
import dsl._
val theme = new SharedTheme // Instantiate shared styles
val headingTitle = style(
theme.title, // Extend shared style
color(red)
)
}
Example usage in scalajs-react:
def showDetailsButton =
<.button(
MyAppStyles.theme.button,
^.onClick ~~> showLoginDetails(user),
"Show Details"))
def render =
<.div(
<.h1(
MyAppStyles.headingTitle,
"Your Login Details"),
showDetailsButton)
If you're writing a shared library, then we tweak the above snippet so that the sharable style is passed in.
def showDetailsButton(theme: SharedTheme) =
<.button(
theme.button,
^.onClick ~~> showLoginDetails(user),
"Show Details"))
If you don't want to pass a stylesheet around, see Global Registry.