|
| 1 | +import css from "css"; |
| 2 | +import { assert } from "tsafe/assert"; |
| 3 | + |
| 4 | +export type BreakpointsValues = { |
| 5 | + unit: string /* em, px ... */; |
| 6 | + sm: number; |
| 7 | + md: number; |
| 8 | + lg: number; |
| 9 | + xl: number; |
| 10 | +}; |
| 11 | + |
| 12 | +export function parseBreakpointsValues(rawCssCode: string): BreakpointsValues { |
| 13 | + const parsedCss = css.parse(rawCssCode); |
| 14 | + |
| 15 | + let prevUnit: string | undefined = undefined; |
| 16 | + |
| 17 | + const values: number[] = []; |
| 18 | + |
| 19 | + parsedCss.stylesheet?.rules |
| 20 | + .filter(rule => rule.type === "media") |
| 21 | + .forEach(rule => { |
| 22 | + const match = (rule as { media: string }).media.match( |
| 23 | + /^\(min-width:\s*([0-9]+)([^)]+)\)$/ |
| 24 | + ); |
| 25 | + |
| 26 | + if (match === null) { |
| 27 | + return; |
| 28 | + } |
| 29 | + |
| 30 | + const [, valueStr, unit] = match; |
| 31 | + |
| 32 | + if (prevUnit === undefined) { |
| 33 | + prevUnit = unit; |
| 34 | + } else { |
| 35 | + assert(prevUnit === unit); |
| 36 | + } |
| 37 | + |
| 38 | + values.push(parseFloat(valueStr)); |
| 39 | + }); |
| 40 | + |
| 41 | + assert(values.length === 4); |
| 42 | + assert(prevUnit !== undefined); |
| 43 | + |
| 44 | + const [sm, md, lg, xl] = values; |
| 45 | + |
| 46 | + return { |
| 47 | + "unit": prevUnit, |
| 48 | + sm, |
| 49 | + md, |
| 50 | + lg, |
| 51 | + xl |
| 52 | + }; |
| 53 | +} |
| 54 | + |
| 55 | +export function generateBreakpointsValuesTsCode(breakpointsValues: BreakpointsValues): string { |
| 56 | + return [ |
| 57 | + `export const breakpointsValues = {`, |
| 58 | + JSON.stringify(breakpointsValues, null, 2) |
| 59 | + .replace(/^{\n/, "") |
| 60 | + .replace(/\n}$/, "") |
| 61 | + .split("\n") |
| 62 | + .map(line => line.replace(/^[ ]{2}/, "")) |
| 63 | + .map(line => ` ${line}`) |
| 64 | + .join("\n"), |
| 65 | + `} as const;` |
| 66 | + ].join("\n"); |
| 67 | +} |
0 commit comments