@astryxdesign/cli 0.7.15-canary.gbe99721 → 0.7.15-canary.gbef2f83

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (69) hide show
  1. package/README.md +2 -1
  2. package/api/integration/validate-integration.mjs +1 -1
  3. package/api/theme/_adapter.mjs +12 -9
  4. package/api/theme/build/build.d.mts +1 -21
  5. package/api/theme/build/build.mjs +105 -29
  6. package/api/theme/template/template.d.mts +2 -0
  7. package/api/theme/template/template.mjs +41 -12
  8. package/api/theme/theme.type.d.mts +4 -0
  9. package/api/theme/theme.type.mjs +2 -1
  10. package/api/theme/themeBuild.doc.mjs +3 -3
  11. package/api/theme/themeTemplate.doc.mjs +9 -3
  12. package/api/theme-edit/_adapter.d.mts +10 -0
  13. package/api/theme-edit/_adapter.mjs +76 -5
  14. package/api/theme-edit/_check.mjs +181 -50
  15. package/api/theme-edit/_color.d.mts +2 -8
  16. package/api/theme-edit/_color.mjs +126 -55
  17. package/api/theme-edit/_compiler.d.mts +1 -0
  18. package/api/theme-edit/_compiler.mjs +3 -0
  19. package/api/theme-edit/_context.d.mts +7 -0
  20. package/api/theme-edit/_context.mjs +34 -1
  21. package/api/theme-edit/_css.d.mts +21 -1
  22. package/api/theme-edit/_css.mjs +172 -13
  23. package/api/theme-edit/_edit.d.mts +9 -0
  24. package/api/theme-edit/_edit.mjs +377 -48
  25. package/api/theme-edit/_how-commands.d.mts +7 -26
  26. package/api/theme-edit/_how-commands.mjs +27 -1
  27. package/api/theme-edit/_how-question.mjs +330 -12
  28. package/api/theme-edit/_how.mjs +68 -26
  29. package/api/theme-edit/_palette.mjs +10 -0
  30. package/api/theme-edit/_parts.d.mts +16 -0
  31. package/api/theme-edit/_parts.mjs +49 -1
  32. package/api/theme-edit/_preview-app.mjs +176 -9
  33. package/api/theme-edit/_preview.mjs +7 -3
  34. package/api/theme-edit/_project.d.mts +11 -0
  35. package/api/theme-edit/_project.mjs +35 -9
  36. package/api/theme-edit/_settings.d.mts +46 -5
  37. package/api/theme-edit/_settings.mjs +217 -25
  38. package/api/theme-edit/theme-edit.type.d.mts +2 -1
  39. package/api/theme-edit/theme-edit.type.mjs +1 -1
  40. package/api/theme-edit/themeEditNew.doc.mjs +1 -1
  41. package/api/theme-edit/themeEditShow.doc.mjs +1 -1
  42. package/assets/docs/tree/tokens-and-setup.doc.mjs +39 -3
  43. package/assets/docs.generated.json +2 -2
  44. package/assets/preview-app/next.config.mjs +7 -1
  45. package/assets/self-audit.generated.json +1 -1
  46. package/assets/templates/blocks/components/Table/InfiniteScrollHookUsage.doc.mjs +14 -0
  47. package/assets/templates/blocks/components/Table/InfiniteScrollHookUsage.tsx +33 -0
  48. package/assets/templates/components.generated.json +1 -1
  49. package/clients/cli/build-id.generated.json +1 -1
  50. package/clients/cli/commands/experimental/theme.mjs +113 -34
  51. package/clients/cli/commands/experimental-theme-compile.doc.mjs +1 -1
  52. package/clients/cli/commands/experimental-theme-editor-new.doc.mjs +1 -1
  53. package/clients/cli/commands/experimental-theme-editor-show.doc.mjs +1 -1
  54. package/clients/cli/commands/experimental-theme-editor.doc.mjs +1 -1
  55. package/clients/cli/commands/experimental-theme-template.doc.mjs +1 -1
  56. package/clients/cli/commands/theme-build.doc.mjs +2 -2
  57. package/clients/cli/commands/theme-template.doc.mjs +3 -1
  58. package/clients/cli/commands/theme.mjs +82 -5
  59. package/clients/cli/manifest.generated.json +1 -1
  60. package/foundation/config/project.mjs +50 -14
  61. package/foundation/fs/gather-cache.mjs +4 -3
  62. package/foundation/fs/paths.d.mts +16 -0
  63. package/foundation/fs/paths.mjs +25 -0
  64. package/foundation/response/error-codes.d.mts +2 -1
  65. package/foundation/response/error-codes.d.ts +1 -0
  66. package/foundation/response/error-codes.doc.mjs +5 -0
  67. package/foundation/response/error-codes.mjs +3 -0
  68. package/foundation/response/response-types.doc.mjs +1 -1
  69. package/package.json +7 -6
@@ -9,7 +9,15 @@
9
9
  */
10
10
 
11
11
  import {CSS_WIDE} from './_tables.mjs';
12
- import {MATH_FUNCTION, matchType} from './_css.mjs';
12
+ import {
13
+ MATH_FUNCTION,
14
+ cssNumber,
15
+ keywordsOf,
16
+ matchType,
17
+ splitTop,
18
+ } from './_css.mjs';
19
+
20
+ export {splitTop};
13
21
  import {luminance, oklabToLinearRgb} from '../theme/palette/generate/color.mjs';
14
22
 
15
23
  /** @typedef {[number, number, number]} Rgb */
@@ -489,30 +497,6 @@ function linearToOklab([r, g, b]) {
489
497
  ];
490
498
  }
491
499
 
492
- /**
493
- * A value split at `sep` outside brackets: `a(b, c), d` by `,` is
494
- * [`a(b, c)`, ` d`]. A space separator also splits runs of spaces.
495
- * @param {string} v
496
- * @param {',' | ' '} sep
497
- * @returns {string[]}
498
- */
499
- export function splitTop(v, sep) {
500
- /** @type {string[]} */
501
- const out = [];
502
- let depth = 0;
503
- let cur = '';
504
- for (const c of v) {
505
- if (c === '(') depth++;
506
- if (c === ')') depth--;
507
- if (depth === 0 && (sep === ' ' ? /\s/.test(c) : c === sep)) {
508
- if (cur.trim() || sep === ',') out.push(cur);
509
- cur = '';
510
- } else cur += c;
511
- }
512
- if (cur.trim() || sep === ',') out.push(cur);
513
- return out.filter(x => sep === ',' || x.trim());
514
- }
515
-
516
500
  /**
517
501
  * One side of a color-mix(): the color, and the share written before or
518
502
  * after it at the top level (null when none). A percentage inside the
@@ -522,22 +506,19 @@ export function splitTop(v, sep) {
522
506
  */
523
507
  export function mixSide(side) {
524
508
  const words = splitTop(side.trim(), ' ');
525
- const share = (/** @type {string | undefined} */ w) =>
526
- w != null && /^-?\d*\.?\d+%$/.test(w) ? Number.parseFloat(w) : null;
527
- // A share outside 0-100% is invalid CSS: the side then names no color,
528
- // so the mix is refused rather than extrapolated.
509
+ // Any CSS percentage: an exponent or a sign (5e1%, +50%), or math that
510
+ // gives one percentage (calc(50%)).
511
+ const share = (/** @type {string | undefined} */ w) => {
512
+ if (w == null) return null;
513
+ const plain = /^calc\(\s*(.*?)\s*\)$/i.exec(w)?.[1] ?? w;
514
+ const n = cssNumber(plain);
515
+ return n?.unit === '%' ? n.value : null;
516
+ };
529
517
  if (words.length < 2) return {color: side.trim(), pct: null};
530
- const inRange = (/** @type {number} */ p) => p >= 0 && p <= 100;
531
518
  const last = share(words.at(-1));
532
- if (last != null)
533
- return inRange(last)
534
- ? {color: words.slice(0, -1).join(' '), pct: last}
535
- : {color: '', pct: null};
519
+ if (last != null) return {color: words.slice(0, -1).join(' '), pct: last};
536
520
  const first = share(words[0]);
537
- if (first != null)
538
- return inRange(first)
539
- ? {color: words.slice(1).join(' '), pct: first}
540
- : {color: '', pct: null};
521
+ if (first != null) return {color: words.slice(1).join(' '), pct: first};
541
522
  return {color: side.trim(), pct: null};
542
523
  }
543
524
 
@@ -548,9 +529,11 @@ export function mixSide(side) {
548
529
  * color with no fixed value, a space this reader does not mix in, or
549
530
  * shares that add up to 0.
550
531
  * @param {string} inner the arguments
532
+ * @param {boolean} [approx] mix a space this reader does not mix in as
533
+ * OKLab, for a suggestion only
551
534
  * @returns {{rgb: Rgb, alpha: number} | null}
552
535
  */
553
- function mixColor(inner) {
536
+ function mixColor(inner, approx = false) {
554
537
  const args = splitTop(inner, ',').map(x => x.trim());
555
538
  if (args.length !== 3) return null;
556
539
  const sp =
@@ -558,12 +541,15 @@ function mixColor(inner) {
558
541
  args[0],
559
542
  );
560
543
  const space = sp?.[1].toLowerCase() ?? '';
561
- if (!MIX_SPACES.includes(space)) return null;
544
+ if (!MIX_SPACES.includes(space) && !approx) return null;
562
545
  const hueWay = (sp?.[2] ?? 'shorter').toLowerCase();
546
+ const mixIn = MIX_SPACES.includes(space) ? space : 'oklab';
563
547
  const sides = args.slice(1).map(a => {
564
548
  const {color, pct} = mixSide(a);
565
549
  return {read: readColor(color), pct};
566
550
  });
551
+ // A share is 0% to 100%; past that the mix is no color at all.
552
+ if (sides.some(x => x.pct != null && (x.pct < 0 || x.pct > 100))) return null;
567
553
  if (sides.some(x => !x.read)) return null;
568
554
  let [p1, p2] = sides.map(x => x.pct);
569
555
  if (p1 == null && p2 == null) [p1, p2] = [50, 50];
@@ -578,10 +564,10 @@ function mixColor(inner) {
578
564
  );
579
565
  /** @param {Rgb} rgb @returns {number[]} */
580
566
  const into = rgb => {
581
- if (space === 'srgb') return rgb.map(c => c / 255);
567
+ if (mixIn === 'srgb') return rgb.map(c => c / 255);
582
568
  const lin = rgb.map(toLinear);
583
- if (space === 'srgb-linear') return lin;
584
- if (space === 'xyz' || space === 'xyz-d65')
569
+ if (mixIn === 'srgb-linear') return lin;
570
+ if (mixIn === 'xyz' || mixIn === 'xyz-d65')
585
571
  return [
586
572
  0.41239079926595934 * lin[0] +
587
573
  0.357584339383878 * lin[1] +
@@ -594,7 +580,7 @@ function mixColor(inner) {
594
580
  0.9505321522496607 * lin[2],
595
581
  ];
596
582
  const lab = linearToOklab(lin);
597
- if (space === 'oklab') return lab;
583
+ if (mixIn === 'oklab') return lab;
598
584
  const c = Math.hypot(lab[1], lab[2]);
599
585
  return [
600
586
  lab[0],
@@ -604,12 +590,12 @@ function mixColor(inner) {
604
590
  };
605
591
  /** @param {number[]} v @returns {Rgb} */
606
592
  const back = v => {
607
- if (space === 'srgb')
593
+ if (mixIn === 'srgb')
608
594
  return /** @type {Rgb} */ (v.map(c => clamp(c, 0, 1) * 255));
609
- if (space === 'srgb-linear') return fromLinear(v);
610
- if (space === 'xyz' || space === 'xyz-d65')
595
+ if (mixIn === 'srgb-linear') return fromLinear(v);
596
+ if (mixIn === 'xyz' || mixIn === 'xyz-d65')
611
597
  return colorSpaceToRgb('xyz-d65', v);
612
- if (space === 'oklab') return oklabToRgb(v[0], v[1], v[2]);
598
+ if (mixIn === 'oklab') return oklabToRgb(v[0], v[1], v[2]);
613
599
  const h = (v[2] * Math.PI) / 180;
614
600
  return oklabToRgb(v[0], v[1] * Math.cos(h), v[1] * Math.sin(h));
615
601
  };
@@ -618,7 +604,7 @@ function mixColor(inner) {
618
604
  // Premultiplied by alpha, as CSS mixes; a missing hue takes the other's.
619
605
  const alpha = a.alpha * w1 + b.alpha * w2;
620
606
  const out = x.map((_, i) => {
621
- if (space === 'oklch' && i === 2) {
607
+ if (mixIn === 'oklch' && i === 2) {
622
608
  let h1 = Number.isNaN(x[2]) ? y[2] : x[2];
623
609
  let h2 = Number.isNaN(y[2]) ? x[2] : y[2];
624
610
  if (Number.isNaN(h1)) return 0;
@@ -636,6 +622,19 @@ function mixColor(inner) {
636
622
  return {rgb: back(out), alpha: alpha * Math.min(1, total / 100)};
637
623
  }
638
624
 
625
+ /** The channel keywords of each relative color function, in order. */
626
+ const RELATIVE_CHANNELS = /** @type {Record<string, string>} */ ({
627
+ rgb: 'r g b',
628
+ rgba: 'r g b',
629
+ hsl: 'h s l',
630
+ hsla: 'h s l',
631
+ hwb: 'h w b',
632
+ lab: 'l a b',
633
+ lch: 'l c h',
634
+ oklab: 'l a b',
635
+ oklch: 'l c h',
636
+ });
637
+
639
638
  /**
640
639
  * A fixed CSS color read as CSS Color 4 reads it: hues wrap, saturation,
641
640
  * whiteness, blackness and lightness clamp to their range, and chroma
@@ -660,6 +659,34 @@ function readColor(s) {
660
659
  if (named) return readColor(named);
661
660
  const fn = /^([a-z-]+)\((.*)\)$/i.exec(s);
662
661
  if (fn && fn[1].toLowerCase() === 'color-mix') return mixColor(fn[2]);
662
+ if (fn) {
663
+ const name = fn[1].toLowerCase();
664
+ // The same color in both modes is that color.
665
+ if (name === 'light-dark') {
666
+ const halves = splitTop(fn[2], ',').map(x => x.trim());
667
+ const [a, b] = halves.map(x => readColor(x));
668
+ return halves.length === 2 &&
669
+ a &&
670
+ b &&
671
+ hex(a.rgb) === hex(b.rgb) &&
672
+ a.alpha === b.alpha
673
+ ? a
674
+ : null;
675
+ }
676
+ // A relative color that keeps every channel as it is (rgb(from red r g
677
+ // b)) is its origin color.
678
+ const rel =
679
+ /^from\s+(.+?)\s+([a-z]+)\s+([a-z]+)\s+([a-z]+)(?:\s*\/\s*([a-z]+))?$/i.exec(
680
+ fn[2].trim(),
681
+ );
682
+ const keep = RELATIVE_CHANNELS[name];
683
+ if (rel && keep) {
684
+ const kept =
685
+ [rel[2], rel[3], rel[4]].map(x => x.toLowerCase()).join(' ') === keep &&
686
+ (rel[5] == null || rel[5].toLowerCase() === 'alpha');
687
+ return kept ? readColor(rel[1]) : null;
688
+ }
689
+ }
663
690
  if (!fn || !FIXED.test(fn[1])) return null;
664
691
  const name = fn[1].toLowerCase();
665
692
  if (name === 'color') {
@@ -800,11 +827,51 @@ export function colorProblem(value) {
800
827
  return {kind: 'malformed', message: 'is not a valid CSS color'};
801
828
  // A mix this reader cannot work out (another space, a color with no
802
829
  // fixed value) says so, rather than calling the mix unfixed.
803
- if (fn && fn[1].toLowerCase() === 'color-mix' && !/var\(|env\(/i.test(fn[2]))
830
+ if (
831
+ fn &&
832
+ fn[1].toLowerCase() === 'color-mix' &&
833
+ !/var\(|env\(/i.test(fn[2])
834
+ ) {
835
+ // The shares, beside each color (a color's own percentages aside).
836
+ const [space, ...sides] = splitTop(fn[2], ',').map(x => x.trim());
837
+ const parts = sides.map(mixSide);
838
+ if (parts.some(x => x.pct != null && (x.pct < 0 || x.pct > 100)))
839
+ return {
840
+ kind: 'malformed',
841
+ message:
842
+ 'has a color-mix() share outside 0% to 100%, which CSS does not take',
843
+ ...(() => {
844
+ const near = mixColor(
845
+ [
846
+ space,
847
+ ...parts.map(x =>
848
+ x.pct == null
849
+ ? x.color
850
+ : `${x.color} ${Math.max(0, Math.min(100, x.pct))}%`,
851
+ ),
852
+ ].join(', '),
853
+ );
854
+ return near ? {opaque: hex(near.rgb)} : {};
855
+ })(),
856
+ };
857
+ const near = mixColor(fn[2], true);
858
+ return {
859
+ kind: 'unfixed',
860
+ message: `is a color-mix() this editor does not work out (it mixes in ${MIX_SPACES.join(', ')}, from colors with fixed values)${near ? `; mixed in oklab it is about ${hex(near.rgb)}` : ''}: give the mixed color itself`,
861
+ ...(near ? {opaque: hex(near.rgb)} : {}),
862
+ };
863
+ }
864
+ // A relative color that changes its channels is not worked out here.
865
+ const rel =
866
+ fn && /^from\s+(.+?)\s+\S+\s+\S+\s+\S+(\s*\/.*)?$/i.exec(fn[2].trim());
867
+ if (rel && !/var\(|env\(/i.test(fn?.[2] ?? '')) {
868
+ const origin = readColor(rel[1]);
804
869
  return {
805
870
  kind: 'unfixed',
806
- message: `is a color-mix() this editor cannot work out (it mixes in ${MIX_SPACES.join(', ')}, from colors with fixed values); give the mixed color itself`,
871
+ message: `is a relative color that changes its channels, which this editor does not work out${origin ? ` (it starts from ${hex(origin.rgb)})` : ''}: give the color itself`,
872
+ ...(origin ? {opaque: hex(origin.rgb)} : {}),
807
873
  };
874
+ }
808
875
  if (isColorValue(s))
809
876
  return {
810
877
  kind: 'unfixed',
@@ -900,20 +967,24 @@ export const isSize = (v, name = '') => {
900
967
  export const isNumber = (v, name = '') => {
901
968
  const s = String(v).trim();
902
969
  if (/^var\(--[a-z0-9-]+\)$/i.test(s)) return true;
970
+ const n = cssNumber(s);
971
+ // A weight: a font-weight keyword, or a number from 1 to 1000.
903
972
  if (/weight/.test(name))
904
973
  return (
905
- /^(normal|bold|bolder|lighter)$/.test(s) ||
906
- (/^\d+(\.\d+)?$/.test(s) && Number(s) >= 1 && Number(s) <= 1000) ||
974
+ keywordsOf('font-weight').includes(s.toLowerCase()) ||
975
+ (n?.unit === '' && n.value >= 1 && n.value <= 1000) ||
907
976
  (MATH_FUNCTION.test(s) && matchType('number', s) != null)
908
977
  );
909
978
  if (/leading|line-height/.test(name))
910
979
  return (
911
980
  s === 'normal' ||
912
- (/^\d*\.?\d+(px|rem|em|%)?$/.test(s) && Number.parseFloat(s) >= 0) ||
981
+ (n != null &&
982
+ ['', 'px', 'rem', 'em', '%'].includes(n.unit) &&
983
+ n.value >= 0) ||
913
984
  (MATH_FUNCTION.test(s) && matchType('length-percentage', s) != null) ||
914
985
  (MATH_FUNCTION.test(s) && matchType('number', s) != null)
915
986
  );
916
- return /^-?\d*\.?\d+$/.test(s);
987
+ return n?.unit === '';
917
988
  };
918
989
 
919
990
  /**
@@ -12,6 +12,7 @@
12
12
  export function makeCompiler(project: import("./_project.mjs").ThemeProject, parts: PartData): {
13
13
  MAP: Record<string, import("./_parts.mjs").PartRecord>;
14
14
  typeOf: (tok: string) => string;
15
+ isToken: (tok: string) => boolean;
15
16
  propsReading: (tok: string) => string[];
16
17
  feeds: (target: string, token: string) => Array<{
17
18
  part: string;
@@ -85,6 +85,8 @@ export function makeCompiler(project, parts) {
85
85
  }
86
86
  /** @param {string} tok */
87
87
  const typeOf = tok => TYPE[tok] ?? 'other';
88
+ /** Whether Core defines the token. @param {string} tok */
89
+ const isToken = tok => Object.hasOwn(TYPE, tok);
88
90
 
89
91
  /** @param {string} p */
90
92
  const groupOfProp = p =>
@@ -539,6 +541,7 @@ export function makeCompiler(project, parts) {
539
541
  return {
540
542
  MAP,
541
543
  typeOf,
544
+ isToken,
542
545
  propsReading,
543
546
  feeds,
544
547
  fmtFeeds,
@@ -18,6 +18,7 @@ export function context(cwd: string): Promise<{
18
18
  C: {
19
19
  MAP: Record<string, import("./_parts.mjs").PartRecord>;
20
20
  typeOf: (tok: string) => string;
21
+ isToken: (tok: string) => boolean;
21
22
  propsReading: (tok: string) => string[];
22
23
  feeds: (target: string, token: string) => Array<{
23
24
  part: string;
@@ -63,6 +64,12 @@ export function context(cwd: string): Promise<{
63
64
  parts: import("./_parts.mjs").PartData;
64
65
  unchecked: string | null;
65
66
  uncheckedCode: string | null;
67
+ derived: Record<string, {
68
+ property: string;
69
+ vars?: string[];
70
+ replaces?: boolean;
71
+ expand?: string;
72
+ }[]>;
66
73
  }>;
67
74
  /**
68
75
  * Pictures of HTML files, on request.
@@ -11,11 +11,13 @@
11
11
  import * as fs from 'node:fs';
12
12
  import {createRequire} from 'node:module';
13
13
  import * as path from 'node:path';
14
+ import {pathToFileURL} from 'node:url';
14
15
  import {AstryxError} from '../error.mjs';
15
16
  import {isOutsideProject} from '../../foundation/env/project-scope.mjs';
16
17
  import {
17
18
  CLOSEST_OPEN_FONT,
18
19
  FONT_ROLES,
20
+ FONTS,
19
21
  OPEN_FONTS,
20
22
  isDesktopFamily,
21
23
  oneSystemOf,
@@ -114,9 +116,27 @@ export async function context(cwd) {
114
116
  parts,
115
117
  unchecked,
116
118
  uncheckedCode,
119
+ derived: await derivedVars(project.coreDir),
117
120
  };
118
121
  }
119
122
 
123
+ /**
124
+ * Core's registry of the variables a part's plain border-radius or padding
125
+ * also writes (a card's inner corners), or empty on a Core without it.
126
+ * @param {string} coreDir
127
+ * @returns {Promise<Record<string, Array<{property: string, vars?: string[], replaces?: boolean, expand?: string}>>>}
128
+ */
129
+ async function derivedVars(coreDir) {
130
+ const file = path.join(coreDir, 'dist', 'theme', 'derivedVarRegistry.js');
131
+ if (!fs.existsSync(file)) return {};
132
+ try {
133
+ const mod = await import(pathToFileURL(file).href);
134
+ return mod.derivedVarRegistry ?? {};
135
+ } catch {
136
+ return {};
137
+ }
138
+ }
139
+
120
140
  /** @param {unknown} e */
121
141
  const isRenderFailure = e =>
122
142
  e instanceof AstryxError &&
@@ -219,6 +239,18 @@ export function fontNotes(ctx, data) {
219
239
  : `${family} is not installed, so it does not load: the previews and the app show the next font in the stack. Install it: ${installLine(ctx.project.cwd, [pkg])}. Then the preview imports it on the next set or show, and the app imports it once: import '${pkg}'; Until then, the closest font that needs no install is ${near}: ${P} set ${data.name} font ${near}`,
220
240
  );
221
241
  }
242
+ // A family the editor's own presets lead with, where the preset gets no
243
+ // note (Comic Sans MS, of comic), is no more a font to load typed by name.
244
+ const presetFamily = (/** @type {string} */ family) => {
245
+ const f = family.replace(/["']/g, '').trim().toLowerCase();
246
+ // A one-system font keeps its note, preset or not.
247
+ if (oneSystemOf(family.replace(/["']/g, '').trim())) return false;
248
+ return Object.entries(FONTS).some(
249
+ ([k, [first]]) =>
250
+ (SYSTEM_FONTS.includes(k) || k === 'comic' || k === 'rounded') &&
251
+ first.replace(/["']/g, '').trim().toLowerCase() === f,
252
+ );
253
+ };
222
254
  for (const s of data.settings) {
223
255
  if (
224
256
  s.thing !== 'font' ||
@@ -228,7 +260,8 @@ export function fontNotes(ctx, data) {
228
260
  fontOf(s.value).pkg ||
229
261
  packages.some(x => x.of === s) ||
230
262
  s.value === 'rounded' ||
231
- s.value === 'comic'
263
+ s.value === 'comic' ||
264
+ presetFamily(fontOf(s.value).family)
232
265
  )
233
266
  continue;
234
267
  const family = fontOf(s.value).family.replace(/["']/g, '').toLowerCase();
@@ -29,7 +29,8 @@ export function matchType(type: string, value: string): any | null;
29
29
  /**
30
30
  * Whether a value that matches a property's grammar is still below a range
31
31
  * the specs set and css-tree's data does not carry: a `<line-width>` (a
32
- * border or outline width) and a duration are never negative.
32
+ * border or outline width) and a duration are never negative, nor is any
33
+ * number the current specifications' grammar ranges at 0 or more.
33
34
  * @param {string} property
34
35
  * @param {string} value
35
36
  */
@@ -58,6 +59,25 @@ export function keywordsOf(prop: string): string[];
58
59
  * @returns {string | null}
59
60
  */
60
61
  export function initialOf(prop: string): string | null;
62
+ /**
63
+ * One CSS number, percentage or dimension, read by css-tree's tokenizer as
64
+ * the browser reads it (`1.5e0`, `+1.5`, `15E-1`, `1.5EM`; never `50.%`),
65
+ * or null for anything else.
66
+ * @param {string} value
67
+ * @returns {{value: number, unit: string} | null}
68
+ */
69
+ export function cssNumber(value: string): {
70
+ value: number;
71
+ unit: string;
72
+ } | null;
73
+ /**
74
+ * A value split at `sep` outside brackets: `a(b, c), d` by `,` is
75
+ * [`a(b, c)`, ` d`]. A space separator also splits runs of spaces.
76
+ * @param {string} v
77
+ * @param {',' | ' '} sep
78
+ * @returns {string[]}
79
+ */
80
+ export function splitTop(v: string, sep: "," | " "): string[];
61
81
  /**
62
82
  * The parts of a CSS `font` value, by the longhand each sets, as written:
63
83
  * `italic small-caps 700 1rem/1 Arial` gives font-style, font-variant-caps,
@@ -58,15 +58,35 @@ let names = null;
58
58
  export function cssProperties() {
59
59
  if (names) return names;
60
60
  const mdn = mdnProperties();
61
+ const current = syntaxPatches().properties;
61
62
  names = new Set([
62
63
  ...Object.keys(csstree().lexer.properties).filter(
63
- k => !k.startsWith('-') && mdn[k] && mdn[k].status !== 'obsolete',
64
+ k =>
65
+ !k.startsWith('-') &&
66
+ mdn[k] &&
67
+ // MDN marks a renamed property obsolete (font-stretch is font-width
68
+ // now); one the current specifications still define, as browsers
69
+ // ship it, stays.
70
+ (mdn[k].status !== 'obsolete' || k in current),
64
71
  ),
65
72
  ...NOT_IN_MDN_YET,
66
73
  ]);
67
74
  return names;
68
75
  }
69
76
 
77
+ /**
78
+ * The current specifications' grammar, as patches to css-tree's: the
79
+ * ranges MDN's data leaves out (`line-height` takes `<number [0,∞]>`).
80
+ * @returns {{properties: Record<string, string>, types: Record<string, string>, atrules: Record<string, unknown>}}
81
+ */
82
+ const syntaxPatches = () =>
83
+ require('@csstools/css-syntax-patches-for-csstree').next;
84
+
85
+ /** @type {any} */
86
+ let patched = null;
87
+ /** css-tree's lexer with the current specifications' grammar. */
88
+ const currentLexer = () => (patched ??= csstree().fork(syntaxPatches()).lexer);
89
+
70
90
  /** What a var() or env() may stand for while the rest of a value is matched. */
71
91
  const VAR_STANDS_FOR = ['0', '1px', '1ms', 'red', 'ease', 'serif', '0 0 red'];
72
92
 
@@ -178,7 +198,8 @@ function matchWith(value, match) {
178
198
  /**
179
199
  * Whether a value that matches a property's grammar is still below a range
180
200
  * the specs set and css-tree's data does not carry: a `<line-width>` (a
181
- * border or outline width) and a duration are never negative.
201
+ * border or outline width) and a duration are never negative, nor is any
202
+ * number the current specifications' grammar ranges at 0 or more.
182
203
  * @param {string} property
183
204
  * @param {string} value
184
205
  */
@@ -208,6 +229,19 @@ export function belowRange(property, value) {
208
229
  numbersIn(ast).some(n => n.value < 0 && ['s', 'ms'].includes(n.unit))
209
230
  )
210
231
  below = true;
232
+ // A negative number the current grammar's range refuses (`line-height
233
+ // -1`, `gap -2px`).
234
+ // Only the sign decides: the same value with every number made positive
235
+ // must match the current grammar.
236
+ if (!below && numbersIn(ast).some(n => n.value < 0)) {
237
+ const lexer = currentLexer();
238
+ const positive = parse(value.replace(/(^|[\s(,/])-(?=\.?\d)/g, '$1'), {
239
+ context: 'value',
240
+ });
241
+ below =
242
+ Boolean(lexer.matchProperty(property, ast).error) &&
243
+ !lexer.matchProperty(property, positive).error;
244
+ }
211
245
  return below;
212
246
  }
213
247
 
@@ -513,10 +547,15 @@ export function numbersIn(ast) {
513
547
  csstree().walk(ast, {
514
548
  enter(/** @type {any} */ node) {
515
549
  if (node.type === 'Function') fns.push(node.name.toLowerCase());
516
- if (node.type === 'Dimension' || node.type === 'Number')
550
+ if (
551
+ node.type === 'Dimension' ||
552
+ node.type === 'Number' ||
553
+ node.type === 'Percentage'
554
+ )
517
555
  out.push({
518
556
  value: Number(node.value),
519
- unit: (node.unit ?? '').toLowerCase(),
557
+ unit:
558
+ node.type === 'Percentage' ? '%' : (node.unit ?? '').toLowerCase(),
520
559
  fn: fns.at(-1) ?? null,
521
560
  });
522
561
  },
@@ -583,6 +622,55 @@ export function initialOf(prop) {
583
622
  : null;
584
623
  }
585
624
 
625
+ /**
626
+ * One CSS number, percentage or dimension, read by css-tree's tokenizer as
627
+ * the browser reads it (`1.5e0`, `+1.5`, `15E-1`, `1.5EM`; never `50.%`),
628
+ * or null for anything else.
629
+ * @param {string} value
630
+ * @returns {{value: number, unit: string} | null}
631
+ */
632
+ export function cssNumber(value) {
633
+ /** @type {any} */
634
+ let ast;
635
+ try {
636
+ ast = csstree().parse(value.trim(), {context: 'value'});
637
+ } catch {
638
+ return null;
639
+ }
640
+ const nodes = ast.children?.toArray?.() ?? [];
641
+ if (nodes.length !== 1) return null;
642
+ const [n] = nodes;
643
+ if (n.type === 'Number') return {value: Number(n.value), unit: ''};
644
+ if (n.type === 'Percentage') return {value: Number(n.value), unit: '%'};
645
+ if (n.type === 'Dimension')
646
+ return {value: Number(n.value), unit: String(n.unit).toLowerCase()};
647
+ return null;
648
+ }
649
+
650
+ /**
651
+ * A value split at `sep` outside brackets: `a(b, c), d` by `,` is
652
+ * [`a(b, c)`, ` d`]. A space separator also splits runs of spaces.
653
+ * @param {string} v
654
+ * @param {',' | ' '} sep
655
+ * @returns {string[]}
656
+ */
657
+ export function splitTop(v, sep) {
658
+ /** @type {string[]} */
659
+ const out = [];
660
+ let depth = 0;
661
+ let cur = '';
662
+ for (const c of v) {
663
+ if (c === '(') depth++;
664
+ if (c === ')') depth--;
665
+ if (depth === 0 && (sep === ' ' ? /\s/.test(c) : c === sep)) {
666
+ if (cur.trim() || sep === ',') out.push(cur);
667
+ cur = '';
668
+ } else cur += c;
669
+ }
670
+ if (cur.trim() || sep === ',') out.push(cur);
671
+ return out.filter(x => sep === ',' || x.trim());
672
+ }
673
+
586
674
  /** The longhand each type of the `font` grammar sets, where css-tree names a type, not a property. */
587
675
  const FONT_TYPE_LONGHAND = /** @type {Record<string, string>} */ ({
588
676
  'font-variant-css2': 'font-variant-caps',
@@ -602,15 +690,86 @@ const FONT_TYPE_LONGHAND = /** @type {Record<string, string>} */ ({
602
690
  */
603
691
  export function fontShorthandParts(value) {
604
692
  const {lexer, parse, generate} = csstree();
605
- const word = value.trim().toLowerCase();
606
- if (/^[a-z-]+$/.test(word))
607
- for (const prop of [
608
- 'font-weight',
609
- 'font-style',
610
- 'font-variant-caps',
611
- 'font-stretch',
612
- ])
613
- if (keywordsOf(prop).includes(word)) return {[prop]: word};
693
+ // Words that are each one longhand's keyword, size or weight (`bold`,
694
+ // `italic bold`, `bold 1rem`) are those longhands, in any order before the
695
+ // size; after the size the rest is the family (`1rem bold` names a family
696
+ // called bold), as CSS reads it.
697
+ const LONGHANDS = [
698
+ 'font-weight',
699
+ 'font-style',
700
+ 'font-variant-caps',
701
+ 'font-stretch',
702
+ 'font-size',
703
+ ];
704
+ if (!value.includes(',')) {
705
+ /** @type {Record<string, string>} */
706
+ const each = {};
707
+ const words = splitTop(value.trim(), ' ');
708
+ let all = true;
709
+ // `normal` fits several longhands: every other word is placed first,
710
+ // then each `normal` takes the first longhand still free.
711
+ const normals = words.filter(w => w.toLowerCase() === 'normal').length;
712
+ // A normal after the size is part of the family, read below.
713
+ const sizeAt = words.findIndex(
714
+ w => matchValue('font-size', w.split('/')[0]) && !/^[a-z-]+$/i.test(w),
715
+ );
716
+ if (
717
+ sizeAt >= 0 &&
718
+ words.slice(sizeAt + 1).some(w => w.toLowerCase() === 'normal')
719
+ )
720
+ all = false;
721
+ for (const w of words.filter(x => x.toLowerCase() !== 'normal')) {
722
+ if (!all) break;
723
+ const lower = w.toLowerCase();
724
+ // After the size, the rest is the family (16px bold names a family
725
+ // called bold): the grammar below reads it.
726
+ if ('font-size' in each) {
727
+ all = false;
728
+ break;
729
+ }
730
+ // A size with its line height (1rem/1.5).
731
+ const slash = /^([^/]+)\/([^/]+)$/.exec(w);
732
+ if (
733
+ slash &&
734
+ !('font-size' in each) &&
735
+ matchValue('font-size', slash[1]) &&
736
+ matchValue('line-height', slash[2])
737
+ ) {
738
+ each['font-size'] = slash[1];
739
+ each['line-height'] = slash[2];
740
+ continue;
741
+ }
742
+ const takers = LONGHANDS.filter(p => keywordsOf(p).includes(lower));
743
+ const keyword = takers.find(p => !(p in each));
744
+ // A part given twice (bold bold, bold lighter, italic oblique) is no
745
+ // font value.
746
+ if (takers.length && !keyword) return {repeat: lower, part: takers[0]};
747
+ const prop =
748
+ keyword ??
749
+ ['font-size', 'font-weight'].find(
750
+ p => !(p in each) && !/^[a-z-]+$/i.test(w) && matchValue(p, w),
751
+ );
752
+ if (!prop) {
753
+ all = false;
754
+ break;
755
+ }
756
+ each[prop] = /^[a-z-]+$/i.test(w) ? lower : w;
757
+ }
758
+ for (let n = 0; all && n < normals; n += 1) {
759
+ const free = LONGHANDS.find(
760
+ p => !(p in each) && keywordsOf(p).includes('normal'),
761
+ );
762
+ if (!free)
763
+ return {
764
+ repeat: 'normal',
765
+ part: LONGHANDS.filter(p => keywordsOf(p).includes('normal')).join(
766
+ ', ',
767
+ ),
768
+ };
769
+ each[free] = 'normal';
770
+ }
771
+ if (all && words.length) return each;
772
+ }
614
773
  /** @type {any} */
615
774
  let ast;
616
775
  try {