@clhaas/palette-kit 0.1.7 → 0.3.0

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 (293) hide show
  1. package/.codex/skills/color-pipeline-implementer/SKILL.md +23 -0
  2. package/.codex/skills/commit-message-crafter/SKILL.md +63 -0
  3. package/.codex/skills/commit-message-crafter/references/benchmarks.md +20 -0
  4. package/.codex/skills/contrast-solver-helper/SKILL.md +20 -0
  5. package/.codex/skills/exporters-builder/SKILL.md +20 -0
  6. package/.codex/skills/markdownlint-writer/SKILL.md +32 -0
  7. package/.codex/skills/phase-implementation-runbook/SKILL.md +92 -0
  8. package/.codex/skills/type-contract-auditor/SKILL.md +21 -0
  9. package/.github/skills/review-guide/SKILL.md +23 -0
  10. package/.github/skills/review-guide/references/review-guide-v0.3.md +629 -0
  11. package/.markdownlint.json +4 -0
  12. package/AGENTS.md +16 -0
  13. package/CHANGELOG.md +34 -0
  14. package/README.md +79 -169
  15. package/biome.json +43 -0
  16. package/dist/cli/args.d.ts +12 -0
  17. package/dist/cli/args.js +56 -0
  18. package/dist/cli/args.test.js +22 -0
  19. package/dist/cli/codegen/__snapshots__/tokens.test.js.snap +87 -0
  20. package/dist/cli/codegen/tokens.d.ts +12 -0
  21. package/dist/cli/codegen/tokens.js +139 -0
  22. package/dist/cli/codegen/tokens.test.d.ts +1 -0
  23. package/dist/cli/codegen/tokens.test.js +51 -0
  24. package/dist/cli/config.d.ts +40 -0
  25. package/dist/cli/config.js +34 -0
  26. package/dist/cli/validate.d.ts +2 -0
  27. package/dist/cli/validate.js +33 -0
  28. package/dist/cli/validate.test.d.ts +1 -0
  29. package/dist/cli/validate.test.js +40 -0
  30. package/dist/cli.js +138 -140
  31. package/dist/contrast/apca.d.ts +2 -2
  32. package/dist/contrast/apca.js +14 -4
  33. package/dist/contrast/apca.test.d.ts +1 -0
  34. package/dist/contrast/apca.test.js +16 -0
  35. package/dist/contrast/index.d.ts +4 -0
  36. package/dist/contrast/index.js +4 -0
  37. package/dist/contrast/scoring.d.ts +4 -0
  38. package/dist/contrast/scoring.js +31 -0
  39. package/dist/contrast/scoring.test.d.ts +1 -0
  40. package/dist/contrast/scoring.test.js +148 -0
  41. package/dist/contrast/solver.d.ts +13 -0
  42. package/dist/contrast/solver.js +170 -0
  43. package/dist/contrast/solver.test.d.ts +1 -0
  44. package/dist/contrast/solver.test.js +75 -0
  45. package/dist/contrast/types.d.ts +17 -0
  46. package/dist/contrast/types.js +1 -0
  47. package/dist/contrast/utils.d.ts +4 -0
  48. package/dist/contrast/utils.js +18 -0
  49. package/dist/contrast/wcag2.d.ts +3 -0
  50. package/dist/contrast/wcag2.js +19 -0
  51. package/dist/contrast/wcag2.test.d.ts +1 -0
  52. package/dist/contrast/wcag2.test.js +17 -0
  53. package/dist/core/createTheme.d.ts +35 -0
  54. package/dist/core/createTheme.js +24 -0
  55. package/dist/core/dx-helpers.test.d.ts +1 -0
  56. package/dist/core/dx-helpers.test.js +61 -0
  57. package/dist/core/index.d.ts +2 -0
  58. package/dist/core/index.js +2 -0
  59. package/dist/core/onSolid.test.d.ts +1 -0
  60. package/dist/core/onSolid.test.js +118 -0
  61. package/dist/core/qa.v1.test.d.ts +1 -0
  62. package/dist/core/qa.v1.test.js +112 -0
  63. package/dist/core/resolve.d.ts +3 -0
  64. package/dist/core/resolve.js +8 -0
  65. package/dist/core/resolve.test.d.ts +1 -0
  66. package/dist/core/resolve.test.js +89 -0
  67. package/dist/core/resolveMany.d.ts +8 -0
  68. package/dist/core/resolveMany.js +17 -0
  69. package/dist/core/tokenRegistry.d.ts +23 -0
  70. package/dist/core/tokenRegistry.js +83 -0
  71. package/dist/core/tokenRegistry.test.d.ts +1 -0
  72. package/dist/core/tokenRegistry.test.js +133 -0
  73. package/dist/engine/applyOperators.d.ts +3 -0
  74. package/dist/engine/applyOperators.js +23 -0
  75. package/dist/engine/context.d.ts +4 -0
  76. package/dist/engine/context.js +1 -0
  77. package/dist/engine/gamut.d.ts +13 -0
  78. package/dist/engine/gamut.js +101 -0
  79. package/dist/engine/gamut.test.d.ts +1 -0
  80. package/dist/engine/gamut.test.js +23 -0
  81. package/dist/engine/generateScale.d.ts +15 -0
  82. package/dist/engine/generateScale.js +29 -0
  83. package/dist/engine/generateScale.test.d.ts +1 -0
  84. package/dist/engine/generateScale.test.js +32 -0
  85. package/dist/engine/index.d.ts +8 -0
  86. package/dist/engine/index.js +4 -0
  87. package/dist/engine/normalize.d.ts +43 -0
  88. package/dist/engine/normalize.js +403 -0
  89. package/dist/engine/normalize.test.d.ts +1 -0
  90. package/dist/engine/normalize.test.js +136 -0
  91. package/dist/engine/onSolid.d.ts +3 -0
  92. package/dist/engine/onSolid.js +110 -0
  93. package/dist/engine/resolveBaseColor.d.ts +25 -0
  94. package/dist/engine/resolveBaseColor.js +127 -0
  95. package/dist/engine/resolveBaseColor.test.d.ts +1 -0
  96. package/dist/engine/resolveBaseColor.test.js +97 -0
  97. package/dist/export/__snapshots__/exportTheme.test.js.snap +74 -0
  98. package/dist/export/exportTheme.d.ts +47 -0
  99. package/dist/export/exportTheme.js +170 -0
  100. package/dist/export/exportTheme.test.d.ts +1 -0
  101. package/dist/export/exportTheme.test.js +118 -0
  102. package/dist/export/index.d.ts +1 -0
  103. package/dist/export/index.js +1 -0
  104. package/dist/export/serializeColor.d.ts +1 -0
  105. package/dist/export/serializeColor.js +1 -0
  106. package/dist/export/serializeColor.test.d.ts +1 -0
  107. package/dist/export/serializeColor.test.js +54 -0
  108. package/dist/export.d.ts +1 -0
  109. package/dist/export.js +1 -0
  110. package/dist/index.d.ts +3 -20
  111. package/dist/index.js +2 -17
  112. package/dist/operators/emphasis.d.ts +3 -0
  113. package/dist/operators/emphasis.js +113 -0
  114. package/dist/operators/emphasis.test.d.ts +1 -0
  115. package/dist/operators/emphasis.test.js +69 -0
  116. package/dist/operators/index.d.ts +3 -0
  117. package/dist/operators/index.js +2 -0
  118. package/dist/operators/state.d.ts +3 -0
  119. package/dist/operators/state.js +102 -0
  120. package/dist/operators/state.test.d.ts +1 -0
  121. package/dist/operators/state.test.js +48 -0
  122. package/dist/operators/types.d.ts +13 -0
  123. package/dist/operators/types.js +1 -0
  124. package/dist/operators/utils.d.ts +16 -0
  125. package/dist/operators/utils.js +23 -0
  126. package/dist/presets/curves.d.ts +28 -0
  127. package/dist/presets/curves.js +145 -0
  128. package/dist/presets/index.d.ts +2 -0
  129. package/dist/presets/index.js +1 -0
  130. package/dist/presets/tokens/index.d.ts +3 -0
  131. package/dist/presets/tokens/index.js +3 -0
  132. package/dist/presets/tokens/minimal-ui.d.ts +6 -0
  133. package/dist/presets/tokens/minimal-ui.js +53 -0
  134. package/dist/presets/tokens/modern-ui.d.ts +5 -0
  135. package/dist/presets/tokens/modern-ui.js +83 -0
  136. package/dist/presets/tokens/presets.test.d.ts +1 -0
  137. package/dist/presets/tokens/presets.test.js +31 -0
  138. package/dist/presets/tokens/radixLike-ui.d.ts +6 -0
  139. package/dist/presets/tokens/radixLike-ui.js +77 -0
  140. package/dist/serialize/index.d.ts +1 -0
  141. package/dist/serialize/index.js +1 -0
  142. package/dist/serialize/normalizeOutput.d.ts +6 -0
  143. package/dist/serialize/normalizeOutput.js +45 -0
  144. package/dist/serialize/serializeColor.d.ts +21 -0
  145. package/dist/serialize/serializeColor.js +178 -0
  146. package/dist/serialize/serializeResolved.test.d.ts +1 -0
  147. package/dist/serialize/serializeResolved.test.js +45 -0
  148. package/dist/serialize.d.ts +1 -0
  149. package/dist/serialize.js +1 -0
  150. package/dist/types/index.d.ts +187 -0
  151. package/dist/types/index.js +1 -0
  152. package/dist/utils/clamp.d.ts +1 -0
  153. package/dist/utils/clamp.js +1 -0
  154. package/dist/utils/index.d.ts +1 -0
  155. package/dist/utils/index.js +1 -0
  156. package/dist/utils/lerp.d.ts +1 -0
  157. package/dist/utils/lerp.js +1 -0
  158. package/dist/utils/parseColor.d.ts +6 -0
  159. package/dist/utils/parseColor.js +67 -0
  160. package/dist/utils/parseColor.test.d.ts +1 -0
  161. package/dist/utils/parseColor.test.js +51 -0
  162. package/dist/utils/smoothstep.d.ts +1 -0
  163. package/dist/utils/smoothstep.js +5 -0
  164. package/package.json +19 -12
  165. package/planning/phase-10-review.md +550 -0
  166. package/planning/phase-7-review.md +411 -0
  167. package/planning/phase-8-review.md +669 -0
  168. package/planning/phase-9-review.md +564 -0
  169. package/planning/roadmap-v0.3.md +284 -0
  170. package/planning/spec-serializer-v0.3.md +324 -0
  171. package/planning/spec-v0.3.md +305 -0
  172. package/src/cli/args.test.ts +28 -0
  173. package/src/cli/args.ts +66 -0
  174. package/src/cli/codegen/__snapshots__/tokens.test.ts.snap +87 -0
  175. package/src/cli/codegen/tokens.test.ts +61 -0
  176. package/src/cli/codegen/tokens.ts +191 -0
  177. package/src/cli/config.ts +71 -0
  178. package/src/cli/validate.test.ts +49 -0
  179. package/src/cli/validate.ts +38 -0
  180. package/src/cli.ts +183 -0
  181. package/src/contrast/apca.test.ts +20 -0
  182. package/src/contrast/apca.ts +26 -0
  183. package/src/contrast/index.ts +4 -0
  184. package/src/contrast/scoring.test.ts +188 -0
  185. package/src/contrast/scoring.ts +48 -0
  186. package/src/contrast/solver.test.ts +147 -0
  187. package/src/contrast/solver.ts +235 -0
  188. package/src/contrast/types.ts +20 -0
  189. package/src/contrast/utils.ts +28 -0
  190. package/src/contrast/wcag2.test.ts +21 -0
  191. package/src/contrast/wcag2.ts +24 -0
  192. package/src/core/createTheme.ts +78 -0
  193. package/src/core/dx-helpers.test.ts +82 -0
  194. package/src/core/index.ts +7 -0
  195. package/src/core/onSolid.test.ts +146 -0
  196. package/src/core/qa.v1.test.ts +149 -0
  197. package/src/core/resolve.test.ts +99 -0
  198. package/src/core/resolve.ts +11 -0
  199. package/src/core/resolveMany.ts +22 -0
  200. package/src/core/tokenRegistry.test.ts +153 -0
  201. package/src/core/tokenRegistry.ts +114 -0
  202. package/src/engine/applyOperators.ts +32 -0
  203. package/src/engine/context.ts +8 -0
  204. package/src/engine/gamut.test.ts +30 -0
  205. package/src/engine/gamut.ts +144 -0
  206. package/src/engine/generateScale.test.ts +46 -0
  207. package/src/engine/generateScale.ts +48 -0
  208. package/src/engine/index.ts +8 -0
  209. package/src/engine/normalize.test.ts +222 -0
  210. package/src/engine/normalize.ts +550 -0
  211. package/src/engine/onSolid.ts +178 -0
  212. package/src/engine/resolveBaseColor.test.ts +117 -0
  213. package/src/engine/resolveBaseColor.ts +203 -0
  214. package/src/export/__snapshots__/exportTheme.test.ts.snap +74 -0
  215. package/src/export/exportTheme.test.ts +144 -0
  216. package/src/export/exportTheme.ts +251 -0
  217. package/src/export/index.ts +1 -0
  218. package/src/export/serializeColor.test.ts +73 -0
  219. package/src/export/serializeColor.ts +1 -0
  220. package/src/export.ts +1 -0
  221. package/src/index.ts +3 -0
  222. package/src/operators/emphasis.test.ts +85 -0
  223. package/src/operators/emphasis.ts +132 -0
  224. package/src/operators/index.ts +3 -0
  225. package/src/operators/state.test.ts +66 -0
  226. package/src/operators/state.ts +122 -0
  227. package/src/operators/types.ts +14 -0
  228. package/src/operators/utils.ts +44 -0
  229. package/src/presets/curves.ts +168 -0
  230. package/src/presets/index.ts +2 -0
  231. package/src/presets/tokens/index.ts +3 -0
  232. package/src/presets/tokens/minimal-ui.ts +55 -0
  233. package/src/presets/tokens/modern-ui.ts +85 -0
  234. package/src/presets/tokens/presets.test.ts +46 -0
  235. package/src/presets/tokens/radixLike-ui.ts +79 -0
  236. package/src/serialize/index.ts +1 -0
  237. package/src/serialize/normalizeOutput.ts +63 -0
  238. package/src/serialize/serializeColor.ts +260 -0
  239. package/src/serialize/serializeResolved.test.ts +57 -0
  240. package/src/serialize.ts +1 -0
  241. package/src/types/index.ts +207 -0
  242. package/src/utils/clamp.ts +2 -0
  243. package/src/utils/index.ts +1 -0
  244. package/src/utils/lerp.ts +1 -0
  245. package/src/utils/parseColor.test.ts +66 -0
  246. package/src/utils/parseColor.ts +87 -0
  247. package/src/utils/smoothstep.ts +6 -0
  248. package/tsconfig.build.json +11 -0
  249. package/tsconfig.json +15 -0
  250. package/dist/alpha/generateAlphaScale.d.ts +0 -5
  251. package/dist/alpha/generateAlphaScale.js +0 -34
  252. package/dist/contrast/onSolid.d.ts +0 -6
  253. package/dist/contrast/onSolid.js +0 -28
  254. package/dist/contrast/solveText.d.ts +0 -2
  255. package/dist/contrast/solveText.js +0 -31
  256. package/dist/createTheme.d.ts +0 -38
  257. package/dist/createTheme.js +0 -137
  258. package/dist/data/radixSeeds.d.ts +0 -3
  259. package/dist/data/radixSeeds.js +0 -34
  260. package/dist/diagnostics/analyzeScale.d.ts +0 -2
  261. package/dist/diagnostics/analyzeScale.js +0 -7
  262. package/dist/diagnostics/analyzeTheme.d.ts +0 -2
  263. package/dist/diagnostics/analyzeTheme.js +0 -35
  264. package/dist/diagnostics/warnings.d.ts +0 -2
  265. package/dist/diagnostics/warnings.js +0 -20
  266. package/dist/engine/curves.d.ts +0 -9
  267. package/dist/engine/curves.js +0 -48
  268. package/dist/engine/oklch.d.ts +0 -8
  269. package/dist/engine/oklch.js +0 -40
  270. package/dist/engine/templates.d.ts +0 -14
  271. package/dist/engine/templates.js +0 -45
  272. package/dist/exporters/selectColorMode.d.ts +0 -2
  273. package/dist/exporters/selectColorMode.js +0 -19
  274. package/dist/exporters/toCssVars.d.ts +0 -13
  275. package/dist/exporters/toCssVars.js +0 -108
  276. package/dist/exporters/toJson.d.ts +0 -3
  277. package/dist/exporters/toJson.js +0 -25
  278. package/dist/exporters/toReactNative.d.ts +0 -54
  279. package/dist/exporters/toReactNative.js +0 -33
  280. package/dist/exporters/toTailwind.d.ts +0 -17
  281. package/dist/exporters/toTailwind.js +0 -111
  282. package/dist/exporters/toTs.d.ts +0 -3
  283. package/dist/exporters/toTs.js +0 -43
  284. package/dist/generateScale.d.ts +0 -48
  285. package/dist/generateScale.js +0 -274
  286. package/dist/overlays/generateOverlayScale.d.ts +0 -2
  287. package/dist/overlays/generateOverlayScale.js +0 -34
  288. package/dist/text/generateTextScale.d.ts +0 -8
  289. package/dist/text/generateTextScale.js +0 -18
  290. package/dist/tokens/presetRadixLikeUi.d.ts +0 -5
  291. package/dist/tokens/presetRadixLikeUi.js +0 -55
  292. package/dist/types.d.ts +0 -69
  293. /package/dist/{types.js → cli/args.test.d.ts} +0 -0
@@ -0,0 +1,101 @@
1
+ import { clampChroma, converter } from "culori";
2
+ import { clamp } from "../utils/clamp.js";
3
+ const toRgb = converter("rgb");
4
+ const toP3 = converter("p3");
5
+ const toOklch = converter("oklch");
6
+ const normalizeHue = (hue) => ((hue % 360) + 360) % 360;
7
+ const toCuloriOklch = (color) => ({
8
+ mode: "oklch",
9
+ l: clamp(color.l, 0, 100) / 100,
10
+ c: Math.max(0, color.c),
11
+ h: color.h,
12
+ alpha: color.alpha ?? 1,
13
+ });
14
+ const fromCuloriOklch = (color) => ({
15
+ l: clamp(typeof color.l === "number" && Number.isFinite(color.l) ? color.l * 100 : 0, 0, 100),
16
+ c: Math.max(0, typeof color.c === "number" && Number.isFinite(color.c) ? color.c : 0),
17
+ h: normalizeHue(typeof color.h === "number" && Number.isFinite(color.h) ? color.h : 0),
18
+ ...(typeof color.alpha === "number" ? { alpha: color.alpha } : {}),
19
+ });
20
+ const clamp01 = (value) => Math.min(1, Math.max(0, value));
21
+ const toTargetRgb = (color, target) => {
22
+ const source = toCuloriOklch(color);
23
+ const rgb = target === "p3" ? toP3(source) : toRgb(source);
24
+ if (!rgb) {
25
+ return null;
26
+ }
27
+ const r = typeof rgb.r === "number" && Number.isFinite(rgb.r) ? rgb.r : Number.NaN;
28
+ const g = typeof rgb.g === "number" && Number.isFinite(rgb.g) ? rgb.g : Number.NaN;
29
+ const b = typeof rgb.b === "number" && Number.isFinite(rgb.b) ? rgb.b : Number.NaN;
30
+ if (!Number.isFinite(r) || !Number.isFinite(g) || !Number.isFinite(b)) {
31
+ return null;
32
+ }
33
+ return { r, g, b };
34
+ };
35
+ const toOklchFromRgb = (rgb, target) => {
36
+ const converted = toOklch({
37
+ mode: (target === "p3" ? "p3" : "rgb"),
38
+ r: clamp01(rgb.r),
39
+ g: clamp01(rgb.g),
40
+ b: clamp01(rgb.b),
41
+ });
42
+ if (!converted) {
43
+ return null;
44
+ }
45
+ return fromCuloriOklch(converted);
46
+ };
47
+ const GAMUT_EPSILON = 1e-6;
48
+ const inGamut = (rgb) => !!rgb &&
49
+ Number.isFinite(rgb.r) &&
50
+ Number.isFinite(rgb.g) &&
51
+ Number.isFinite(rgb.b) &&
52
+ rgb.r >= -GAMUT_EPSILON &&
53
+ rgb.r <= 1 + GAMUT_EPSILON &&
54
+ rgb.g >= -GAMUT_EPSILON &&
55
+ rgb.g <= 1 + GAMUT_EPSILON &&
56
+ rgb.b >= -GAMUT_EPSILON &&
57
+ rgb.b <= 1 + GAMUT_EPSILON;
58
+ const fallbackColor = (color) => ({
59
+ l: 0,
60
+ c: 0,
61
+ h: 0,
62
+ alpha: color.alpha ?? 1,
63
+ });
64
+ export const isInGamut = (color, target) => inGamut(toTargetRgb(color, target));
65
+ export const mapToGamut = (color, target, mapping, strict) => {
66
+ // Note:
67
+ // `preferP3ThenCompress` is primarily a caller-level strategy (e.g. serializeColor prefers P3 when possible).
68
+ // Inside this mapper, any non-clip mapping uses chroma compression (via clampChroma) when mapping is needed.
69
+ const rgb = toTargetRgb(color, target);
70
+ if (!rgb) {
71
+ if (strict) {
72
+ throw new Error(`Unable to convert color to ${target}`);
73
+ }
74
+ return fallbackColor(color);
75
+ }
76
+ if (mapping === "clip") {
77
+ if (inGamut(rgb)) {
78
+ return color;
79
+ }
80
+ const clipped = { r: clamp01(rgb.r), g: clamp01(rgb.g), b: clamp01(rgb.b) };
81
+ const clippedOklch = toOklchFromRgb(clipped, target);
82
+ return clippedOklch
83
+ ? {
84
+ ...clippedOklch,
85
+ ...(typeof color.alpha === "number" ? { alpha: color.alpha } : {}),
86
+ }
87
+ : fallbackColor(color);
88
+ }
89
+ if (inGamut(rgb)) {
90
+ return color;
91
+ }
92
+ const clamped = clampChroma(toCuloriOklch(color), "oklch", target === "p3" ? "p3" : "rgb");
93
+ if (!clamped) {
94
+ if (strict) {
95
+ throw new Error(`Unable to clamp chroma for ${target}`);
96
+ }
97
+ return fallbackColor(color);
98
+ }
99
+ return fromCuloriOklch(clamped);
100
+ };
101
+ export const toGamutRgb = (color, target) => toTargetRgb(color, target);
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,23 @@
1
+ import { describe, expect, it } from "vitest";
2
+ import { isInGamut, mapToGamut } from "./gamut.js";
3
+ describe("gamut mapping", () => {
4
+ const outOfSrgbInP3 = { l: 60, c: 0.2, h: 40 };
5
+ it("detects out-of-gamut sRGB colors", () => {
6
+ expect(isInGamut(outOfSrgbInP3, "srgb")).toBe(false);
7
+ expect(isInGamut(outOfSrgbInP3, "p3")).toBe(true);
8
+ });
9
+ it("clips to sRGB gamut", () => {
10
+ const clipped = mapToGamut(outOfSrgbInP3, "srgb", "clip", false);
11
+ expect(isInGamut(clipped, "srgb")).toBe(true);
12
+ });
13
+ it("compresses chroma to sRGB gamut", () => {
14
+ const compressed = mapToGamut(outOfSrgbInP3, "srgb", "compressChroma", false);
15
+ expect(isInGamut(compressed, "srgb")).toBe(true);
16
+ expect(compressed.c).toBeLessThanOrEqual(outOfSrgbInP3.c);
17
+ });
18
+ it("keeps chroma when already in P3", () => {
19
+ const mapped = mapToGamut(outOfSrgbInP3, "p3", "preferP3ThenCompress", false);
20
+ expect(isInGamut(mapped, "p3")).toBe(true);
21
+ expect(mapped.c).toBeCloseTo(outOfSrgbInP3.c, 4);
22
+ });
23
+ });
@@ -0,0 +1,15 @@
1
+ import type { CurvePresetName } from "../presets/index.js";
2
+ import type { SurfaceIntent } from "../types/index.js";
3
+ export type OkLchColor = {
4
+ l: number;
5
+ c: number;
6
+ h: number;
7
+ alpha?: number;
8
+ };
9
+ type GenerateScaleOptions = {
10
+ context: "light" | "dark";
11
+ surface: SurfaceIntent;
12
+ preset?: CurvePresetName;
13
+ };
14
+ export declare function generateScale(seed: OkLchColor, options: GenerateScaleOptions): OkLchColor[];
15
+ export {};
@@ -0,0 +1,29 @@
1
+ import { curvePresets } from "../presets/index.js";
2
+ import { clamp } from "../utils/clamp.js";
3
+ import { lerp } from "../utils/lerp.js";
4
+ const STEPS = 12;
5
+ const OKLCH_L_MIN = 0;
6
+ const OKLCH_L_MAX = 100;
7
+ export function generateScale(seed, options) {
8
+ const presetName = options.preset ?? "modern";
9
+ const preset = curvePresets[presetName];
10
+ const surfaceCurve = preset.surfaces[options.surface];
11
+ const range = surfaceCurve.ranges[options.context];
12
+ return Array.from({ length: STEPS }, (_, index) => {
13
+ const t = index / (STEPS - 1);
14
+ const lightnessT = surfaceCurve.l(t);
15
+ const chromaT = surfaceCurve.c(lightnessT);
16
+ const l = clamp(lerp(range.l[0], range.l[1], lightnessT), OKLCH_L_MIN, OKLCH_L_MAX);
17
+ // Allow select surfaces to exceed seed chroma slightly while staying within range caps.
18
+ const chromaBoost = range.chromaBoost ?? 1;
19
+ const boostedSeed = (seed.c ?? range.cMax) * chromaBoost;
20
+ const maxChroma = Math.min(range.cMax, Math.max(0, boostedSeed));
21
+ const c = clamp(lerp(range.cMin, maxChroma, chromaT), 0, range.cMax);
22
+ return {
23
+ l,
24
+ c,
25
+ h: seed.h,
26
+ alpha: seed.alpha,
27
+ };
28
+ });
29
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,32 @@
1
+ import { describe, expect, it } from "vitest";
2
+ import { generateScale } from "./generateScale.js";
3
+ const seed = { l: 49.5, c: 0.19, h: 264.0 };
4
+ const isMonotonic = (values) => values.every((value, index) => index === 0 || value >= values[index - 1] - 1e-6);
5
+ describe("generateScale", () => {
6
+ it("returns 12 steps", () => {
7
+ const result = generateScale(seed, { context: "light", surface: "surface" });
8
+ expect(result).toHaveLength(12);
9
+ });
10
+ it("keeps lightness monotonic in light context", () => {
11
+ const result = generateScale(seed, { context: "light", surface: "surface" });
12
+ const lightness = result.map((step) => step.l);
13
+ expect(isMonotonic(lightness)).toBe(true);
14
+ });
15
+ it("keeps lightness monotonic in dark context", () => {
16
+ const result = generateScale(seed, { context: "dark", surface: "surface" });
17
+ const lightness = result.map((step) => step.l);
18
+ expect(isMonotonic(lightness)).toBe(true);
19
+ });
20
+ it("keeps hue constant across steps", () => {
21
+ const result = generateScale(seed, { context: "light", surface: "surface" });
22
+ result.forEach((step) => {
23
+ expect(step.h).toBeCloseTo(seed.h, 6);
24
+ });
25
+ });
26
+ it("never produces negative chroma", () => {
27
+ const result = generateScale(seed, { context: "light", surface: "surface" });
28
+ result.forEach((step) => {
29
+ expect(step.c).toBeGreaterThanOrEqual(0);
30
+ });
31
+ });
32
+ });
@@ -0,0 +1,8 @@
1
+ export type { EngineContext } from "./context.js";
2
+ export { mapColorContextToEngine } from "./context.js";
3
+ export type { OkLchColor } from "./generateScale.js";
4
+ export { generateScale } from "./generateScale.js";
5
+ export type { NormalizedOnSolidQuery, NormalizedQuery } from "./normalize.js";
6
+ export { normalizeOnSolidQuery, normalizeQuery } from "./normalize.js";
7
+ export type { BaseResolvedColor, ThemeConfig } from "./resolveBaseColor.js";
8
+ export { resolveBaseColor } from "./resolveBaseColor.js";
@@ -0,0 +1,4 @@
1
+ export { mapColorContextToEngine } from "./context.js";
2
+ export { generateScale } from "./generateScale.js";
3
+ export { normalizeOnSolidQuery, normalizeQuery } from "./normalize.js";
4
+ export { resolveBaseColor } from "./resolveBaseColor.js";
@@ -0,0 +1,43 @@
1
+ import type { ColorQuery, ColorState, OnSolidQuery, OutputOptions } from "../types/index.js";
2
+ export type NormalizedQuery = Required<Pick<ColorQuery, "role" | "usage" | "context" | "surface" | "state" | "emphasis">> & {
3
+ variant?: ColorQuery["variant"];
4
+ on?: ColorQuery["on"];
5
+ contrast?: ColorQuery["contrast"];
6
+ alpha?: ColorQuery["alpha"];
7
+ output: Required<Omit<OutputOptions, "format">>;
8
+ };
9
+ export type NormalizedOnSolidQuery = Required<Pick<OnSolidQuery, "bgRole" | "usage" | "context" | "state" | "emphasis">> & {
10
+ alpha?: OnSolidQuery["alpha"];
11
+ contrast?: OnSolidQuery["contrast"];
12
+ output: Required<Omit<OutputOptions, "format">>;
13
+ };
14
+ export declare const COLOR_STATES: readonly ColorState[];
15
+ /**
16
+ * Normalize a user-facing ColorQuery into a fully populated, validated structure.
17
+ *
18
+ * - Applies defaults for missing fields (context, surface, state, emphasis, output).
19
+ * - Infers usage and surface from role naming patterns when not provided.
20
+ * - In strict mode, missing required fields throw actionable errors.
21
+ * - In non-strict mode, safe defaults are applied with explicit warnings.
22
+ * - Validates nested objects (background hints, contrast requirements, alpha strategies).
23
+ * - Trims string inputs and enforces allowed enum values.
24
+ *
25
+ * @example
26
+ * normalizeQuery({ role: "text.primary" });
27
+ * @example
28
+ * normalizeQuery({
29
+ * role: "bg.canvas",
30
+ * on: { kind: "color", value: "#fff" },
31
+ * contrast: { model: "apca", targetLc: 60 },
32
+ * output: { strict: true },
33
+ * });
34
+ */
35
+ export declare function normalizeQuery(q: ColorQuery): NormalizedQuery;
36
+ /**
37
+ * Normalize a user-facing OnSolidQuery into a fully populated, validated structure.
38
+ *
39
+ * - Applies defaults for missing fields (context, state, emphasis, output).
40
+ * - Validates usage ("text" | "icon") and required background role.
41
+ * - Validates nested objects (contrast requirements, alpha strategies).
42
+ */
43
+ export declare function normalizeOnSolidQuery(q: OnSolidQuery): NormalizedOnSolidQuery;
@@ -0,0 +1,403 @@
1
+ const usages = ["bg", "border", "text", "icon", "ring", "shadow", "stroke", "fill"];
2
+ const onSolidUsages = ["text", "icon"];
3
+ const contexts = ["light", "dark", "highContrast", "dimmed"];
4
+ const surfaces = [
5
+ "app",
6
+ "surface",
7
+ "subtle",
8
+ "solid",
9
+ "overlay",
10
+ "data",
11
+ "transparent",
12
+ ];
13
+ export const COLOR_STATES = [
14
+ "default",
15
+ "hover",
16
+ "active",
17
+ "selected",
18
+ "focus",
19
+ "disabled",
20
+ ];
21
+ const emphases = ["muted", "subtle", "default", "strong", "inverted"];
22
+ const semanticVariants = [
23
+ "neutral",
24
+ "accent",
25
+ "success",
26
+ "warning",
27
+ "danger",
28
+ "info",
29
+ "highlight",
30
+ "premium",
31
+ ];
32
+ const colorSpaces = ["srgb", "p3", "oklch"];
33
+ const gamutMappings = [
34
+ "clip",
35
+ "compressChroma",
36
+ "preferP3ThenCompress",
37
+ ];
38
+ const srgbFormats = ["hex", "rgb", "rgba"];
39
+ const formatString = (value) => (value ? value.trim() : undefined);
40
+ const assertOneOf = (value, options, label) => {
41
+ if (!options.includes(value)) {
42
+ throw new Error(`Invalid ${label}: "${value}"`);
43
+ }
44
+ return value;
45
+ };
46
+ const normalizeRole = (role) => {
47
+ if (role === undefined) {
48
+ throw new Error("Color role is required");
49
+ }
50
+ const trimmed = role.trim();
51
+ if (!trimmed) {
52
+ throw new Error("Color role is required");
53
+ }
54
+ return trimmed;
55
+ };
56
+ const normalizeBgRole = (role) => {
57
+ if (role === undefined) {
58
+ throw new Error("Background role (bgRole) is required");
59
+ }
60
+ const trimmed = role.trim();
61
+ if (!trimmed) {
62
+ throw new Error("Background role (bgRole) is required");
63
+ }
64
+ return trimmed;
65
+ };
66
+ const hexColorPattern = /^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})$/;
67
+ const inferUsageFromRole = (role) => {
68
+ const normalizedRole = role.trim().toLowerCase();
69
+ if (normalizedRole.startsWith("text.")) {
70
+ return "text";
71
+ }
72
+ if (normalizedRole.startsWith("icon.")) {
73
+ return "icon";
74
+ }
75
+ if (normalizedRole.startsWith("border.")) {
76
+ return "border";
77
+ }
78
+ if (normalizedRole.startsWith("bg.") ||
79
+ normalizedRole.startsWith("surface.") ||
80
+ normalizedRole.startsWith("overlay.")) {
81
+ return "bg";
82
+ }
83
+ if (normalizedRole.startsWith("focus.") || normalizedRole.startsWith("ring.")) {
84
+ return "ring";
85
+ }
86
+ if (normalizedRole.startsWith("chart.")) {
87
+ const tokens = normalizedRole.split(".");
88
+ if (tokens.includes("stroke")) {
89
+ return "stroke";
90
+ }
91
+ if (tokens.includes("fill")) {
92
+ return "fill";
93
+ }
94
+ if (tokens.includes("grid")) {
95
+ return "border";
96
+ }
97
+ if (tokens.includes("label") || tokens.includes("text")) {
98
+ return "text";
99
+ }
100
+ }
101
+ return undefined;
102
+ };
103
+ /**
104
+ * Infer surface intent from role naming patterns.
105
+ *
106
+ * Recognizes:
107
+ * - Direct surface token prefixes: `"app.*"`, `"surface.*"`, `"solid.*"`, etc.
108
+ * - Background patterns: `"bg.app"`, `"bg.surface"`, `"bg.solid"`, etc.
109
+ *
110
+ * @example
111
+ * inferSurfaceFromRole("bg.app") // "app"
112
+ * @example
113
+ * inferSurfaceFromRole("app.bg") // "app"
114
+ */
115
+ const inferSurfaceFromRole = (role) => {
116
+ const normalizedRole = role.trim().toLowerCase();
117
+ const tokens = normalizedRole.split(".");
118
+ const [first, second] = tokens;
119
+ if (first && surfaces.includes(first)) {
120
+ return first;
121
+ }
122
+ if (first === "bg" && second && surfaces.includes(second)) {
123
+ return second;
124
+ }
125
+ return undefined;
126
+ };
127
+ /**
128
+ * Infer semantic variant from role token.
129
+ *
130
+ * Recognizes:
131
+ * - Semantic variants: `"neutral"`, `"accent"`, `"success"`, `"warning"`, etc.
132
+ * - Custom categories: `"category:*"`
133
+ * - Chart variants: `"chart:*"`
134
+ *
135
+ * @example
136
+ * inferVariantFromRole("success.bg") // "success"
137
+ * @example
138
+ * inferVariantFromRole("category:sales.fill") // "category:sales"
139
+ */
140
+ const inferVariantFromRole = (role) => {
141
+ const token = role.trim().split(".")[0];
142
+ const normalized = token?.toLowerCase();
143
+ if (!normalized) {
144
+ return undefined;
145
+ }
146
+ if (semanticVariants.includes(normalized)) {
147
+ return normalized;
148
+ }
149
+ if (/^(category|chart):.+/.test(normalized)) {
150
+ return normalized;
151
+ }
152
+ return undefined;
153
+ };
154
+ const normalizeVariant = (variant) => {
155
+ if (!variant) {
156
+ return undefined;
157
+ }
158
+ const trimmed = variant.trim();
159
+ if (semanticVariants.includes(trimmed)) {
160
+ return trimmed;
161
+ }
162
+ if (/^(category|chart):.+/.test(trimmed)) {
163
+ return trimmed;
164
+ }
165
+ throw new Error(`Invalid variant: "${variant}"`);
166
+ };
167
+ const warn = (message) => {
168
+ console.warn(message);
169
+ };
170
+ /**
171
+ * Cache used to deduplicate inference warnings.
172
+ *
173
+ * Notes:
174
+ * - This is intentionally module-scoped so repeated calls don't spam logs.
175
+ * - To avoid unbounded growth in long-running processes, this cache is capped
176
+ * and clears itself when the cap is reached.
177
+ */
178
+ const inferenceWarnings = new Set();
179
+ const MAX_INFERENCE_WARNINGS = 1000;
180
+ const warnInferenceOnce = (key, message) => {
181
+ if (inferenceWarnings.has(key))
182
+ return;
183
+ if (inferenceWarnings.size >= MAX_INFERENCE_WARNINGS) {
184
+ inferenceWarnings.clear();
185
+ }
186
+ inferenceWarnings.add(key);
187
+ console.warn(message);
188
+ };
189
+ const missingUsageMessage = (role) => `Usage is required for role: "${role}". Provide usage explicitly (e.g. { usage: "text" }) or use a role prefix like "text.", "icon.", "bg.", "border.", "ring."`;
190
+ const missingSurfaceMessage = (role) => `Surface is required for role: "${role}". Provide surface explicitly (e.g. { surface: "surface" }) or use a role pattern like "bg.app", "bg.surface", "app.*"`;
191
+ const normalizeBackgroundHint = (hint, strict) => {
192
+ if (!hint) {
193
+ return undefined;
194
+ }
195
+ if (hint.kind === "auto") {
196
+ return hint;
197
+ }
198
+ if (hint.kind === "role") {
199
+ const trimmedRole = normalizeRole(hint.role);
200
+ return { kind: "role", role: trimmedRole };
201
+ }
202
+ if (hint.kind === "color") {
203
+ const value = hint.value.trim();
204
+ if (!value) {
205
+ throw new Error("Background hint color value is required");
206
+ }
207
+ if (!hexColorPattern.test(value)) {
208
+ if (strict) {
209
+ throw new Error(`Invalid background hint color value: "${hint.value}"`);
210
+ }
211
+ warn(`Unvalidated background hint color value: "${hint.value}"`);
212
+ }
213
+ return { kind: "color", value };
214
+ }
215
+ throw new Error(`Invalid background hint kind: "${hint.kind}"`);
216
+ };
217
+ const normalizeContrast = (contrast) => {
218
+ if (!contrast) {
219
+ return undefined;
220
+ }
221
+ if (contrast.model === "apca") {
222
+ if (!Number.isFinite(contrast.targetLc)) {
223
+ throw new Error("APCA targetLc must be a number");
224
+ }
225
+ if (contrast.minLc !== undefined && !Number.isFinite(contrast.minLc)) {
226
+ throw new Error("APCA minLc must be a number");
227
+ }
228
+ if (contrast.maxLc !== undefined && !Number.isFinite(contrast.maxLc)) {
229
+ throw new Error("APCA maxLc must be a number");
230
+ }
231
+ // Validate logical relationships between APCA contrast bounds
232
+ if (contrast.minLc !== undefined && contrast.maxLc !== undefined) {
233
+ if (contrast.minLc > contrast.maxLc) {
234
+ throw new Error("APCA minLc cannot be greater than maxLc");
235
+ }
236
+ }
237
+ if (contrast.minLc !== undefined && contrast.minLc > contrast.targetLc) {
238
+ throw new Error("APCA minLc cannot be greater than targetLc");
239
+ }
240
+ if (contrast.maxLc !== undefined && contrast.targetLc > contrast.maxLc) {
241
+ throw new Error("APCA targetLc cannot be greater than maxLc");
242
+ }
243
+ return contrast;
244
+ }
245
+ if (contrast.model === "wcag2") {
246
+ const minRatio = "minRatio" in contrast ? contrast.minRatio : contrast.ratio;
247
+ if (minRatio === undefined) {
248
+ throw new Error("WCAG2 contrast requires either 'minRatio' or legacy 'ratio' property");
249
+ }
250
+ if (!Number.isFinite(minRatio)) {
251
+ throw new Error("WCAG2 minRatio must be a number");
252
+ }
253
+ return { model: "wcag2", minRatio };
254
+ }
255
+ if (contrast.model === "none") {
256
+ return contrast;
257
+ }
258
+ throw new Error(`Invalid contrast model: "${contrast.model}"`);
259
+ };
260
+ const validateIncludeSpaces = (includeSpaces) => {
261
+ const value = includeSpaces ?? [];
262
+ value.forEach((space) => {
263
+ assertOneOf(space, colorSpaces, "output includeSpaces");
264
+ });
265
+ return value;
266
+ };
267
+ const normalizeAlpha = (alpha) => {
268
+ if (!alpha) {
269
+ return undefined;
270
+ }
271
+ if (alpha.mode === "none") {
272
+ return alpha;
273
+ }
274
+ if (alpha.mode === "fixed") {
275
+ if (!Number.isFinite(alpha.alpha)) {
276
+ throw new Error("Fixed alpha must be a number");
277
+ }
278
+ return alpha;
279
+ }
280
+ if (alpha.mode === "solveOnBackground") {
281
+ return alpha;
282
+ }
283
+ throw new Error(`Invalid alpha strategy mode: "${alpha.mode}"`);
284
+ };
285
+ const normalizeOutput = (output) => {
286
+ const preferSpaceValue = formatString(output?.preferSpace);
287
+ const gamutMappingValue = formatString(output?.gamutMapping);
288
+ const srgbFormatValue = formatString(output?.srgbFormat);
289
+ const includeSpaces = validateIncludeSpaces(output?.includeSpaces);
290
+ const preferSpace = preferSpaceValue
291
+ ? assertOneOf(preferSpaceValue, colorSpaces, "output preferSpace")
292
+ : "oklch";
293
+ const gamutMapping = gamutMappingValue
294
+ ? assertOneOf(gamutMappingValue, gamutMappings, "output gamutMapping")
295
+ : "preferP3ThenCompress";
296
+ const srgbFormat = srgbFormatValue
297
+ ? assertOneOf(srgbFormatValue, srgbFormats, "output srgbFormat")
298
+ : "hex";
299
+ if (output?.strict !== undefined && typeof output.strict !== "boolean") {
300
+ throw new Error("Output strict must be a boolean");
301
+ }
302
+ if (output?.includeMeta !== undefined && typeof output.includeMeta !== "boolean") {
303
+ throw new Error("Output includeMeta must be a boolean");
304
+ }
305
+ return {
306
+ preferSpace,
307
+ includeSpaces,
308
+ gamutMapping,
309
+ strict: output?.strict ?? false,
310
+ precision: {
311
+ l: 1,
312
+ c: 3,
313
+ h: 1,
314
+ ...output?.precision,
315
+ },
316
+ includeMeta: output?.includeMeta ?? false,
317
+ srgbFormat,
318
+ };
319
+ };
320
+ /**
321
+ * Normalize a user-facing ColorQuery into a fully populated, validated structure.
322
+ *
323
+ * - Applies defaults for missing fields (context, surface, state, emphasis, output).
324
+ * - Infers usage and surface from role naming patterns when not provided.
325
+ * - In strict mode, missing required fields throw actionable errors.
326
+ * - In non-strict mode, safe defaults are applied with explicit warnings.
327
+ * - Validates nested objects (background hints, contrast requirements, alpha strategies).
328
+ * - Trims string inputs and enforces allowed enum values.
329
+ *
330
+ * @example
331
+ * normalizeQuery({ role: "text.primary" });
332
+ * @example
333
+ * normalizeQuery({
334
+ * role: "bg.canvas",
335
+ * on: { kind: "color", value: "#fff" },
336
+ * contrast: { model: "apca", targetLc: 60 },
337
+ * output: { strict: true },
338
+ * });
339
+ */
340
+ export function normalizeQuery(q) {
341
+ const role = normalizeRole(formatString(q.role));
342
+ const contextValue = formatString(q.context) ?? "light";
343
+ const inferredSurface = inferSurfaceFromRole(role);
344
+ const surfaceValue = formatString(q.surface) ?? inferredSurface ?? "surface";
345
+ const stateValue = formatString(q.state) ?? "default";
346
+ const emphasisValue = formatString(q.emphasis) ?? "default";
347
+ const output = normalizeOutput(q.output);
348
+ const usageValue = formatString(q.usage) ?? inferUsageFromRole(role);
349
+ const variantValue = formatString(q.variant) ?? inferVariantFromRole(role);
350
+ if (!usageValue) {
351
+ if (output.strict) {
352
+ throw new Error(missingUsageMessage(role));
353
+ }
354
+ warnInferenceOnce(`usage:${role}`, `Defaulting usage to "bg" for role: "${role}". ${missingUsageMessage(role)}`);
355
+ }
356
+ if (!formatString(q.surface) && !inferredSurface) {
357
+ if (output.strict) {
358
+ throw new Error(missingSurfaceMessage(role));
359
+ }
360
+ warnInferenceOnce(`surface:${role}`, `Defaulting surface to "surface" for role: "${role}". ${missingSurfaceMessage(role)}`);
361
+ }
362
+ return {
363
+ role,
364
+ usage: assertOneOf(usageValue ?? "bg", usages, "usage"),
365
+ context: assertOneOf(contextValue, contexts, "context"),
366
+ surface: assertOneOf(surfaceValue, surfaces, "surface"),
367
+ state: assertOneOf(stateValue, COLOR_STATES, "state"),
368
+ emphasis: assertOneOf(emphasisValue, emphases, "emphasis"),
369
+ variant: normalizeVariant(variantValue),
370
+ on: normalizeBackgroundHint(q.on, output.strict),
371
+ contrast: normalizeContrast(q.contrast),
372
+ alpha: normalizeAlpha(q.alpha),
373
+ output,
374
+ };
375
+ }
376
+ /**
377
+ * Normalize a user-facing OnSolidQuery into a fully populated, validated structure.
378
+ *
379
+ * - Applies defaults for missing fields (context, state, emphasis, output).
380
+ * - Validates usage ("text" | "icon") and required background role.
381
+ * - Validates nested objects (contrast requirements, alpha strategies).
382
+ */
383
+ export function normalizeOnSolidQuery(q) {
384
+ const bgRole = normalizeBgRole(formatString(q.bgRole));
385
+ const usageValue = formatString(q.usage);
386
+ const contextValue = formatString(q.context) ?? "light";
387
+ const stateValue = formatString(q.state) ?? "default";
388
+ const emphasisValue = formatString(q.emphasis) ?? "default";
389
+ const output = normalizeOutput(q.output);
390
+ if (!usageValue) {
391
+ throw new Error("On-solid usage is required (text or icon)");
392
+ }
393
+ return {
394
+ bgRole,
395
+ usage: assertOneOf(usageValue, onSolidUsages, "onSolid usage"),
396
+ context: assertOneOf(contextValue, contexts, "context"),
397
+ state: assertOneOf(stateValue, COLOR_STATES, "state"),
398
+ emphasis: assertOneOf(emphasisValue, emphases, "emphasis"),
399
+ contrast: normalizeContrast(q.contrast),
400
+ alpha: normalizeAlpha(q.alpha),
401
+ output,
402
+ };
403
+ }
@@ -0,0 +1 @@
1
+ export {};