@motion-proto/live-tokens 0.49.1 → 0.52.1

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 (111) hide show
  1. package/CHANGELOG.md +72 -0
  2. package/dist-plugin/adjust/index.d.cts +1 -1
  3. package/dist-plugin/adjust/index.d.ts +1 -1
  4. package/dist-plugin/{chunk-76TFDTJO.js → chunk-JIGIIE5P.js} +60 -132
  5. package/dist-plugin/{chunk-44RSTAII.js → chunk-TKZBVIW5.js} +33 -5
  6. package/dist-plugin/chunk-YR6GPXW2.js +129 -0
  7. package/dist-plugin/generateColorsAndType/index.cjs +100 -33
  8. package/dist-plugin/generateColorsAndType/index.d.cts +1 -1
  9. package/dist-plugin/generateColorsAndType/index.d.ts +1 -1
  10. package/dist-plugin/generateColorsAndType/index.js +35 -14
  11. package/dist-plugin/index.cjs +95 -55
  12. package/dist-plugin/index.js +5 -3
  13. package/dist-plugin/{themeTypes-DSwKq-bj.d.cts → themeTypes-Dky03HL9.d.cts} +18 -5
  14. package/dist-plugin/{themeTypes-DSwKq-bj.d.ts → themeTypes-Dky03HL9.d.ts} +18 -5
  15. package/dist-plugin/tokensCssMigrations/index.cjs +71 -5
  16. package/dist-plugin/tokensCssMigrations/index.d.cts +20 -9
  17. package/dist-plugin/tokensCssMigrations/index.d.ts +20 -9
  18. package/dist-plugin/tokensCssMigrations/index.js +4 -1
  19. package/package.json +8 -1
  20. package/src/editor/bootstrap.ts +2 -0
  21. package/src/editor/component-editor/ButtonEditor.svelte +1 -1
  22. package/src/editor/component-editor/CardEditor.svelte +5 -2
  23. package/src/editor/component-editor/IconButtonEditor.svelte +1 -1
  24. package/src/editor/component-editor/ImageEditor.svelte +1 -1
  25. package/src/editor/component-editor/NotificationEditor.svelte +6 -0
  26. package/src/editor/component-editor/SectionDividerEditor.svelte +4 -1
  27. package/src/editor/component-editor/SideNavigationEditor.svelte +6 -0
  28. package/src/editor/component-editor/TabBarEditor.svelte +1 -5
  29. package/src/editor/component-editor/scaffolding/ComponentEditorBase.svelte +8 -1
  30. package/src/editor/component-editor/scaffolding/ComponentFileManager.svelte +10 -32
  31. package/src/editor/component-editor/scaffolding/StateBlock.svelte +2 -0
  32. package/src/editor/component-editor/scaffolding/TypeEditor.svelte +3 -1
  33. package/src/editor/component-editor/scaffolding/types.ts +3 -0
  34. package/src/editor/core/components/componentConfigService.ts +25 -0
  35. package/src/editor/core/cssVarSync.ts +65 -7
  36. package/src/editor/core/fonts/fontLoader.ts +12 -3
  37. package/src/editor/core/fonts/fontWeightAvailability.ts +97 -0
  38. package/src/editor/core/palettes/oklch.ts +3 -137
  39. package/src/editor/core/palettes/paletteDerivation.ts +79 -37
  40. package/src/editor/core/preview/lookPreview.ts +23 -18
  41. package/src/editor/core/store/editorRenderer.ts +22 -7
  42. package/src/editor/core/store/editorStore.ts +31 -0
  43. package/src/editor/core/store/gradientSource.ts +5 -0
  44. package/src/editor/core/themes/colorsAndTypeService.ts +2 -12
  45. package/src/editor/core/themes/generateColorsAndType.ts +18 -8
  46. package/src/editor/core/themes/migrations/2026-05-20-sectiondivider-slim-variants.ts +4 -1
  47. package/src/editor/core/themes/migrations/2026-05-21-sectiondivider-spacing-to-padding.ts +4 -1
  48. package/src/editor/core/themes/migrations/2026-05-25-cornerbadge-flatten-variants.ts +8 -0
  49. package/src/editor/core/themes/slices/fonts.ts +4 -5
  50. package/src/editor/core/themes/themeDocumentSync.ts +66 -0
  51. package/src/editor/core/themes/themeInit.ts +7 -10
  52. package/src/editor/core/themes/themeService.ts +10 -3
  53. package/src/editor/core/themes/themeTypes.ts +18 -6
  54. package/src/editor/docs/content/editing-tokens.md +6 -2
  55. package/src/editor/docs/content/themes-workflow.md +14 -11
  56. package/src/editor/docs/content/where-themes-live.md +2 -2
  57. package/src/editor/docs/content.generated.ts +3 -3
  58. package/src/editor/ui/BezierCurveEditor.svelte +90 -67
  59. package/src/editor/ui/FileLoadList.svelte +1 -0
  60. package/src/editor/ui/FontStackEditor.svelte +1 -2
  61. package/src/editor/ui/GradientEditor.svelte +5 -1
  62. package/src/editor/ui/PaletteEditor.svelte +150 -44
  63. package/src/editor/ui/ProjectFontsSection.svelte +0 -5
  64. package/src/editor/ui/ThemePanel.svelte +206 -42
  65. package/src/editor/ui/Toggle.svelte +14 -2
  66. package/src/editor/ui/UIDialog.svelte +7 -1
  67. package/src/editor/ui/UIFontFamilySelector.svelte +13 -13
  68. package/src/editor/ui/UIFontSizeSelector.svelte +5 -5
  69. package/src/editor/ui/UIFontWeightSelector.svelte +52 -2
  70. package/src/editor/ui/UIOptionItem.svelte +14 -1
  71. package/src/editor/ui/UIPaddingSelector.svelte +4 -3
  72. package/src/editor/ui/UIPaletteSelector.svelte +20 -13
  73. package/src/editor/ui/UIRelinkConfirmDialog.svelte +18 -3
  74. package/src/editor/ui/UITextTransformSelector.svelte +5 -5
  75. package/src/editor/ui/UITokenSelector.svelte +29 -7
  76. package/src/editor/ui/colors/ColorStory.svelte +12 -8
  77. package/src/editor/ui/curveEngine.ts +101 -21
  78. package/src/editor/ui/palette/OverridesPanel.svelte +19 -5
  79. package/src/editor/ui/palette/PaletteBase.svelte +17 -78
  80. package/src/editor/ui/palette/ScaleCurveEditor.svelte +109 -20
  81. package/src/editor/ui/palette/curveSummary.ts +20 -0
  82. package/src/editor/ui/palette/dockMagnify.ts +5 -13
  83. package/src/editor/ui/palette/paletteMath.ts +7 -4
  84. package/src/live-tokens/data/colors-and-type/autumn.json +528 -528
  85. package/src/live-tokens/data/colors-and-type/default.json +247 -247
  86. package/src/live-tokens/data/colors-and-type/halloween.json +532 -532
  87. package/src/live-tokens/data/colors-and-type/midnight-study.json +538 -538
  88. package/src/live-tokens/data/colors-and-type/ocean.json +521 -521
  89. package/src/live-tokens/data/colors-and-type/royal-velvet.json +532 -532
  90. package/src/live-tokens/data/colors-and-type/spring-meadow.json +504 -504
  91. package/src/live-tokens/data/colors-and-type/sunset.json +531 -531
  92. package/src/live-tokens/data/themes/autumn.json +527 -527
  93. package/src/live-tokens/data/themes/halloween.json +531 -531
  94. package/src/live-tokens/data/themes/midnight-study.json +537 -537
  95. package/src/live-tokens/data/themes/ocean.json +520 -520
  96. package/src/live-tokens/data/themes/royal-velvet.json +531 -531
  97. package/src/live-tokens/data/themes/spring-meadow.json +516 -514
  98. package/src/live-tokens/data/themes/sunset.json +531 -531
  99. package/src/live-tokens/data/tokens.generated.css +282 -282
  100. package/src/system/components/Button.svelte +2 -1
  101. package/src/system/components/FloatingTokenTags.css +2 -2
  102. package/src/system/components/FloatingTokenTags.svelte +11 -0
  103. package/src/system/components/IconButton.svelte +2 -1
  104. package/src/system/components/Image.svelte +9 -3
  105. package/src/system/components/ImageLightbox.svelte +2 -0
  106. package/src/system/components/SectionDivider.svelte +20 -2
  107. package/src/system/components/SideNavigation.svelte +15 -1
  108. package/src/system/internal/backgroundContrast.ts +7 -0
  109. package/src/system/internal/oklch.ts +189 -0
  110. package/src/system/styles/fonts.css +6 -6
  111. package/src/system/styles/tokens.css +283 -283
@@ -0,0 +1,97 @@
1
+ import type { FontFamily, FontSource, FontStack } from '../themes/themeTypes';
2
+
3
+ export interface FontWeightAvailability {
4
+ familyName: string;
5
+ weights: ReadonlySet<number>;
6
+ }
7
+
8
+ /** Typography tokens consistently pair `-font-weight` with `-font-family`. */
9
+ export function inferFontFamilyVariable(weightVariable: string): string | null {
10
+ return weightVariable.endsWith('-font-weight')
11
+ ? `${weightVariable.slice(0, -'-font-weight'.length)}-font-family`
12
+ : null;
13
+ }
14
+
15
+ function normalizeFamilyName(value: string): string {
16
+ let name = value.trim();
17
+ // Imported font metadata sometimes retains more than one layer of wrapping
18
+ // quotes (for example `"Comfortaa"`). Peel all balanced wrappers so it can
19
+ // still be compared with a computed font-family value.
20
+ while (
21
+ name.length >= 2
22
+ && ((name.startsWith('"') && name.endsWith('"'))
23
+ || (name.startsWith("'") && name.endsWith("'")))
24
+ ) {
25
+ name = name.slice(1, -1).trim();
26
+ }
27
+ return name.toLocaleLowerCase();
28
+ }
29
+
30
+ function firstFamily(value: string): string {
31
+ let quote: '"' | "'" | null = null;
32
+ for (let i = 0; i < value.length; i += 1) {
33
+ const char = value[i];
34
+ if (quote) {
35
+ if (char === quote && value[i - 1] !== '\\') quote = null;
36
+ continue;
37
+ }
38
+ if (char === '"' || char === "'") {
39
+ quote = char;
40
+ continue;
41
+ }
42
+ if (char === ',') return value.slice(0, i);
43
+ }
44
+ return value;
45
+ }
46
+
47
+ function familyMap(sources: FontSource[]): Map<string, FontFamily> {
48
+ const families = new Map<string, FontFamily>();
49
+ for (const source of sources) {
50
+ for (const family of source.families) {
51
+ families.set(normalizeFamilyName(family.cssName), family);
52
+ families.set(normalizeFamilyName(family.name), family);
53
+ }
54
+ }
55
+ return families;
56
+ }
57
+
58
+ function knownAvailability(family: FontFamily | undefined): FontWeightAvailability | null {
59
+ if (!family?.weights?.length) return null;
60
+ return {
61
+ familyName: family.name,
62
+ weights: new Set(family.weights),
63
+ };
64
+ }
65
+
66
+ /**
67
+ * Find the declared weights for the primary face in a CSS font-family value.
68
+ * Returns null for system fonts and sources whose available weights are not
69
+ * known, so the editor never disables an option on incomplete metadata.
70
+ */
71
+ export function fontWeightAvailability(
72
+ fontFamilyValue: string,
73
+ sources: FontSource[],
74
+ stacks: FontStack[],
75
+ ): FontWeightAvailability | null {
76
+ const families = familyMap(sources);
77
+ const stackRef = fontFamilyValue.match(/^\s*var\(\s*(--font-(?:display|sans|serif|mono))\b/);
78
+
79
+ if (stackRef) {
80
+ const stack = stacks.find((candidate) => candidate.variable === stackRef[1]);
81
+ for (const slot of stack?.slots ?? []) {
82
+ if (slot.kind === 'project') {
83
+ const family = sources.flatMap((source) => source.families)
84
+ .find((candidate) => candidate.id === slot.familyId);
85
+ if (!family) continue;
86
+ return knownAvailability(family);
87
+ }
88
+ // A system or generic slot is a real primary face, but has no reliable
89
+ // per-weight metadata. Do not make assumptions from later fallbacks.
90
+ return null;
91
+ }
92
+ return null;
93
+ }
94
+
95
+ const name = normalizeFamilyName(firstFamily(fontFamilyValue));
96
+ return knownAvailability(families.get(name));
97
+ }
@@ -1,137 +1,3 @@
1
- // OKLCH color space conversions — hand-rolled, no dependencies
2
- // Pipeline: sRGB hex → linear RGB → OKLab (via M1×M2 + cube root) → OKLCH (polar)
3
-
4
- export interface Oklch {
5
- l: number; // 0..1
6
- c: number; // 0..~0.4
7
- h: number; // 0..360
8
- }
9
-
10
- // --- sRGB gamma ---
11
-
12
- function srgbToLinear(c: number): number {
13
- return c <= 0.04045 ? c / 12.92 : Math.pow((c + 0.055) / 1.055, 2.4);
14
- }
15
-
16
- function linearToSrgb(c: number): number {
17
- return c <= 0.0031308 ? 12.92 * c : 1.055 * Math.pow(c, 1 / 2.4) - 0.055;
18
- }
19
-
20
- // --- Hex ↔ linear RGB ---
21
-
22
- function hexToLinearRgb(hex: string): [number, number, number] {
23
- const r = parseInt(hex.slice(1, 3), 16) / 255;
24
- const g = parseInt(hex.slice(3, 5), 16) / 255;
25
- const b = parseInt(hex.slice(5, 7), 16) / 255;
26
- return [srgbToLinear(r), srgbToLinear(g), srgbToLinear(b)];
27
- }
28
-
29
- function linearRgbToHex(r: number, g: number, b: number): string {
30
- const toHex = (c: number) => {
31
- const v = Math.round(Math.max(0, Math.min(1, linearToSrgb(c))) * 255);
32
- return v.toString(16).padStart(2, '0');
33
- };
34
- return `#${toHex(r)}${toHex(g)}${toHex(b)}`;
35
- }
36
-
37
- // --- Linear RGB ↔ OKLab ---
38
- // Uses the two-matrix approach from Björn Ottosson's blog
39
-
40
- function linearRgbToOklab(r: number, g: number, b: number): [number, number, number] {
41
- const l_ = 0.4122214708 * r + 0.5363325363 * g + 0.0514459929 * b;
42
- const m_ = 0.2119034982 * r + 0.6806995451 * g + 0.1073969566 * b;
43
- const s_ = 0.0883024619 * r + 0.2817188376 * g + 0.6299787005 * b;
44
-
45
- const l = Math.cbrt(l_);
46
- const m = Math.cbrt(m_);
47
- const s = Math.cbrt(s_);
48
-
49
- return [
50
- 0.2104542553 * l + 0.7936177850 * m - 0.0040720468 * s,
51
- 1.9779984951 * l - 2.4285922050 * m + 0.4505937099 * s,
52
- 0.0259040371 * l + 0.7827717662 * m - 0.8086757660 * s,
53
- ];
54
- }
55
-
56
- function oklabToLinearRgb(L: number, a: number, b: number): [number, number, number] {
57
- const l_ = L + 0.3963377774 * a + 0.2158037573 * b;
58
- const m_ = L - 0.1055613458 * a - 0.0638541728 * b;
59
- const s_ = L - 0.0894841775 * a - 1.2914855480 * b;
60
-
61
- const l = l_ * l_ * l_;
62
- const m = m_ * m_ * m_;
63
- const s = s_ * s_ * s_;
64
-
65
- return [
66
- +4.0767416621 * l - 3.3077115913 * m + 0.2309699292 * s,
67
- -1.2684380046 * l + 2.6097574011 * m - 0.3413193965 * s,
68
- -0.0041960863 * l - 0.7034186147 * m + 1.7076147010 * s,
69
- ];
70
- }
71
-
72
- // --- OKLab ↔ OKLCH ---
73
-
74
- function oklabToOklch(L: number, a: number, b: number): Oklch {
75
- const c = Math.sqrt(a * a + b * b);
76
- let h = (Math.atan2(b, a) * 180) / Math.PI;
77
- if (h < 0) h += 360;
78
- return { l: L, c, h };
79
- }
80
-
81
- function oklchToOklab(l: number, c: number, h: number): [number, number, number] {
82
- const hRad = (h * Math.PI) / 180;
83
- return [l, c * Math.cos(hRad), c * Math.sin(hRad)];
84
- }
85
-
86
- // --- Public API ---
87
-
88
- export function hexToOklch(hex: string): Oklch {
89
- const [r, g, b] = hexToLinearRgb(hex);
90
- const [L, a, bVal] = linearRgbToOklab(r, g, b);
91
- return oklabToOklch(L, a, bVal);
92
- }
93
-
94
- export function oklchToHex(l: number, c: number, h: number): string {
95
- const [L, a, b] = oklchToOklab(l, c, h);
96
- const [r, g, bVal] = oklabToLinearRgb(L, a, b);
97
- return linearRgbToHex(r, g, bVal);
98
- }
99
-
100
- function isInGamut(r: number, g: number, b: number): boolean {
101
- const eps = 0.0001;
102
- return r >= -eps && r <= 1 + eps && g >= -eps && g <= 1 + eps && b >= -eps && b <= 1 + eps;
103
- }
104
-
105
- /** The clamped sRGB projection: reduce chroma into gamut, then serialize to hex.
106
- * This is the correct projection for unclamped stored intent — naive
107
- * `oklchToHex` per-channel clips (shifting hue), this preserves hue and L. */
108
- export function oklchToHexClamped(l: number, c: number, h: number): string {
109
- const g = gamutClamp(l, c, h);
110
- return oklchToHex(g.l, g.c, g.h);
111
- }
112
-
113
- export function gamutClamp(l: number, c: number, h: number): Oklch {
114
- // Clamp lightness
115
- if (l <= 0) return { l: 0, c: 0, h };
116
- if (l >= 1) return { l: 1, c: 0, h };
117
-
118
- // Binary search: reduce chroma until in sRGB gamut
119
- const [L, a, b] = oklchToOklab(l, c, h);
120
- const [r, g, bVal] = oklabToLinearRgb(L, a, b);
121
-
122
- if (isInGamut(r, g, bVal)) return { l, c, h };
123
-
124
- let lo = 0;
125
- let hi = c;
126
- for (let i = 0; i < 20; i++) {
127
- const mid = (lo + hi) / 2;
128
- const [La, aa, ba] = oklchToOklab(l, mid, h);
129
- const [rr, gg, bb] = oklabToLinearRgb(La, aa, ba);
130
- if (isInGamut(rr, gg, bb)) {
131
- lo = mid;
132
- } else {
133
- hi = mid;
134
- }
135
- }
136
- return { l, c: lo, h };
137
- }
1
+ // The math lives in the system layer because `src/system` ships to consumers
2
+ // and cannot import from `src/editor`; `backgroundContrast.ts` needs it too.
3
+ export * from '../../../system/internal/oklch';
@@ -13,8 +13,8 @@
13
13
  * derives the same CSS vars from the persisted config.
14
14
  */
15
15
 
16
- import { hexToOklch, oklchToHexClamped, gamutClamp, type Oklch } from './oklch';
17
- import { type CurveAnchor, sampleCurve, makeAnchor, tangentAnchor } from '../../ui/curveEngine';
16
+ import { cssColorToOklch, oklchToCssClamped, gamutClamp, type Oklch } from './oklch';
17
+ import { type CurveAnchor, sampleCurve, makeAnchor, tangentAnchor, resmoothAutoCurve } from '../../ui/curveEngine';
18
18
  import type { PaletteConfig } from '../themes/themeTypes';
19
19
 
20
20
  export interface PaletteSpec {
@@ -108,8 +108,18 @@ export const SCALES: readonly Scale[] = [
108
108
  export const BW_GUARD_MIN_L = 0.17;
109
109
  export const BW_GUARD_MAX_L = 0.93;
110
110
 
111
- export const DEFAULT_PALETTE_LIGHTNESS = (): CurveAnchor[] => [makeAnchor(0, 95, 5), makeAnchor(100, 8, 5)];
112
- export const DEFAULT_PALETTE_SATURATION = (): CurveAnchor[] => [makeAnchor(0, 100, 30), makeAnchor(100, 100, 30)];
111
+ /** Defaults ship auto-shaped, so a curve nobody has touched is the one the editor
112
+ * draws with Auto smooth on. Handle lengths come from the points, which is why
113
+ * `makeAnchor`'s tangent argument is left off throughout. */
114
+ const autoCurve = (...anchors: CurveAnchor[]): CurveAnchor[] => resmoothAutoCurve(anchors);
115
+
116
+ export const DEFAULT_PALETTE_LIGHTNESS = (): CurveAnchor[] => autoCurve(makeAnchor(0, 95), makeAnchor(100, 8));
117
+ export const DEFAULT_PALETTE_SATURATION = (): CurveAnchor[] => autoCurve(makeAnchor(0, 100), makeAnchor(100, 100));
118
+ export const DEFAULT_PALETTE_HUE = (): CurveAnchor[] => autoCurve(makeAnchor(0, 0), makeAnchor(100, 0));
119
+
120
+ /** Hue is cyclic, so derivation wraps rather than clamps. The trig accepts
121
+ * any angle; `Oklch.h` is documented 0..360 and readouts print it. */
122
+ const wrapHue = (h: number): number => ((h % 360) + 360) % 360;
113
123
 
114
124
  export type SchemeDirection = 'light' | 'dark';
115
125
 
@@ -133,31 +143,31 @@ export function scaleCurveDefaults(scheme: SchemeDirection = 'dark'): ScaleCurve
133
143
  if (scheme === 'light') {
134
144
  return {
135
145
  Surfaces: {
136
- lightness: () => [makeAnchor(0, 98, 5), makeAnchor(100, 82, 5)],
137
- saturation: () => [makeAnchor(0, 100, 30), makeAnchor(100, 100, 30)],
146
+ lightness: () => autoCurve(makeAnchor(0, 98), makeAnchor(100, 82)),
147
+ saturation: () => autoCurve(makeAnchor(0, 100), makeAnchor(100, 100)),
138
148
  },
139
149
  Borders: {
140
- lightness: () => [makeAnchor(0, 92, 5), makeAnchor(100, 45, 5)],
141
- saturation: () => [makeAnchor(0, 100, 30), makeAnchor(100, 100, 30)],
150
+ lightness: () => autoCurve(makeAnchor(0, 92), makeAnchor(100, 45)),
151
+ saturation: () => autoCurve(makeAnchor(0, 100), makeAnchor(100, 100)),
142
152
  },
143
153
  Text: {
144
- lightness: () => [makeAnchor(0, 30, 30), makeAnchor(100, 120, 30)],
145
- saturation: () => [makeAnchor(0, 100, 30), makeAnchor(100, 15, 30)],
154
+ lightness: () => autoCurve(makeAnchor(0, 30), makeAnchor(100, 120)),
155
+ saturation: () => autoCurve(makeAnchor(0, 100), makeAnchor(100, 15)),
146
156
  },
147
157
  };
148
158
  }
149
159
  return {
150
160
  Surfaces: {
151
- lightness: () => [makeAnchor(0, 15, 5), makeAnchor(100, 47, 5)],
152
- saturation: () => [makeAnchor(0, 100, 30), makeAnchor(100, 100, 30)],
161
+ lightness: () => autoCurve(makeAnchor(0, 15), makeAnchor(100, 47)),
162
+ saturation: () => autoCurve(makeAnchor(0, 100), makeAnchor(100, 100)),
153
163
  },
154
164
  Borders: {
155
- lightness: () => [makeAnchor(0, 25, 5), makeAnchor(100, 80, 5)],
156
- saturation: () => [makeAnchor(0, 100, 30), makeAnchor(100, 100, 30)],
165
+ lightness: () => autoCurve(makeAnchor(0, 25), makeAnchor(100, 80)),
166
+ saturation: () => autoCurve(makeAnchor(0, 100), makeAnchor(100, 100)),
157
167
  },
158
168
  Text: {
159
- lightness: () => [makeAnchor(0, 120, 30), makeAnchor(100, 55, 30)],
160
- saturation: () => [makeAnchor(0, 100, 30), makeAnchor(100, 15, 30)],
169
+ lightness: () => autoCurve(makeAnchor(0, 120), makeAnchor(100, 55)),
170
+ saturation: () => autoCurve(makeAnchor(0, 100), makeAnchor(100, 15)),
161
171
  },
162
172
  };
163
173
  }
@@ -191,10 +201,10 @@ export type DerivedValue =
191
201
 
192
202
  /** The single color → CSS-string projection, and the single clamp point for
193
203
  * derived color: unclamped stored intent is chroma-reduced into sRGB gamut,
194
- * then serialized (hex this wave; `oklch()` after Part B). Idempotent on the
195
- * already-in-gamut per-step derivation output. `raw` passes through untouched. */
204
+ * then serialized as `oklch()`. Idempotent on the already-in-gamut per-step
205
+ * derivation output. `raw` passes through untouched. */
196
206
  export function serializeDerivedValue(value: DerivedValue): string {
197
- return value.kind === 'raw' ? value.css : oklchToHexClamped(value.l, value.c, value.h);
207
+ return value.kind === 'raw' ? value.css : oklchToCssClamped(value.l, value.c, value.h);
198
208
  }
199
209
 
200
210
  export function computePaletteOklch(
@@ -203,12 +213,18 @@ export function computePaletteOklch(
203
213
  lightnessCurve: CurveAnchor[],
204
214
  saturationCurve: CurveAnchor[],
205
215
  curveOffset: Record<string, number>,
216
+ hueCurve?: CurveAnchor[],
206
217
  ): Oklch {
207
- const { c: baseC, h } = base;
218
+ const { c: baseC } = base;
208
219
  const xPos = stepIndexToX(index);
209
220
  const targetL = Math.max(0, Math.min(100, sampleCurve(lightnessCurve, xPos) + (curveOffset.lightness ?? 0))) / 100;
210
221
  const satMul = Math.max(0, Math.min(2, (sampleCurve(saturationCurve, xPos) + (curveOffset.saturation ?? 0)) / 100));
211
222
  const targetC = baseC * satMul;
223
+ // Zero delta skips the wrap rather than folding through it: `%360` round-trips
224
+ // introduce a one-ULP drift for most floats already in range, which would break
225
+ // byte-identity (Global invariant 1) for every palette with no hue curve.
226
+ const hueDelta = (hueCurve ? sampleCurve(hueCurve, xPos) : 0) + (curveOffset.hue ?? 0);
227
+ const h = hueDelta === 0 ? base.h : wrapHue(base.h + hueDelta);
212
228
  return gamutClamp(targetL, targetC, h);
213
229
  }
214
230
 
@@ -348,9 +364,10 @@ export function liftCurveAnchor(
348
364
  }
349
365
 
350
366
  /**
351
- * Place the base color in the ramp: pin a lightness anchor (base L) and a
352
- * saturation anchor (multiplier 100) at the step whose lightness is nearest
353
- * the base L, so the picked color renders verbatim at that step. Placement
367
+ * Place the base color in the ramp: pin a lightness anchor (base L), a
368
+ * saturation anchor (multiplier 100), and, when a hue curve exists, a hue
369
+ * anchor (delta 0), all at the step whose lightness is nearest the base L,
370
+ * so the picked color renders verbatim at that step. Placement
354
371
  * is measured against the curve with the previous placement lifted out —
355
372
  * the pinned anchor equals base L at its own x by construction, so measuring
356
373
  * against it would be circular and the anchor could never move. Runs inside
@@ -362,6 +379,9 @@ export function syncBaseAnchor(cfg: PaletteConfig): void {
362
379
  const fresh = prev === undefined;
363
380
  let lCurve = cfg.lightnessCurve;
364
381
  let sCurve = cfg.saturationCurve;
382
+ // Hue is pinned only once a curve exists (RJC 5): an absent curve is flat
383
+ // zero already, so there is nothing to lift or re-place.
384
+ let hCurve = cfg.hueCurve;
365
385
  if (prev) {
366
386
  // Re-placing an existing anchor (a hue move, typically) must preserve
367
387
  // whatever is currently on the curve, edited or not — never restore the
@@ -370,6 +390,7 @@ export function syncBaseAnchor(cfg: PaletteConfig): void {
370
390
  const prevX = stepIndexToX(prev.step);
371
391
  lCurve = liftCurveAnchor(lCurve, prevX, prev.displacedL);
372
392
  sCurve = liftCurveAnchor(sCurve, prevX, prev.displacedS);
393
+ if (hCurve) hCurve = liftCurveAnchor(hCurve, prevX, prev.displacedH);
373
394
  }
374
395
  const step = nearestPaletteStep(lCurve, cfg.baseColor.l);
375
396
  const x = stepIndexToX(step);
@@ -377,6 +398,8 @@ export function syncBaseAnchor(cfg: PaletteConfig): void {
377
398
  const s = setCurveAnchor(sCurve, x, 100, fresh);
378
399
  cfg.lightnessCurve = l.curve;
379
400
  cfg.saturationCurve = s.curve;
401
+ const h = hCurve ? setCurveAnchor(hCurve, x, 0, fresh) : undefined;
402
+ if (h) cfg.hueCurve = h.curve;
380
403
  // priorEndpoints is captured once, on the curve's first-ever placement,
381
404
  // and carried forward untouched thereafter so a later clear can still
382
405
  // restore the true original regardless of how many times the anchor moved.
@@ -384,18 +407,27 @@ export function syncBaseAnchor(cfg: PaletteConfig): void {
384
407
  step,
385
408
  displacedL: l.displacedY,
386
409
  displacedS: s.displacedY,
410
+ displacedH: h?.displacedY,
387
411
  priorLightnessEndpoints: prev?.priorLightnessEndpoints ?? l.priorEndpoints,
388
412
  priorSaturationEndpoints: prev?.priorSaturationEndpoints ?? s.priorEndpoints,
413
+ // No else-branch reading `prev?.priorHueEndpoints`: that could only fire
414
+ // if a placed hue curve later went absent, which RJC 7 (reset never
415
+ // deletes) never lets happen.
416
+ priorHueEndpoints: h ? (prev?.priorHueEndpoints ?? h.priorEndpoints) : undefined,
389
417
  };
390
418
  }
391
419
 
392
- /** Toggle-off: lift the placement out of both curves and drop the flag. */
420
+ /** Toggle-off: lift the placement out of every curve it touched (hue only
421
+ * if present) and drop the flag. */
393
422
  export function clearBaseAnchor(cfg: PaletteConfig): void {
394
423
  const prev = cfg.anchorPlacement;
395
424
  if (prev) {
396
425
  const x = stepIndexToX(prev.step);
397
426
  cfg.lightnessCurve = liftCurveAnchor(cfg.lightnessCurve, x, prev.displacedL, prev.priorLightnessEndpoints);
398
427
  cfg.saturationCurve = liftCurveAnchor(cfg.saturationCurve, x, prev.displacedS, prev.priorSaturationEndpoints);
428
+ if (cfg.hueCurve) {
429
+ cfg.hueCurve = liftCurveAnchor(cfg.hueCurve, x, prev.displacedH, prev.priorHueEndpoints);
430
+ }
399
431
  cfg.anchorPlacement = undefined;
400
432
  }
401
433
  cfg.anchorToBase = false;
@@ -405,7 +437,7 @@ export function computeDerivedOklch(
405
437
  step: Step,
406
438
  base: Oklch,
407
439
  scaleTitle: string,
408
- scaleCurves: Record<string, { lightness: CurveAnchor[]; saturation: CurveAnchor[] }>,
440
+ scaleCurves: Record<string, { lightness: CurveAnchor[]; saturation: CurveAnchor[]; hue?: CurveAnchor[] }>,
409
441
  curveOffset: Record<string, number>,
410
442
  ): Oklch {
411
443
  const scale = SCALES.find((s) => s.title === scaleTitle)!;
@@ -413,8 +445,10 @@ export function computeDerivedOklch(
413
445
  const defs = defaultScaleCurves[scaleTitle];
414
446
  const lCurve = scaleCurves[scaleTitle]?.lightness ?? defs.lightness();
415
447
  const sCurve = scaleCurves[scaleTitle]?.saturation ?? defs.saturation();
448
+ const hCurve = scaleCurves[scaleTitle]?.hue;
416
449
  const lOff = curveOffset[`${scaleTitle}-lightness`] ?? 0;
417
450
  const sOff = curveOffset[`${scaleTitle}-saturation`] ?? 0;
451
+ const hOff = curveOffset[`${scaleTitle}-hue`] ?? 0;
418
452
  const { l: baseL, c: baseC, h: baseH } = base;
419
453
  let targetL: number;
420
454
  if (scale.isText) {
@@ -425,7 +459,10 @@ export function computeDerivedOklch(
425
459
  }
426
460
  const satMul = Math.max(0, Math.min(2, (sampleCurve(sCurve, xPos) + sOff) / 100));
427
461
  const targetC = baseC * satMul;
428
- return gamutClamp(targetL, targetC, baseH);
462
+ // See computePaletteOklch: zero delta skips the wrap to preserve byte-identity.
463
+ const hueDelta = (hCurve ? sampleCurve(hCurve, xPos) : 0) + hOff;
464
+ const targetH = hueDelta === 0 ? baseH : wrapHue(baseH + hueDelta);
465
+ return gamutClamp(targetL, targetC, targetH);
429
466
  }
430
467
 
431
468
  export function scaleToCssVar(scaleTitle: string, stepName: string, cssNamespace: string | null): string | null {
@@ -461,7 +498,7 @@ export function derivePaletteValues(spec: PaletteSpec, config: PaletteConfig | u
461
498
  // Overrides are numeric OKLCH intent; pass straight through as color-kind.
462
499
  const value: DerivedValue = (k in overrides)
463
500
  ? { kind: 'color', ...overrides[k] }
464
- : { kind: 'color', ...computePaletteOklch(index, baseColor, lightnessCurve, saturationCurve, curveOffset) };
501
+ : { kind: 'color', ...computePaletteOklch(index, baseColor, lightnessCurve, saturationCurve, curveOffset, config.hueCurve) };
465
502
  out[`--color-${spec.cssNamespace}-${ps.label}`] = value;
466
503
  });
467
504
 
@@ -512,8 +549,8 @@ export function derivePaletteValues(spec: PaletteSpec, config: PaletteConfig | u
512
549
  const stopsCss = sortedStops
513
550
  .map((s) => {
514
551
  const stopValue = out[`--color-${spec.cssNamespace}-${s.paletteLabel}`];
515
- const hex = stopValue ? serializeDerivedValue(stopValue) : '#000000';
516
- return `${hex} ${s.position}%`;
552
+ const css = stopValue ? serializeDerivedValue(stopValue) : 'oklch(0 0 0)';
553
+ return `${css} ${s.position}%`;
517
554
  })
518
555
  .join(', ');
519
556
  let gradient: string;
@@ -554,8 +591,6 @@ export function palettesToVars(palettes: Record<string, PaletteConfig>): Record<
554
591
  return out;
555
592
  }
556
593
 
557
- const HEX_RE = /^#[0-9a-f]{6}$/i;
558
-
559
594
  /**
560
595
  * Reconcile palette typed state against the catch-all `cssVariables` bag and
561
596
  * report the set of variable names the typed slice now owns. Two operations:
@@ -596,11 +631,13 @@ export function reconcilePalettesFromCssVars(
596
631
  if (current === undefined) continue;
597
632
 
598
633
  if (current._imported === true) {
599
- const anchorHex = cssVars[`--color-${spec.cssNamespace}-500`];
600
- if (anchorHex && HEX_RE.test(anchorHex.trim())) {
601
- // Input boundary: the imported cssVariables anchor is a hex string;
602
- // parse it to the OKLCH basis exactly once, here.
603
- next[spec.label] = { ...current, baseColor: hexToOklch(anchorHex.trim()), _imported: false };
634
+ const anchor = cssVars[`--color-${spec.cssNamespace}-500`];
635
+ const anchorOklch = anchor ? cssColorToOklch(anchor) : null;
636
+ if (anchorOklch) {
637
+ // Input boundary: the imported cssVariables anchor is a CSS string in
638
+ // either serialization this system has shipped (hex before the OKLCH
639
+ // flip, `oklch()` after); parse it to the basis exactly once, here.
640
+ next[spec.label] = { ...current, baseColor: anchorOklch, _imported: false };
604
641
  syncBaseAnchor(next[spec.label]);
605
642
  snapped.add(spec.label);
606
643
  } else {
@@ -611,7 +648,12 @@ export function reconcilePalettesFromCssVars(
611
648
  }
612
649
  }
613
650
 
614
- for (const k of Object.keys(derivePaletteVars(spec, next[spec.label]))) {
651
+ // Key names only: which variables this palette owns is a structural
652
+ // question, so read the IR rather than serializing values that are
653
+ // discarded. Callers reach here with pre-migration configs whose
654
+ // `baseColor` is still a hex string; serializing those derived NaNs used
655
+ // to produce junk strings nobody read.
656
+ for (const k of Object.keys(derivePaletteValues(spec, next[spec.label]))) {
615
657
  consumed.add(k);
616
658
  }
617
659
  }
@@ -2,8 +2,8 @@ import { get } from 'svelte/store';
2
2
  import type { FontSource, Theme, ColorsAndType } from '../themes/themeTypes';
3
3
  import { editorState, colorsAndTypeToState, toComponentSlice } from '../store/editorStore';
4
4
  import { deriveCssVars } from '../store/editorRenderer';
5
- import { setCssVar, removeCssVar } from '../cssVarSync';
6
- import { applyFontSources, resolveFontStackValues } from '../fonts/fontLoader';
5
+ import { batchCssVarChanges, setCssVar, removeCssVar } from '../cssVarSync';
6
+ import { applyFontSources } from '../fonts/fontLoader';
7
7
  import { migrateColorsAndTypeFonts } from '../fonts/fontMigration';
8
8
  import { loadTheme } from '../themes/themeService';
9
9
 
@@ -50,7 +50,6 @@ export function themeLook(theme: Theme, defaults: Theme): RenderedLook {
50
50
  state.components[comp] = toComponentSlice(comp, config.aliases, config.config, config.schemaVersion);
51
51
  }
52
52
  const vars = deriveCssVars(state);
53
- Object.assign(vars, resolveFontStackValues(colorsAndType.fontStacks ?? [], colorsAndType.fontSources ?? []));
54
53
  return { vars, fontSources: colorsAndType.fontSources ?? [] };
55
54
  }
56
55
 
@@ -65,7 +64,6 @@ export function colorsAndTypeLook(colorsAndType: ColorsAndType): RenderedLook {
65
64
  const next = structuredClone(colorsAndType);
66
65
  migrateColorsAndTypeFonts(next);
67
66
  const vars = deriveCssVars(colorsAndTypeToState(next));
68
- Object.assign(vars, resolveFontStackValues(next.fontStacks ?? [], next.fontSources ?? []));
69
67
  return { vars, fontSources: next.fontSources ?? [] };
70
68
  }
71
69
 
@@ -73,7 +71,6 @@ export function colorsAndTypeLook(colorsAndType: ColorsAndType): RenderedLook {
73
71
  export function liveLook(): RenderedLook {
74
72
  const state = get(editorState);
75
73
  const vars = deriveCssVars(state);
76
- Object.assign(vars, resolveFontStackValues(state.fonts.stacks, state.fonts.sources));
77
74
  return { vars, fontSources: state.fonts.sources };
78
75
  }
79
76
 
@@ -91,24 +88,24 @@ function loadDefaults(): Promise<Theme> {
91
88
  }
92
89
 
93
90
  function paint(next: RenderedLook, from: RenderedLook): void {
94
- for (const [name, value] of Object.entries(next.vars)) {
95
- if (from.vars[name] !== value) setCssVar(name, value);
96
- }
97
- for (const name of Object.keys(from.vars)) {
98
- if (!(name in next.vars)) removeCssVar(name);
99
- }
100
- applyFontSources(next.fontSources);
91
+ batchCssVarChanges(() => {
92
+ for (const [name, value] of Object.entries(next.vars)) {
93
+ if (from.vars[name] !== value) setCssVar(name, value);
94
+ }
95
+ for (const name of Object.keys(from.vars)) {
96
+ if (!(name in next.vars)) removeCssVar(name);
97
+ }
98
+ applyFontSources(next.fontSources);
99
+ });
101
100
  }
102
101
 
103
102
  /**
104
- * Show `look` on the page. Re-entrant: a live preview is reverted first, so
105
- * every look is painted as a diff against the user's real state and a var one
106
- * look sets but the next does not returns to its live value instead of vanishing.
107
- * The two passes run in one task, so the browser never paints the intermediate.
103
+ * Show `look` on the page. Re-entrant previews diff directly from the look
104
+ * already painted; only Cancel restores the live store projection. This avoids
105
+ * repainting the live theme as an invisible intermediate on every picker row.
108
106
  */
109
107
  function applyPreview(look: RenderedLook): void {
110
- revertPreview();
111
- paint(look, liveLook());
108
+ paint(look, livePreview ?? liveLook());
112
109
  livePreview = look;
113
110
  }
114
111
 
@@ -130,6 +127,14 @@ export function revertPreview(): void {
130
127
  livePreview = null;
131
128
  }
132
129
 
130
+ /** Release the preview without repainting. The caller must immediately load
131
+ * the exact look being previewed into the store. This is the Save handoff: the
132
+ * selected theme is already on screen, so restoring the old live look before
133
+ * applying it would add work and create a visible flash across the request. */
134
+ export function commitPreview(): void {
135
+ livePreview = null;
136
+ }
137
+
133
138
  export function isPreviewing(): boolean {
134
139
  return livePreview !== null;
135
140
  }
@@ -12,7 +12,8 @@
12
12
  */
13
13
 
14
14
  import type { EditorState } from './editorTypes';
15
- import { setCssVar, removeCssVar } from '../cssVarSync';
15
+ import { batchCssVarChanges, setCssVar, removeCssVar } from '../cssVarSync';
16
+ import { applyFontSources, resolveFontStackValues } from '../fonts/fontLoader';
16
17
  import { palettesToVars } from '../palettes/paletteDerivation';
17
18
  import {
18
19
  editorState,
@@ -38,10 +39,12 @@ export function deriveCssVars(state: EditorState): Record<string, string> {
38
39
  }
39
40
  Object.assign(out, palettesToVars(state.palettes));
40
41
  Object.assign(out, componentsToVars(state.components));
42
+ Object.assign(out, resolveFontStackValues(state.fonts.stacks, state.fonts.sources));
41
43
  return out;
42
44
  }
43
45
 
44
46
  let lastApplied: Record<string, string> = {};
47
+ let lastFontSources = '';
45
48
  let installed = false;
46
49
 
47
50
  /**
@@ -55,17 +58,29 @@ export function installRenderer(): void {
55
58
  if (typeof window === 'undefined') return;
56
59
  editorState.subscribe((state) => {
57
60
  const next = deriveCssVars(state);
58
- for (const name in next) {
59
- if (next[name] !== lastApplied[name]) setCssVar(name, next[name]);
60
- }
61
- for (const name in lastApplied) {
62
- if (!(name in next)) removeCssVar(name);
63
- }
61
+ batchCssVarChanges(() => {
62
+ for (const name in next) {
63
+ if (next[name] !== lastApplied[name]) setCssVar(name, next[name]);
64
+ }
65
+ for (const name in lastApplied) {
66
+ if (!(name in next)) removeCssVar(name);
67
+ }
68
+ });
64
69
  lastApplied = next;
70
+
71
+ // Font source nodes are DOM state just like root custom properties. Keep
72
+ // them behind the same authoritative store subscription so load,
73
+ // undo/redo, reset, and every future mutation path all reconcile them.
74
+ const nextFontSources = JSON.stringify(state.fonts.sources);
75
+ if (nextFontSources !== lastFontSources) {
76
+ applyFontSources(state.fonts.sources);
77
+ lastFontSources = nextFontSources;
78
+ }
65
79
  });
66
80
  }
67
81
 
68
82
  /** Test-only: clear the diff cache so independent test runs don't leak applied vars. */
69
83
  export function __resetRendererCacheForTests(): void {
70
84
  lastApplied = {};
85
+ lastFontSources = '';
71
86
  }