|
| 1 | +import RuleList from '../RuleList' |
| 2 | +import getWhitespaceSymbols from '../utils/getWhitespaceSymbols' |
| 3 | + |
| 4 | +const defaultToStringOptions = { |
| 5 | + indent: 1, |
| 6 | + children: true |
| 7 | +} |
| 8 | + |
| 9 | +const atRegExp = /@([\w-]+)/ |
| 10 | + |
| 11 | +/** |
| 12 | + * Rule for @layer |
| 13 | + */ |
| 14 | +export class LayerRule { |
| 15 | + type = 'layer' |
| 16 | + |
| 17 | + isProcessed = false |
| 18 | + |
| 19 | + constructor(key, styles, options) { |
| 20 | + this.key = key |
| 21 | + const atMatch = key.match(atRegExp) |
| 22 | + this.at = atMatch ? atMatch[1] : 'unknown' |
| 23 | + // Key might contain a unique suffix in case the `name` passed by user was duplicate. |
| 24 | + this.query = options.name || `@${this.at}` |
| 25 | + this.options = options |
| 26 | + this.rules = new RuleList({...options, parent: this}) |
| 27 | + |
| 28 | + for (const name in styles) { |
| 29 | + this.rules.add(name, styles[name]) |
| 30 | + } |
| 31 | + |
| 32 | + this.rules.process() |
| 33 | + } |
| 34 | + |
| 35 | + /** |
| 36 | + * Get a rule. |
| 37 | + */ |
| 38 | + getRule(name) { |
| 39 | + return this.rules.get(name) |
| 40 | + } |
| 41 | + |
| 42 | + /** |
| 43 | + * Get index of a rule. |
| 44 | + */ |
| 45 | + indexOf(rule) { |
| 46 | + return this.rules.indexOf(rule) |
| 47 | + } |
| 48 | + |
| 49 | + /** |
| 50 | + * Create and register rule, run plugins. |
| 51 | + */ |
| 52 | + addRule(name, style, options) { |
| 53 | + const rule = this.rules.add(name, style, options) |
| 54 | + if (!rule) return null |
| 55 | + this.options.jss.plugins.onProcessRule(rule) |
| 56 | + return rule |
| 57 | + } |
| 58 | + |
| 59 | + /** |
| 60 | + * Replace rule, run plugins. |
| 61 | + */ |
| 62 | + replaceRule(name, style, options) { |
| 63 | + const newRule = this.rules.replace(name, style, options) |
| 64 | + if (newRule) this.options.jss.plugins.onProcessRule(newRule) |
| 65 | + return newRule |
| 66 | + } |
| 67 | + |
| 68 | + /** |
| 69 | + * Generates a CSS string. |
| 70 | + */ |
| 71 | + toString(options = defaultToStringOptions) { |
| 72 | + const {linebreak} = getWhitespaceSymbols(options) |
| 73 | + if (options.indent == null) options.indent = defaultToStringOptions.indent |
| 74 | + if (options.children == null) options.children = defaultToStringOptions.children |
| 75 | + if (options.children === false) { |
| 76 | + return `${this.query} {}` |
| 77 | + } |
| 78 | + const children = this.rules.toString(options) |
| 79 | + return children ? `${this.query} {${linebreak}${children}${linebreak}}` : '' |
| 80 | + } |
| 81 | +} |
| 82 | + |
| 83 | +const keyRegExp = /@layer\s+/ |
| 84 | + |
| 85 | +export default { |
| 86 | + onCreateRule(key, styles, options) { |
| 87 | + return keyRegExp.test(key) ? new LayerRule(key, styles, options) : null |
| 88 | + } |
| 89 | +} |
0 commit comments