@vaadin/vaadin-themable-mixin 22.0.0-alpha1 → 22.0.0-alpha10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,574 +1,12 @@
1
- # Table of Contents
1
+ # vaadin-themable-mixin
2
2
 
3
- 1. [Style Scopes](#style-scopes)
4
- 1. [Adding Styles to Local Scope](#adding-styles-to-local-scope)
5
- 1. [Stylable Shadow Parts](#stylable-shadow-parts)
6
- 1. [Scoping Styles in a Theme Module](#scoping-styles-in-a-theme-module)
7
- 1. [Theme Attribute and Subcomponents](#theme-attribute-and-subcomponents)
8
- 1. [External resources](#external-resources)
3
+ A mixin to enable customization of Shadow DOM used by Vaadin components.
9
4
 
5
+ [Documentation ↗](https://vaadin.com/docs/latest/ds/customization/styling-components)
10
6
 
7
+ [![npm version](https://badgen.net/npm/v/@vaadin/vaadin-themable-mixin)](https://www.npmjs.com/package/@vaadin/vaadin-themable-mixin)
8
+ [![Discord](https://img.shields.io/discord/732335336448852018?label=discord)](https://discord.gg/PHmkCKC)
11
9
 
12
- # Style Scopes
10
+ ## License
13
11
 
14
- With the addition of Shadow DOM, styles on a webpage can be divided into two groups:
15
- 1. Styles affecting elements in the [global scope](#global-style-scope), i.e. traditional styles
16
- 2. Styles affecting elements inside a [local scope](#local-style-scope-shadow-dom), i.e. styles inside a shadow DOM
17
-
18
- ## Global Style Scope
19
-
20
- On a regular website, all elements are inside the same global style scope, and can be styled with global stylesheets (either `<link rel="stylesheet">` or `<style>` elements), using regular CSS selectors.
21
-
22
- #### Example: Global stylesheet
23
- ![vaadin-text-field light DOM](docs-images/vaadin-text-field-light-dom.png)
24
-
25
- The only thing we can style using global styles is the whole `<vaadin-text-field>` element, but nothing inside it, like the *label* or the *input field*.
26
-
27
- For example, we could have the following styles in an imported stylesheet:
28
-
29
- ```css
30
- vaadin-text-field {
31
- border: 1px solid gray;
32
- }
33
- ```
34
-
35
- And it would produce the following result:
36
-
37
- ![vaadin-text-field with a border around the whole component](docs-images/vaadin-text-field-border.png)
38
-
39
- ## Local Style Scope (Shadow DOM)
40
-
41
- Styling Web Components (or custom elements to be more precise), which use shadow DOM, is different from styling regular websites.
42
-
43
- When a custom element has its own shadow DOM, the browser creates a new style scope for the elements that are placed inside the shadow DOM hierarchy, and CSS selectors in global stylesheets can’t affect those elements.
44
-
45
- The only CSS selectors that can affect the elements inside a shadow DOM need to be in a `<style>` element which is somewhere inside the shadow DOM hierarchy. At the same time, the styles inside a shadow DOM can’t affect elements outside the shadow DOM. The styles are placed in the “local style scope” of the shadow DOM.
46
-
47
- #### Example: Local style
48
-
49
- ![vaadin-text-field shadow DOM](docs-images/vaadin-text-field-shadow-dom.png)
50
-
51
- Only the `<style>` element highlighted in the inspector can affect the elements inside the `<vaadin-text-field>` element’s shadow DOM.
52
-
53
- For example, if we move the same styles from the previous example inside the `<style>` element inside the shadow DOM, the result is the same as without the style rules:
54
-
55
- ```html
56
- #shadow-root (open)
57
- <style>
58
- vaadin-text-field {
59
- border: 1px solid gray;
60
- }
61
- </style>
62
- ```
63
-
64
- ![vaadin-text-field with default styles](docs-images/vaadin-text-field.png)
65
-
66
- That is because there are no `<vaadin-text-field>` elements inside the shadow DOM. If we want the same result as with the global stylesheet, we need to use the `:host` selector to match the element which is the “host” for this shadow DOM or style scope:
67
-
68
- ```html
69
- #shadow-root (open)
70
- <style>
71
- :host {
72
- border: 1px solid gray;
73
- }
74
- </style>
75
- ```
76
-
77
- Then we get the same result as with the global stylesheet:
78
-
79
- ![vaadin-text-field with a border around the whole component](docs-images/vaadin-text-field-border.png)
80
-
81
- If we wanted to move the border to the actual text input element, we would need to inspect the shadow DOM hierarchy and see which selector would match that particular element. For `<vaadin-text-field>`, the correct selector would be `[part="input-field"]`:
82
-
83
- ```html
84
- #shadow-root
85
- <style>
86
- [part="input-field"] {
87
- border: 1px solid gray;
88
- }
89
- </style>
90
- ```
91
- ![vaadin-text-field with a border around the input only](docs-images/vaadin-text-field-input-border.png)
92
-
93
-
94
- # Adding Styles to Local Scope
95
-
96
- *Read the documentation about [Style Scopes](#style-scopes) before continuing.*
97
-
98
-
99
- ## Property inheritance
100
-
101
- Currently, the only global CSS that can affect styles inside a shadow DOM’s local scope are properties that are inherited. Properties can be inherited by default, like `font-family` or all [CSS Custom Properties](https://www.w3.org/TR/css-variables/), or explicitly by the custom element, using the `inherit` property value.
102
-
103
-
104
- #### Example: using a custom property to affect the styles in a local scope
105
- ```html
106
- <custom-style>
107
- <style>
108
- vaadin-combo-box {
109
- --vaadin-combo-box-overlay-max-height: 50vh;
110
- }
111
- </style>
112
- </custom-style>
113
- ```
114
-
115
- > Note: for cross-browser compatibility, [use the `<custom-style>` element](https://polymer-library.polymer-project.org/2.0/docs/devguide/style-shadow-dom#custom-style).
116
-
117
- > Note: check the API documentation of each element for the custom properties they expose. See the [API documentation for vaadin-combo-box](https://vaadin.com/elements/vaadin-combo-box/html-api/elements/Vaadin.ComboBoxElement#styling) for example.
118
-
119
-
120
- #### Example: explicitly inheriting a property value from the global scope into local scope
121
- ```html
122
- #shadow-root
123
- <style>
124
- :host {
125
- background-color: inherit;
126
- }
127
- </style>
128
- ```
129
-
130
-
131
- ## Selector matching
132
-
133
- The web platform doesn’t currently provide a way to write selectors in the global scope that would match elements in a local scope (Oct 2017). There’s a [CSS spec proposal](http://tabatkins.github.io/specs/css-shadow-parts/) that will add that, but for now, we need to work around this limitation using proprietary solutions, like Vaadin’s [`ThemableMixin`](https://github.com/vaadin/vaadin-themable-mixin).
134
-
135
-
136
- ## Theme modules
137
-
138
- Custom elements extending [`ThemableMixin`](https://github.com/vaadin/vaadin-themable-mixin) allow you to inject styles into their local scope by defining new [style modules](https://polymer-library.polymer-project.org/2.0/docs/devguide/style-shadow-dom#style-modules) in the global scope. You specify the targeted element using the `theme-for` attribute.
139
-
140
- ```html
141
- <!-- Define a theme module (in index.html or in a separate HTML import) -->
142
- <dom-module id="my-theme-module" theme-for="my-element">
143
- <template>
144
- <style>
145
- /* Styles which will be included in my-element local scope */
146
- </style>
147
- </template>
148
- </dom-module>
149
- ```
150
-
151
- You can place these “theme module” definitions directly in your `index.html` or in a separate HTML import.
152
-
153
- > Note: a theme module needs to be imported and registered in the DOM before the element(s), which the module targets with the `theme-for` attribute, are registered and upgraded (before the first instantiation of the component).
154
-
155
- The `id` attribute of the theme module should be unique. You can also re-use an existing id if you want to override a previously defined/imported module.
156
-
157
- > Note: The theme modules are included in an order that enables custom modules to override styles defined by the Vaadin's built-in modules. The built-in theme modules use id's prefixed with `vaadin-`, `lumo-` and `material-` so avoid using these prefixes in your custom theme module `id`'s.
158
-
159
- The value of the `theme-for` attribute can be a space-separated list of element names, and can contain wildcard element names as well.</p>
160
-
161
- ### Styling in JavaScript
162
-
163
- When working with ES modules/JavaScript generally, constructing theme modules programmatically might end up producing boilerplate code to the application. Where possible, prefer the `registerStyles` utility which provides a convenient abstraction over the declarative API.
164
-
165
- Importing the helper as an HTMLImport
166
- ```html
167
- <link rel="import" href="/bower_components/vaadin-themable-mixin/register-styles.html">
168
- ...
169
- <script>
170
- const { registerStyles, css, unsafeCSS } = Vaadin;
171
- </script>
172
- ```
173
-
174
- Importing the helper as an ES module
175
- ```js
176
- import { registerStyles, css } from '@vaadin/vaadin-themable-mixin/register-styles.js';
177
- ```
178
-
179
- Use the `registerStyles(themeFor, styles)` function to register CSS styles to be included in a component's local scope.
180
-
181
- The `themeFor` parameter is of type string and is used to identify the component type the styles are applied to. It works the same as with style modules.
182
-
183
- The `styles` accepts an object or an array of objects built as template literals tagged with `css`, containing CSS style rules to be included in the targeted component's local style.
184
-
185
- ```js
186
- registerStyles('my-element', css`
187
- /* Styles which will be included in my-element local scope */
188
- `);
189
- ```
190
-
191
- Including untrusted CSS can also be a security issue. Whenever you're dealing with predefined CSS text, you can use `unsafeCSS` function to wrap the value as an object that can be passed to the `registerStyles` function.
192
-
193
- > Note: Only use `unsafeCSS` with CSS text that you trust.
194
-
195
- ```js
196
- const trustedCSSValue = ... // some CSS string fetched from a DB for example
197
-
198
- registerStyles('my-element', unsafeCSS(trustedCSSValue));
199
- ```
200
-
201
- The second parameter for `registerStyles` also accepts an array, so you can include multiple styles to an element at the same time.
202
-
203
- Using registerStyles imported as an ES module
204
- ```js
205
- const myStyles = css`
206
- /* Styles which will be included in my-element local scope */
207
- `;
208
- const trustedStyles = unsafeCSS(trustedCSSValue);
209
-
210
- registerStyles('my-element', [myStyles, trustedStyles]);
211
- ```
212
-
213
- If you need to include styles defined as Polymer style modules with id, you can still pass the module ids as `include` array of the third `options` parameter to the function. Consider this API deprecated.
214
-
215
- ```js
216
- // Use of "include" is deprecated!
217
- registerStyles('my-element', css`
218
- /* Optional styles to be included in my-element local scope */
219
- `, {include: ['my-style-module']});
220
- ```
221
-
222
- If you need to get styles defined with `registerStyles` registered as a Polymer style module with a pre-defined id, you can still do so by passing an object with `moduleId` as the third parameter for the function. Consider this API deprecated.
223
-
224
- ```js
225
- // Use of "moduleId" is deprecated!
226
- registerStyles(undefined, css`
227
- /* Styles which will be included in the style module */
228
- `, {moduleId: 'my-extended-style-module'});
229
- ```
230
-
231
-
232
- #### Examples of valid `theme-for` values:
233
- - `"vaadin-button"`
234
- - `"vaadin-overlay vaadin-date-picker-overlay"`
235
- - `"vaadin-*"`
236
-
237
-
238
- ### Theme modules are global
239
-
240
- When creating a theme module for an element, the styles in that theme module will apply to all instances of that element. The styles are always “global” in that sense and can’t be scoped by default with anything.
241
-
242
-
243
-
244
- # Stylable Shadow Parts
245
-
246
- *Read the documentation about [Style Scopes](#style-scopes) and [Adding Styles to Local Scope](#adding-styles-to-local-scope) before continuing.*
247
-
248
-
249
- ## Stylable elements
250
-
251
- ### Host element
252
-
253
- The host element is the main element which has a shadow DOM, for example `<vaadin-text-field>`.
254
-
255
- ### Named parts
256
-
257
- In addition to the host element, only certain elements inside a themable element (i.e. an element extending [`ThemableMixin`](https://github.com/vaadin/vaadin-themable-mixin)) should be styled.
258
-
259
- Other elements should be **considered as internal implementation details**, and you should not expect these elements to remain constant or be available in the future.
260
-
261
- The stylable elements have the `part` attribute, which gives the elements a descriptive name.
262
-
263
- #### Example: stylable parts of vaadin-text-field
264
- ![vaadin-text-field with stylable parts highlighted in the UI and in shadow DOM markup](docs-images/vaadin-text-field-parts.png)
265
-
266
- You can expect these part names to remain constant and rely on the hierarchy of these parts (i.e. the `value` part will always be contained within `input-field`).
267
-
268
-
269
- ## How do I know what parts are available?
270
-
271
- The stylable parts of each Vaadin component are listed in their API documentation. See the [API documentation for vaadin-text-field](https://vaadin.com/components/vaadin-text-field/html-api/elements/Vaadin.TextFieldElement#styling) for example.
272
-
273
-
274
- ## Supported selectors
275
-
276
- ### :host
277
-
278
- The host element can be targeted using the `:host` selector.
279
-
280
- ```html
281
- <dom-module id="my-button" theme-for="vaadin-button">
282
- <template>
283
- <style>
284
- :host {
285
- /* Styles for vaadin-button element */
286
- }
287
- </style>
288
- </template>
289
- </dom-module>
290
- ```
291
-
292
-
293
- ### [part="..."]
294
-
295
- The stylable elements (marked with a `part` attribute) should only be targeted using the `[part="..."]` attribute selector.
296
-
297
- ```html
298
- <dom-module id="my-text-field" theme-for="vaadin-text-field">
299
- <template>
300
- <style>
301
- [part="input-field"] {
302
- /* Styles for vaadin-text-field's input-field part */
303
- }
304
- </style>
305
- </template>
306
- </dom-module>
307
- ```
308
-
309
- ### [part~="..."]
310
-
311
- Use `part~="..."` to match a part which might have multiple names, for example the cells inside a `<vaadin-grid>` which can have multiple names like `"cell"` and `"body-cell"`.
312
-
313
- You can use this kind of attribute selector in all cases, if you want to be safe. It will work for parts with only one name as well.
314
-
315
- ```html
316
- <dom-module id="my-grid" theme-for="vaadin-grid">
317
- <template>
318
- <style>
319
- [part~="cell"] {
320
- /* Styles that affect all grid cells, including header, body and footer cells */
321
- }
322
-
323
- [part~="body-cell"] {
324
- /* Styles that only affect all body cells */
325
- }
326
- </style>
327
- </template>
328
- </dom-module>
329
- ```
330
-
331
- **Do not rely on the element type** which a part applies to. For example, given `<input type="text" part="value">`, you should not rely on the information that the element is actually a native `<input>` element. This is considered as an internal implementation detail, and the element type could change in the future (while the part name stays the same), for example to `<div contenteditable="true" part="value">`.
332
-
333
- ### State attributes
334
-
335
- Some custom elements expose some of their internal state as top-level attributes for styling purposes. You can find these attributes in the elements API documentation.
336
-
337
- For example, you can target styles for a disabled `<vaadin-button>` using the `disabled` attribute in combination with the `:host` selector:
338
-
339
- ```html
340
- <dom-module id="my-button" theme-for="vaadin-button">
341
- <template>
342
- <style>
343
- :host([disabled]) {
344
- /* Styles for disabled vaadin-button element */
345
- }
346
- </style>
347
- </template>
348
- </dom-module>
349
- ```
350
-
351
- You can also target any named parts in a specific state of the host. For example, you can add a red border for the `input-field` part of a `<vaadin-text-field>` which is marked `invalid`:
352
-
353
- ```html
354
- <dom-module id="my-text-field" theme-for="vaadin-text-field">
355
- <template>
356
- <style>
357
- :host([invalid]) [part="input-field"] {
358
- border: 1px solid red;
359
- }
360
- </style>
361
- </template>
362
- </dom-module>
363
- ```
364
-
365
-
366
-
367
- Similarly to the host element, the named parts can also expose state attributes for themselves, which can be used for styling. These are also listed in the element’s API documentation.
368
-
369
- For example, you can target a selected date in a `<vaadin-date-picker>`:
370
-
371
- ```html
372
- <dom-module id="my-month-calendar-styles" theme-for="vaadin-month-calendar">
373
- <template>
374
- <style>
375
- [part~="date"][selected] {
376
- /* Styles for a selected date */
377
- }
378
- </style>
379
- </template>
380
- </dom-module>
381
- ```
382
-
383
-
384
-
385
- # Scoping Styles in a Theme Module
386
-
387
- The styles defined in a “theme module” affect all the instances of the element the module targets with the `theme-for` attribute.
388
-
389
- There are two ways to scope the styles that you write in a theme module.
390
-
391
- 1. **Expose new custom properties**
392
- This is the recommended first option for simple situations. If you end up exposing more than a handful of properties, you should consider the second option.
393
- 2. **Use scoping selectors**
394
- This approach is used by the built-in variations in Vaadin themes (Lumo and Material), i.e. `theme` attribute. The downside of this approach is that you end up adding the selectors and properties to all instances, even though only some instances will need those styles (they won’t apply unless the scoping selector is used on the host element).
395
-
396
- #### Example: expose new custom properties
397
- ```html
398
- <!-- Define the theme module (in index.html or in a separate HTML import) -->
399
- <dom-module id="my-text-field-theme" theme-for="vaadin-text-field">
400
- <template>
401
- <style>
402
- [part="input-field"] {
403
- background-color: var(--input-field-background-color, #fff);
404
- }
405
- </style>
406
- </template>
407
- </dom-module>
408
-
409
- <!-- Use the new custom property -->
410
- <custom-style>
411
- <style>
412
- .some-part-of-my-app vaadin-text-field {
413
- --input-field-background-color: #eee;
414
- }
415
- </style>
416
- </custom-style>
417
-
418
- <div class="some-part-of-my-app">
419
- <vaadin-text-field></vaadin-text-field>
420
- </div>
421
- ```
422
-
423
- #### Example: use scoping selectors
424
-
425
- ```html
426
- <!-- Define the theme module (in index.html or in a separate HTML import) -->
427
- <dom-module id="my-text-field-theme" theme-for="vaadin-text-field">
428
- <template>
429
- <style>
430
- :host(.special-field) [part="input-field"] {
431
- background-color: #000;
432
- color: #fff;
433
- border: 2px solid #fff;
434
- border-radius: 9px;
435
- }
436
- </style>
437
- </template>
438
- </dom-module>
439
-
440
- <!-- Use the new scoping selector anywhere in your app -->
441
- <div>
442
- <vaadin-text-field class="special-field"></vaadin-text-field>
443
- </div>
444
- ```
445
-
446
- You can also use a `theme` attribute as a scoping selector for your style overrides, as shown in the example below.
447
-
448
- #### Example: scoping with `theme` attribute selector
449
-
450
- ```html
451
- <!-- Define the theme module (in index.html or in a separate HTML import) -->
452
- <dom-module id="special-field-theme" theme-for="vaadin-text-field">
453
- <template>
454
- <style>
455
- :host([theme~="special-field"]) [part="input-field"] {
456
- background-color: #000;
457
- color: #fff;
458
- border: 2px solid #fff;
459
- border-radius: 9px;
460
- }
461
- </style>
462
- </template>
463
- </dom-module>
464
-
465
- <!-- Apply the theme attribute to any text-field in your app -->
466
- <div>
467
- <vaadin-text-field theme="special-field"></vaadin-text-field>
468
- </div>
469
- ```
470
-
471
-
472
- # Theme Attribute and Subcomponents
473
-
474
- Sometimes components using `VaadinThemableMixin` are contained in Shadow DOM of other components. In such a case, we propagate the `theme` attribute of the host web component to subcomponents.
475
-
476
- For example, Vaadin components using `<vaadin-text-field>` is used as an internal input field subcomponent, including `<vaadin-combo-box>`, `<vaadin-date-picker>`, and so on, propagate the `theme` attribute. You can use theme variants defined for `<vaadin-text-field>` in, e. g., `<vaadin-combo-box>`, and this will affect the internal subcomponent:
477
-
478
- #### Example: using `small` Lumo theme variant on `<vaadin-combo-box>`
479
-
480
- ```html
481
- <vaadin-combo-box theme="small"></vaadin-combo-box>
482
- ```
483
-
484
- If you can define a custom theme variant for `<vaadin-text-field>`, you can use it with other Vaadin components that have an internal `<vaadin-text-field>` too:
485
-
486
- #### Example: using a custom text field `theme` variant with `<vaadin-combo-box>`
487
-
488
- ```html
489
- <!-- Define the theme module (in index.html or in a separate HTML import) -->
490
- <dom-module id="special-field-theme" theme-for="vaadin-text-field">
491
- <template>
492
- <style>
493
- :host([theme~="special-field"]) [part="input-field"] {
494
- background-color: #000;
495
- color: #fff;
496
- border: 2px solid #fff;
497
- border-radius: 9px;
498
- }
499
- </style>
500
- </template>
501
- </dom-module>
502
-
503
- <!-- Apply the theme attribute to <vaadin-combo-box> -->
504
- <vaadin-combo-box theme="special-field"></vaadin-combo-box>
505
- ```
506
-
507
- ### How to propagate the `theme` attribute in your components
508
-
509
- With your Polymer-based web components you can use `VaadinThemePropertyMixin` to propagate the `theme` to subcomponents. The mixin provides the `theme` property that you can bind to descendant attributes.
510
-
511
- #### Example: a Polymer-based element that propagates the `theme` to Vaadin subcomponents:
512
-
513
- ```js
514
- class MyFieldElement extends Vaadin.ThemePropertyMixin(Polymer.Element) {
515
- static get is() { return 'my-field'; }
516
-
517
- static get template() {
518
- return html`<vaadin-text-field theme$="[[theme]]"></vaadin-text-field>`;
519
- }
520
- }
521
-
522
- CustomElements.define(MyFieldElement.is, MyFieldElement);
523
- ```
524
-
525
- ```html
526
- <my-field theme="small"></my-field>
527
- ```
528
-
529
- ## List of Vaadin components that propagate `theme` to subcomponents
530
-
531
- - `<vaadin-context-menu>`’s theme propagates to internal:
532
- - `<vaadin-context-menu-overlay>`
533
- - `<vaadin-time-picker>`:
534
- - `<vaadin-combo-box-light>`
535
- - `<vaadin-time-picker-text-field>`
536
- - `<vaadin-select>`:
537
- - `<vaadin-text-field>`
538
- - `<vaadin-select-overlay>`
539
- - `<vaadin-dialog>`:
540
- - `<vaadin-dialog-overlay>`
541
- - `<vaadin-combo-box>`:
542
- - `<vaadin-text-field>`
543
- - `<vaadin-combo-box-dropdown-wrapper>`
544
- - `<vaadin-combo-box-dropdown>`
545
- - `<vaadin-combo-box-item>`
546
- - `<vaadin-combo-box-light>`:
547
- - `<vaadin-combo-box-dropdown-wrapper>`
548
- - `<vaadin-combo-box-dropdown>`
549
- - `<vaadin-combo-box-item>`
550
- - `<vaadin-crud>`:
551
- - `<vaadin-crud-grid>`
552
- - `<vaadin-dialog-layout>`
553
- - `<vaadin-dialog>`
554
- - `<vaadin-confirm-dialog>`
555
- - `<vaadin-date-picker>`:
556
- - `<vaadin-text-field>`
557
- - `<vaadin-date-picker-overlay>`
558
- - `<vaadin-date-picker-overlay-content>`
559
- - `<vaadin-month-calendar>`
560
- - `<vaadin-date-picker-light>`:
561
- - `<vaadin-date-picker-overlay>`
562
- - `<vaadin-date-picker-overlay-content>`
563
- - `<vaadin-month-calendar>`
564
- - `<vaadin-notification>`:
565
- - `<vaadin-notification-card>`
566
- - `<vaadin-login-overlay>`:
567
- - `<vaadin-login-overlay-wrapper>`
568
- - `<vaadin-login-form>`:
569
- - `<vaadin-login-form-wrapper>`
570
-
571
-
572
-
573
- # External resources
574
- - [Polymer styling documentation](https://polymer-library.polymer-project.org/2.0/docs/devguide/style-shadow-dom)
12
+ Apache License 2.0
package/package.json CHANGED
@@ -1,38 +1,42 @@
1
1
  {
2
2
  "name": "@vaadin/vaadin-themable-mixin",
3
- "version": "22.0.0-alpha1",
3
+ "version": "22.0.0-alpha10",
4
+ "publishConfig": {
5
+ "access": "public"
6
+ },
4
7
  "description": "vaadin-themable-mixin",
8
+ "license": "Apache-2.0",
9
+ "repository": {
10
+ "type": "git",
11
+ "url": "https://github.com/vaadin/web-components.git",
12
+ "directory": "packages/vaadin-themable-mixin"
13
+ },
14
+ "author": "Vaadin Ltd",
15
+ "homepage": "https://vaadin.com/elements",
16
+ "bugs": {
17
+ "url": "https://github.com/vaadin/vaadin-themable-mixin/issues"
18
+ },
5
19
  "main": "vaadin-themable-mixin.js",
6
20
  "module": "vaadin-themable-mixin.js",
7
- "repository": "vaadin/vaadin-themable-mixin",
21
+ "files": [
22
+ "*.d.ts",
23
+ "register-styles.js",
24
+ "vaadin-*.js"
25
+ ],
8
26
  "keywords": [
9
27
  "Vaadin",
10
28
  "web-components",
11
29
  "web-component",
12
30
  "polymer"
13
31
  ],
14
- "author": "Vaadin Ltd",
15
- "license": "Apache-2.0",
16
- "bugs": {
17
- "url": "https://github.com/vaadin/vaadin-themable-mixin/issues"
18
- },
19
- "homepage": "https://vaadin.com/elements",
20
- "files": [
21
- "*.d.ts",
22
- "vaadin-*.js",
23
- "register-styles.js"
24
- ],
25
32
  "dependencies": {
26
- "@polymer/polymer": "^3.0.0",
27
- "lit": "^2.0.0-rc.1"
33
+ "lit": "^2.0.0"
28
34
  },
29
35
  "devDependencies": {
30
- "@esm-bundle/chai": "^4.1.5",
31
- "@vaadin/testing-helpers": "^0.2.1",
36
+ "@esm-bundle/chai": "^4.3.4",
37
+ "@polymer/polymer": "^3.0.0",
38
+ "@vaadin/testing-helpers": "^0.3.0",
32
39
  "sinon": "^9.2.4"
33
40
  },
34
- "publishConfig": {
35
- "access": "public"
36
- },
37
- "gitHead": "c9694d6549bff1f7fffb9ece26178e57fc228a51"
41
+ "gitHead": "6d3055383b9c3c8306ea34c6f2e2087e63c49348"
38
42
  }
@@ -1,11 +1,6 @@
1
- import { CSSResultGroup } from 'lit';
2
-
3
- export { css, unsafeCSS } from 'lit';
4
-
5
1
  /**
6
- * Registers CSS styles for a component type. Make sure to register the styles before
7
- * the first instance of a component of the type is attached to DOM.
2
+ * @license
3
+ * Copyright (c) 2021 Vaadin Ltd.
4
+ * This program is available under Apache License Version 2.0, available at https://vaadin.com/license/
8
5
  */
9
- declare function registerStyles(themeFor: string | null, styles: CSSResultGroup, options?: object | null): void;
10
-
11
- export { registerStyles };
6
+ export { registerStyles, css, unsafeCSS } from './vaadin-themable-mixin.js';
@@ -1,63 +1,6 @@
1
- import '@polymer/polymer/lib/elements/dom-module.js';
2
- import { CSSResult } from 'lit';
3
- import { stylesFromTemplate } from '@polymer/polymer/lib/utils/style-gather.js';
4
- export { css, unsafeCSS } from 'lit';
5
-
6
- let moduleIdIndex = 0;
7
- // Map of <CSSResult, Polymer.DomModule> pairs.
8
- const styleMap = {};
9
-
10
1
  /**
11
- * Registers CSS styles for a component type. Make sure to register the styles before
12
- * the first instance of a component of the type is attached to DOM.
13
- *
14
- * @param {String} themeFor The local/tag name of the component type to register the styles for
15
- * @param {CSSResultGroup} styles The CSS style rules to be registered for the component type
16
- * matching themeFor and included in the local scope of each component instance
17
- * @param {Object=} options Additional options
18
- * @return {void}
2
+ * @license
3
+ * Copyright (c) 2021 Vaadin Ltd.
4
+ * This program is available under Apache License Version 2.0, available at https://vaadin.com/license/
19
5
  */
20
- export const registerStyles = (themeFor, styles, options) => {
21
- const themeId = (options && options.moduleId) || `custom-style-module-${moduleIdIndex++}`;
22
-
23
- if (!Array.isArray(styles)) {
24
- styles = styles ? [styles] : [];
25
- }
26
-
27
- const processedStyles = styles.map((cssResult) => {
28
- if (!(cssResult instanceof CSSResult)) {
29
- throw new Error('An item in styles is not of type CSSResult. Use `unsafeCSS` or `css`.');
30
- }
31
- if (!styleMap[cssResult]) {
32
- const template = document.createElement('template');
33
- template.innerHTML = `<style>${cssResult.toString()}</style>`;
34
-
35
- styleMap[cssResult] = stylesFromTemplate(template)[0];
36
- }
37
-
38
- return styleMap[cssResult].textContent;
39
- });
40
-
41
- const themeModuleElement = document.createElement('dom-module');
42
- if (themeFor) {
43
- const elementClass = customElements.get(themeFor);
44
- if (elementClass && Object.prototype.hasOwnProperty.call(elementClass, '__finalized')) {
45
- console.warn(`The custom element definition for "${themeFor}"
46
- was finalized before a style module was registered.
47
- Make sure to add component specific style modules before
48
- importing the corresponding custom element.`);
49
- }
50
- themeModuleElement.setAttribute('theme-for', themeFor);
51
- }
52
-
53
- const moduleIncludes = (options && options.include) || [];
54
-
55
- themeModuleElement.innerHTML = `
56
- <template>
57
- ${moduleIncludes.map((include) => `<style include=${include}></style>`)}
58
- ${processedStyles.length ? `<style>${processedStyles.join('\n')}</style>` : ''}
59
- </template>
60
- `;
61
-
62
- themeModuleElement.register(themeId);
63
- };
6
+ export { registerStyles, css, unsafeCSS } from './vaadin-themable-mixin.js';
@@ -1,3 +1,9 @@
1
+ /**
2
+ * @license
3
+ * Copyright (c) 2021 Vaadin Ltd.
4
+ * This program is available under Apache License Version 2.0, available at https://vaadin.com/license/
5
+ */
6
+ import { CSSResult, CSSResultGroup } from 'lit';
1
7
  import { ThemePropertyMixin, ThemePropertyMixinConstructor } from './vaadin-theme-property-mixin.js';
2
8
 
3
9
  declare function ThemableMixin<T extends new (...args: any[]) => {}>(
@@ -11,4 +17,24 @@ interface ThemableMixinConstructor {
11
17
 
12
18
  interface ThemableMixin extends ThemePropertyMixin {}
13
19
 
14
- export { ThemableMixin, ThemableMixinConstructor };
20
+ /**
21
+ * Registers CSS styles for a component type. Make sure to register the styles before
22
+ * the first instance of a component of the type is attached to DOM.
23
+ */
24
+ declare function registerStyles(themeFor: string | null, styles: CSSResultGroup, options?: object | null): void;
25
+
26
+ type Theme = {
27
+ themeFor: string;
28
+ styles: CSSResult[];
29
+ moduleId?: string;
30
+ include?: string | string[];
31
+ };
32
+
33
+ /**
34
+ * For internal purposes only.
35
+ */
36
+ declare const __themeRegistry: Theme[];
37
+
38
+ export { css, unsafeCSS } from 'lit';
39
+
40
+ export { ThemableMixin, ThemableMixinConstructor, registerStyles, __themeRegistry };
@@ -1,83 +1,230 @@
1
- import { DomModule } from '@polymer/polymer/lib/elements/dom-module.js';
1
+ /**
2
+ * @license
3
+ * Copyright (c) 2021 Vaadin Ltd.
4
+ * This program is available under Apache License Version 2.0, available at https://vaadin.com/license/
5
+ */
6
+ import { CSSResult, css, unsafeCSS } from 'lit';
2
7
  import { ThemePropertyMixin } from './vaadin-theme-property-mixin.js';
3
8
 
9
+ export { css, unsafeCSS };
10
+
11
+ /**
12
+ * @typedef {Object} Theme
13
+ * @property {string} themeFor
14
+ * @property {CSSResult[]} styles
15
+ * @property {string | string[]} [include]
16
+ * @property {string} [moduleId]
17
+ *
18
+ * @typedef {CSSResult[] | CSSResult} CSSResultGroup
19
+ */
20
+
21
+ /**
22
+ * @type {Theme[]}
23
+ */
24
+ const themeRegistry = [];
25
+
26
+ /**
27
+ * Registers CSS styles for a component type. Make sure to register the styles before
28
+ * the first instance of a component of the type is attached to DOM.
29
+ *
30
+ * @param {string} themeFor The local/tag name of the component type to register the styles for
31
+ * @param {CSSResultGroup} styles The CSS style rules to be registered for the component type
32
+ * matching themeFor and included in the local scope of each component instance
33
+ * @param {{moduleId?: string, include?: string | string[]}} options Additional options
34
+ * @return {void}
35
+ */
36
+ export function registerStyles(themeFor, styles, options = {}) {
37
+ if (themeFor) {
38
+ const elementClass = customElements.get(themeFor);
39
+ if (elementClass && Object.prototype.hasOwnProperty.call(elementClass, '__finalized')) {
40
+ console.warn(`The custom element definition for "${themeFor}"
41
+ was finalized before a style module was registered.
42
+ Make sure to add component specific style modules before
43
+ importing the corresponding custom element.`);
44
+ }
45
+ }
46
+
47
+ styles = recursiveFlattenStyles(styles);
48
+
49
+ if (window.Vaadin && window.Vaadin.styleModules) {
50
+ window.Vaadin.styleModules.registerStyles(themeFor, styles, options);
51
+ } else {
52
+ themeRegistry.push({
53
+ themeFor,
54
+ styles,
55
+ include: options.include,
56
+ moduleId: options.moduleId
57
+ });
58
+ }
59
+ }
60
+
61
+ /**
62
+ * Returns all registered themes. By default the themeRegistry is returend as is.
63
+ * In case the style-modules adapter is imported, the themes are obtained from there instead
64
+ * @returns {Theme[]}
65
+ */
66
+ function getAllThemes() {
67
+ if (window.Vaadin && window.Vaadin.styleModules) {
68
+ return window.Vaadin.styleModules.getAllThemes();
69
+ } else {
70
+ return themeRegistry;
71
+ }
72
+ }
73
+
74
+ /**
75
+ * Returns true if the themeFor string matches the tag name
76
+ * @param {string} themeFor
77
+ * @param {string} tagName
78
+ * @returns {boolean}
79
+ */
80
+ function matchesThemeFor(themeFor, tagName) {
81
+ return (themeFor || '').split(' ').some((themeForToken) => {
82
+ return new RegExp('^' + themeForToken.split('*').join('.*') + '$').test(tagName);
83
+ });
84
+ }
85
+
86
+ /**
87
+ * Maps the moduleName to an include priority number which is used for
88
+ * determining the order in which styles are applied.
89
+ * @param {string} moduleName
90
+ * @returns {number}
91
+ */
92
+ function getIncludePriority(moduleName = '') {
93
+ let includePriority = 0;
94
+ if (moduleName.indexOf('lumo-') === 0 || moduleName.indexOf('material-') === 0) {
95
+ includePriority = 1;
96
+ } else if (moduleName.indexOf('vaadin-') === 0) {
97
+ includePriority = 2;
98
+ }
99
+ return includePriority;
100
+ }
101
+
102
+ /**
103
+ * Flattens the styles into a single array of styles.
104
+ * @param {CSSResultGroup} styles
105
+ * @param {CSSResult[]} result
106
+ * @returns {CSSResult[]}
107
+ */
108
+ function recursiveFlattenStyles(styles = [], result = []) {
109
+ if (styles instanceof CSSResult) {
110
+ result.push(styles);
111
+ } else if (Array.isArray(styles)) {
112
+ styles.forEach((style) => recursiveFlattenStyles(style, result));
113
+ } else {
114
+ console.warn('An item in styles is not of type CSSResult. Use `unsafeCSS` or `css`.');
115
+ }
116
+ return result;
117
+ }
118
+
119
+ /**
120
+ * Gets an array of CSSResults matching the include property of the theme.
121
+ * @param {Theme} theme
122
+ * @returns {CSSResult[]}
123
+ */
124
+ function getIncludedStyles(theme) {
125
+ const includedStyles = [];
126
+ if (theme.include) {
127
+ [].concat(theme.include).forEach((includeModuleId) => {
128
+ const includedTheme = getAllThemes().find((s) => s.moduleId === includeModuleId);
129
+ if (includedTheme) {
130
+ includedStyles.push(...getIncludedStyles(includedTheme), ...includedTheme.styles);
131
+ } else {
132
+ console.warn(`Included moduleId ${includeModuleId} not found in style registry`);
133
+ }
134
+ }, theme.styles);
135
+ }
136
+ return includedStyles;
137
+ }
138
+
139
+ /**
140
+ * Includes the styles to the template.
141
+ * @param {CSSResult[]} styles
142
+ * @param {HTMLTemplateElement} template
143
+ */
144
+ function addStylesToTemplate(styles, template) {
145
+ const styleEl = document.createElement('style');
146
+ styleEl.innerHTML = styles
147
+ // Remove duplicates so that the last occurrence remains
148
+ .filter((style, index) => index === styles.lastIndexOf(style))
149
+ .map((style) => style.cssText)
150
+ .join('\n');
151
+ template.content.appendChild(styleEl);
152
+ }
153
+
154
+ /**
155
+ * Returns an array of themes that should be used for styling a component matching
156
+ * the tag name. The array is sorted by the include order.
157
+ * @param {string} tagName
158
+ * @returns {Theme[]}
159
+ */
160
+ function getThemes(tagName) {
161
+ const defaultModuleName = tagName + '-default-theme';
162
+
163
+ const themes = getAllThemes()
164
+ // Filter by matching themeFor properties
165
+ .filter((theme) => theme.moduleId !== defaultModuleName && matchesThemeFor(theme.themeFor, tagName))
166
+ .map((theme) => ({
167
+ ...theme,
168
+ // Prepend styles from included themes
169
+ styles: [...getIncludedStyles(theme), ...theme.styles],
170
+ // Map moduleId to includePriority
171
+ includePriority: getIncludePriority(theme.moduleId)
172
+ }))
173
+ // Sort by includePriority
174
+ .sort((themeA, themeB) => themeB.includePriority - themeA.includePriority);
175
+
176
+ if (themes.length > 0) {
177
+ return themes;
178
+ } else {
179
+ // No theme modules found, return the default module if it exists
180
+ return getAllThemes().filter((theme) => theme.moduleId === defaultModuleName);
181
+ }
182
+ }
183
+
4
184
  /**
5
185
  * @polymerMixin
6
186
  * @mixes ThemePropertyMixin
7
187
  */
8
188
  export const ThemableMixin = (superClass) =>
9
189
  class VaadinThemableMixin extends ThemePropertyMixin(superClass) {
10
- /** @protected */
190
+ /**
191
+ * Covers PolymerElement based component styling
192
+ * @protected
193
+ */
11
194
  static finalize() {
12
195
  super.finalize();
13
196
 
14
197
  const template = this.prototype._template;
198
+ if (!template || template.__themes) {
199
+ return;
200
+ }
15
201
 
16
202
  const inheritedTemplate = Object.getPrototypeOf(this.prototype)._template;
17
- if (inheritedTemplate) {
18
- // Include the theme modules from the inherited template
19
- Array.from(inheritedTemplate.content.querySelectorAll('style[include]')).forEach((s) => {
20
- this._includeStyle(s.getAttribute('include'), template);
21
- });
22
- }
203
+ const inheritedThemes = (inheritedTemplate ? inheritedTemplate.__themes : []) || [];
23
204
 
24
- this._includeMatchingThemes(template);
25
- }
205
+ template.__themes = [...inheritedThemes, ...getThemes(this.is)];
26
206
 
27
- /** @private */
28
- static _includeMatchingThemes(template) {
29
- const domModule = DomModule;
30
- const modules = domModule.prototype.modules;
31
-
32
- let hasThemes = false;
33
- const defaultModuleName = this.is + '-default-theme';
34
-
35
- Object.keys(modules)
36
- .sort((moduleNameA, moduleNameB) => {
37
- const vaadinA = moduleNameA.indexOf('vaadin-') === 0;
38
- const vaadinB = moduleNameB.indexOf('vaadin-') === 0;
39
-
40
- const vaadinThemePrefixes = ['lumo-', 'material-'];
41
- const vaadinThemeA = vaadinThemePrefixes.filter((prefix) => moduleNameA.indexOf(prefix) === 0).length > 0;
42
- const vaadinThemeB = vaadinThemePrefixes.filter((prefix) => moduleNameB.indexOf(prefix) === 0).length > 0;
43
-
44
- if (vaadinA !== vaadinB) {
45
- // Include vaadin core styles first
46
- return vaadinA ? -1 : 1;
47
- } else if (vaadinThemeA !== vaadinThemeB) {
48
- // Include vaadin theme styles after that
49
- return vaadinThemeA ? -1 : 1;
50
- } else {
51
- // Lastly include custom styles so they override all vaadin styles
52
- return 0;
53
- }
54
- })
55
- .forEach((moduleName) => {
56
- if (moduleName !== defaultModuleName) {
57
- const themeFor = modules[moduleName].getAttribute('theme-for');
58
- if (themeFor) {
59
- themeFor.split(' ').forEach((themeForToken) => {
60
- if (new RegExp('^' + themeForToken.split('*').join('.*') + '$').test(this.is)) {
61
- hasThemes = true;
62
- this._includeStyle(moduleName, template);
63
- }
64
- });
65
- }
66
- }
67
- });
68
-
69
- if (!hasThemes && modules[defaultModuleName]) {
70
- // No theme modules found, include the default module if it exists
71
- this._includeStyle(defaultModuleName, template);
72
- }
207
+ // Get flattened styles array
208
+ const styles = template.__themes.reduce((styles, theme) => [...styles, ...theme.styles], []);
209
+ addStylesToTemplate(styles, template);
73
210
  }
74
211
 
75
- /** @private */
76
- static _includeStyle(moduleName, template) {
77
- if (template && !template.content.querySelector(`style[include="${moduleName}"]`)) {
78
- const styleEl = document.createElement('style');
79
- styleEl.setAttribute('include', moduleName);
80
- template.content.appendChild(styleEl);
81
- }
212
+ /**
213
+ * Covers LitElement based component styling
214
+ *
215
+ * NOTE: This is not yet an offically supported API!
216
+ *
217
+ * TODO: Add tests (run a variation of themable-mixin.test.js where the components get created as LitElements)
218
+ * @protected
219
+ */
220
+ static finalizeStyles(styles) {
221
+ return (
222
+ getThemes(this.is)
223
+ // Get flattened styles array
224
+ .reduce((styles, theme) => [...styles, ...theme.styles], [])
225
+ .concat(styles)
226
+ );
82
227
  }
83
228
  };
229
+
230
+ export { themeRegistry as __themeRegistry };
@@ -1,3 +1,8 @@
1
+ /**
2
+ * @license
3
+ * Copyright (c) 2021 Vaadin Ltd.
4
+ * This program is available under Apache License Version 2.0, available at https://vaadin.com/license/
5
+ */
1
6
  declare function ThemePropertyMixin<T extends new (...args: any[]) => {}>(base: T): T & ThemePropertyMixinConstructor;
2
7
 
3
8
  interface ThemePropertyMixinConstructor {
@@ -1,3 +1,8 @@
1
+ /**
2
+ * @license
3
+ * Copyright (c) 2021 Vaadin Ltd.
4
+ * This program is available under Apache License Version 2.0, available at https://vaadin.com/license/
5
+ */
1
6
  /**
2
7
  * @polymerMixin
3
8
  */