|
| 1 | +const SELECTOR_SPLIT_SYMBOLS = ','; |
| 2 | +const PATH_SPLIT_SYMBOLS = ' '; |
| 3 | +const PATH_SPLIT_CLEANUP = /\s+/g; |
| 4 | +const SPLIT_SYMBOLS = /\./g; |
| 5 | + |
| 6 | +/* |
| 7 | + Given the string form of a CSS Selector for a given set of rules, |
| 8 | + return an array of unique selector rules. |
| 9 | + |
| 10 | + Example: |
| 11 | + |
| 12 | + ``` |
| 13 | + .fixed, .sidebar > .sticky { |
| 14 | + position: fixed; |
| 15 | + } |
| 16 | + ``` |
| 17 | + |
| 18 | + becomes |
| 19 | + |
| 20 | + ``` |
| 21 | + ['.fixed', '.sidebar > .sticky'] |
| 22 | + ``` |
| 23 | + |
| 24 | + @return Array<String> an array of CSS rules |
| 25 | + */ |
| 26 | +function extractSelectors(selectorString) { |
| 27 | + return selectorString.split(SELECTOR_SPLIT_SYMBOLS); |
| 28 | +} |
| 29 | + |
| 30 | +/* |
| 31 | + Given the string form of a CSS rule, return the individual element |
| 32 | + matchers (segments). |
| 33 | + |
| 34 | + Note: `>` is treated as a segment which is special cased elsewhere. |
| 35 | + |
| 36 | + Example: |
| 37 | + |
| 38 | + ``` |
| 39 | + .sidebar.foo > .sticky |
| 40 | + ``` |
| 41 | + |
| 42 | + becomes |
| 43 | + |
| 44 | + ``` |
| 45 | + ['.sidebar.foo', '>', '.sticky'] |
| 46 | + ``` |
| 47 | + |
| 48 | + @return Array<String> an array of segments. |
| 49 | + */ |
| 50 | +function extractSegments(selector) { |
| 51 | + return selector |
| 52 | + .split('>') |
| 53 | + .join(' > ') |
| 54 | + .replace(PATH_SPLIT_CLEANUP, ' ') |
| 55 | + .split(PATH_SPLIT_SYMBOLS) |
| 56 | + .reverse(); |
| 57 | +} |
| 58 | + |
| 59 | +/* |
| 60 | + Given the string form of a CSS rule segment, return the individual |
| 61 | + selectors that compose it. Because of our constraints, this will |
| 62 | + always be constrained to elements, classNames, and their pseudo-variants. |
| 63 | + |
| 64 | + Example: |
| 65 | + |
| 66 | + ``` |
| 67 | + 'div.sidebar.foo' |
| 68 | + ``` |
| 69 | + |
| 70 | + Becomes: |
| 71 | + |
| 72 | + ``` |
| 73 | + ['div', '.sidebar', '.foo'] |
| 74 | + ``` |
| 75 | + |
| 76 | + @return Array<String> an array of symbols. |
| 77 | + */ |
| 78 | +function extractSymbols(segment) { |
| 79 | + return segment |
| 80 | + .replace(SPLIT_SYMBOLS, '##.') |
| 81 | + .split('##') |
| 82 | + .filter(a => a) |
| 83 | + .sort() |
| 84 | + .reverse(); |
| 85 | +} |
| 86 | + |
| 87 | +module.exports = { |
| 88 | + extractSelectors, |
| 89 | + extractSegments, |
| 90 | + extractSymbols |
| 91 | +}; |
0 commit comments