@paulperigault/tokens 0.0.0 → 0.1.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 (64) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +37 -0
  3. package/dist/customize/derive-overrides.d.ts +13 -0
  4. package/dist/customize/derive-overrides.js +40 -0
  5. package/dist/customize/derive-roles.d.ts +16 -0
  6. package/dist/customize/derive-roles.js +38 -0
  7. package/dist/customize/font-stack.d.ts +5 -0
  8. package/dist/customize/font-stack.js +26 -0
  9. package/dist/customize/hue.d.ts +8 -0
  10. package/dist/customize/hue.js +20 -0
  11. package/dist/customize/index.d.ts +8 -0
  12. package/dist/customize/index.js +5 -0
  13. package/dist/customize/input.d.ts +11 -0
  14. package/dist/customize/input.js +26 -0
  15. package/dist/customize/result.d.ts +16 -0
  16. package/dist/customize/result.js +18 -0
  17. package/dist/customize/settle.d.ts +8 -0
  18. package/dist/customize/settle.js +16 -0
  19. package/dist/lib/color-data.d.ts +30 -0
  20. package/dist/lib/color-data.js +28 -0
  21. package/dist/lib/color.d.ts +24 -0
  22. package/dist/lib/color.js +105 -0
  23. package/dist/lib/contrast.d.ts +13 -0
  24. package/dist/lib/contrast.js +90 -0
  25. package/dist/palette/domain/categorical.d.ts +7 -0
  26. package/dist/palette/domain/categorical.js +42 -0
  27. package/dist/palette/domain/color/cvd.d.ts +18 -0
  28. package/dist/palette/domain/color/cvd.js +29 -0
  29. package/dist/palette/domain/color/delta-e.d.ts +2 -0
  30. package/dist/palette/domain/color/delta-e.js +73 -0
  31. package/dist/palette/domain/color/gamut.d.ts +5 -0
  32. package/dist/palette/domain/color/gamut.js +24 -0
  33. package/dist/palette/domain/color/lab.d.ts +8 -0
  34. package/dist/palette/domain/color/lab.js +21 -0
  35. package/dist/palette/domain/color/vision.d.ts +11 -0
  36. package/dist/palette/domain/color/vision.js +28 -0
  37. package/dist/palette/domain/derive.d.ts +8 -0
  38. package/dist/palette/domain/derive.js +55 -0
  39. package/dist/palette/domain/ink.d.ts +12 -0
  40. package/dist/palette/domain/ink.js +13 -0
  41. package/dist/palette/domain/ramps.d.ts +8 -0
  42. package/dist/palette/domain/ramps.js +43 -0
  43. package/dist/palette/domain/result.d.ts +10 -0
  44. package/dist/palette/domain/result.js +6 -0
  45. package/dist/palette/domain/thresholds.d.ts +12 -0
  46. package/dist/palette/domain/thresholds.js +12 -0
  47. package/dist/palette/domain/tokens.d.ts +6 -0
  48. package/dist/palette/domain/tokens.js +25 -0
  49. package/dist/palette/domain/types.d.ts +22 -0
  50. package/dist/palette/domain/types.js +1 -0
  51. package/dist/palette/errors.d.ts +10 -0
  52. package/dist/palette/errors.js +14 -0
  53. package/dist/palette/index.d.ts +10 -0
  54. package/dist/palette/index.js +6 -0
  55. package/dist/palette/infrastructure/guards.d.ts +2 -0
  56. package/dist/palette/infrastructure/guards.js +1 -0
  57. package/dist/palette/infrastructure/series-ink.d.ts +12 -0
  58. package/dist/palette/infrastructure/series-ink.js +30 -0
  59. package/dist/palette/infrastructure/theme-base.d.ts +7 -0
  60. package/dist/palette/infrastructure/theme-base.js +44 -0
  61. package/generated/tokens.css +92 -0
  62. package/generated/tokens.d.ts +73 -0
  63. package/generated/tokens.json +223 -0
  64. package/package.json +66 -1
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Paul Perigault
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,37 @@
1
+ # @paulperigault/tokens
2
+
3
+ Design tokens DTCG 2025.10 de paulperigault.fr : CSS, JSON et types générés ; couleur et contraste.
4
+
5
+ Statut : en construction (0.0.0). Voir le [README du dépôt](../../README.md).
6
+
7
+ ## Entrées du build : teinte d'accent et pile de police
8
+
9
+ Contrat d'un projet externe (ADR-0006 décision 3, ADR-0007 décision 4) :
10
+
11
+ | Entrée | Valeur | Sorties régénérées |
12
+ | ----------------- | --------------------------------------------- | ---------------------------------------------------------------------------------- |
13
+ | `--pp-accent-hue` | degrés OKLCH, 0 à 360 (nombre ou texte) | `--pp-color-accent`, `--pp-chart-1` à `6` (clair et sombre), `on-accent` reconduit |
14
+ | `--pp-font-stack` | liste de familles CSS, 256 caractères au plus | `--pp-font-family-sans` (`--pp-font-family-mono` ne change pas) |
15
+
16
+ Clarté et chroma de l'accent sont fixés par le système (clair `oklch(47% 0.19 h)`, sombre
17
+ `oklch(78% 0.1 h)`) ; les neutres d'Encre restent à la teinte 270,7. Sans entrée, la sortie est
18
+ identique octet pour octet à `generated/`.
19
+
20
+ ```
21
+ node scripts/build.ts --accent-hue 145 --font-stack "'Inter Variable', system-ui, sans-serif" --out-dir ./theme
22
+ ```
23
+
24
+ Une variante s'écrit toujours hors de `generated/` (`--out-dir` obligatoire, `--check` refusé).
25
+ En code : `parseBuildInput` et `deriveOverrides` (`@paulperigault/tokens/customize`) rendent un
26
+ `Result` ; jamais de `throw`. Erreurs (`error.code`) :
27
+
28
+ - teinte : `build.hue-missing`, `build.hue-not-finite`, `build.hue-out-of-range` ;
29
+ - dérivation : `build.contrast-failed` (texte sur accent) et `build.role-contrast-failed` (focus
30
+ et statut « en cours » sous leur seuil), teinte, thème et rapport mesuré dans le message ;
31
+ `build.derivation-failed` ;
32
+ - pile : `build.stack-empty`, `build.stack-too-long`, `build.stack-unsafe` (`;`, accolades,
33
+ `url(`, `@import`, retours à la ligne, commentaires, guillemets ou parenthèses non appariés) ;
34
+ - ligne de commande : `build.bad-usage`.
35
+
36
+ Limites : les rampes `--pp-chart-seq-*` et `--pp-chart-div-*` sont dérivées mais pas émises (le
37
+ défaut ne les porte pas). Décisions : D-056, D-057.
@@ -0,0 +1,13 @@
1
+ import type { TokenMap } from '../palette/domain/tokens.ts';
2
+ import type { Theme } from '../palette/domain/types.ts';
3
+ import type { ThemeSource } from './derive-roles.ts';
4
+ import type { Result } from './result.ts';
5
+ export declare const THEME_NAMES: readonly Theme[];
6
+ /** Variables d'un thème (accent, texte sur accent, séries, rampes, focus, statut) en `oklch(...)`. */
7
+ export type ThemeOverrides = Readonly<Record<Theme, TokenMap>>;
8
+ /**
9
+ * Dérive les variables des deux thèmes depuis la teinte. Les bases (clarté, chroma de l'accent,
10
+ * neutres, focus, statut) viennent des jetons : seule la teinte change, les neutres restent à leur
11
+ * teinte.
12
+ */
13
+ export declare function deriveOverrides(hue: number, bases: Readonly<Record<Theme, ThemeSource>>): Result<ThemeOverrides>;
@@ -0,0 +1,40 @@
1
+ import { contrastRatio } from "../lib/contrast.js";
2
+ import { fitToGamut } from "../palette/domain/color/gamut.js";
3
+ import { derivePalettes } from "../palette/domain/derive.js";
4
+ import { paletteTokens } from "../palette/domain/tokens.js";
5
+ import { deriveRoles } from "./derive-roles.js";
6
+ import { settleAll } from "./settle.js";
7
+ import { fail, ok } from "./result.js";
8
+ export const THEME_NAMES = ['light', 'dark'];
9
+ const RATIO_DIGITS = 2;
10
+ function withRoles(palettes, theme, source) {
11
+ const roles = deriveRoles(palettes.hue, theme, source);
12
+ if (!roles.ok)
13
+ return roles;
14
+ return ok({ ...settleAll(paletteTokens(palettes)), ...roles.value });
15
+ }
16
+ function deriveTheme(hue, theme, source) {
17
+ const palettes = derivePalettes(hue, theme, source);
18
+ if (palettes.ok)
19
+ return withRoles(palettes.value, theme, source);
20
+ const { code, message } = palettes.error;
21
+ if (code === 'palette.contrast-failed') {
22
+ const ratio = contrastRatio(source.onAccent, fitToGamut({ ...source.accent, h: hue })).toFixed(RATIO_DIGITS);
23
+ return fail('build.contrast-failed', `Teinte ${hue}, thème ${theme} : texte sur accent à ${ratio}:1, 4,5:1 exigé.`);
24
+ }
25
+ return fail('build.derivation-failed', `Teinte ${hue}, thème ${theme} : ${message}`);
26
+ }
27
+ /**
28
+ * Dérive les variables des deux thèmes depuis la teinte. Les bases (clarté, chroma de l'accent,
29
+ * neutres, focus, statut) viennent des jetons : seule la teinte change, les neutres restent à leur
30
+ * teinte.
31
+ */
32
+ export function deriveOverrides(hue, bases) {
33
+ const light = deriveTheme(hue, 'light', bases.light);
34
+ if (!light.ok)
35
+ return light;
36
+ const dark = deriveTheme(hue, 'dark', bases.dark);
37
+ if (!dark.ok)
38
+ return dark;
39
+ return ok({ light: light.value, dark: dark.value });
40
+ }
@@ -0,0 +1,16 @@
1
+ import type { Oklch } from '../lib/color.ts';
2
+ import type { TokenMap } from '../palette/domain/tokens.ts';
3
+ import type { Theme, ThemeBase } from '../palette/domain/types.ts';
4
+ import type { Result } from './result.ts';
5
+ /** Rôles qui portent la teinte d'accent, et surface contre laquelle ils sont mesurés. */
6
+ export interface RoleBase {
7
+ readonly focus: Oklch;
8
+ readonly running: Oklch;
9
+ readonly surface: Oklch;
10
+ }
11
+ export type ThemeSource = ThemeBase & RoleBase;
12
+ /**
13
+ * Dérive focus et statut « en cours » : clarté et chroma des jetons, teinte de l'accent (déjà
14
+ * normalisée par la dérivation des palettes). Le contraste est mesuré sur la valeur émise.
15
+ */
16
+ export declare function deriveRoles(hue: number, theme: Theme, source: ThemeSource): Result<TokenMap>;
@@ -0,0 +1,38 @@
1
+ import { formatOklch, parseOklch } from "../lib/color.js";
2
+ import { contrastRatio } from "../lib/contrast.js";
3
+ import { fitToGamut } from "../palette/domain/color/gamut.js";
4
+ import { MIN_GRAPHIC_CONTRAST, MIN_TEXT_CONTRAST } from "../palette/domain/thresholds.js";
5
+ import { fail, ok } from "./result.js";
6
+ import { settle } from "./settle.js";
7
+ const RATIO_DIGITS = 2;
8
+ /** Seuils de `roles.json` : anneau de focus 1.4.11 (3:1), statut en texte 1.4.3 (4,5:1). */
9
+ const ROLES = [
10
+ { token: '--pp-color-focus', key: 'focus', min: MIN_GRAPHIC_CONTRAST },
11
+ { token: '--pp-color-status-running', key: 'running', min: MIN_TEXT_CONTRAST },
12
+ ];
13
+ function measure(token, color, min, grounds) {
14
+ return grounds
15
+ .map(([name, ground]) => [name, contrastRatio(color, ground)])
16
+ .filter(([, ratio]) => ratio < min)
17
+ .map(([name, ratio]) => `${token} à ${ratio.toFixed(RATIO_DIGITS)}:1 sur ${name}, ${min}:1`);
18
+ }
19
+ /**
20
+ * Dérive focus et statut « en cours » : clarté et chroma des jetons, teinte de l'accent (déjà
21
+ * normalisée par la dérivation des palettes). Le contraste est mesuré sur la valeur émise.
22
+ */
23
+ export function deriveRoles(hue, theme, source) {
24
+ const tokens = {};
25
+ const failures = [];
26
+ const grounds = [
27
+ ['le fond', source.bg],
28
+ ['la surface', source.surface],
29
+ ];
30
+ for (const { token, key, min } of ROLES) {
31
+ const value = settle(formatOklch(fitToGamut({ ...source[key], h: hue })));
32
+ tokens[token] = value;
33
+ failures.push(...measure(token, parseOklch(value), min, grounds));
34
+ }
35
+ if (failures.length === 0)
36
+ return ok(tokens);
37
+ return fail('build.role-contrast-failed', `Teinte ${hue}, thème ${theme} : ${failures.join(' ; ')} exigé.`);
38
+ }
@@ -0,0 +1,5 @@
1
+ import type { Result } from './result.ts';
2
+ /** Convention : une pile de quelques familles tient bien sous cette longueur. */
3
+ export declare const MAX_STACK_LENGTH = 256;
4
+ /** Pile de police du texte (`--pp-font-stack`) : liste de familles CSS, nettoyée des espaces. */
5
+ export declare function parseFontStack(raw: unknown): Result<string>;
@@ -0,0 +1,26 @@
1
+ import { fail, ok } from "./result.js";
2
+ /** Convention : une pile de quelques familles tient bien sous cette longueur. */
3
+ export const MAX_STACK_LENGTH = 256;
4
+ /** Ce qui sortirait d'une déclaration CSS : fin de déclaration, bloc, ressource, commentaire. */
5
+ const FORBIDDEN = /[;{}\r\n\p{Zl}\p{Zp}]|url\(|@import|\/\*|\*\//iu;
6
+ const PAIR = 2;
7
+ const QUOTES = ["'", '"'];
8
+ const countOf = (text, char) => text.split(char).length - 1;
9
+ /** Guillemets et parenthèses appariés : sinon la valeur déborde sur la déclaration suivante. */
10
+ function balanced(text) {
11
+ const quotes = QUOTES.every((quote) => countOf(text, quote) % PAIR === 0);
12
+ return quotes && countOf(text, '(') === countOf(text, ')');
13
+ }
14
+ /** Pile de police du texte (`--pp-font-stack`) : liste de familles CSS, nettoyée des espaces. */
15
+ export function parseFontStack(raw) {
16
+ const text = typeof raw === 'string' ? raw.trim() : '';
17
+ if (text === '')
18
+ return fail('build.stack-empty', '--pp-font-stack : pile vide.');
19
+ if (text.length > MAX_STACK_LENGTH) {
20
+ return fail('build.stack-too-long', `--pp-font-stack : ${text.length} caractères, ${MAX_STACK_LENGTH} au plus.`);
21
+ }
22
+ if (FORBIDDEN.test(text) || !balanced(text)) {
23
+ return fail('build.stack-unsafe', '--pp-font-stack : caractères hors d’une déclaration CSS.');
24
+ }
25
+ return ok(text);
26
+ }
@@ -0,0 +1,8 @@
1
+ import type { Result } from './result.ts';
2
+ export declare const MIN_HUE = 0;
3
+ export declare const MAX_HUE = 360;
4
+ /**
5
+ * Teinte d'accent en degrés OKLCH, dans [0, 360]. Accepte un nombre ou son écriture décimale
6
+ * (argument de ligne de commande) ; une valeur vide ou absente est refusée.
7
+ */
8
+ export declare function parseAccentHue(raw: unknown): Result<number>;
@@ -0,0 +1,20 @@
1
+ import { fail, ok } from "./result.js";
2
+ export const MIN_HUE = 0;
3
+ export const MAX_HUE = 360;
4
+ const isBlank = (raw) => raw === undefined || raw === null || (typeof raw === 'string' && raw.trim() === '');
5
+ /**
6
+ * Teinte d'accent en degrés OKLCH, dans [0, 360]. Accepte un nombre ou son écriture décimale
7
+ * (argument de ligne de commande) ; une valeur vide ou absente est refusée.
8
+ */
9
+ export function parseAccentHue(raw) {
10
+ if (isBlank(raw))
11
+ return fail('build.hue-missing', '--pp-accent-hue : teinte absente.');
12
+ const hue = typeof raw === 'string' ? Number(raw) : raw;
13
+ if (typeof hue !== 'number' || !Number.isFinite(hue)) {
14
+ return fail('build.hue-not-finite', `--pp-accent-hue : « ${String(raw)} » n'est pas fini.`);
15
+ }
16
+ if (hue < MIN_HUE || hue > MAX_HUE) {
17
+ return fail('build.hue-out-of-range', `--pp-accent-hue : ${hue} hors de ${MIN_HUE} à ${MAX_HUE} degrés.`);
18
+ }
19
+ return ok(hue);
20
+ }
@@ -0,0 +1,8 @@
1
+ export type { CustomizeError, CustomizeErrorCode, Result } from './result.ts';
2
+ export { CUSTOMIZE_ERROR_CODES } from './result.ts';
3
+ export { MAX_HUE, MIN_HUE, parseAccentHue } from './hue.ts';
4
+ export { MAX_STACK_LENGTH, parseFontStack } from './font-stack.ts';
5
+ export type { BuildInput } from './input.ts';
6
+ export { parseBuildInput } from './input.ts';
7
+ export type { ThemeOverrides } from './derive-overrides.ts';
8
+ export { deriveOverrides, THEME_NAMES } from './derive-overrides.ts';
@@ -0,0 +1,5 @@
1
+ export { CUSTOMIZE_ERROR_CODES } from "./result.js";
2
+ export { MAX_HUE, MIN_HUE, parseAccentHue } from "./hue.js";
3
+ export { MAX_STACK_LENGTH, parseFontStack } from "./font-stack.js";
4
+ export { parseBuildInput } from "./input.js";
5
+ export { deriveOverrides, THEME_NAMES } from "./derive-overrides.js";
@@ -0,0 +1,11 @@
1
+ import type { Result } from './result.ts';
2
+ /** Entrées validées : une entrée absente garde la valeur par défaut des sources DTCG. */
3
+ export interface BuildInput {
4
+ readonly accentHue?: number;
5
+ readonly fontStack?: string;
6
+ }
7
+ /**
8
+ * Entrées brutes `{ accentHue?, fontStack? }` → entrées validées. Pas d'entrée, ou clé absente :
9
+ * défaut. Clé présente mais vide ou `undefined` : erreur (teinte absente, pile vide).
10
+ */
11
+ export declare function parseBuildInput(raw: unknown): Result<BuildInput>;
@@ -0,0 +1,26 @@
1
+ import { parseAccentHue } from "./hue.js";
2
+ import { parseFontStack } from "./font-stack.js";
3
+ import { ok } from "./result.js";
4
+ const isRecord = (value) => typeof value === 'object' && value !== null;
5
+ /**
6
+ * Entrées brutes `{ accentHue?, fontStack? }` → entrées validées. Pas d'entrée, ou clé absente :
7
+ * défaut. Clé présente mais vide ou `undefined` : erreur (teinte absente, pile vide).
8
+ */
9
+ export function parseBuildInput(raw) {
10
+ if (!isRecord(raw))
11
+ return ok({});
12
+ const result = {};
13
+ if (Object.hasOwn(raw, 'accentHue')) {
14
+ const hue = parseAccentHue(raw['accentHue']);
15
+ if (!hue.ok)
16
+ return hue;
17
+ result.accentHue = hue.value;
18
+ }
19
+ if (Object.hasOwn(raw, 'fontStack')) {
20
+ const stack = parseFontStack(raw['fontStack']);
21
+ if (!stack.ok)
22
+ return stack;
23
+ result.fontStack = stack.value;
24
+ }
25
+ return ok(result);
26
+ }
@@ -0,0 +1,16 @@
1
+ /** Erreurs typées des entrées du build : union fermée à champ `code`, jamais de `throw`. */
2
+ export declare const CUSTOMIZE_ERROR_CODES: readonly ["build.hue-missing", "build.hue-not-finite", "build.hue-out-of-range", "build.contrast-failed", "build.derivation-failed", "build.role-contrast-failed", "build.stack-empty", "build.stack-too-long", "build.stack-unsafe", "build.bad-usage"];
3
+ export type CustomizeErrorCode = (typeof CUSTOMIZE_ERROR_CODES)[number];
4
+ export interface CustomizeError {
5
+ readonly code: CustomizeErrorCode;
6
+ readonly message: string;
7
+ }
8
+ export type Result<T> = {
9
+ readonly ok: true;
10
+ readonly value: T;
11
+ } | {
12
+ readonly ok: false;
13
+ readonly error: CustomizeError;
14
+ };
15
+ export declare const ok: <T>(value: T) => Result<T>;
16
+ export declare const fail: <T = never>(code: CustomizeErrorCode, message: string) => Result<T>;
@@ -0,0 +1,18 @@
1
+ /** Erreurs typées des entrées du build : union fermée à champ `code`, jamais de `throw`. */
2
+ export const CUSTOMIZE_ERROR_CODES = [
3
+ 'build.hue-missing',
4
+ 'build.hue-not-finite',
5
+ 'build.hue-out-of-range',
6
+ 'build.contrast-failed',
7
+ 'build.derivation-failed',
8
+ 'build.role-contrast-failed',
9
+ 'build.stack-empty',
10
+ 'build.stack-too-long',
11
+ 'build.stack-unsafe',
12
+ 'build.bad-usage',
13
+ ];
14
+ export const ok = (value) => ({ ok: true, value });
15
+ export const fail = (code, message) => ({
16
+ ok: false,
17
+ error: { code, message },
18
+ });
@@ -0,0 +1,8 @@
1
+ import type { TokenMap } from '../palette/domain/tokens.ts';
2
+ /**
3
+ * Une couleur au bord du gamut peut sortir de sRGB une fois arrondie à l'écriture : on réduit le
4
+ * chroma par pas de la précision d'écriture. Le CSS, l'hexadécimal et le contrôle de contraste
5
+ * lisent alors la même valeur.
6
+ */
7
+ export declare function settle(value: string): string;
8
+ export declare const settleAll: (tokens: TokenMap) => TokenMap;
@@ -0,0 +1,16 @@
1
+ import { formatOklch, inSrgbGamut, parseOklch } from "../lib/color.js";
2
+ /** Pas de réduction du chroma : la précision d'écriture de `formatOklch` (4 décimales). */
3
+ const CHROMA_STEP = 1e-4;
4
+ /**
5
+ * Une couleur au bord du gamut peut sortir de sRGB une fois arrondie à l'écriture : on réduit le
6
+ * chroma par pas de la précision d'écriture. Le CSS, l'hexadécimal et le contrôle de contraste
7
+ * lisent alors la même valeur.
8
+ */
9
+ export function settle(value) {
10
+ let color = parseOklch(value);
11
+ while (!inSrgbGamut(color) && color.c > 0) {
12
+ color = parseOklch(formatOklch({ ...color, c: Math.max(0, color.c - CHROMA_STEP) }));
13
+ }
14
+ return formatOklch(color);
15
+ }
16
+ export const settleAll = (tokens) => Object.fromEntries(Object.entries(tokens).map(([name, value]) => [name, settle(value)]));
@@ -0,0 +1,30 @@
1
+ /**
2
+ * Types et matrices de couleur.
3
+ * Matrices : Björn Ottosson, « A perceptual color space for image processing » (2020),
4
+ * https://bottosson.github.io/posts/oklab/ (révision du 25 janvier 2021). Une ligne par sortie,
5
+ * `x`, `y`, `z` = coefficients des entrées ; LMS_PRIME = LMS non linéaire (racine cubique).
6
+ */
7
+ /** Couleur OKLCH : `l` dans [0, 1], `c` ≥ 0, `h` en degrés. */
8
+ export interface Oklch {
9
+ l: number;
10
+ c: number;
11
+ h: number;
12
+ }
13
+ /** Canaux sRGB, linéaires ou gamma selon la fonction ; [0, 1] dans le gamut. */
14
+ export interface Rgb {
15
+ r: number;
16
+ g: number;
17
+ b: number;
18
+ }
19
+ export type Vec3 = readonly [number, number, number];
20
+ export interface Row {
21
+ x: number;
22
+ y: number;
23
+ z: number;
24
+ }
25
+ export type Matrix = readonly [Row, Row, Row];
26
+ export declare const OKLAB_TO_LMS_PRIME: Matrix;
27
+ export declare const LMS_TO_LINEAR_SRGB: Matrix;
28
+ export declare const LINEAR_SRGB_TO_LMS: Matrix;
29
+ export declare const LMS_PRIME_TO_OKLAB: Matrix;
30
+ export declare const multiply: (m: Matrix, v: Vec3) => Vec3;
@@ -0,0 +1,28 @@
1
+ /**
2
+ * Types et matrices de couleur.
3
+ * Matrices : Björn Ottosson, « A perceptual color space for image processing » (2020),
4
+ * https://bottosson.github.io/posts/oklab/ (révision du 25 janvier 2021). Une ligne par sortie,
5
+ * `x`, `y`, `z` = coefficients des entrées ; LMS_PRIME = LMS non linéaire (racine cubique).
6
+ */
7
+ export const OKLAB_TO_LMS_PRIME = [
8
+ { x: 1, y: 0.3963377774, z: 0.2158037573 },
9
+ { x: 1, y: -0.1055613458, z: -0.0638541728 },
10
+ { x: 1, y: -0.0894841775, z: -1.291485548 },
11
+ ];
12
+ export const LMS_TO_LINEAR_SRGB = [
13
+ { x: 4.0767416621, y: -3.3077115913, z: 0.2309699292 },
14
+ { x: -1.2684380046, y: 2.6097574011, z: -0.3413193965 },
15
+ { x: -0.0041960863, y: -0.7034186147, z: 1.707614701 },
16
+ ];
17
+ export const LINEAR_SRGB_TO_LMS = [
18
+ { x: 0.4122214708, y: 0.5363325363, z: 0.0514459929 },
19
+ { x: 0.2119034982, y: 0.6806995451, z: 0.1073969566 },
20
+ { x: 0.0883024619, y: 0.2817188376, z: 0.6299787005 },
21
+ ];
22
+ export const LMS_PRIME_TO_OKLAB = [
23
+ { x: 0.2104542553, y: 0.793617785, z: -0.0040720468 },
24
+ { x: 1.9779984951, y: -2.428592205, z: 0.4505937099 },
25
+ { x: 0.0259040371, y: 0.7827717662, z: -0.808675766 },
26
+ ];
27
+ const dot = ({ x, y, z }, [a, b, c]) => x * a + y * b + z * c;
28
+ export const multiply = (m, v) => [dot(m[0], v), dot(m[1], v), dot(m[2], v)];
@@ -0,0 +1,24 @@
1
+ /**
2
+ * Couleur : OKLCH ↔ sRGB, gamut, hexadécimal. ESM pur, sans dépendance.
3
+ * Formules : CSS Color Module Level 4 (W3C), § 9 (Oklab, OkLCh) et § 10.2 (sRGB).
4
+ * Matrices et types : color-data.ts.
5
+ */
6
+ import type { Oklch, Rgb } from './color-data.ts';
7
+ export type { Oklch, Rgb } from './color-data.ts';
8
+ /** `'oklch(0.47 0.19 270.7)'` ou `'oklch(47% 0.19 270.7)'` ; lève une `TypeError` sinon. */
9
+ export declare function parseOklch(text: string): Oklch;
10
+ /** `'oklch(47% 0.19 270.7)'` : 4 décimales au plus, sans zéros inutiles. */
11
+ export declare function formatOklch({ l, c, h }: Oklch): string;
12
+ /** OKLCH → Oklab → LMS → sRGB linéaire (CSS Color 4, matrices d'Ottosson). */
13
+ export declare function oklchToLinearSrgb({ l, c, h }: Oklch): Rgb;
14
+ /** sRGB linéaire → gamma ; prolongée par symétrie hors de [0, 1] (CSS Color 4 § 10.2). */
15
+ export declare function linearToGamma(value: number): number;
16
+ export declare function gammaToLinear(value: number): number;
17
+ /** Sans rognage : hors gamut, les canaux sortent de [0, 1]. */
18
+ export declare function oklchToSrgb(color: Oklch): Rgb;
19
+ /** Vrai si chaque canal gamma est dans [-epsilon, 1 + epsilon]. */
20
+ export declare function inSrgbGamut(color: Oklch, epsilon?: number): boolean;
21
+ /** La palette doit tenir dans sRGB (règle du design system) : RangeError, jamais de rognage. */
22
+ export declare function toHex(color: Oklch): string;
23
+ /** `'#rrggbb'` → OKLCH, `h` dans [0, 360), 0 pour un gris ; lève une `TypeError` sinon. */
24
+ export declare function hexToOklch(hex: string): Oklch;
@@ -0,0 +1,105 @@
1
+ import * as data from "./color-data.js";
2
+ const PERCENT = 100;
3
+ const MAX_DECIMALS = 4;
4
+ const HALF_TURN_DEGREES = 180;
5
+ const FULL_TURN_DEGREES = 360;
6
+ const LMS_EXPONENT = 3;
7
+ const ACHROMATIC_CHROMA = 1e-6; // en deçà, gris : bruit d'arrondi des matrices (~4e-8)
8
+ const DEFAULT_GAMUT_EPSILON = 1e-4;
9
+ const BYTE_MAX = 255;
10
+ const HEX_RADIX = 16;
11
+ const HEX_PAIR_LENGTH = 2;
12
+ // Fonction de transfert sRGB : IEC 61966-2-1:1999, reprise par CSS Color 4 § 10.2.
13
+ const SRGB_LINEAR_THRESHOLD = 0.0031308;
14
+ const SRGB_GAMMA_THRESHOLD = 0.04045;
15
+ const SRGB_LINEAR_SLOPE = 12.92;
16
+ const SRGB_GAMMA = 2.4;
17
+ const SRGB_OFFSET = 0.055;
18
+ const SRGB_SCALE = 1 + SRGB_OFFSET;
19
+ const NUMBER = String.raw `([+-]?(?:\d+\.?\d*|\.\d+)(?:e[+-]?\d+)?)`;
20
+ const OKLCH_BODY = [`${NUMBER}(%?)`, NUMBER, NUMBER].join(String.raw `\s+`);
21
+ const OKLCH_PATTERN = new RegExp(String.raw `^\s*oklch\(\s*${OKLCH_BODY}\s*\)\s*$`, 'i');
22
+ const HEX_PATTERN = /^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i;
23
+ const cube = (value) => value ** LMS_EXPONENT;
24
+ const trimNumber = (value) => String(Number(value.toFixed(MAX_DECIMALS)));
25
+ const pairToLinear = (pair) => gammaToLinear(Number.parseInt(pair, HEX_RADIX) / BYTE_MAX);
26
+ const toByte = (value) => Math.round(Math.min(1, Math.max(0, value)) * BYTE_MAX);
27
+ const toHexPair = (value) => toByte(value).toString(HEX_RADIX).padStart(HEX_PAIR_LENGTH, '0');
28
+ /** `'oklch(0.47 0.19 270.7)'` ou `'oklch(47% 0.19 270.7)'` ; lève une `TypeError` sinon. */
29
+ export function parseOklch(text) {
30
+ const match = OKLCH_PATTERN.exec(String(text));
31
+ if (!match)
32
+ throw new TypeError(`parseOklch : « ${text} » attendu oklch(L C H).`);
33
+ const [, lightness, percent, chroma, hue] = match;
34
+ const l = Number(lightness) / (percent ? PERCENT : 1);
35
+ const c = Number(chroma);
36
+ if (l < 0 || l > 1 || c < 0)
37
+ throw new TypeError(`parseOklch : « ${text} » hors bornes.`);
38
+ return { l, c, h: Number(hue) };
39
+ }
40
+ /** `'oklch(47% 0.19 270.7)'` : 4 décimales au plus, sans zéros inutiles. */
41
+ export function formatOklch({ l, c, h }) {
42
+ return `oklch(${trimNumber(l * PERCENT)}% ${trimNumber(c)} ${trimNumber(h)})`;
43
+ }
44
+ /** OKLCH → Oklab → LMS → sRGB linéaire (CSS Color 4, matrices d'Ottosson). */
45
+ export function oklchToLinearSrgb({ l, c, h }) {
46
+ const hue = (h * Math.PI) / HALF_TURN_DEGREES;
47
+ const lmsPrime = data.multiply(data.OKLAB_TO_LMS_PRIME, [
48
+ l,
49
+ c * Math.cos(hue),
50
+ c * Math.sin(hue),
51
+ ]);
52
+ const [p, q, s] = lmsPrime;
53
+ const [r, g, b] = data.multiply(data.LMS_TO_LINEAR_SRGB, [cube(p), cube(q), cube(s)]);
54
+ return { r, g, b };
55
+ }
56
+ /** sRGB linéaire → gamma ; prolongée par symétrie hors de [0, 1] (CSS Color 4 § 10.2). */
57
+ export function linearToGamma(value) {
58
+ const abs = Math.abs(value);
59
+ if (abs <= SRGB_LINEAR_THRESHOLD)
60
+ return value * SRGB_LINEAR_SLOPE;
61
+ return Math.sign(value) * (SRGB_SCALE * abs ** (1 / SRGB_GAMMA) - SRGB_OFFSET);
62
+ }
63
+ export function gammaToLinear(value) {
64
+ const abs = Math.abs(value);
65
+ if (abs <= SRGB_GAMMA_THRESHOLD)
66
+ return value / SRGB_LINEAR_SLOPE;
67
+ return Math.sign(value) * ((abs + SRGB_OFFSET) / SRGB_SCALE) ** SRGB_GAMMA;
68
+ }
69
+ /** Sans rognage : hors gamut, les canaux sortent de [0, 1]. */
70
+ export function oklchToSrgb(color) {
71
+ const { r, g, b } = oklchToLinearSrgb(color);
72
+ return { r: linearToGamma(r), g: linearToGamma(g), b: linearToGamma(b) };
73
+ }
74
+ /** Vrai si chaque canal gamma est dans [-epsilon, 1 + epsilon]. */
75
+ export function inSrgbGamut(color, epsilon = DEFAULT_GAMUT_EPSILON) {
76
+ return Object.values(oklchToSrgb(color)).every((v) => v >= -epsilon && v <= 1 + epsilon);
77
+ }
78
+ /** La palette doit tenir dans sRGB (règle du design system) : RangeError, jamais de rognage. */
79
+ export function toHex(color) {
80
+ if (!inSrgbGamut(color))
81
+ throw new RangeError(`toHex : ${formatOklch(color)} hors gamut sRGB.`);
82
+ return `#${Object.values(oklchToSrgb(color)).map(toHexPair).join('')}`;
83
+ }
84
+ /** `'#rrggbb'` → OKLCH, `h` dans [0, 360), 0 pour un gris ; lève une `TypeError` sinon. */
85
+ export function hexToOklch(hex) {
86
+ const match = HEX_PATTERN.exec(String(hex));
87
+ if (!match)
88
+ throw new TypeError(`hexToOklch : « ${hex} » attendu #rrggbb.`);
89
+ const [, rr = '', gg = '', bb = ''] = match;
90
+ const [x, y, z] = data.multiply(data.LINEAR_SRGB_TO_LMS, [
91
+ pairToLinear(rr),
92
+ pairToLinear(gg),
93
+ pairToLinear(bb),
94
+ ]);
95
+ const [l, a, b] = data.multiply(data.LMS_PRIME_TO_OKLAB, [
96
+ Math.cbrt(x),
97
+ Math.cbrt(y),
98
+ Math.cbrt(z),
99
+ ]);
100
+ const c = Math.hypot(a, b);
101
+ if (c < ACHROMATIC_CHROMA)
102
+ return { l, c: 0, h: 0 };
103
+ const h = (Math.atan2(b, a) * HALF_TURN_DEGREES) / Math.PI;
104
+ return { l, c, h: (h + FULL_TURN_DEGREES) % FULL_TURN_DEGREES };
105
+ }
@@ -0,0 +1,13 @@
1
+ /**
2
+ * Contraste : rapport WCAG 2 (normatif) et Lc APCA (informatif). ESM pur.
3
+ * Calcul sur la couleur sRGB rendue (gamma), jamais sur le L d'OKLCH.
4
+ */
5
+ import type { Oklch, Rgb } from './color.ts';
6
+ /** `'oklch(L C H)'`, `'#rrggbb'` ou objet OKLCH ; hors gamut sRGB : `RangeError`. */
7
+ export type ContrastColor = string | Oklch;
8
+ /** Luminance relative WCAG 2.x, de canaux sRGB gamma dans [0, 1]. */
9
+ export declare function relativeLuminance({ r, g, b }: Rgb): number;
10
+ /** Rapport de contraste WCAG 2, de 1 à 21, indépendant de l'ordre des couleurs. */
11
+ export declare function contrastRatio(a: ContrastColor, b: ContrastColor): number;
12
+ /** Lc APCA signé : positif = texte sombre sur fond clair, négatif = texte clair sur fond sombre. */
13
+ export declare function apcaLc(text: ContrastColor, background: ContrastColor): number;