ShtukbaseStandard
файл пакета→ .shtukbase/packages/design-components/lib/css.ts

lib/css.ts

49 строк, 2.1 КБ.

Файл как есть в пакете: код и комментарии в нём не переводятся.

  1. // Raw colours in component CSS: a colour literal (hex, rgb, hsl, hwb, lab, lch, oklab, oklch, color()) in a declaration
  2. // value, outside the fallback of a `var()`. Component CSS takes its colours from the contract, so a style can be swapped.
  3. /** Comments become spaces (newlines stay, so lines stay right). */
  4. export function stripComments(css: string): string {
  5. return css.replace(/\/\*[\s\S]*?\*\//g, (m) => m.replace(/[^\n]/g, ' '));
  6. }
  7. export type Raw = { line: number; prop: string; literal: string };
  8. const FUNC = /\b(?:rgba?|hsla?|hwb|lab|lch|oklab|oklch|color)\s*\(/gi;
  9. const HEX = /#[0-9a-fA-F]{3,8}\b/g;
  10. /** Which functions enclose each offset of a value: `[…]` of names, outermost first. */
  11. function enclosing(value: string, at: number): string[] {
  12. const stack: string[] = [];
  13. for (let i = 0; i < at; i++) {
  14. const c = value[i];
  15. if (c === '(') {
  16. const name = /([\w-]*)\s*$/.exec(value.slice(0, i))?.[1] ?? '';
  17. stack.push(name.toLowerCase());
  18. } else if (c === ')') stack.pop();
  19. }
  20. return stack;
  21. }
  22. /** The raw colours in the declaration values of a stylesheet. Selectors and at-rule preludes are not looked at. */
  23. export function rawColours(css: string): Raw[] {
  24. const text = stripComments(css);
  25. const out: Raw[] = [];
  26. const decl = /(?:^|[;{}])\s*(--[\w-]+|[a-zA-Z-][\w-]*)\s*:\s*([^;{}]*)/g;
  27. for (let m = decl.exec(text); m; m = decl.exec(text)) {
  28. const prop = m[1];
  29. const value = m[2];
  30. const valueStart = m.index + m[0].length - value.length;
  31. const line = text.slice(0, valueStart).split('\n').length;
  32. const hits: { at: number; literal: string }[] = [];
  33. for (const re of [HEX, FUNC]) {
  34. re.lastIndex = 0;
  35. for (let x = re.exec(value); x; x = re.exec(value)) hits.push({ at: x.index, literal: x[0].replace(/\s*\($/, '(') });
  36. }
  37. for (const h of hits.sort((a, b) => a.at - b.at)) {
  38. // the literal sits in a var() fallback when some enclosing call is var(…)
  39. if (enclosing(value, h.at).includes('var')) continue;
  40. out.push({ line: line + value.slice(0, h.at).split('\n').length - 1, prop, literal: h.literal.endsWith('(') ? `${h.literal}…)` : h.literal });
  41. }
  42. }
  43. return out;
  44. }