файл пакета→ .shtukbase/packages/design-components/lib/css.ts
lib/css.ts
49 строк, 2.1 КБ.
Файл как есть в пакете: код и комментарии в нём не переводятся.
- // Raw colours in component CSS: a colour literal (hex, rgb, hsl, hwb, lab, lch, oklab, oklch, color()) in a declaration
- // value, outside the fallback of a `var()`. Component CSS takes its colours from the contract, so a style can be swapped.
- /** Comments become spaces (newlines stay, so lines stay right). */
- export function stripComments(css: string): string {
- return css.replace(/\/\*[\s\S]*?\*\//g, (m) => m.replace(/[^\n]/g, ' '));
- }
- export type Raw = { line: number; prop: string; literal: string };
- const FUNC = /\b(?:rgba?|hsla?|hwb|lab|lch|oklab|oklch|color)\s*\(/gi;
- const HEX = /#[0-9a-fA-F]{3,8}\b/g;
- /** Which functions enclose each offset of a value: `[…]` of names, outermost first. */
- function enclosing(value: string, at: number): string[] {
- const stack: string[] = [];
- for (let i = 0; i < at; i++) {
- const c = value[i];
- if (c === '(') {
- const name = /([\w-]*)\s*$/.exec(value.slice(0, i))?.[1] ?? '';
- stack.push(name.toLowerCase());
- } else if (c === ')') stack.pop();
- }
- return stack;
- }
- /** The raw colours in the declaration values of a stylesheet. Selectors and at-rule preludes are not looked at. */
- export function rawColours(css: string): Raw[] {
- const text = stripComments(css);
- const out: Raw[] = [];
- const decl = /(?:^|[;{}])\s*(--[\w-]+|[a-zA-Z-][\w-]*)\s*:\s*([^;{}]*)/g;
- for (let m = decl.exec(text); m; m = decl.exec(text)) {
- const prop = m[1];
- const value = m[2];
- const valueStart = m.index + m[0].length - value.length;
- const line = text.slice(0, valueStart).split('\n').length;
- const hits: { at: number; literal: string }[] = [];
- for (const re of [HEX, FUNC]) {
- re.lastIndex = 0;
- for (let x = re.exec(value); x; x = re.exec(value)) hits.push({ at: x.index, literal: x[0].replace(/\s*\($/, '(') });
- }
- for (const h of hits.sort((a, b) => a.at - b.at)) {
- // the literal sits in a var() fallback when some enclosing call is var(…)
- if (enclosing(value, h.at).includes('var')) continue;
- out.push({ line: line + value.slice(0, h.at).split('\n').length - 1, prop, literal: h.literal.endsWith('(') ? `${h.literal}…)` : h.literal });
- }
- }
- return out;
- }