Jack Franklin | a5fd0a4 | 2022-12-09 11:30:24 +0000 | [diff] [blame] | 1 | 'use strict'; |
| 2 | const valueParser = require('postcss-value-parser'); |
| 3 | const mappings = require('./lib/map.js'); |
| 4 | |
| 5 | /** |
| 6 | * @param {string} value |
| 7 | * @return {string} |
| 8 | */ |
| 9 | function transform(value) { |
| 10 | const { nodes } = valueParser(value); |
| 11 | |
| 12 | if (nodes.length === 1) { |
| 13 | return value; |
| 14 | } |
| 15 | |
| 16 | const values = nodes |
| 17 | .filter((list, index) => index % 2 === 0) |
| 18 | .filter((node) => node.type === 'word') |
| 19 | .map((n) => n.value.toLowerCase()); |
| 20 | |
| 21 | if (values.length === 0) { |
| 22 | return value; |
| 23 | } |
| 24 | |
| 25 | const match = mappings.get(values.toString()); |
| 26 | |
| 27 | if (!match) { |
| 28 | return value; |
| 29 | } |
| 30 | |
| 31 | return match; |
| 32 | } |
| 33 | |
| 34 | /** |
| 35 | * @type {import('postcss').PluginCreator<void>} |
| 36 | * @return {import('postcss').Plugin} |
| 37 | */ |
| 38 | function pluginCreator() { |
| 39 | return { |
| 40 | postcssPlugin: 'postcss-normalize-display-values', |
| 41 | |
| 42 | prepare() { |
| 43 | const cache = new Map(); |
| 44 | return { |
| 45 | OnceExit(css) { |
| 46 | css.walkDecls(/^display$/i, (decl) => { |
| 47 | const value = decl.value; |
| 48 | |
| 49 | if (!value) { |
| 50 | return; |
| 51 | } |
| 52 | |
| 53 | if (cache.has(value)) { |
| 54 | decl.value = cache.get(value); |
| 55 | |
| 56 | return; |
| 57 | } |
| 58 | |
| 59 | const result = transform(value); |
| 60 | |
| 61 | decl.value = result; |
| 62 | cache.set(value, result); |
| 63 | }); |
| 64 | }, |
| 65 | }; |
| 66 | }, |
| 67 | }; |
| 68 | } |
| 69 | |
| 70 | pluginCreator.postcss = true; |
| 71 | module.exports = pluginCreator; |