-
Notifications
You must be signed in to change notification settings - Fork 1
/
lit-style.js
86 lines (72 loc) · 2.88 KB
/
lit-style.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
/*
* Create a decorator to style your Lit components with a base style.
*
* `styles` should be a CSS object generated by Lit's `css` function.
*
* Example usage:
*
* import { litStyle } from 'lit-element-style';
* import { LitElement, css } from 'lit-element';
*
* const myStyles = litStyle(css`h1 { color: red; }`);
*
* class MyComponent extends myStyles(LitElement) {
* // ...
* }
*/
export function litStyle(styles) {
const func = wrappedEl => {
// This allows to use a `litStyle()` generated function to extend
// another stylesheet:
//
// const basicStyle = litStyle(css`p { font-size: 3px; }`);
// const extendedStyle = basicStyle(css`input { font-size: 2px; }`);
if (typeof wrappedEl === 'object' && 'cssText' in wrappedEl) {
return litStyle([styles, wrappedEl]);
}
return class extends wrappedEl {
static getStyles() {
const superStyles = super.getStyles();
if (!superStyles) {
return styles;
}
// The first time this method is called, then the `superStyles`
// get precedence over the `styles`. Because this gets the
// styles from any `static get styles()` method. That should
// get the highest precedence.
//
// The times this method is called after that, the
// `superStyles` are coming from a parent class that implements
// the `getStyles()` method, possibly another LitStyle
// decorator. These styles should not get precedence, because
// the wrapped component extends from these style decorators.
// And with extending you expect that you can override things.
//
// The styles that appear later in the returned array get
// precedence, because they override the old ones.
if (this.__lit_style_past_root) {
this.__lit_style_past_root = false;
if (Array.isArray(superStyles)) {
return [...superStyles, styles];
} else {
return [superStyles, styles];
}
} else {
this.__lit_style_past_root = true;
if (Array.isArray(superStyles)) {
return [styles, ...superStyles];
} else {
return [styles, superStyles];
}
}
}
}
};
// This allows you to access the original CSS object like this:
//
// cssObj = css`h1 { color: red; }`;
// const myStyles = litStyle(cssObj);
// myStyles.css === cssObj;
func.css = styles;
return func;
}