UNPKG

1.86 kBPlain TextView Raw
1/**
2@license
3Copyright (c) 2019 The Polymer Project Authors. All rights reserved.
4This code may only be used under the BSD style license found at
5http://polymer.github.io/LICENSE.txt The complete set of authors may be found at
6http://polymer.github.io/AUTHORS.txt The complete set of contributors may be
7found at http://polymer.github.io/CONTRIBUTORS.txt Code distributed by Google as
8part of the polymer project is also subject to an additional IP rights grant
9found at http://polymer.github.io/PATENTS.txt
10*/
11
12export const supportsAdoptingStyleSheets =
13 ('adoptedStyleSheets' in Document.prototype);
14
15export class CSSResult {
16
17 _styleSheet?: CSSStyleSheet|null;
18
19 readonly cssText: string;
20
21 constructor(cssText: string) { this.cssText = cssText; }
22
23 // Note, this is a getter so that it's lazy. In practice, this means
24 // stylesheets are not created until the first element instance is made.
25 get styleSheet(): CSSStyleSheet|null {
26 if (this._styleSheet === undefined) {
27 // Note, if `adoptedStyleSheets` is supported then we assume CSSStyleSheet
28 // is constructable.
29 if (supportsAdoptingStyleSheets) {
30 this._styleSheet = new CSSStyleSheet();
31 this._styleSheet.replaceSync(this.cssText);
32 } else {
33 this._styleSheet = null;
34 }
35 }
36 return this._styleSheet;
37 }
38}
39
40const textFromCSSResult = (value: CSSResult) => {
41 if (value instanceof CSSResult) {
42 return value.cssText;
43 } else {
44 throw new Error(
45 `Value passed to 'css' function must be a 'css' function result: ${
46 value}.`);
47 }
48};
49
50export const css =
51 (strings: TemplateStringsArray, ...values: CSSResult[]): CSSResult => {
52 const cssText = values.reduce(
53 (acc, v, idx) => acc + textFromCSSResult(v) + strings[idx + 1],
54 strings[0]);
55 return new CSSResult(cssText);
56 };
\No newline at end of file