An open source design system that's fully customizable and agent ready
TypeScript
feat(sandbox): add tonal palette decision lab (#5818)
rubyycheunga05c13734451
diff --git a/apps/sandbox/package.json b/apps/sandbox/package.jsonindex 455e47f33b..95c4f699fb 100644--- a/apps/sandbox/package.json+++ b/apps/sandbox/package.json@@ -3,6 +3,8 @@"version": "0.0.1","private": true,"scripts": {+ "test": "vitest run",+ "test:watch": "vitest","build:deps": "pnpm -F @astryxdesign/theme-neutral build && pnpm -F @astryxdesign/theme-matcha build && pnpm -F @astryxdesign/theme-stone build && pnpm -F @astryxdesign/theme-gothic build && pnpm -F @astryxdesign/theme-chocolate build && pnpm -F @astryxdesign/theme-y2k build && pnpm -F @astryxdesign/theme-butter build","generate:motion-audit": "node \"src/app/(sandbox)/pages/motion-lab/generate-motion-audit.mjs\"","generate:changelog": "node scripts/generate-changelog.js",@@ -44,6 +46,7 @@"@types/react-dom": "^19.2.3","commander": "^12.1.0","typescript": "^6.0.3",- "@astryxdesign/build": "*"+ "@astryxdesign/build": "*",+ "vitest": "^4.1.9"}}diff --git a/apps/sandbox/src/app/(sandbox)/pages/palette-generator/README.md b/apps/sandbox/src/app/(sandbox)/pages/palette-generator/README.mdnew file mode 100644index 0000000000..9970ee085c--- /dev/null+++ b/apps/sandbox/src/app/(sandbox)/pages/palette-generator/README.md@@ -0,0 +1,31 @@+# Palette Generator Lab++This sandbox page is experimental decision tooling for AST-008. It does not+define a public generator API, adopt generated colors into a theme, or claim+that a palette is accessible.++## Reference data++- **Neutral — PR #5628** is an exact snapshot of `neutralPalettes` from commit+ `b19fc7a740ee43fa52db5555ccd0ac63bd0305d4` in+ `neutralThemePaletteReference.ts`. Keeping the snapshot local makes the+ comparison reproducible while #5668 remains unmerged.+- **Neutral — legacy preview** uses the seeds and HCT-based light/dark behavior+ from `apps/sandbox/src/app/(fullscreen)/pages/neutral-palette/page.tsx`.+- **Stone**, **Gothic**, **Y2K**, and **Butter** use the exported palette objects+ consumed by their corresponding sandbox palette pages. Page-level mode+ behavior and Butter-specific overrides are represented in `themeCorpus.ts`.++The deployed GitHub Pages versions of those sandbox pages are visual+verification references. The lab does not fetch them at runtime because network+state cannot be part of deterministic generation.++Run the sandbox-owned generator tests with `pnpm --filter+@astryxdesign/sandbox test`.++## Interpretation++Existing-theme comparisons exclude the shared black and white endpoints from+the visual difference summary. Suggested vibrancy values minimize average OKLab+distance across stops 5–95 for the selected algorithm. They are starting points,+not approvals or immutable theme settings.diff --git a/apps/sandbox/src/app/(sandbox)/pages/palette-generator/generator.test.ts b/apps/sandbox/src/app/(sandbox)/pages/palette-generator/generator.test.tsnew file mode 100644index 0000000000..6bd1f56180--- /dev/null+++ b/apps/sandbox/src/app/(sandbox)/pages/palette-generator/generator.test.ts@@ -0,0 +1,353 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++import {describe, expect, it} from 'vitest';++import {hexToOklch} from '../color-studio/colorUtils';+import {THEME_REFERENCES} from './themeCorpus';++import {+ COMPACT_11_STOPS,+ FULL_21_STOPS,+ generatePaletteSet,+ parseStopList,+ perceptualDelta,+ serializeGenerationResult,+ validateStops,+ type PaletteGenerationRequest,+} from './generator';++function request(+ overrides: Partial<PaletteGenerationRequest> = {},+): PaletteGenerationRequest {+ return {+ algorithm: 'oklch-v1-experimental',+ vibrancy: 50,+ neutralProfile: 'neutral-v1',+ modeStrategy: 'light-and-dark',+ stops: [...FULL_21_STOPS],+ families: [+ {+ id: 'blue',+ name: 'Blue',+ seed: '#0074e2',+ anchors: [],+ },+ ],+ ...overrides,+ };+}++describe('experimental palette generator', () => {+ it('loads complete existing-theme comparison ramps', () => {+ expect(THEME_REFERENCES.map(theme => theme.id)).toEqual([+ 'neutral-pr-5628',+ 'neutral-legacy',+ 'stone',+ 'gothic',+ 'y2k',+ 'butter',+ ]);+ for (const theme of THEME_REFERENCES) {+ expect(theme.suggestedVibrancy.oklch).toBeGreaterThanOrEqual(0);+ expect(theme.suggestedVibrancy.oklch).toBeLessThanOrEqual(100);+ for (const family of theme.families) {+ for (const mode of theme.modes) {+ expect(Object.keys(family[mode] ?? {})).toHaveLength(21);+ }+ }+ }+ });++ it('supports the full and compact stop presets', () => {+ expect(validateStops([...FULL_21_STOPS])).toHaveLength(21);+ expect(validateStops([...COMPACT_11_STOPS])).toHaveLength(11);+ expect(parseStopList('0, 25, 50, 75, 100')).toEqual([0, 25, 50, 75, 100]);+ });++ it('rejects incomplete, duplicate, and unordered stop layouts', () => {+ expect(() => validateStops([10, 50, 100])).toThrow(+ 'include stops 0 and 100',+ );+ expect(() => validateStops([0, 50, 50, 100])).toThrow(+ 'unique and strictly increasing',+ );+ expect(() => validateStops([0, 75, 50, 100])).toThrow(+ 'unique and strictly increasing',+ );+ expect(() => parseStopList('0, nope, 100')).toThrow(+ 'Every custom stop must be a number',+ );+ });++ it('is byte-deterministic for an identical normalized request', () => {+ const input = request();+ expect(serializeGenerationResult(generatePaletteSet(input))).toBe(+ serializeGenerationResult(generatePaletteSet(input)),+ );+ });++ it('preserves exact anchors byte-for-byte', () => {+ const result = generatePaletteSet(+ request({+ families: [+ {+ id: 'blue',+ name: 'Blue',+ seed: '#0064e0',+ anchors: [+ {+ mode: 'light',+ stop: 50,+ color: '#0074e2',+ policy: 'exact',+ },+ ],+ },+ ],+ }),+ );++ expect(result.errors).toEqual([]);+ expect(result.families[0].light?.colors[50]).toBe('#0074e2');+ expect(result.families[0].light?.diagnostics.anchors[0].deltaE).toBe(0);+ });++ it('supports more than one anchor in the same family', () => {+ const result = generatePaletteSet(+ request({+ families: [+ {+ id: 'blue',+ name: 'Blue',+ seed: '#0064e0',+ anchors: [+ {+ mode: 'light',+ stop: 40,+ color: '#005ac0',+ policy: 'exact',+ },+ {+ mode: 'light',+ stop: 70,+ color: '#75b4ff',+ policy: 'exact',+ },+ ],+ },+ ],+ }),+ );++ expect(result.errors).toEqual([]);+ expect(result.families[0].light?.colors[40]).toBe('#005ac0');+ expect(result.families[0].light?.colors[70]).toBe('#75b4ff');+ });++ it('tapers an exact anchor into neighboring stops instead of creating a single-stop spike', () => {+ const result = generatePaletteSet(+ request({+ modeStrategy: 'light-only',+ families: [+ {+ id: 'blue',+ name: 'Blue',+ seed: '#0074e2',+ anchors: [+ {+ mode: 'light',+ stop: 50,+ color: '#7a3cff',+ policy: 'exact',+ },+ ],+ },+ ],+ }),+ );+ const colors = result.families[0].light?.colors;++ expect(result.errors).toEqual([]);+ expect(colors?.[50]).toBe('#7a3cff');+ expect(+ perceptualDelta(colors?.[45] ?? '', colors?.[50] ?? ''),+ ).toBeLessThan(7);+ expect(+ perceptualDelta(colors?.[50] ?? '', colors?.[55] ?? ''),+ ).toBeLessThan(7);+ });++ it('keeps bounded anchors within their declared tolerance', () => {+ const result = generatePaletteSet(+ request({+ families: [+ {+ id: 'blue',+ name: 'Blue',+ seed: '#0064e0',+ anchors: [+ {+ mode: 'light',+ stop: 50,+ color: '#0074e2',+ policy: 'bounded',+ maxDeltaE: 1.5,+ },+ ],+ },+ ],+ }),+ );++ expect(result.errors).toEqual([]);+ expect(+ result.families[0].light?.diagnostics.anchors[0].deltaE,+ ).toBeLessThanOrEqual(1.51);+ });++ it('fails a family when an anchor references a missing stop', () => {+ const result = generatePaletteSet(+ request({+ stops: [...COMPACT_11_STOPS],+ families: [+ {+ id: 'blue',+ name: 'Blue',+ seed: '#0064e0',+ anchors: [+ {+ mode: 'light',+ stop: 45,+ color: '#0074e2',+ policy: 'exact',+ },+ ],+ },+ ],+ }),+ );++ expect(result.families).toEqual([]);+ expect(result.errors[0].message).toContain('not present');+ });++ it('produces distinct, monotonic light and dark ramps', () => {+ const result = generatePaletteSet(request());+ const family = result.families[0];++ expect(result.errors).toEqual([]);+ expect(family.light?.diagnostics.monotonic).toBe(true);+ expect(family.dark?.diagnostics.monotonic).toBe(true);+ expect(family.light?.colors[50]).not.toBe(family.dark?.colors[50]);+ expect(result.coordination.map(item => item.mode)).toEqual([+ 'light',+ 'dark',+ ]);+ });++ it('does not emit a light ramp when dark-only output was requested', () => {+ const result = generatePaletteSet(request({modeStrategy: 'dark-only'}));++ expect(result.families[0].light).toBeUndefined();+ expect(result.families[0].dark).toBeDefined();+ expect(result.coordination.map(item => item.mode)).toEqual(['dark']);+ });++ it('makes continuous vibrancy values observably different', () => {+ const muted = generatePaletteSet(request({vibrancy: 25}));+ const vibrant = generatePaletteSet(request({vibrancy: 75}));+ const mutedColor = muted.families[0].light?.colors[50] ?? '#000000';+ const vibrantColor = vibrant.families[0].light?.colors[50] ?? '#000000';++ expect(perceptualDelta(mutedColor, vibrantColor)).toBeGreaterThan(1);+ });++ it('makes zero vibrancy genuinely achromatic', () => {+ const result = generatePaletteSet(+ request({vibrancy: 0, modeStrategy: 'light-only'}),+ );++ expect(result.families[0].light?.colors[50]).toMatch(+ /^#([0-9a-f]{2})\1\1$/,+ );+ });++ it('rejects vibrancy values outside the slider range', () => {+ expect(() => generatePaletteSet(request({vibrancy: 101}))).toThrow(+ 'Vibrancy must be a number from 0 to 100',+ );+ });++ it('makes the known blue hue-drift tradeoff visible in the comparison', () => {+ const oklch = generatePaletteSet(request());+ const hct = generatePaletteSet(request({algorithm: 'hct-v1-experimental'}));++ expect(oklch.families[0].light?.diagnostics.maximumHueDrift).toBeLessThan(+ 12,+ );+ expect(hct.families[0].light?.diagnostics.maximumHueDrift).toBeGreaterThan(+ 12,+ );+ });++ it('keeps low-tone OKLCH orange from becoming a low-chroma brown band', () => {+ const result = generatePaletteSet(+ request({+ modeStrategy: 'light-only',+ families: [{id: 'orange', name: 'Orange', seed: '#d57113'}],+ }),+ );+ const tone30 = hexToOklch(+ result.families[0].light?.colors[30] ?? '#000000',+ );++ expect(tone30.H).toBeGreaterThan(35);+ expect(tone30.H).toBeLessThan(48);+ expect(tone30.C).toBeGreaterThan(0.1);+ expect(result.families[0].light?.diagnostics.hueIdentityRisk).toBeNull();+ });++ it('supports distinct neutral profiles without semantic family names affecting chromatic ramps', () => {+ const neutralFamily = {+ id: 'neutral',+ name: 'Whatever the author calls it',+ seed: '#777777',+ kind: 'neutral' as const,+ };+ const neutral = generatePaletteSet(+ request({neutralProfile: 'neutral-v1', families: [neutralFamily]}),+ );+ const cool = generatePaletteSet(+ request({neutralProfile: 'cool-v1', families: [neutralFamily]}),+ );++ expect(neutral.families[0].light?.colors[50]).not.toBe(+ cool.families[0].light?.colors[50],+ );+ expect(neutral.families[0].light?.colors[50]).toMatch(+ /^#([0-9a-f]{2})\1\1$/,+ );+ expect(neutral.families[0].dark?.colors[90]).not.toBe('#ffffff');+ expect(neutral.families[0].dark?.colors[100]).toBe('#ffffff');+ });++ it('reports cross-family distinction and chroma balance at a shared stop', () => {+ const result = generatePaletteSet(+ request({+ modeStrategy: 'light-only',+ families: [+ {id: 'blue', name: 'Blue', seed: '#0074e2'},+ {id: 'green', name: 'Green', seed: '#358a3a'},+ {id: 'purple', name: 'Purple', seed: '#980fb2'},+ ],+ }),+ );+ const diagnostic = result.coordination[0];++ expect(diagnostic.stop).toBe(50);+ expect(diagnostic.closestFamilies).not.toBeNull();+ expect(diagnostic.minimumFamilyDeltaE).toBeGreaterThan(0);+ expect(diagnostic.chromaRatio).toBeGreaterThanOrEqual(1);+ expect(diagnostic.chromaRatio).toBeLessThan(2);+ });+});diff --git a/apps/sandbox/src/app/(sandbox)/pages/palette-generator/generator.ts b/apps/sandbox/src/app/(sandbox)/pages/palette-generator/generator.tsnew file mode 100644index 0000000000..190d3ccb19--- /dev/null+++ b/apps/sandbox/src/app/(sandbox)/pages/palette-generator/generator.ts@@ -0,0 +1,828 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * Experimental tonal-palette generator used only by the sandbox decision tool.+ *+ * This intentionally remains outside Core. It makes the proposed AST-008 input+ * choices executable without claiming that the algorithm or output is canonical.+ */++import {+ hexToHct,+ hexToOklch,+ hctToHex,+ luminance,+ maxOklchChroma,+ oklchClampedHex,+ parseColorInput,+ toneToOklabL,+} from '../color-studio/colorUtils';++export const FULL_21_STOPS = [+ 0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95,+ 100,+] as const;++export const COMPACT_11_STOPS = [+ 0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100,+] as const;++export type PaletteAlgorithm = 'oklch-v1-experimental' | 'hct-v1-experimental';+export type NeutralProfile = 'neutral-v1' | 'warm-v1' | 'cool-v1' | 'custom';+export type PaletteMode = 'light' | 'dark';+export type ModeStrategy = 'light-only' | 'dark-only' | 'light-and-dark';+export type AnchorPolicy = 'exact' | 'bounded' | 'preferred';++export interface PaletteAnchor {+ mode: PaletteMode;+ stop: number;+ color: string;+ policy: AnchorPolicy;+ /** OKLab Euclidean distance × 100. Required for bounded anchors. */+ maxDeltaE?: number;+}++export interface PaletteFamilyRequest {+ id: string;+ name: string;+ seed: string;+ kind?: 'chromatic' | 'neutral';+ anchors?: PaletteAnchor[];+}++export interface PaletteGenerationRequest {+ algorithm: PaletteAlgorithm;+ /** Continuous perceptual color strength from 0 (subdued) to 100 (vivid). */+ vibrancy: number;+ neutralProfile: NeutralProfile;+ modeStrategy: ModeStrategy;+ stops: number[];+ families: PaletteFamilyRequest[];+}++export interface AnchorResult extends PaletteAnchor {+ generatedColor: string;+ deltaE: number;+}++export interface RampDiagnostics {+ monotonic: boolean;+ minimumAdjacentDeltaE: number;+ maximumAdjacentDeltaE: number;+ maximumHueDrift: number;+ hueIdentityRisk: 'blue-to-purple' | 'yellow-to-brown' | null;+ gamutMappedStops: number[];+ anchors: AnchorResult[];+}++export interface GeneratedRamp {+ colors: Record<number, string>;+ diagnostics: RampDiagnostics;+}++export interface GeneratedFamily {+ id: string;+ name: string;+ seed: string;+ light?: GeneratedRamp;+ dark?: GeneratedRamp;+}++export interface CoordinationDiagnostic {+ mode: PaletteMode;+ stop: number;+ closestFamilies: [string, string] | null;+ minimumFamilyDeltaE: number | null;+ strongestFamily: string | null;+ weakestFamily: string | null;+ chromaRatio: number | null;+}++export interface PaletteGenerationResult {+ request: PaletteGenerationRequest;+ families: GeneratedFamily[];+ coordination: CoordinationDiagnostic[];+ errors: {familyId: string; message: string}[];+}++interface PolarColor {+ lightness: number;+ chroma: number;+ hue: number;+}++const DARK_CHROMA_FACTOR = 0.85;+const DARK_TONE_LIFT = 5;+const DARK_LIFT_TAPER_START = 80;+const DARK_LIFT_TAPER_END = 95;++function normalizeHue(hue: number): number {+ return ((hue % 360) + 360) % 360;+}++function hueDistance(a: number, b: number): number {+ const difference = Math.abs(normalizeHue(a) - normalizeHue(b));+ return Math.min(difference, 360 - difference);+}++function signedHueDelta(from: number, to: number): number {+ return ((normalizeHue(to) - normalizeHue(from) + 540) % 360) - 180;+}++function interpolateHue(a: number, b: number, amount: number): number {+ const delta = ((b - a + 540) % 360) - 180;+ return normalizeHue(a + delta * amount);+}++function clamp(value: number, minimum: number, maximum: number): number {+ return Math.min(maximum, Math.max(minimum, value));+}++function normalizedHex(input: string): string {+ const parsed = parseColorInput(input);+ if (!parsed) {+ throw new Error(`Invalid color: ${input}`);+ }+ return parsed.toLowerCase();+}++export function validateStops(stops: number[]): number[] {+ if (stops.length < 2) {+ throw new Error('A palette requires at least two stops.');+ }++ const normalized = [...stops];+ for (const stop of normalized) {+ if (!Number.isFinite(stop) || stop < 0 || stop > 100) {+ throw new Error(+ `Stop ${String(stop)} must be a finite number from 0 to 100.`,+ );+ }+ }++ for (let index = 1; index < normalized.length; index++) {+ if (normalized[index] <= normalized[index - 1]) {+ throw new Error('Stops must be unique and strictly increasing.');+ }+ }++ if (normalized[0] !== 0 || normalized[normalized.length - 1] !== 100) {+ throw new Error('Complete ramps must include stops 0 and 100.');+ }++ return normalized;+}++export function parseStopList(input: string): number[] {+ const tokens = input.split(',').map(value => value.trim());+ if (tokens.some(value => value === '' || !Number.isFinite(Number(value)))) {+ throw new Error('Every custom stop must be a number from 0 to 100.');+ }+ const values = tokens.map(Number);+ return validateStops(values);+}++function modesForStrategy(strategy: ModeStrategy): PaletteMode[] {+ if (strategy === 'light-only') {+ return ['light'];+ }+ if (strategy === 'dark-only') {+ return ['dark'];+ }+ return ['light', 'dark'];+}++/**+ * Hue-dependent compensation derived from the existing Astryx palette work.+ * It keeps naturally forceful green/cyan and purple regions from dominating+ * while allowing blue to retain more chroma. Names never affect this math.+ */+function hueBalanceFactor(hue: number): number {+ const h = normalizeHue(hue);+ if (h >= 70 && h < 115) {+ return 0.94; // yellow+ }+ if (h >= 115 && h < 175) {+ return 0.78; // green+ }+ if (h >= 175 && h < 230) {+ return 0.82; // teal/cyan+ }+ if (h >= 285 && h < 340) {+ return 0.9; // purple/magenta+ }+ return 1;+}++/**+ * Constant-hue orange becomes brown quickly in the lower sRGB gamut. A gentle+ * redward rotation below tone 50 preserves orange identity and unlocks more+ * usable chroma without changing the shared luminance scale. Other hue regions+ * stay fixed so this compensation cannot make blue drift toward purple.+ */+function toneAdjustedHue(+ algorithm: PaletteAlgorithm,+ hue: number,+ tone: number,+): number {+ const normalized = normalizeHue(hue);+ if (+ algorithm !== 'oklch-v1-experimental' ||+ normalized < 40 ||+ normalized >= 70 ||+ tone >= 50+ ) {+ return normalized;+ }++ const darkening = clamp((50 - tone) / 40, 0, 1);+ return normalizeHue(normalized - 18 * Math.sqrt(darkening));+}++function toneChromaEnvelope(tone: number): number {+ const normalized = clamp(tone / 100, 0, 1);+ return 0.18 + 0.82 * Math.sqrt(Math.max(0, Math.sin(Math.PI * normalized)));+}++function vibrancyMultiplier(vibrancy: number): number {+ if (!Number.isFinite(vibrancy) || vibrancy < 0 || vibrancy > 100) {+ throw new Error('Vibrancy must be a number from 0 to 100.');+ }++ // Preserve the preset calibration while making 0 genuinely achromatic:+ // 0 = no chroma, 25 = muted (0.72), 50 = balanced (1.0),+ // 75 = vibrant (1.24), and 100 = maximum (1.48).+ if (vibrancy <= 25) {+ return (vibrancy / 25) * 0.72;+ }+ if (vibrancy <= 50) {+ return 0.72 + ((vibrancy - 25) / 25) * 0.28;+ }+ return 1 + (vibrancy - 50) * 0.0096;+}++/**+ * Pull seed colors toward a shared perceptual intensity before applying the+ * hue-specific compensation. Anchors can still preserve intentional brand+ * differences, but arbitrary source saturation should not make one family+ * three times louder than its neighbors by accident.+ */+function coordinatedChroma(+ algorithm: PaletteAlgorithm,+ sourceChroma: number,+): number {+ const target = algorithm === 'oklch-v1-experimental' ? 0.18 : 65;+ return sourceChroma * 0.35 + target * 0.65;+}++function darkTone(tone: number): number {+ if (tone >= DARK_LIFT_TAPER_END) {+ return tone;+ }+ if (tone <= DARK_LIFT_TAPER_START) {+ return Math.min(100, tone + DARK_TONE_LIFT);+ }+ const ratio =+ (DARK_LIFT_TAPER_END - tone) /+ (DARK_LIFT_TAPER_END - DARK_LIFT_TAPER_START);+ return Math.min(100, tone + DARK_TONE_LIFT * ratio);+}++function neutralPolar(+ algorithm: PaletteAlgorithm,+ profile: NeutralProfile,+ seed: string,+): PolarColor {+ if (profile === 'custom') {+ return colorToPolar(algorithm, seed);+ }++ const hue = profile === 'warm-v1' ? 75 : profile === 'cool-v1' ? 250 : 0;+ if (algorithm === 'oklch-v1-experimental') {+ return {+ lightness: 0.5,+ chroma: profile === 'neutral-v1' ? 0 : 0.018,+ hue,+ };+ }+ return {+ lightness: 50,+ chroma: profile === 'neutral-v1' ? 0 : 4,+ hue,+ };+}++function colorToPolar(algorithm: PaletteAlgorithm, color: string): PolarColor {+ if (algorithm === 'oklch-v1-experimental') {+ const value = hexToOklch(color);+ return {lightness: value.L, chroma: value.C, hue: value.H};+ }+ const value = hexToHct(color);+ return {lightness: value.tone, chroma: value.chroma, hue: value.hue};+}++function anchorPolarAtStop(+ algorithm: PaletteAlgorithm,+ seed: PolarColor,+ anchors: PaletteAnchor[],+ stop: number,+): PolarColor {+ if (anchors.length === 0) {+ return seed;+ }++ const sorted = [...anchors].sort((a, b) => a.stop - b.stop);+ const lower = [...sorted].reverse().find(anchor => anchor.stop <= stop);+ const upper = sorted.find(anchor => anchor.stop >= stop);++ if (!lower || !upper || lower.stop === upper.stop) {+ return colorToPolar(+ algorithm,+ normalizedHex((lower ?? upper ?? sorted[0]).color),+ );+ }++ const start = colorToPolar(algorithm, normalizedHex(lower.color));+ const end = colorToPolar(algorithm, normalizedHex(upper.color));+ const amount = (stop - lower.stop) / (upper.stop - lower.stop);+ return {+ lightness: start.lightness + (end.lightness - start.lightness) * amount,+ chroma: start.chroma + (end.chroma - start.chroma) * amount,+ hue: interpolateHue(start.hue, end.hue, amount),+ };+}++function generateCandidate(+ algorithm: PaletteAlgorithm,+ source: PolarColor,+ tone: number,+ mode: PaletteMode,+ vibrancy: number,+ coordinateWithOtherFamilies: boolean,+): {hex: string; gamutMapped: boolean} {+ const adjustedTone = mode === 'dark' ? darkTone(tone) : tone;+ const adjustedHue = toneAdjustedHue(algorithm, source.hue, adjustedTone);+ const modeChroma = mode === 'dark' ? DARK_CHROMA_FACTOR : 1;+ const baseChroma = coordinateWithOtherFamilies+ ? coordinatedChroma(algorithm, source.chroma)+ : source.chroma;+ const chroma =+ baseChroma *+ vibrancyMultiplier(vibrancy) *+ hueBalanceFactor(adjustedHue) *+ toneChromaEnvelope(adjustedTone) *+ modeChroma;++ if (algorithm === 'oklch-v1-experimental') {+ const lightness = toneToOklabL(adjustedTone);+ const maximum = maxOklchChroma(adjustedHue, lightness);+ return {+ hex: oklchClampedHex(lightness, chroma, adjustedHue),+ gamutMapped: chroma > maximum + 0.000001,+ };+ }++ const boost = adjustedTone < 50 ? 1 + (50 - adjustedTone) / 40 : 1;+ const requestedChroma = chroma * boost;+ const hex = hctToHex({+ hue: source.hue,+ chroma: requestedChroma,+ tone: adjustedTone,+ });+ const achieved = hexToHct(hex).chroma;+ return {+ hex,+ gamutMapped: achieved + 0.5 < requestedChroma,+ };+}++function oklabCoordinates(color: string): [number, number, number] {+ const value = hexToOklch(color);+ const radians = (value.H * Math.PI) / 180;+ return [value.L, value.C * Math.cos(radians), value.C * Math.sin(radians)];+}++function oklabToHex([lightness, a, b]: [number, number, number]): string {+ const chroma = Math.sqrt(a * a + b * b);+ const hue = normalizeHue((Math.atan2(b, a) * 180) / Math.PI);+ return oklchClampedHex(clamp(lightness, 0, 1), chroma, hue);+}++export function perceptualDelta(colorA: string, colorB: string): number {+ const [l1, a1, b1] = oklabCoordinates(colorA);+ const [l2, a2, b2] = oklabCoordinates(colorB);+ return Math.sqrt((l1 - l2) ** 2 + (a1 - a2) ** 2 + (b1 - b2) ** 2) * 100;+}++function interpolateColor(+ colorA: string,+ colorB: string,+ amount: number,+): string {+ const start = hexToOklch(colorA);+ const end = hexToOklch(colorB);+ return oklchClampedHex(+ start.L + (end.L - start.L) * amount,+ start.C + (end.C - start.C) * amount,+ interpolateHue(start.H, end.H, amount),+ );+}++function applyAnchor(candidate: string, anchor: PaletteAnchor): AnchorResult {+ const target = normalizedHex(anchor.color);+ let generatedColor = candidate;++ if (anchor.policy === 'exact') {+ generatedColor = target;+ } else if (anchor.policy === 'bounded') {+ const tolerance = anchor.maxDeltaE;+ if (tolerance == null || !Number.isFinite(tolerance) || tolerance < 0) {+ throw new Error(+ `Bounded anchor at stop ${anchor.stop} requires a non-negative maxDeltaE.`,+ );+ }+ if (perceptualDelta(candidate, target) > tolerance) {+ let low = 0;+ let high = 1;+ for (let index = 0; index < 18; index++) {+ const amount = (low + high) / 2;+ const mixed = interpolateColor(target, candidate, amount);+ if (perceptualDelta(mixed, target) <= tolerance) {+ low = amount;+ } else {+ high = amount;+ }+ }+ generatedColor = interpolateColor(target, candidate, low);+ }+ } else {+ generatedColor = interpolateColor(candidate, target, 0.35);+ }++ return {+ ...anchor,+ color: target,+ generatedColor,+ deltaE: perceptualDelta(generatedColor, target),+ };+}++interface AnchorCorrection {+ stop: number;+ delta: [number, number, number];+ result: AnchorResult;+}++function smoothstep(amount: number): number {+ const value = clamp(amount, 0, 1);+ return value * value * (3 - 2 * value);+}++function interpolateDelta(+ start: [number, number, number],+ end: [number, number, number],+ amount: number,+): [number, number, number] {+ return [+ start[0] + (end[0] - start[0]) * amount,+ start[1] + (end[1] - start[1]) * amount,+ start[2] + (end[2] - start[2]) * amount,+ ];+}++function correctionAtStop(+ corrections: AnchorCorrection[],+ stop: number,+): [number, number, number] {+ const zero: [number, number, number] = [0, 0, 0];+ if (corrections.length === 0) {+ return zero;+ }++ const first = corrections[0];+ if (stop <= first.stop) {+ const boundary = Math.max(0, first.stop - 25);+ if (stop <= boundary && boundary !== first.stop) {+ return zero;+ }+ const amount =+ boundary === first.stop+ ? 1+ : smoothstep((stop - boundary) / (first.stop - boundary));+ return interpolateDelta(zero, first.delta, amount);+ }++ const last = corrections[corrections.length - 1];+ if (stop >= last.stop) {+ const boundary = Math.min(100, last.stop + 25);+ if (stop >= boundary && boundary !== last.stop) {+ return zero;+ }+ const amount =+ boundary === last.stop+ ? 1+ : smoothstep((stop - last.stop) / (boundary - last.stop));+ return interpolateDelta(last.delta, zero, amount);+ }++ const upperIndex = corrections.findIndex(item => item.stop > stop);+ const lower = corrections[upperIndex - 1];+ const upper = corrections[upperIndex];+ const amount = smoothstep((stop - lower.stop) / (upper.stop - lower.stop));+ return interpolateDelta(lower.delta, upper.delta, amount);+}++function applyAnchorCorrections(+ colors: Record<number, string>,+ stops: number[],+ anchors: PaletteAnchor[],+): {colors: Record<number, string>; anchors: AnchorResult[]} {+ if (anchors.length === 0) {+ return {colors, anchors: []};+ }++ const corrections = anchors+ .map(anchor => {+ const candidate = colors[anchor.stop];+ const result = applyAnchor(candidate, anchor);+ const base = oklabCoordinates(candidate);+ const target = oklabCoordinates(result.generatedColor);+ return {+ stop: anchor.stop,+ delta: [+ target[0] - base[0],+ target[1] - base[1],+ target[2] - base[2],+ ] as [number, number, number],+ result,+ };+ })+ .sort((a, b) => a.stop - b.stop);++ const corrected: Record<number, string> = {};+ for (const stop of stops) {+ const base = oklabCoordinates(colors[stop]);+ const delta = correctionAtStop(corrections, stop);+ corrected[stop] = oklabToHex([+ base[0] + delta[0],+ base[1] + delta[1],+ base[2] + delta[2],+ ]);+ }++ // Preserve the canonical anchor value after conversion and gamut mapping.+ for (const correction of corrections) {+ corrected[correction.stop] = correction.result.generatedColor;+ }++ return {+ colors: corrected,+ anchors: corrections.map(correction => correction.result),+ };+}++function assertAnchorSet(anchors: PaletteAnchor[], stops: number[]): void {+ const seen = new Set<string>();+ for (const anchor of anchors) {+ normalizedHex(anchor.color);+ if (!stops.includes(anchor.stop)) {+ throw new Error(+ `Anchor stop ${anchor.stop} is not present in the requested stop layout.`,+ );+ }+ const key = `${anchor.mode}:${anchor.stop}`;+ if (seen.has(key)) {+ throw new Error(+ `Duplicate anchor for ${anchor.mode} stop ${anchor.stop}.`,+ );+ }+ seen.add(key);+ }+}++function buildDiagnostics(+ colors: Record<number, string>,+ stops: number[],+ sourceHue: number,+ gamutMappedStops: number[],+ anchors: AnchorResult[],+): RampDiagnostics {+ let monotonic = true;+ let minimumAdjacentDeltaE = Number.POSITIVE_INFINITY;+ let maximumAdjacentDeltaE = 0;+ let maximumHueDrift = 0;+ let hueIdentityRisk: RampDiagnostics['hueIdentityRisk'] = null;++ for (let index = 0; index < stops.length; index++) {+ const stop = stops[index];+ const color = colors[stop];+ const oklch = hexToOklch(color);+ if (oklch.C >= 0.015) {+ const drift = signedHueDelta(sourceHue, oklch.H);+ maximumHueDrift = Math.max(+ maximumHueDrift,+ hueDistance(sourceHue, oklch.H),+ );+ if (sourceHue >= 230 && sourceHue < 285 && drift > 12) {+ hueIdentityRisk = 'blue-to-purple';+ }+ if (sourceHue >= 70 && sourceHue < 115 && drift < -12) {+ hueIdentityRisk = 'yellow-to-brown';+ }+ }+ if (index === 0) {+ continue;+ }+ const previous = colors[stops[index - 1]];+ if (luminance(color) + 0.000001 < luminance(previous)) {+ monotonic = false;+ }+ const adjacentDelta = perceptualDelta(previous, color);+ minimumAdjacentDeltaE = Math.min(minimumAdjacentDeltaE, adjacentDelta);+ maximumAdjacentDeltaE = Math.max(maximumAdjacentDeltaE, adjacentDelta);+ }++ return {+ monotonic,+ minimumAdjacentDeltaE:+ minimumAdjacentDeltaE === Number.POSITIVE_INFINITY+ ? 0+ : minimumAdjacentDeltaE,+ maximumAdjacentDeltaE,+ maximumHueDrift,+ hueIdentityRisk,+ gamutMappedStops,+ anchors,+ };+}++function generateRamp(+ request: PaletteGenerationRequest,+ family: PaletteFamilyRequest,+ mode: PaletteMode,+): GeneratedRamp {+ const stops = validateStops(request.stops);+ const seedHex = normalizedHex(family.seed);+ const anchors = (family.anchors ?? []).filter(anchor => anchor.mode === mode);+ assertAnchorSet(family.anchors ?? [], stops);++ const seed =+ family.kind === 'neutral'+ ? neutralPolar(request.algorithm, request.neutralProfile, seedHex)+ : colorToPolar(request.algorithm, seedHex);+ const baseColors: Record<number, string> = {};+ const gamutMappedStops: number[] = [];+ const diagnosticReference = generateCandidate(+ request.algorithm,+ seed,+ 50,+ mode,+ request.vibrancy,+ family.kind !== 'neutral',+ ).hex;++ for (const stop of stops) {+ const source = anchorPolarAtStop(request.algorithm, seed, anchors, stop);+ const generated = generateCandidate(+ request.algorithm,+ source,+ stop,+ mode,+ request.vibrancy,+ family.kind !== 'neutral',+ );+ const color = generated.hex;+ if (generated.gamutMapped) {+ gamutMappedStops.push(stop);+ }++ baseColors[stop] = color;+ }++ const corrected = applyAnchorCorrections(baseColors, stops, anchors);++ const diagnostics = buildDiagnostics(+ corrected.colors,+ stops,+ hexToOklch(diagnosticReference).H,+ gamutMappedStops,+ corrected.anchors,+ );++ if (!diagnostics.monotonic) {+ throw new Error(+ `${family.name} ${mode} ramp is not luminance-monotonic with the requested anchors.`,+ );+ }++ return {colors: corrected.colors, diagnostics};+}++function nearestStop(stops: number[], target: number): number {+ return stops.reduce((best, stop) =>+ Math.abs(stop - target) < Math.abs(best - target) ? stop : best,+ );+}++function buildCoordinationDiagnostics(+ request: PaletteGenerationRequest,+ families: GeneratedFamily[],+): CoordinationDiagnostic[] {+ const stop = nearestStop(request.stops, 50);+ const chromaticIds = new Set(+ request.families+ .filter(family => family.kind !== 'neutral')+ .map(family => family.id),+ );++ return modesForStrategy(request.modeStrategy).map(mode => {+ const samples = families+ .filter(family => chromaticIds.has(family.id) && family[mode])+ .map(family => {+ const color = family[mode]?.colors[stop] ?? '#000000';+ return {+ id: family.id,+ name: family.name,+ color,+ chroma: hexToOklch(color).C,+ };+ });++ let closestFamilies: [string, string] | null = null;+ let minimumFamilyDeltaE = Number.POSITIVE_INFINITY;+ for (let index = 0; index < samples.length; index++) {+ for (let next = index + 1; next < samples.length; next++) {+ const delta = perceptualDelta(+ samples[index].color,+ samples[next].color,+ );+ if (delta < minimumFamilyDeltaE) {+ minimumFamilyDeltaE = delta;+ closestFamilies = [samples[index].name, samples[next].name];+ }+ }+ }++ const byChroma = [...samples].sort((a, b) => a.chroma - b.chroma);+ const weakest = byChroma[0];+ const strongest = byChroma[byChroma.length - 1];+ const chromaRatio =+ weakest && strongest && weakest.chroma > 0.0001+ ? strongest.chroma / weakest.chroma+ : null;++ return {+ mode,+ stop,+ closestFamilies,+ minimumFamilyDeltaE:+ minimumFamilyDeltaE === Number.POSITIVE_INFINITY+ ? null+ : minimumFamilyDeltaE,+ strongestFamily: strongest?.name ?? null,+ weakestFamily: weakest?.name ?? null,+ chromaRatio,+ };+ });+}++export function generatePaletteSet(+ request: PaletteGenerationRequest,+): PaletteGenerationResult {+ vibrancyMultiplier(request.vibrancy);+ validateStops(request.stops);+ const families: GeneratedFamily[] = [];+ const errors: {familyId: string; message: string}[] = [];++ for (const family of request.families) {+ try {+ const generated: GeneratedFamily = {+ id: family.id,+ name: family.name,+ seed: normalizedHex(family.seed),+ };+ for (const mode of modesForStrategy(request.modeStrategy)) {+ generated[mode] = generateRamp(request, family, mode);+ }+ families.push(generated);+ } catch (error) {+ errors.push({+ familyId: family.id,+ message: error instanceof Error ? error.message : String(error),+ });+ }+ }++ return {+ request,+ families,+ coordination: buildCoordinationDiagnostics(request, families),+ errors,+ };+}++export function serializeGenerationResult(+ result: PaletteGenerationResult,+): string {+ return `${JSON.stringify(result, null, 2)}\n`;+}diff --git a/apps/sandbox/src/app/(sandbox)/pages/palette-generator/neutralThemePaletteReference.ts b/apps/sandbox/src/app/(sandbox)/pages/palette-generator/neutralThemePaletteReference.tsnew file mode 100644index 0000000000..888b7308ee--- /dev/null+++ b/apps/sandbox/src/app/(sandbox)/pages/palette-generator/neutralThemePaletteReference.ts@@ -0,0 +1,540 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * Exact approved Neutral light/dark ramps from merged PR #5628 at+ * b19fc7a740ee43fa52db5555ccd0ac63bd0305d4. This temporary fixture can be+ * replaced by the package export after the #5668 palette-contract stack lands.+ */+export const NEUTRAL_THEME_PALETTE_REFERENCE = {+ neutral: {+ light: {+ 0: '#000000',+ 5: '#111111',+ 10: '#1b1b1b',+ 15: '#262626',+ 20: '#303030',+ 25: '#3b3b3b',+ 30: '#474747',+ 35: '#525252',+ 40: '#5e5e5e',+ 45: '#6a6a6a',+ 50: '#777777',+ 55: '#848484',+ 60: '#919191',+ 65: '#9e9e9e',+ 70: '#ababab',+ 75: '#b9b9b9',+ 80: '#c6c6c6',+ 85: '#d4d4d4',+ 90: '#e2e2e2',+ 95: '#f1f1f1',+ 100: '#ffffff',+ },+ dark: {+ 0: '#111111',+ 5: '#1b1b1b',+ 10: '#262626',+ 15: '#303030',+ 20: '#3b3b3b',+ 25: '#474747',+ 30: '#525252',+ 35: '#5e5e5e',+ 40: '#6a6a6a',+ 45: '#777777',+ 50: '#848484',+ 55: '#919191',+ 60: '#9e9e9e',+ 65: '#ababab',+ 70: '#b9b9b9',+ 75: '#c6c6c6',+ 80: '#d4d4d4',+ 85: '#dedede',+ 90: '#e7e7e7',+ 95: '#f1f1f1',+ 100: '#ffffff',+ },+ description:+ 'Pure grayscale foundation for surfaces, text, borders, and neutral states.',+ },+ red: {+ light: {+ 0: '#000000',+ 5: '#2c0000',+ 10: '#3e0002',+ 15: '#500004',+ 20: '#620008',+ 25: '#76000c',+ 30: '#8a0011',+ 35: '#9e0017',+ 40: '#b3001b',+ 45: '#c71024',+ 50: '#d62830',+ 55: '#e53c3e',+ 60: '#f44c4b',+ 65: '#ff635e',+ 70: '#ff7e78',+ 75: '#ff9790',+ 80: '#ffaea7',+ 85: '#ffc4be',+ 90: '#ffd8d3',+ 95: '#feecea',+ 100: '#ffffff',+ hue: 25,+ chroma: 0.0767,+ },+ dark: {+ 0: '#2c0000',+ 5: '#3e0002',+ 10: '#500004',+ 15: '#620008',+ 20: '#76000c',+ 25: '#890012',+ 30: '#9b0e1a',+ 35: '#ab2126',+ 40: '#ba3132',+ 45: '#ca3f3e',+ 50: '#d94e4a',+ 55: '#e85c57',+ 60: '#f76a65',+ 65: '#f7847d',+ 70: '#f99c94',+ 75: '#fab1aa',+ 80: '#fac5c0',+ 85: '#fbd3cf',+ 90: '#fce0dc',+ 95: '#fcedeb',+ 100: '#ffffff',+ hue: 25,+ chroma: 0.0767,+ },+ semantic: 'error',+ description: 'Error, destructive, and red categorical states.',+ },+ orange: {+ light: {+ 0: '#000000',+ 5: '#200b00',+ 10: '#2d1500',+ 15: '#3b1e00',+ 20: '#492700',+ 25: '#583100',+ 30: '#673a00',+ 35: '#774500',+ 40: '#884f00',+ 45: '#985900',+ 50: '#aa6400',+ 55: '#bb6f00',+ 60: '#cd7a00',+ 65: '#df8600',+ 70: '#f19100',+ 75: '#f6a44b',+ 80: '#f7b87a',+ 85: '#f8cba0',+ 90: '#faddc2',+ 95: '#fbeee3',+ 100: '#ffffff',+ hue: 65,+ chroma: 0.0826,+ },+ dark: {+ 0: '#200b00',+ 5: '#2d1500',+ 10: '#3b1e00',+ 15: '#492700',+ 20: '#583100',+ 25: '#673a00',+ 30: '#774500',+ 35: '#884f00',+ 40: '#985900',+ 45: '#aa6400',+ 50: '#bb6f00',+ 55: '#cd7a00',+ 60: '#df8600',+ 65: '#eb952c',+ 70: '#eea75f',+ 75: '#f2ba85',+ 80: '#f4cca7',+ 85: '#f6d8bc',+ 90: '#f8e3d1',+ 95: '#faefe5',+ 100: '#ffffff',+ hue: 65,+ chroma: 0.0826,+ },+ description: 'Orange categorical states.',+ },+ yellow: {+ light: {+ 0: '#000000',+ 5: '#190f00',+ 10: '#251a00',+ 15: '#312400',+ 20: '#3d2e00',+ 25: '#4b3900',+ 30: '#584400',+ 35: '#664f00',+ 40: '#745b00',+ 45: '#836700',+ 50: '#927300',+ 55: '#a17f00',+ 60: '#b18c00',+ 65: '#c09800',+ 70: '#d0a500',+ 75: '#e1b300',+ 80: '#f1c000',+ 85: '#f9d05b',+ 90: '#f9e19e',+ 95: '#fbf0d3',+ 100: '#ffffff',+ hue: 90,+ chroma: 0.1534,+ },+ dark: {+ 0: '#190f00',+ 5: '#251a00',+ 10: '#312400',+ 15: '#3d2e00',+ 20: '#4b3900',+ 25: '#584400',+ 30: '#664f00',+ 35: '#745b00',+ 40: '#836700',+ 45: '#927300',+ 50: '#a17f00',+ 55: '#b18c00',+ 60: '#c09800',+ 65: '#d0a500',+ 70: '#e1b300',+ 75: '#f1c000',+ 80: '#f4d170',+ 85: '#f6dc97',+ 90: '#f7e6b8',+ 95: '#f9f0d7',+ 100: '#ffffff',+ hue: 90,+ chroma: 0.1534,+ },+ semantic: 'warning',+ description: 'Warning and yellow categorical states.',+ },+ green: {+ light: {+ 0: '#000000',+ 5: '#001800',+ 10: '#002401',+ 15: '#003004',+ 20: '#003d08',+ 25: '#004a0c',+ 30: '#005711',+ 35: '#006516',+ 40: '#00731b',+ 45: '#008120',+ 50: '#009026',+ 55: '#079f2b',+ 60: '#27ad3c',+ 65: '#3dba4b',+ 70: '#67c46d',+ 75: '#85cd88',+ 80: '#a1d7a1',+ 85: '#bbe1bb',+ 90: '#d2ead2',+ 95: '#eaf4ea',+ 100: '#ffffff',+ hue: 145,+ chroma: 0.0708,+ },+ dark: {+ 0: '#001800',+ 5: '#002401',+ 10: '#003004',+ 15: '#003d08',+ 20: '#004a0c',+ 25: '#005711',+ 30: '#006518',+ 35: '#00731c',+ 40: '#0c8124',+ 45: '#228e31',+ 50: '#339c3f',+ 55: '#43a94c',+ 60: '#53b75a',+ 65: '#74c177',+ 70: '#8ecb8f',+ 75: '#a6d5a6',+ 80: '#bedfbe',+ 85: '#cee6cd',+ 90: '#dcecdb',+ 95: '#ebf4eb',+ 100: '#ffffff',+ hue: 145,+ chroma: 0.0708,+ },+ semantic: 'success',+ description: 'Success and green categorical states.',+ },+ teal: {+ light: {+ 0: '#000000',+ 5: '#001612',+ 10: '#00221c',+ 15: '#002e27',+ 20: '#003a31',+ 25: '#00463d',+ 30: '#005348',+ 35: '#006154',+ 40: '#006e60',+ 45: '#007c6d',+ 50: '#008b79',+ 55: '#009986',+ 60: '#00a893',+ 65: '#00b7a1',+ 70: '#00c6ae',+ 75: '#34d4bc',+ 80: '#76dcc9',+ 85: '#a2e4d6',+ 90: '#c3ede3',+ 95: '#e4f5f1',+ 100: '#ffffff',+ hue: 180,+ chroma: 0.0767,+ },+ dark: {+ 0: '#001612',+ 5: '#00221c',+ 10: '#002e27',+ 15: '#003a31',+ 20: '#00463d',+ 25: '#005348',+ 30: '#006154',+ 35: '#006e60',+ 40: '#007c6d',+ 45: '#008b79',+ 50: '#009986',+ 55: '#00a893',+ 60: '#00b7a1',+ 65: '#00c6ae',+ 70: '#55d1bb',+ 75: '#84dac8',+ 80: '#a8e2d6',+ 85: '#bee9df',+ 90: '#d2eee8',+ 95: '#e6f5f1',+ 100: '#ffffff',+ hue: 180,+ chroma: 0.0767,+ },+ description: 'Teal categorical states.',+ },+ cyan: {+ light: {+ 0: '#000000',+ 5: '#00151b',+ 10: '#002028',+ 15: '#002c35',+ 20: '#003742',+ 25: '#004350',+ 30: '#00505f',+ 35: '#005d6d',+ 40: '#006a7d',+ 45: '#00788c',+ 50: '#00869c',+ 55: '#0094ac',+ 60: '#00a2bd',+ 65: '#00b1ce',+ 70: '#00bfdf',+ 75: '#29ceed',+ 80: '#71d7ef',+ 85: '#9ee1f1',+ 90: '#c2eaf5',+ 95: '#e3f4f9',+ 100: '#ffffff',+ hue: 215,+ chroma: 0.0767,+ },+ dark: {+ 0: '#00151b',+ 5: '#002028',+ 10: '#002c35',+ 15: '#003742',+ 20: '#004350',+ 25: '#00505f',+ 30: '#005d6d',+ 35: '#006a7d',+ 40: '#00788c',+ 45: '#00869c',+ 50: '#0094ac',+ 55: '#00a2bd',+ 60: '#00b1ce',+ 65: '#00bfdf',+ 70: '#50cbe7',+ 75: '#80d6ea',+ 80: '#a7dfed',+ 85: '#bce7f1',+ 90: '#d1edf5',+ 95: '#e5f4f8',+ 100: '#ffffff',+ hue: 215,+ chroma: 0.0767,+ },+ description: 'Cyan categorical states.',+ },+ blue: {+ light: {+ 0: '#000000',+ 5: '#000f30',+ 10: '#001a41',+ 15: '#002452',+ 20: '#002f64',+ 25: '#003a78',+ 30: '#00458c',+ 35: '#0050a1',+ 40: '#005cb6',+ 45: '#0068cc',+ 50: '#0074e2',+ 55: '#0081f9',+ 60: '#2f90ff',+ 65: '#529fff',+ 70: '#6eaeff',+ 75: '#87bcff',+ 80: '#a0caff',+ 85: '#b8d7ff',+ 90: '#d0e5ff',+ 95: '#e8f2ff',+ 100: '#ffffff',+ hue: 255,+ chroma: 0.1003,+ },+ dark: {+ 0: '#000f30',+ 5: '#001a41',+ 10: '#002452',+ 15: '#002f64',+ 20: '#003a78',+ 25: '#00458c',+ 30: '#0050a1',+ 35: '#005cb6',+ 40: '#0068cc',+ 45: '#0074e2',+ 50: '#0080f9',+ 55: '#2f90ff',+ 60: '#529fff',+ 65: '#6eaeff',+ 70: '#87bcff',+ 75: '#a0caff',+ 80: '#b8d7ff',+ 85: '#c8e0ff',+ 90: '#d8e9ff',+ 95: '#e8f2ff',+ 100: '#ffffff',+ hue: 255,+ chroma: 0.1003,+ },+ semantic: 'info',+ description: 'Information, accent, and blue categorical states.',+ },+ purple: {+ light: {+ 0: '#000000',+ 5: '#22002a',+ 10: '#31003b',+ 15: '#40004c',+ 20: '#4f005e',+ 25: '#5f0070',+ 30: '#6f0782',+ 35: '#7c1a90',+ 40: '#8b2a9f',+ 45: '#9838ad',+ 50: '#a746bb',+ 55: '#b455c9',+ 60: '#c263d7',+ 65: '#cf71e6',+ 70: '#d58ae6',+ 75: '#dc9fe9',+ 80: '#e1b3ed',+ 85: '#e8c7ef',+ 90: '#f0dbf4',+ 95: '#f6edf8',+ 100: '#ffffff',+ hue: 320,+ chroma: 0.0708,+ },+ dark: {+ 0: '#22002a',+ 5: '#31003b',+ 10: '#40004c',+ 15: '#4f005d',+ 20: '#5c116b',+ 25: '#6a1e78',+ 30: '#762b87',+ 35: '#843895',+ 40: '#9244a3',+ 45: '#a051b1',+ 50: '#ae5fc0',+ 55: '#bb6cce',+ 60: '#c979dc',+ 65: '#d090de',+ 70: '#d7a3e3',+ 75: '#dfb6e8',+ 80: '#e6c9ec',+ 85: '#ebd5ef',+ 90: '#f0e2f4',+ 95: '#f6eef7',+ 100: '#ffffff',+ hue: 320,+ chroma: 0.0708,+ },+ description: 'Purple categorical states.',+ },+ pink: {+ light: {+ 0: '#000000',+ 5: '#290013',+ 10: '#3b001e',+ 15: '#4b0028',+ 20: '#5d0034',+ 25: '#70003f',+ 30: '#82004b',+ 35: '#960058',+ 40: '#a81064',+ 45: '#b72470',+ 50: '#c6357d',+ 55: '#d5458a',+ 60: '#e45397',+ 65: '#f363a4',+ 70: '#f47fb0',+ 75: '#f697bc',+ 80: '#f7adc9',+ 85: '#f9c4d6',+ 90: '#fad7e4',+ 95: '#fbecf1',+ 100: '#ffffff',+ hue: 355,+ chroma: 0.0708,+ },+ dark: {+ 0: '#290013',+ 5: '#3b001e',+ 10: '#4b0028',+ 15: '#5d0034',+ 20: '#6f003f',+ 25: '#800a4a',+ 30: '#8f1b56',+ 35: '#9e2b63',+ 40: '#ad3870',+ 45: '#bc467c',+ 50: '#cb5389',+ 55: '#d96196',+ 60: '#e86ea3',+ 65: '#eb87b0',+ 70: '#ee9cbd',+ 75: '#f1b1c9',+ 80: '#f4c6d6',+ 85: '#f6d3df',+ 90: '#f8e0e8',+ 95: '#faedf1',+ 100: '#ffffff',+ hue: 355,+ chroma: 0.0708,+ },+ description: 'Pink categorical states.',+ },+} as const;diff --git a/apps/sandbox/src/app/(sandbox)/pages/palette-generator/page.tsx b/apps/sandbox/src/app/(sandbox)/pages/palette-generator/page.tsxnew file mode 100644index 0000000000..7c198a1a1e--- /dev/null+++ b/apps/sandbox/src/app/(sandbox)/pages/palette-generator/page.tsx@@ -0,0 +1,1576 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++'use client';++import {useMemo, useState} from 'react';+import {Button} from '@astryxdesign/core/Button';+import {IconButton} from '@astryxdesign/core/IconButton';+import {HStack, VStack} from '@astryxdesign/core/Layout';+import {NumberInput} from '@astryxdesign/core/NumberInput';+import {+ SegmentedControl,+ SegmentedControlItem,+} from '@astryxdesign/core/SegmentedControl';+import {Selector} from '@astryxdesign/core/Selector';+import {Slider} from '@astryxdesign/core/Slider';+import {Text, Heading} from '@astryxdesign/core/Text';+import {TextInput} from '@astryxdesign/core/TextInput';++import {+ COMPACT_11_STOPS,+ FULL_21_STOPS,+ generatePaletteSet,+ parseStopList,+ perceptualDelta,+ serializeGenerationResult,+ type AnchorPolicy,+ type GeneratedFamily,+ type GeneratedRamp,+ type ModeStrategy,+ type NeutralProfile,+ type PaletteAlgorithm,+ type PaletteFamilyRequest,+ type PaletteGenerationResult,+ type PaletteMode,+} from './generator';+import {+ THEME_REFERENCES,+ type ThemeReference,+ type ThemeReferenceFamily,+} from './themeCorpus';++const MONO = "'JetBrains Mono', 'SF Mono', Menlo, monospace";++type AlgorithmView = 'oklch' | 'hct' | 'compare';+type LabView = 'generator' | 'themes';+type VibrancyPreset = 'muted' | 'balanced' | 'vibrant';+type StopPreset = 'full-21' | 'compact-11' | 'custom';+type EditableAnchor = {+ mode: PaletteMode;+ stop: number;+ color: string;+ policy: AnchorPolicy;+ maxDeltaE: number;+};+type EditableFamily = Omit<PaletteFamilyRequest, 'anchors'> & {+ anchors: EditableAnchor[];+};++function editableFamily(+ id: string,+ name: string,+ seed: string,+ options: {+ kind?: 'chromatic' | 'neutral';+ anchors?: EditableAnchor[];+ } = {},+): EditableFamily {+ return {+ id,+ name,+ seed,+ kind: options.kind ?? 'chromatic',+ anchors: options.anchors ?? [],+ };+}++const INITIAL_FAMILIES: EditableFamily[] = [+ editableFamily('neutral', 'Neutral', '#777777', {kind: 'neutral'}),+ editableFamily('blue', 'Blue', '#0074e2', {+ anchors: [+ {+ mode: 'light',+ stop: 50,+ color: '#0074e2',+ policy: 'exact',+ maxDeltaE: 2,+ },+ ],+ }),+ editableFamily('red', 'Red', '#d62830'),+ editableFamily('orange', 'Orange', '#d57113'),+ editableFamily('yellow', 'Yellow', '#f8c723', {+ anchors: [+ {+ mode: 'light',+ stop: 80,+ color: '#f8c723',+ policy: 'preferred',+ maxDeltaE: 3,+ },+ ],+ }),+ editableFamily('green', 'Green', '#358a3a', {+ anchors: [+ {+ mode: 'light',+ stop: 50,+ color: '#358a3a',+ policy: 'preferred',+ maxDeltaE: 3,+ },+ ],+ }),+ editableFamily('teal', 'Teal', '#0c7365'),+ editableFamily('cyan', 'Cyan', '#0c6f82'),+ editableFamily('purple', 'Purple', '#980fb2', {+ anchors: [+ {+ mode: 'light',+ stop: 50,+ color: '#980fb2',+ policy: 'preferred',+ maxDeltaE: 3,+ },+ ],+ }),+ editableFamily('pink', 'Pink', '#b10e69'),+];++const styles = {+ page: {+ display: 'flex',+ height: '100vh',+ overflow: 'hidden',+ backgroundColor: 'var(--color-background-surface, #fff)',+ } satisfies React.CSSProperties,+ sidebar: {+ width: 380,+ flexShrink: 0,+ height: '100vh',+ padding: 8,+ } satisfies React.CSSProperties,+ panel: {+ height: '100%',+ overflow: 'hidden',+ display: 'flex',+ flexDirection: 'column' as const,+ border: '1px solid var(--color-border, #ddd)',+ borderRadius: 16,+ backgroundColor: 'var(--color-background-card, #fff)',+ } satisfies React.CSSProperties,+ header: {+ padding: 16,+ borderBottom: '1px solid var(--color-border, #ddd)',+ } satisfies React.CSSProperties,+ controls: {+ flex: 1,+ minHeight: 0,+ overflowY: 'auto' as const,+ padding: 16,+ } satisfies React.CSSProperties,+ main: {+ flex: 1,+ minWidth: 0,+ height: '100vh',+ overflowY: 'auto' as const,+ padding: 24,+ } satisfies React.CSSProperties,+ fieldLabel: {+ minWidth: 74,+ flexShrink: 0,+ } satisfies React.CSSProperties,+ family: {+ borderTop: '1px solid var(--color-border, #ddd)',+ paddingTop: 12,+ } satisfies React.CSSProperties,+ swatchStrip: {+ display: 'grid',+ gridAutoFlow: 'column' as const,+ gridAutoColumns: 'minmax(28px, 1fr)',+ overflowX: 'auto' as const,+ border: '1px solid var(--color-border, #ddd)',+ borderRadius: 8,+ } satisfies React.CSSProperties,+ swatch: (color: string): React.CSSProperties => ({+ minWidth: 28,+ height: 54,+ backgroundColor: color,+ position: 'relative' as const,+ }),+ stopLabel: {+ position: 'absolute' as const,+ insetInline: 0,+ bottom: 3,+ textAlign: 'center' as const,+ fontFamily: MONO,+ fontSize: 8,+ color: 'var(--color-text-primary, #111)',+ mixBlendMode: 'difference' as const,+ filter: 'invert(1)',+ } satisfies React.CSSProperties,+ resultSection: {+ padding: 16,+ border: '1px solid var(--color-border, #ddd)',+ borderRadius: 12,+ backgroundColor: 'var(--color-background-card, #fff)',+ } satisfies React.CSSProperties,+ diagnostic: {+ fontFamily: MONO,+ fontSize: 10,+ color: 'var(--color-text-secondary, #666)',+ } satisfies React.CSSProperties,+ sampleGrid: {+ display: 'grid',+ gridTemplateColumns: 'repeat(2, minmax(220px, 1fr))',+ gap: 12,+ } satisfies React.CSSProperties,+};++function algorithmForView(+ view: Exclude<AlgorithmView, 'compare'>,+): PaletteAlgorithm {+ return view === 'oklch' ? 'oklch-v1-experimental' : 'hct-v1-experimental';+}++function presetForVibrancy(vibrancy: number): VibrancyPreset {+ if (vibrancy < 38) {+ return 'muted';+ }+ if (vibrancy > 62) {+ return 'vibrant';+ }+ return 'balanced';+}++function vibrancyForPreset(preset: VibrancyPreset): number {+ return preset === 'muted' ? 25 : preset === 'vibrant' ? 75 : 50;+}++function nearestStop(stops: number[], target: number): number {+ return stops.reduce((best, stop) =>+ Math.abs(stop - target) < Math.abs(best - target) ? stop : best,+ );+}++function nextAnchorStop(+ stops: number[],+ anchors: EditableAnchor[],+ mode: PaletteMode,+): number {+ const occupied = new Set(+ anchors.filter(anchor => anchor.mode === mode).map(anchor => anchor.stop),+ );+ return (+ [...stops]+ .sort((a, b) => Math.abs(a - 50) - Math.abs(b - 50))+ .find(stop => !occupied.has(stop)) ?? stops[0]+ );+}++function resultColor(+ result: PaletteGenerationResult,+ familyId: string,+ mode: PaletteMode,+ targetStop: number,+ fallback: string,+): string {+ const ramp = result.families.find(family => family.id === familyId)?.[mode];+ if (!ramp) {+ return fallback;+ }+ const stop = nearestStop(result.request.stops, targetStop);+ return ramp.colors[stop] ?? fallback;+}++function ContextPreview({result}: {result: PaletteGenerationResult}) {+ const lightBg = resultColor(result, 'neutral', 'light', 95, '#f5f5f5');+ const lightText = resultColor(result, 'neutral', 'light', 10, '#222222');+ const darkBg = resultColor(result, 'neutral', 'dark', 10, '#1b1b1b');+ const darkText = resultColor(result, 'neutral', 'dark', 90, '#ededed');+ const lightBlue = resultColor(result, 'blue', 'light', 50, '#0064e0');+ const darkBlue = resultColor(result, 'blue', 'dark', 70, '#70a0ff');+ const lightYellow = resultColor(result, 'yellow', 'light', 80, '#e0b600');+ const darkYellow = resultColor(result, 'yellow', 'dark', 70, '#e8c94c');+ const lightGreen = resultColor(result, 'green', 'light', 50, '#248a36');+ const darkGreen = resultColor(result, 'green', 'dark', 70, '#75c47c');++ const examples = [+ result.request.modeStrategy !== 'dark-only'+ ? {+ mode: 'light' as const,+ label: 'Light context',+ background: lightBg,+ text: lightText,+ colors: [lightBlue, lightYellow, lightGreen],+ }+ : null,+ result.request.modeStrategy !== 'light-only'+ ? {+ mode: 'dark' as const,+ label: 'Dark context',+ background: darkBg,+ text: darkText,+ colors: [darkBlue, darkYellow, darkGreen],+ }+ : null,+ ].filter(example => example != null);++ return (+ <div style={styles.sampleGrid}>+ {examples.map(example => (+ <div+ key={example.label}+ style={{+ padding: 18,+ borderRadius: 12,+ backgroundColor: example.background,+ color: example.text,+ border: '1px solid var(--color-border, #ddd)',+ }}>+ <div style={{fontWeight: 700, marginBottom: 6}}>{example.label}</div>+ <div style={{fontSize: 12, opacity: 0.8, marginBottom: 14}}>+ Context preview only—not an accessibility approval.+ </div>+ {example.mode === 'dark' && (+ <div style={{fontSize: 12, marginBottom: 14, maxWidth: 460}}>+ Body text uses the generated near-white neutral. Pure white is+ intentionally avoided because it can feel harsh or “vibrate” on a+ dark surface.+ </div>+ )}+ <div style={{display: 'flex', gap: 8, flexWrap: 'wrap'}}>+ {example.colors.map((color, index) => (+ <div+ key={color}+ style={{+ padding: '8px 12px',+ borderRadius: 999,+ backgroundColor: color,+ color: index === 1 ? '#241b00' : example.background,+ fontWeight: 700,+ fontSize: 12,+ }}>+ {['Blue', 'Yellow', 'Green'][index]}+ </div>+ ))}+ </div>+ </div>+ ))}+ </div>+ );+}++function CompactRampDiagnostics({+ label,+ ramp,+}: {+ label: string;+ ramp: GeneratedRamp;+}) {+ return (+ <div style={styles.diagnostic}>+ {label}: min/max adjacent ΔE{' '}+ {ramp.diagnostics.minimumAdjacentDeltaE.toFixed(1)}/+ {ramp.diagnostics.maximumAdjacentDeltaE.toFixed(1)} · hue drift{' '}+ {ramp.diagnostics.maximumHueDrift.toFixed(1)}° · mapped{' '}+ {ramp.diagnostics.gamutMappedStops.length}+ </div>+ );+}++function HueIdentityWarning({+ label,+ ramp,+}: {+ label?: string;+ ramp: GeneratedRamp;+}) {+ if (!ramp.diagnostics.hueIdentityRisk) {+ return null;+ }+ const message =+ ramp.diagnostics.hueIdentityRisk === 'blue-to-purple'+ ? 'blue may shift toward purple'+ : 'yellow may shift toward orange/brown';+ return (+ <Text+ type="supporting"+ style={{color: 'var(--color-text-yellow, #7a5700)'}}>+ {label ? `${label}: ` : ''}Review hue identity—{message}.+ </Text>+ );+}++function CompareRampRows({+ familyName,+ mode,+ stops,+ oklchRamp,+ hctRamp,+}: {+ familyName: string;+ mode: PaletteMode;+ stops: number[];+ oklchRamp?: GeneratedRamp;+ hctRamp?: GeneratedRamp;+}) {+ const rows = [+ {label: 'OKLCH', ramp: oklchRamp},+ {label: 'HCT-like', ramp: hctRamp},+ ].filter(+ (row): row is {label: string; ramp: GeneratedRamp} => row.ramp != null,+ );++ return (+ <VStack gap={2}>+ <Text type="supporting" weight="semibold">+ {mode === 'light' ? 'Light' : 'Dark'}+ </Text>+ <div>+ {rows.map((row, rowIndex) => (+ <div+ key={row.label}+ style={{+ display: 'grid',+ gridTemplateColumns: '72px minmax(0, 1fr)',+ alignItems: 'stretch',+ }}>+ <div+ style={{+ display: 'flex',+ alignItems: 'center',+ paddingInlineEnd: 8,+ fontFamily: MONO,+ fontSize: 10,+ fontWeight: 700,+ }}>+ {row.label}+ </div>+ <div+ style={{+ ...styles.swatchStrip,+ borderRadius:+ rows.length === 1+ ? 8+ : rowIndex === 0+ ? '8px 8px 0 0'+ : '0 0 8px 8px',+ borderBottomWidth: rows.length > 1 && rowIndex === 0 ? 0 : 1,+ borderTopWidth: rows.length > 1 && rowIndex === 1 ? 0 : 1,+ }}>+ {stops.map(stop => (+ <div+ key={stop}+ title={`${familyName} ${row.label} ${mode} ${stop}: ${row.ramp.colors[stop]}`}+ style={styles.swatch(row.ramp.colors[stop])}>+ <span style={styles.stopLabel}>{stop}</span>+ </div>+ ))}+ </div>+ </div>+ ))}+ </div>+ {oklchRamp && <CompactRampDiagnostics label="OKLCH" ramp={oklchRamp} />}+ {hctRamp && <CompactRampDiagnostics label="HCT-like" ramp={hctRamp} />}+ {oklchRamp && <HueIdentityWarning label="OKLCH" ramp={oklchRamp} />}+ {hctRamp && <HueIdentityWarning label="HCT-like" ramp={hctRamp} />}+ {hctRamp &&+ oklchRamp &&+ hctRamp.diagnostics.maximumHueDrift >+ oklchRamp.diagnostics.maximumHueDrift + 8 && (+ <Text+ type="supporting"+ style={{color: 'var(--color-text-yellow, #7a5700)'}}>+ HCT-like has materially more hue drift in this ramp.+ </Text>+ )}+ </VStack>+ );+}++function CompareResultView({+ oklch,+ hct,+}: {+ oklch: PaletteGenerationResult;+ hct: PaletteGenerationResult;+}) {+ function familyFor(+ result: PaletteGenerationResult,+ familyId: string,+ ): GeneratedFamily | undefined {+ return result.families.find(family => family.id === familyId);+ }++ return (+ <VStack gap={5} style={styles.resultSection}>+ <VStack gap={1}>+ <Heading level={3}>Direct algorithm comparison</Heading>+ <Text type="supporting" color="secondary">+ Matching ramps share an edge so differences appear in the same visual+ position.+ </Text>+ </VStack>++ {[...oklch.errors, ...hct.errors].map((error, index) => (+ <div+ key={`${error.familyId}-${index}`}+ style={{+ padding: 10,+ borderRadius: 8,+ color: 'var(--color-error)',+ backgroundColor: 'var(--color-error-muted)',+ }}>+ <strong>{error.familyId}:</strong> {error.message}+ </div>+ ))}++ {oklch.request.families.map(requestedFamily => {+ const oklchFamily = familyFor(oklch, requestedFamily.id);+ const hctFamily = familyFor(hct, requestedFamily.id);+ if (!oklchFamily && !hctFamily) {+ return null;+ }++ return (+ <VStack key={requestedFamily.id} gap={3}>+ <Text weight="semibold">{requestedFamily.name}</Text>+ {(['light', 'dark'] as const).map(mode => {+ const oklchRamp = oklchFamily?.[mode];+ const hctRamp = hctFamily?.[mode];+ if (!oklchRamp && !hctRamp) {+ return null;+ }+ return (+ <CompareRampRows+ key={mode}+ familyName={requestedFamily.name}+ mode={mode}+ stops={oklch.request.stops}+ oklchRamp={oklchRamp}+ hctRamp={hctRamp}+ />+ );+ })}+ </VStack>+ );+ })}++ <div+ style={{+ display: 'grid',+ gridTemplateColumns: 'repeat(2, minmax(0, 1fr))',+ gap: 12,+ }}>+ <VStack gap={2}>+ <Text weight="semibold">OKLCH contexts</Text>+ <ContextPreview result={oklch} />+ </VStack>+ <VStack gap={2}>+ <Text weight="semibold">HCT-like contexts</Text>+ <ContextPreview result={hct} />+ </VStack>+ </div>+ </VStack>+ );+}++function differenceStats(+ reference: Record<number, string>,+ generated: Record<number, string>,+ stops: number[],+): {average: number; maximum: number; maximumStop: number} {+ const differences = stops.map(stop => ({+ stop,+ delta: perceptualDelta(reference[stop], generated[stop]),+ }));+ const maximum = differences.reduce((largest, item) =>+ item.delta > largest.delta ? item : largest,+ );+ return {+ average:+ differences.reduce((sum, item) => sum + item.delta, 0) /+ differences.length,+ maximum: maximum.delta,+ maximumStop: maximum.stop,+ };+}++function ThemeFamilyComparison({+ reference,+ results,+ stops,+ sharedAcrossModes,+}: {+ reference: ThemeReferenceFamily;+ results: PaletteGenerationResult[];+ stops: number[];+ sharedAcrossModes?: boolean;+}) {+ return (+ <VStack gap={3}>+ <HStack vAlign="center" style={{justifyContent: 'space-between'}}>+ <Text weight="semibold">{reference.name}</Text>+ <Text type="supporting" color="secondary">+ source {reference.seed}+ </Text>+ </HStack>+ {(['light', 'dark'] as const).map(mode => {+ const existing = reference[mode];+ if (!existing) {+ return null;+ }+ const generatedRows = results+ .map(result => {+ const family = result.families.find(+ item => item.id === reference.id,+ );+ const ramp = family?.[mode];+ return ramp+ ? {+ label:+ result.request.algorithm === 'oklch-v1-experimental'+ ? 'OKLCH'+ : 'HCT-like',+ colors: ramp.colors,+ stats: differenceStats(existing, ramp.colors, stops),+ }+ : null;+ })+ .filter(+ (+ row,+ ): row is {+ label: string;+ colors: Record<number, string>;+ stats: {average: number; maximum: number; maximumStop: number};+ } => row != null,+ );+ const existingRow = {+ label: sharedAcrossModes ? 'Existing shared' : 'Existing',+ colors: existing,+ stats: null,+ };+ const rows =+ generatedRows.length === 2+ ? [generatedRows[0], existingRow, generatedRows[1]]+ : [existingRow, ...generatedRows];++ return (+ <VStack key={mode} gap={2}>+ <Text type="supporting" weight="semibold">+ {mode === 'light' ? 'Light' : 'Dark'} candidate+ {sharedAcrossModes ? ' vs shared reference' : ''}+ </Text>+ <div>+ {rows.map((row, rowIndex) => (+ <div+ key={row.label}+ style={{+ display: 'grid',+ gridTemplateColumns: '96px minmax(0, 1fr)',+ alignItems: 'stretch',+ }}>+ <div+ style={{+ display: 'flex',+ alignItems: 'center',+ paddingInlineEnd: 8,+ fontFamily: MONO,+ fontSize: 10,+ fontWeight: 700,+ }}>+ {row.label}+ </div>+ <div+ style={{+ ...styles.swatchStrip,+ borderRadius:+ rowIndex === 0+ ? '8px 8px 0 0'+ : rowIndex === rows.length - 1+ ? '0 0 8px 8px'+ : 0,+ borderTopWidth: rowIndex === 0 ? 1 : 0,+ borderBottomWidth: rowIndex === rows.length - 1 ? 1 : 0,+ }}>+ {stops.map(stop => (+ <div+ key={stop}+ title={`${reference.name} ${row.label} ${mode} ${stop}: ${row.colors[stop]}`}+ style={styles.swatch(row.colors[stop])}>+ <span style={styles.stopLabel}>{stop}</span>+ </div>+ ))}+ </div>+ </div>+ ))}+ </div>+ {generatedRows.map(row => (+ <div key={row.label} style={styles.diagnostic}>+ {row.label} vs existing: average ΔE{' '}+ {row.stats.average.toFixed(1)} · maximum{' '}+ {row.stats.maximum.toFixed(1)} at stop {row.stats.maximumStop}+ </div>+ ))}+ </VStack>+ );+ })}+ </VStack>+ );+}++function ThemeComparisonView({+ theme,+ results,+}: {+ theme: ThemeReference;+ results: PaletteGenerationResult[];+}) {+ const stops = FULL_21_STOPS.filter(stop => stop !== 0 && stop !== 100);+ const hasSharedReferences = theme.families.some(+ family => family.sharedAcrossModes,+ );+ return (+ <VStack gap={5} style={styles.resultSection}>+ <VStack gap={1}>+ <HStack vAlign="center" style={{justifyContent: 'space-between'}}>+ <Heading level={3}>{theme.name} theme comparison</Heading>+ <Text type="supporting" color="secondary">+ {theme.referenceKind === 'stored'+ ? 'stored reference ramps'+ : 'legacy generated reference'}+ </Text>+ </HStack>+ <Text type="supporting" color="secondary">+ {theme.description} Shared black and white endpoints are omitted from+ the display but remain in exported data.+ </Text>+ {hasSharedReferences && (+ <Text+ type="supporting"+ style={{color: 'var(--color-text-yellow, #7a5700)'}}>+ This package publishes one mode-agnostic ramp. Repeating it beside+ both candidates does not mean its dark-mode palette was reviewed+ independently.+ </Text>+ )}+ </VStack>+ {theme.families.map(family => (+ <ThemeFamilyComparison+ key={family.id}+ reference={family}+ results={results}+ stops={stops}+ sharedAcrossModes={family.sharedAcrossModes}+ />+ ))}+ </VStack>+ );+}++function ResultView({result}: {result: PaletteGenerationResult}) {+ return (+ <VStack gap={5} style={styles.resultSection}>+ <HStack vAlign="center" style={{justifyContent: 'space-between'}}>+ <Heading level={3}>+ {result.request.algorithm === 'oklch-v1-experimental'+ ? 'OKLCH experiment'+ : 'CIELAB / HCT-like experiment'}+ </Heading>+ <Text type="supporting" color="secondary">+ vibrancy {result.request.vibrancy} · {result.request.stops.length}{' '}+ stops+ </Text>+ </HStack>++ {result.errors.map(error => (+ <div+ key={error.familyId}+ style={{+ padding: 10,+ borderRadius: 8,+ color: 'var(--color-error)',+ backgroundColor: 'var(--color-error-muted)',+ }}>+ <strong>{error.familyId}:</strong> {error.message}+ </div>+ ))}++ {result.coordination.map(diagnostic => (+ <div+ key={diagnostic.mode}+ style={{+ padding: 10,+ borderRadius: 8,+ backgroundColor: 'var(--color-background-secondary, #f4f4f4)',+ }}>+ <Text type="supporting" weight="semibold">+ {diagnostic.mode === 'light' ? 'Light' : 'Dark'} family balance at+ stop {diagnostic.stop}+ </Text>+ <div style={styles.diagnostic}>+ Closest pair:{' '}+ {diagnostic.closestFamilies+ ? `${diagnostic.closestFamilies.join(' / ')} (ΔE ${diagnostic.minimumFamilyDeltaE?.toFixed(1)})`+ : 'not enough chromatic families'}+ {' · '}Strongest chroma: {diagnostic.strongestFamily ?? 'n/a'}+ {' · '}Weakest chroma: {diagnostic.weakestFamily ?? 'n/a'}+ {diagnostic.chromaRatio != null+ ? ` · ratio ${diagnostic.chromaRatio.toFixed(2)}×`+ : ''}+ </div>+ {diagnostic.minimumFamilyDeltaE != null &&+ diagnostic.minimumFamilyDeltaE < 8 && (+ <Text+ type="supporting"+ style={{color: 'var(--color-text-yellow, #7a5700)'}}>+ Review this pair in real components: neighboring families may be+ too similar to communicate different meanings reliably.+ </Text>+ )}+ {diagnostic.chromaRatio != null && diagnostic.chromaRatio > 2 && (+ <Text+ type="supporting"+ style={{color: 'var(--color-text-yellow, #7a5700)'}}>+ Review visual weight: the strongest family is more than twice as+ chromatic as the weakest.+ </Text>+ )}+ </div>+ ))}++ {result.families.map(family => (+ <VStack key={family.id} gap={2}>+ <HStack vAlign="center" style={{justifyContent: 'space-between'}}>+ <Text weight="semibold">{family.name}</Text>+ <Text type="supporting" color="secondary">+ seed {family.seed}+ </Text>+ </HStack>+ {(['light', 'dark'] as const).map(mode => {+ const ramp = family[mode];+ if (!ramp) {+ return null;+ }+ return (+ <VStack key={mode} gap={1}>+ <HStack+ vAlign="center"+ style={{justifyContent: 'space-between'}}>+ <Text type="supporting" weight="semibold">+ {mode === 'light' ? 'Light' : 'Dark'}+ </Text>+ <span style={styles.diagnostic}>+ {ramp.diagnostics.monotonic ? 'monotonic' : 'not monotonic'}{' '}+ · min ΔE {ramp.diagnostics.minimumAdjacentDeltaE.toFixed(1)}{' '}+ · max ΔE {ramp.diagnostics.maximumAdjacentDeltaE.toFixed(1)}{' '}+ · max hue drift{' '}+ {ramp.diagnostics.maximumHueDrift.toFixed(1)}° · mapped{' '}+ {ramp.diagnostics.gamutMappedStops.length}+ </span>+ </HStack>+ <div style={styles.swatchStrip}>+ {result.request.stops.map(stop => (+ <div+ key={stop}+ title={`${family.name} ${mode} ${stop}: ${ramp.colors[stop]}`}+ style={styles.swatch(ramp.colors[stop])}>+ <span style={styles.stopLabel}>{stop}</span>+ </div>+ ))}+ </div>+ <HueIdentityWarning ramp={ramp} />+ {ramp.diagnostics.anchors.map(anchor => (+ <Text+ key={`${anchor.mode}-${anchor.stop}`}+ type="supporting"+ color="secondary">+ {anchor.policy} anchor · {mode} {anchor.stop} · requested{' '}+ {anchor.color} · produced {anchor.generatedColor} · ΔE{' '}+ {anchor.deltaE.toFixed(2)}+ </Text>+ ))}+ </VStack>+ );+ })}+ </VStack>+ ))}++ <ContextPreview result={result} />+ </VStack>+ );+}++export default function PaletteGeneratorPage() {+ const [labView, setLabView] = useState<LabView>('generator');+ const [algorithmView, setAlgorithmView] = useState<AlgorithmView>('compare');+ const [vibrancy, setVibrancy] = useState(50);+ const [neutralProfile, setNeutralProfile] =+ useState<NeutralProfile>('neutral-v1');+ const [modeStrategy, setModeStrategy] =+ useState<ModeStrategy>('light-and-dark');+ const [stopPreset, setStopPreset] = useState<StopPreset>('full-21');+ const [customStops, setCustomStops] = useState(+ '0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100',+ );+ const [families, setFamilies] = useState<EditableFamily[]>(INITIAL_FAMILIES);+ const [selectedThemeId, setSelectedThemeId] = useState(+ THEME_REFERENCES[0].id,+ );+ const [copied, setCopied] = useState(false);++ const stopResolution = useMemo(() => {+ try {+ const stops =+ stopPreset === 'full-21'+ ? [...FULL_21_STOPS]+ : stopPreset === 'compact-11'+ ? [...COMPACT_11_STOPS]+ : parseStopList(customStops);+ return {stops, error: null};+ } catch (error) {+ return {+ stops: [...FULL_21_STOPS],+ error: error instanceof Error ? error.message : String(error),+ };+ }+ }, [customStops, stopPreset]);++ const familyRequests = useMemo<PaletteFamilyRequest[]>(+ () =>+ families.map(family => ({+ id: family.id,+ name: family.name,+ seed: family.seed,+ kind: family.kind,+ anchors: family.anchors.map(anchor => ({+ ...anchor,+ maxDeltaE: anchor.policy === 'bounded' ? anchor.maxDeltaE : undefined,+ })),+ })),+ [families],+ );++ const algorithms = useMemo<PaletteAlgorithm[]>(+ () =>+ algorithmView === 'compare'+ ? ['oklch-v1-experimental', 'hct-v1-experimental']+ : [algorithmForView(algorithmView)],+ [algorithmView],+ );++ const results = useMemo(+ () =>+ algorithms.map(algorithm =>+ generatePaletteSet({+ algorithm,+ vibrancy,+ neutralProfile,+ modeStrategy,+ stops: stopResolution.stops,+ families: familyRequests,+ }),+ ),+ [+ algorithms,+ familyRequests,+ modeStrategy,+ neutralProfile,+ stopResolution.stops,+ vibrancy,+ ],+ );++ const selectedTheme =+ THEME_REFERENCES.find(theme => theme.id === selectedThemeId) ??+ THEME_REFERENCES[0];++ const themeResults = useMemo(() => {+ const themeModeStrategy: ModeStrategy =+ selectedTheme.modes.length === 1+ ? selectedTheme.modes[0] === 'dark'+ ? 'dark-only'+ : 'light-only'+ : 'light-and-dark';+ return algorithms.map(algorithm =>+ generatePaletteSet({+ algorithm,+ vibrancy,+ neutralProfile: 'custom',+ modeStrategy: themeModeStrategy,+ stops: [...FULL_21_STOPS],+ families: selectedTheme.families.map(family => ({+ id: family.id,+ name: family.name,+ seed: family.seed,+ kind: family.kind,+ anchors: [],+ })),+ }),+ );+ }, [algorithms, selectedTheme, vibrancy]);++ const suggestedThemeVibrancy = selectedTheme.suggestedVibrancy[algorithmView];++ function selectLabView(value: LabView): void {+ setLabView(value);+ if (value === 'themes') {+ setVibrancy(selectedTheme.suggestedVibrancy[algorithmView]);+ }+ }++ function selectAlgorithm(value: AlgorithmView): void {+ setAlgorithmView(value);+ if (labView === 'themes') {+ setVibrancy(selectedTheme.suggestedVibrancy[value]);+ }+ }++ function selectTheme(value: string): void {+ const theme =+ THEME_REFERENCES.find(item => item.id === value) ?? THEME_REFERENCES[0];+ setSelectedThemeId(theme.id);+ setVibrancy(theme.suggestedVibrancy[algorithmView]);+ }++ function updateFamily(id: string, changes: Partial<EditableFamily>): void {+ setFamilies(current =>+ current.map(family =>+ family.id === id ? {...family, ...changes} : family,+ ),+ );+ }++ function updateAnchor(+ familyId: string,+ anchorIndex: number,+ changes: Partial<EditableAnchor>,+ ): void {+ setFamilies(current =>+ current.map(family =>+ family.id === familyId+ ? {+ ...family,+ anchors: family.anchors.map((anchor, index) =>+ index === anchorIndex ? {...anchor, ...changes} : anchor,+ ),+ }+ : family,+ ),+ );+ }++ function copyResults(): void {+ const output = (labView === 'themes' ? themeResults : results).map(result =>+ JSON.parse(serializeGenerationResult(result)),+ );+ navigator.clipboard+ .writeText(`${JSON.stringify(output, null, 2)}\n`)+ .then(() => {+ setCopied(true);+ window.setTimeout(() => setCopied(false), 1600);+ });+ }++ return (+ <div style={styles.page}>+ <aside style={styles.sidebar}>+ <div style={styles.panel}>+ <div style={styles.header}>+ <VStack gap={2}>+ <HStack vAlign="center" style={{justifyContent: 'space-between'}}>+ <Heading level={3}>Palette Generator</Heading>+ <Button+ label={copied ? 'Copied' : 'Copy JSON'}+ variant="ghost"+ size="sm"+ onClick={copyResults}+ />+ </HStack>+ <Text type="supporting" color="secondary">+ Experimental AST-008 decision tool. Outputs are candidates, not+ adopted theme colors.+ </Text>+ <SegmentedControl+ label="Lab view"+ value={labView}+ onChange={value => selectLabView(value as LabView)}+ size="sm">+ <SegmentedControlItem value="generator" label="Generator" />+ <SegmentedControlItem value="themes" label="Themes" />+ </SegmentedControl>+ </VStack>+ </div>++ <div style={styles.controls}>+ <VStack gap={5}>+ <VStack gap={2}>+ <Text type="label" weight="semibold">+ Algorithm+ </Text>+ <SegmentedControl+ label="Algorithm"+ value={algorithmView}+ onChange={value => selectAlgorithm(value as AlgorithmView)}+ size="sm">+ <SegmentedControlItem value="oklch" label="OKLCH" />+ <SegmentedControlItem value="hct" label="HCT-like" />+ <SegmentedControlItem value="compare" label="Compare" />+ </SegmentedControl>+ </VStack>++ <VStack gap={2}>+ <Text type="label" weight="semibold">+ Vibrancy presets+ </Text>+ <SegmentedControl+ label="Vibrancy preset"+ value={presetForVibrancy(vibrancy)}+ onChange={value =>+ setVibrancy(vibrancyForPreset(value as VibrancyPreset))+ }+ size="sm">+ <SegmentedControlItem value="muted" label="Muted" />+ <SegmentedControlItem value="balanced" label="Balanced" />+ <SegmentedControlItem value="vibrant" label="Vibrant" />+ </SegmentedControl>+ <Slider+ label="Vibrancy"+ description="Fine-tune perceptual color strength"+ value={vibrancy}+ onChange={setVibrancy}+ min={0}+ max={100}+ step={1}+ formatValue={value => `${value}%`}+ valueDisplay="text"+ marks={[+ {value: 25, label: 'Muted'},+ {value: 50, label: 'Balanced'},+ {value: 75, label: 'Vibrant'},+ ]}+ />+ </VStack>++ {labView === 'themes' && (+ <VStack gap={2}>+ <Text type="label" weight="semibold">+ Existing theme+ </Text>+ <Selector+ label="Existing theme"+ isLabelHidden+ value={selectedThemeId}+ onChange={selectTheme}+ options={THEME_REFERENCES.map(theme => ({+ value: theme.id,+ label: theme.name,+ }))}+ />+ <Text type="supporting" color="secondary">+ Theme comparisons use the full 21-stop reference and each+ theme's supported mode. Matcha and Chocolate do not yet+ publish complete tonal ramps.+ </Text>+ <HStack+ gap={2}+ vAlign="center"+ style={{justifyContent: 'space-between'}}>+ <Text type="supporting" color="secondary">+ Best-fit starting point: {suggestedThemeVibrancy}%+ </Text>+ {vibrancy !== suggestedThemeVibrancy && (+ <Button+ label="Use best fit"+ size="sm"+ variant="ghost"+ onClick={() => setVibrancy(suggestedThemeVibrancy)}+ />+ )}+ </HStack>+ </VStack>+ )}++ {labView === 'generator' && (+ <>+ <HStack+ vAlign="center"+ style={{justifyContent: 'space-between'}}>+ <Text+ type="supporting"+ color="secondary"+ style={styles.fieldLabel}>+ Neutral+ </Text>+ <Selector+ label="Neutral profile"+ isLabelHidden+ size="sm"+ value={neutralProfile}+ onChange={value =>+ setNeutralProfile(value as NeutralProfile)+ }+ options={[+ {value: 'neutral-v1', label: 'Neutral'},+ {value: 'warm-v1', label: 'Warm'},+ {value: 'cool-v1', label: 'Cool / blue'},+ {value: 'custom', label: 'Use neutral seed'},+ ]}+ />+ </HStack>++ <HStack+ vAlign="center"+ style={{justifyContent: 'space-between'}}>+ <Text+ type="supporting"+ color="secondary"+ style={styles.fieldLabel}>+ Modes+ </Text>+ <Selector+ label="Mode strategy"+ isLabelHidden+ size="sm"+ value={modeStrategy}+ onChange={value => setModeStrategy(value as ModeStrategy)}+ options={[+ {value: 'light-and-dark', label: 'Light + dark'},+ {value: 'light-only', label: 'Light only'},+ {value: 'dark-only', label: 'Dark only'},+ ]}+ />+ </HStack>++ <VStack gap={2}>+ <Text type="label" weight="semibold">+ Stops+ </Text>+ <SegmentedControl+ label="Stop layout"+ value={stopPreset}+ onChange={value => setStopPreset(value as StopPreset)}+ size="sm">+ <SegmentedControlItem value="full-21" label="21" />+ <SegmentedControlItem value="compact-11" label="11" />+ <SegmentedControlItem value="custom" label="Custom" />+ </SegmentedControl>+ {stopPreset === 'custom' && (+ <TextInput+ label="Custom stops"+ value={customStops}+ onChange={setCustomStops}+ description="Comma-separated values from 0 to 100"+ size="sm"+ />+ )}+ {stopResolution.error && (+ <Text+ type="supporting"+ style={{color: 'var(--color-text-red, #b42318)'}}>+ {stopResolution.error} Showing 21-stop fallback.+ </Text>+ )}+ </VStack>++ <VStack gap={3}>+ <HStack+ vAlign="center"+ style={{justifyContent: 'space-between'}}>+ <Text type="label" weight="semibold">+ Color families+ </Text>+ <IconButton+ label="Add family"+ variant="ghost"+ size="sm"+ icon={<span style={{fontSize: 16}}>+</span>}+ onClick={() => {+ const next = families.length + 1;+ setFamilies(current => [+ ...current,+ {+ id: `custom-${next}`,+ name: `Color ${next}`,+ seed: '#c44a70',+ kind: 'chromatic',+ anchors: [],+ },+ ]);+ }}+ />+ </HStack>++ {families.map(family => (+ <VStack key={family.id} gap={2} style={styles.family}>+ <HStack gap={2} vAlign="center">+ <div style={{flex: 1}}>+ <TextInput+ label={`${family.name} family name`}+ isLabelHidden+ value={family.name}+ onChange={value =>+ updateFamily(family.id, {name: value})+ }+ size="sm"+ />+ </div>+ <IconButton+ label={`Remove ${family.name}`}+ variant="ghost"+ size="sm"+ icon={<span aria-hidden="true">×</span>}+ onClick={() =>+ setFamilies(current =>+ current.filter(item => item.id !== family.id),+ )+ }+ />+ </HStack>+ <HStack gap={2} vAlign="center">+ <input+ aria-label={`${family.name} seed color`}+ type="color"+ value={family.seed}+ onChange={event =>+ updateFamily(family.id, {+ seed: event.target.value,+ })+ }+ style={{+ width: 34,+ height: 34,+ border: 0,+ padding: 0,+ }}+ />+ <div style={{flex: 1}}>+ <TextInput+ label={`${family.name} seed`}+ isLabelHidden+ value={family.seed}+ onChange={value =>+ updateFamily(family.id, {seed: value})+ }+ size="sm"+ />+ </div>+ <Selector+ label={`${family.name} kind`}+ isLabelHidden+ size="sm"+ value={family.kind ?? 'chromatic'}+ onChange={value =>+ updateFamily(family.id, {+ kind: value as 'chromatic' | 'neutral',+ })+ }+ options={[+ {value: 'chromatic', label: 'Color'},+ {value: 'neutral', label: 'Neutral'},+ ]}+ />+ </HStack>++ <HStack+ gap={2}+ vAlign="center"+ style={{justifyContent: 'space-between'}}>+ <Text type="supporting" color="secondary">+ Anchors ({family.anchors.length})+ </Text>+ <IconButton+ label={`Add ${family.name} anchor`}+ variant="ghost"+ size="sm"+ icon={<span aria-hidden="true">+</span>}+ onClick={() =>+ updateFamily(family.id, {+ anchors: [+ ...family.anchors,+ {+ mode: 'light',+ stop: nextAnchorStop(+ stopResolution.stops,+ family.anchors,+ 'light',+ ),+ color: family.seed,+ policy: 'preferred',+ maxDeltaE: 2,+ },+ ],+ })+ }+ />+ </HStack>++ {family.anchors.map((anchor, anchorIndex) => (+ <VStack+ key={`${anchor.mode}-${anchor.stop}-${anchorIndex}`}+ gap={2}+ style={{+ padding: 10,+ borderRadius: 8,+ backgroundColor:+ 'var(--color-background-secondary, #f4f4f4)',+ }}>+ <HStack gap={2} vAlign="center">+ <Selector+ label="Anchor policy"+ size="sm"+ value={anchor.policy}+ onChange={value =>+ updateAnchor(family.id, anchorIndex, {+ policy: value as AnchorPolicy,+ })+ }+ options={[+ {value: 'exact', label: 'Exact'},+ {value: 'bounded', label: 'Bounded'},+ {value: 'preferred', label: 'Preferred'},+ ]}+ />+ <IconButton+ label={`Remove ${family.name} anchor ${anchorIndex + 1}`}+ variant="ghost"+ size="sm"+ icon={<span aria-hidden="true">×</span>}+ onClick={() =>+ updateFamily(family.id, {+ anchors: family.anchors.filter(+ (_, index) => index !== anchorIndex,+ ),+ })+ }+ />+ </HStack>+ <HStack gap={2} vAlign="center">+ <TextInput+ label="Anchor color"+ value={anchor.color}+ onChange={value =>+ updateAnchor(family.id, anchorIndex, {+ color: value,+ })+ }+ size="sm"+ />+ <NumberInput+ label="Stop"+ value={anchor.stop}+ onChange={value =>+ updateAnchor(family.id, anchorIndex, {+ stop: value,+ })+ }+ min={0}+ max={100}+ step={5}+ size="sm"+ />+ </HStack>+ <HStack gap={2} vAlign="center">+ <Selector+ label="Anchor mode"+ size="sm"+ value={anchor.mode}+ onChange={value =>+ updateAnchor(family.id, anchorIndex, {+ mode: value as PaletteMode,+ })+ }+ options={[+ {value: 'light', label: 'Light'},+ {value: 'dark', label: 'Dark'},+ ]}+ />+ {anchor.policy === 'bounded' && (+ <NumberInput+ label="Max ΔE"+ value={anchor.maxDeltaE}+ onChange={value =>+ updateAnchor(family.id, anchorIndex, {+ maxDeltaE: Math.max(0, value),+ })+ }+ min={0}+ max={20}+ step={0.5}+ size="sm"+ />+ )}+ </HStack>+ </VStack>+ ))}+ </VStack>+ ))}+ </VStack>+ </>+ )}+ </VStack>+ </div>+ </div>+ </aside>++ <main style={styles.main}>+ <VStack gap={5}>+ {labView === 'themes' ? (+ <>+ <VStack gap={2}>+ <Heading level={1}>Existing theme comparison</Heading>+ <Text color="secondary">+ Compare the selected Astryx theme with newly generated ramps+ from the same source colors.+ </Text>+ </VStack>+ <ThemeComparisonView+ theme={selectedTheme}+ results={themeResults}+ />+ </>+ ) : (+ <>+ <VStack gap={2}>+ <Heading level={1}>Tonal palette decision lab</Heading>+ <Text color="secondary">+ Compare complete recipes, preserve declared anchors, and+ inspect light and dark output before selecting a canonical+ algorithm.+ </Text>+ </VStack>+ <div style={styles.resultSection}>+ <VStack gap={2}>+ <Heading level={3}>How to read this experiment</Heading>+ <Text type="supporting" color="secondary">+ An algorithm version names a fixed recipe. If its behavior+ changes later, it needs a new version so existing themes do+ not silently change.+ </Text>+ <Text type="supporting" color="secondary">+ Vibrancy is hue-, tone-, and mode-aware—not one chroma+ multiplier applied equally to every family. Exact anchors+ must be preserved; bounded anchors may move only within the+ stated ΔE; preferred anchors may move and report the+ difference. Anchor corrections taper through neighboring+ stops instead of changing one isolated swatch.+ </Text>+ <Text type="supporting" color="secondary">+ Dark ramps are generated separately from light ramps. The+ preview deliberately uses a near-white neutral instead of+ pure white body text. Contrast and context still need+ semantic review: a palette alone cannot guarantee+ accessibility.+ </Text>+ <Text type="supporting" color="secondary">+ Transparency and compositing are outside this generator;+ they belong to semantic token usage and adoption guidance.+ </Text>+ </VStack>+ </div>+ {algorithmView === 'compare' && results.length === 2 ? (+ <CompareResultView oklch={results[0]} hct={results[1]} />+ ) : (+ results.map(result => (+ <ResultView key={result.request.algorithm} result={result} />+ ))+ )}+ </>+ )}+ </VStack>+ </main>+ </div>+ );+}diff --git a/apps/sandbox/src/app/(sandbox)/pages/palette-generator/themeCorpus.ts b/apps/sandbox/src/app/(sandbox)/pages/palette-generator/themeCorpus.tsnew file mode 100644index 0000000000..d3a0d40429--- /dev/null+++ b/apps/sandbox/src/app/(sandbox)/pages/palette-generator/themeCorpus.ts@@ -0,0 +1,319 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++import {butterPalettes} from '@astryxdesign/theme-butter';+import {gothicPalettes} from '@astryxdesign/theme-gothic';+import {stonePalettes} from '@astryxdesign/theme-stone';+import {y2kPalettes} from '@astryxdesign/theme-y2k';++import {hexToHct, hctToHex} from '../color-studio/colorUtils';+import {FULL_21_STOPS, type PaletteMode} from './generator';+import {NEUTRAL_THEME_PALETTE_REFERENCE} from './neutralThemePaletteReference';++export interface ThemeReferenceFamily {+ id: string;+ name: string;+ seed: string;+ kind?: 'chromatic' | 'neutral';+ light?: Record<number, string>;+ dark?: Record<number, string>;+ /** The same stored ramp is used in both preview columns. */+ sharedAcrossModes?: boolean;+}++export interface ThemeReference {+ id: string;+ name: string;+ description: string;+ referenceKind: 'stored' | 'legacy-generated';+ /** Best-fit starting points measured against stops 5–95. */+ suggestedVibrancy: {oklch: number; hct: number; compare: number};+ modes: PaletteMode[];+ families: ThemeReferenceFamily[];+}++type RawPalette = Readonly<Record<string | number, string | number>>;++function tones(palette: RawPalette): Record<number, string> {+ return Object.fromEntries(+ FULL_21_STOPS.map(stop => {+ const value = palette[stop];+ if (typeof value !== 'string') {+ throw new Error(`Theme palette is missing stop ${stop}.`);+ }+ return [stop, value.toLowerCase()];+ }),+ );+}++function legacyRamp(seed: string, mode: PaletteMode): Record<number, string> {+ const source = hexToHct(seed);+ const chroma = mode === 'dark' ? source.chroma * 0.85 : source.chroma;+ const maximumChroma = chroma * 1.8;+ return Object.fromEntries(+ FULL_21_STOPS.map(stop => {+ let tone: number = stop;+ if (mode === 'dark') {+ const lift = stop >= 95 ? 0 : stop <= 80 ? 5 : 5 * ((95 - stop) / 15);+ tone = Math.min(100, stop + lift);+ }+ const boost = tone < 50 ? 1 + (50 - tone) / 40 : 1;+ return [+ stop,+ hctToHex({+ hue: source.hue,+ chroma: Math.min(chroma * boost, maximumChroma),+ tone,+ }),+ ];+ }),+ );+}++function generatedFamily(+ id: string,+ name: string,+ seed: string,+ kind: 'chromatic' | 'neutral' = 'chromatic',+): ThemeReferenceFamily {+ return {+ id,+ name,+ seed,+ kind,+ light: legacyRamp(seed, 'light'),+ dark: legacyRamp(seed, 'dark'),+ };+}++function storedFamily(+ id: string,+ name: string,+ seed: string,+ palette: RawPalette,+ kind: 'chromatic' | 'neutral' = 'chromatic',+ darkPalette?: RawPalette,+): ThemeReferenceFamily {+ const ramp = tones(palette);+ return {+ id,+ name,+ seed,+ kind,+ light: ramp,+ dark: darkPalette ? tones(darkPalette) : ramp,+ sharedAcrossModes: darkPalette == null,+ };+}++function neutralReferenceFamily(+ id: keyof typeof NEUTRAL_THEME_PALETTE_REFERENCE,+ name: string,+ kind: 'chromatic' | 'neutral' = 'chromatic',+): ThemeReferenceFamily {+ const palette = NEUTRAL_THEME_PALETTE_REFERENCE[id];+ return {+ id,+ name,+ seed: palette.light[50],+ kind,+ light: tones(palette.light),+ dark: tones(palette.dark),+ };+}++const neutralReferenceFamilies = [+ neutralReferenceFamily('neutral', 'Neutral', 'neutral'),+ neutralReferenceFamily('red', 'Red'),+ neutralReferenceFamily('orange', 'Orange'),+ neutralReferenceFamily('yellow', 'Yellow'),+ neutralReferenceFamily('green', 'Green'),+ neutralReferenceFamily('teal', 'Teal'),+ neutralReferenceFamily('cyan', 'Cyan'),+ neutralReferenceFamily('blue', 'Blue'),+ neutralReferenceFamily('purple', 'Purple'),+ neutralReferenceFamily('pink', 'Pink'),+];++const neutralFamilies = [+ generatedFamily('neutral', 'Neutral', '#e5e5e5', 'neutral'),+ generatedFamily('red', 'Red', '#eb183a'),+ generatedFamily('orange', 'Orange', '#d57113'),+ generatedFamily('yellow', 'Yellow', '#f8c723'),+ generatedFamily('green', 'Green', '#358a3a'),+ generatedFamily('teal', 'Teal', '#0c7365'),+ generatedFamily('cyan', 'Cyan', '#0c6f82'),+ generatedFamily('blue', 'Blue', '#1679fa'),+ generatedFamily('purple', 'Purple', '#980fb2'),+ generatedFamily('pink', 'Pink', '#b10e69'),+];++const stoneFamilies = [+ storedFamily(+ 'neutral',+ 'Stone Neutral',+ '#e2e2e2',+ stonePalettes.neutral,+ 'neutral',+ ),+ storedFamily('blue', 'Blue', '#d7e4f5', stonePalettes.blue),+ storedFamily('cyan', 'Cyan', '#cce8e5', stonePalettes.cyan),+ storedFamily('green', 'Green', '#d0e9ce', stonePalettes.green),+ storedFamily('teal', 'Teal', '#d4e7dc', stonePalettes.teal),+ storedFamily('yellow', 'Yellow', '#f4e1b7', stonePalettes.yellow),+ storedFamily('orange', 'Orange', '#ffdcbb', stonePalettes.orange),+ storedFamily('red', 'Red', '#f9dcd7', stonePalettes.red),+ storedFamily('pink', 'Pink', '#f0dde8', stonePalettes.pink),+ storedFamily('purple', 'Purple', '#e8dff3', stonePalettes.purple),+];++const gothicFamilies = [+ storedFamily(+ 'neutral',+ 'Gothic Neutral',+ '#96a0ab',+ gothicPalettes.neutral,+ 'neutral',+ ),+ storedFamily('green', 'Green', '#b3c79a', gothicPalettes.green),+ storedFamily('red', 'Red', '#c6a6a2', gothicPalettes.red),+ storedFamily('yellow', 'Yellow', '#d3c490', gothicPalettes.yellow),+ storedFamily('blue', 'Blue', '#a3b5d6', gothicPalettes.blue),+ storedFamily('purple', 'Purple', '#b29bc4', gothicPalettes.purple),+ storedFamily('pink', 'Pink', '#c89aab', gothicPalettes.pink),+ storedFamily('cyan', 'Cyan', '#a3c2cf', gothicPalettes.cyan),+ storedFamily('orange', 'Orange', '#d3b89a', gothicPalettes.orange),+ storedFamily('teal', 'Teal', '#a3c2b6', gothicPalettes.teal),+].map(family => ({...family, light: undefined, sharedAcrossModes: false}));++const y2kFamilies = [+ storedFamily(+ 'neutral',+ 'Y2K Neutral',+ '#c3b7ab',+ y2kPalettes.neutral,+ 'neutral',+ ),+ storedFamily('green', 'Green', '#c5e17a', y2kPalettes.green),+ storedFamily('red', 'Red', '#ff9e9a', y2kPalettes.red),+ storedFamily('yellow', 'Yellow', '#ffcc55', y2kPalettes.yellow),+ storedFamily('blue', 'Blue', '#8ecfff', y2kPalettes.blue),+ storedFamily('pink', 'Pink', '#ffa0c8', y2kPalettes.pink),+ storedFamily('purple', 'Purple', '#c0aaff', y2kPalettes.purple),+ storedFamily('cyan', 'Cyan', '#70e8d0', y2kPalettes.cyan),+ storedFamily('orange', 'Orange', '#ffaa66', y2kPalettes.orange),+ storedFamily('teal', 'Teal', '#78e0b0', y2kPalettes.teal),+];++const butterDarkYellow = {+ 0: '#000000',+ 5: '#161100',+ 10: '#211b00',+ 15: '#2c2600',+ 20: '#383100',+ 25: '#443c00',+ 30: '#504700',+ 35: '#5d5300',+ 40: '#6a5f00',+ 45: '#786b00',+ 50: '#867800',+ 55: '#948500',+ 60: '#a29200',+ 65: '#b19f00',+ 70: '#bfac1a',+ 75: '#ceba2c',+ 80: '#ddc73c',+ 85: '#ecd54a',+ 90: '#fbe358',+ 95: '#fff1bd',+ 100: '#ffffff',+} as const;++const butterFamilies = [+ storedFamily(+ 'accent',+ 'Accent',+ '#225bff',+ butterPalettes.accent,+ 'chromatic',+ butterPalettes.yellow,+ ),+ storedFamily('neutral', 'Gray', '#868b99', butterPalettes.neutral, 'neutral'),+ storedFamily('red', 'Red', '#ff7553', butterPalettes.red),+ storedFamily('orange', 'Orange', '#ffa347', butterPalettes.orange),+ storedFamily(+ 'yellow',+ 'Yellow',+ '#edd64b',+ butterPalettes.yellow,+ 'chromatic',+ butterDarkYellow,+ ),+ storedFamily('green', 'Green', '#5dce5f', butterPalettes.green),+ storedFamily('cyan', 'Cyan', '#60cfd3', butterPalettes.cyan),+ storedFamily('teal', 'Teal', '#6cd9a8', butterPalettes.teal),+ storedFamily('blue', 'Blue', '#5681ff', butterPalettes.blue),+ storedFamily('purple', 'Purple', '#b780f6', butterPalettes.purple),+ storedFamily('pink', 'Pink', '#f680e8', butterPalettes.pink),+ storedFamily('error', 'Error', '#ff5947', butterPalettes.error),+ storedFamily('warning', 'Warning', '#f8c726', butterPalettes.warning),+ storedFamily('success', 'Success', '#91d143', butterPalettes.success),+];++export const THEME_REFERENCES: ThemeReference[] = [+ {+ id: 'neutral-pr-5628',+ name: 'Neutral — PR #5628',+ description:+ 'Exact approved higher-chroma light and dark ramps merged in PR #5628.',+ referenceKind: 'stored',+ suggestedVibrancy: {oklch: 66, hct: 49, compare: 61},+ modes: ['light', 'dark'],+ families: neutralReferenceFamilies,+ },+ {+ id: 'neutral-legacy',+ name: 'Neutral — legacy preview',+ description:+ 'Existing HCT-generated reference ramps used by the Neutral preview.',+ referenceKind: 'legacy-generated',+ suggestedVibrancy: {oklch: 71, hct: 71, compare: 71},+ modes: ['light', 'dark'],+ families: neutralFamilies,+ },+ {+ id: 'stone',+ name: 'Stone',+ description: 'Stored hand-tuned warm stone ramps.',+ referenceKind: 'stored',+ suggestedVibrancy: {oklch: 12, hct: 9, compare: 10},+ modes: ['light', 'dark'],+ families: stoneFamilies,+ },+ {+ id: 'gothic',+ name: 'Gothic',+ description: 'Stored dark-only muted gem-tone ramps.',+ referenceKind: 'stored',+ suggestedVibrancy: {oklch: 36, hct: 23, compare: 30},+ modes: ['dark'],+ families: gothicFamilies,+ },+ {+ id: 'y2k',+ name: 'Y2K',+ description: 'Stored high-chroma pastel pop ramps.',+ referenceKind: 'stored',+ suggestedVibrancy: {oklch: 45, hct: 34, compare: 39},+ modes: ['light', 'dark'],+ families: y2kFamilies,+ },+ {+ id: 'butter',+ name: 'Butter',+ description: 'Stored branded pastel ramps.',+ referenceKind: 'stored',+ suggestedVibrancy: {oklch: 24, hct: 22, compare: 23},+ modes: ['light', 'dark'],+ families: butterFamilies,+ },+];diff --git a/apps/sandbox/src/app/SandboxShell.tsx b/apps/sandbox/src/app/SandboxShell.tsxindex f205205311..80e5f8c2d9 100644--- a/apps/sandbox/src/app/SandboxShell.tsx+++ b/apps/sandbox/src/app/SandboxShell.tsx@@ -8,6 +8,7 @@ import {SandboxNav} from './SandboxNav';const FULLSCREEN_PATHS = ['/pages/color-studio',+ '/pages/palette-generator','/pages/mobile-type','/pages/tap-targets',];diff --git a/apps/sandbox/src/app/sandboxPages.ts b/apps/sandbox/src/app/sandboxPages.tsindex 75811b27e6..bcbe4ab10d 100644--- a/apps/sandbox/src/app/sandboxPages.ts+++ b/apps/sandbox/src/app/sandboxPages.ts@@ -208,6 +208,12 @@ export const categories: SandboxCategory[] = [description:'Generate and explore color palettes from an accent color or image',},+ {+ name: 'Palette Generator Lab',+ href: '/pages/palette-generator/',+ description:+ 'Compare experimental OKLCH and HCT-like ramps with profiles, anchors, custom stops, and separate dark-mode generation',+ },],},{diff --git a/apps/sandbox/vitest.config.ts b/apps/sandbox/vitest.config.tsnew file mode 100644index 0000000000..619cd36a60--- /dev/null+++ b/apps/sandbox/vitest.config.ts@@ -0,0 +1,10 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++import {defineConfig} from 'vitest/config';++export default defineConfig({+ test: {+ environment: 'node',+ include: ['src/**/*.test.{ts,tsx}'],+ },+});diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex a91cea38e8..44f22d2309 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -324,6 +324,9 @@ importers:typescript:specifier: ^6.0.3version: 6.0.3+ vitest:+ specifier: ^4.1.9+ version: 4.1.10(@types/[email protected])(@vitest/[email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected]))apps/storybook:dependencies: