@hia/theme-core 0.5.0 → 0.7.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.
@@ -0,0 +1,48 @@
1
+ /**
2
+ * @lang zh-CN APCA(Accessible Perceptual Contrast Algorithm)Lc 对比度副指标(`W-tb-P36`)。
3
+ *
4
+ * **定位(重要)**:仅作为**参考值**并列展示,不替代 WCAG 2.2 AA 合规基线。
5
+ * 截至 2026-11,WCAG 3.0 仍是 W3C Working Draft(最新 2026-09-10),对比度算法未定案,
6
+ * APCA 已被移出草案探索流程——故本实现输出**不得**用于合规判定,只用于专业参考读数。
7
+ *
8
+ * **实现与来源**:按 Myndex/apca-w3 **APCA 0.1.9(W3 版,SA98G 常量组)**自研实现,
9
+ * 常量与分支逻辑逐条对照参考实现 `temp/apca-w3-reference.js`(T-tb-CLEANUP 清理范围)。
10
+ * 未复制其代码文件,仅按其公开文档/源码记载的公式与常量重新表达。
11
+ * 许可注意:apca-w3 采用 W3 License(限 WCAG 无障碍语境使用)——本项目仅在
12
+ * 无障碍参考读数语境下使用并署名,不用于其他用途;已登记 WorkZone 台账。
13
+ *
14
+ * 极性约定:正值 = 深色文字在浅色背景(BoW);**负值 = 浅色文字在深色背景(WoB)**。
15
+ * 这是 APCA 的原设计(极性本身携带信息),UI 展示时取绝对值并标出极性方向。
16
+ *
17
+ * @lang en APCA (Accessible Perceptual Contrast Algorithm) Lc secondary metric (`W-tb-P36`).
18
+ *
19
+ * **Position (important)**: reference readout only — it never replaces the WCAG 2.2 AA compliance baseline.
20
+ * As of 2026-11 WCAG 3.0 is still a W3C Working Draft (latest 2026-09-10) with the contrast algorithm
21
+ * undecided, and APCA was removed from the draft's exploratory process — so this output must not be used
22
+ * for compliance, only as a professional reference value.
23
+ *
24
+ * **Implementation & source**: re-implemented from Myndex/apca-w3 **APCA 0.1.9 (W3, SA98G constants)**,
25
+ * constants and branches cross-checked against the reference copy temp/apca-w3-reference.js
26
+ * (T-tb-CLEANUP scope). Their code file is not copied; the published formula/constants are re-expressed.
27
+ * Licence note: apca-w3 ships a W3 Licence (WCAG accessibility context only) — this project uses it solely
28
+ * as an accessibility reference readout with attribution, registered in the WorkZone ledger.
29
+ *
30
+ * Polarity: positive = dark text on light background (BoW); **negative = light text on dark (WoB)** —
31
+ * APCA's own convention; the UI shows the absolute value plus the polarity direction.
32
+ */
33
+ /**
34
+ * @lang zh-CN HEX → APCA 感知亮度 Y:按 2.4 幂指数线性化后以 sRco/sGco/sBco 加权求和。
35
+ * 与 WCAG 亮度(线性加权)不同:APCA 直接对**编码值**取幂,不做 0.04045 分段。
36
+ * @lang en HEX → APCA perceptual Y: power-2.4 per encoded channel, weighted by sRco/sGco/sBco.
37
+ * Unlike WCAG luminance (linear weights), APCA raises the encoded value directly — no 0.04045分段 branch.
38
+ */
39
+ export declare function apcaY(hex: string): number;
40
+ /**
41
+ * @lang zh-CN 计算 APCA Lc 对比度(带符号,×100 记法)。参数顺序不可交换:**先文字色后背景色**。
42
+ * 实现逐条对照参考实现:黑级软钳 → ΔY 早退 → 极性分支 → 低对比裁剪 → ×100。
43
+ * @lang en Computes the signed APCA Lc contrast (×100 notation). Argument order matters: **text colour first,
44
+ * background second**. Mirrors the reference implementation step by step: black soft clamp → ΔY early
45
+ * return → polarity branch → low-contrast clip → ×100.
46
+ */
47
+ export declare function apcaLc(textHex: string, bgHex: string): number;
48
+ //# sourceMappingURL=apca.d.ts.map
@@ -0,0 +1,94 @@
1
+ /**
2
+ * @lang zh-CN APCA(Accessible Perceptual Contrast Algorithm)Lc 对比度副指标(`W-tb-P36`)。
3
+ *
4
+ * **定位(重要)**:仅作为**参考值**并列展示,不替代 WCAG 2.2 AA 合规基线。
5
+ * 截至 2026-11,WCAG 3.0 仍是 W3C Working Draft(最新 2026-09-10),对比度算法未定案,
6
+ * APCA 已被移出草案探索流程——故本实现输出**不得**用于合规判定,只用于专业参考读数。
7
+ *
8
+ * **实现与来源**:按 Myndex/apca-w3 **APCA 0.1.9(W3 版,SA98G 常量组)**自研实现,
9
+ * 常量与分支逻辑逐条对照参考实现 `temp/apca-w3-reference.js`(T-tb-CLEANUP 清理范围)。
10
+ * 未复制其代码文件,仅按其公开文档/源码记载的公式与常量重新表达。
11
+ * 许可注意:apca-w3 采用 W3 License(限 WCAG 无障碍语境使用)——本项目仅在
12
+ * 无障碍参考读数语境下使用并署名,不用于其他用途;已登记 WorkZone 台账。
13
+ *
14
+ * 极性约定:正值 = 深色文字在浅色背景(BoW);**负值 = 浅色文字在深色背景(WoB)**。
15
+ * 这是 APCA 的原设计(极性本身携带信息),UI 展示时取绝对值并标出极性方向。
16
+ *
17
+ * @lang en APCA (Accessible Perceptual Contrast Algorithm) Lc secondary metric (`W-tb-P36`).
18
+ *
19
+ * **Position (important)**: reference readout only — it never replaces the WCAG 2.2 AA compliance baseline.
20
+ * As of 2026-11 WCAG 3.0 is still a W3C Working Draft (latest 2026-09-10) with the contrast algorithm
21
+ * undecided, and APCA was removed from the draft's exploratory process — so this output must not be used
22
+ * for compliance, only as a professional reference value.
23
+ *
24
+ * **Implementation & source**: re-implemented from Myndex/apca-w3 **APCA 0.1.9 (W3, SA98G constants)**,
25
+ * constants and branches cross-checked against the reference copy temp/apca-w3-reference.js
26
+ * (T-tb-CLEANUP scope). Their code file is not copied; the published formula/constants are re-expressed.
27
+ * Licence note: apca-w3 ships a W3 Licence (WCAG accessibility context only) — this project uses it solely
28
+ * as an accessibility reference readout with attribution, registered in the WorkZone ledger.
29
+ *
30
+ * Polarity: positive = dark text on light background (BoW); **negative = light text on dark (WoB)** —
31
+ * APCA's own convention; the UI shows the absolute value plus the polarity direction.
32
+ */
33
+ // SA98G 常量组(APCA 0.0.98G-4g,W3 版):与参考实现逐值一致,勿擅自调整——
34
+ // 这些是拟合自视觉实验的拟合常数,改动即失去与参考值可比性。
35
+ // <lang en>SA98G constant set (APCA 0.0.98G-4g, W3): identical to the reference implementation; do not tweak —
36
+ // these are experiment-fitted constants and changing them breaks comparability with reference values.</lang>
37
+ const SA98G = {
38
+ /** @lang zh-CN 显示器感知幂指数。 @lang en Monitor perception exponent. */
39
+ mainTRC: 2.4,
40
+ /** @lang zh-CN sRGB 感知亮度系数(注意与 WCAG 线性权重不同,总和略大于 1,属算法设计)。 @lang en sRGB Y coefficients (deliberately differ from WCAG weights; sum slightly > 1 by design). */
41
+ sRco: 0.2126729, sGco: 0.7151522, sBco: 0.0721750,
42
+ /** @lang zh-CN 正常/反极性幂指数(背景/文字各一)。 @lang en Normal/reverse polarity exponents for bg/text. */
43
+ normBG: 0.56, normTXT: 0.57, revTXT: 0.62, revBG: 0.65,
44
+ /** @lang zh-CN 黑级软钳阈值与指数。 @lang en Black soft-clamp threshold and exponent. */
45
+ blkThrs: 0.022, blkClmp: 1.414,
46
+ /** @lang zh-CN 两种极性的缩放系数。 @lang en Scale factors for both polarities. */
47
+ scaleBoW: 1.14, scaleWoB: 1.14,
48
+ /** @lang zh-CN 低对比滚出偏移。 @lang en Low-contrast rollout offsets. */
49
+ loBoWoffset: 0.027, loWoBoffset: 0.027,
50
+ /** @lang zh-CN 极低 ΔY 早退阈值与低对比裁剪点。 @lang en Minimum ΔY early-return and low-contrast clip. */
51
+ deltaYmin: 0.0005, loClip: 0.1
52
+ };
53
+ /**
54
+ * @lang zh-CN HEX → APCA 感知亮度 Y:按 2.4 幂指数线性化后以 sRco/sGco/sBco 加权求和。
55
+ * 与 WCAG 亮度(线性加权)不同:APCA 直接对**编码值**取幂,不做 0.04045 分段。
56
+ * @lang en HEX → APCA perceptual Y: power-2.4 per encoded channel, weighted by sRco/sGco/sBco.
57
+ * Unlike WCAG luminance (linear weights), APCA raises the encoded value directly — no 0.04045分段 branch.
58
+ */
59
+ export function apcaY(hex) {
60
+ const value = hex.replace('#', '');
61
+ const chan = (i) => Math.pow(parseInt(value.slice(i, i + 2), 16) / 255.0, SA98G.mainTRC);
62
+ return SA98G.sRco * chan(0) + SA98G.sGco * chan(2) + SA98G.sBco * chan(4);
63
+ }
64
+ /**
65
+ * @lang zh-CN 计算 APCA Lc 对比度(带符号,×100 记法)。参数顺序不可交换:**先文字色后背景色**。
66
+ * 实现逐条对照参考实现:黑级软钳 → ΔY 早退 → 极性分支 → 低对比裁剪 → ×100。
67
+ * @lang en Computes the signed APCA Lc contrast (×100 notation). Argument order matters: **text colour first,
68
+ * background second**. Mirrors the reference implementation step by step: black soft clamp → ΔY early
69
+ * return → polarity branch → low-contrast clip → ×100.
70
+ */
71
+ export function apcaLc(textHex, bgHex) {
72
+ // 黑级软钳:接近黑的 Y 抬回可视范围,避免对纯黑过度惩罚。
73
+ // <lang en>Black soft clamp lifts near-black Y back into range so pure black is not over-penalised.</lang>
74
+ let txtY = apcaY(textHex);
75
+ let bgY = apcaY(bgHex);
76
+ txtY = txtY > SA98G.blkThrs ? txtY : txtY + Math.pow(SA98G.blkThrs - txtY, SA98G.blkClmp);
77
+ bgY = bgY > SA98G.blkThrs ? bgY : bgY + Math.pow(SA98G.blkThrs - bgY, SA98G.blkClmp);
78
+ // ΔY 极小视作不可分辨,返回 0。
79
+ // <lang en>Negligible ΔY reads as indistinguishable — return 0.</lang>
80
+ if (Math.abs(bgY - txtY) < SA98G.deltaYmin)
81
+ return 0.0;
82
+ if (bgY > txtY) {
83
+ // 正常极性(BoW):深字浅底。SAPC 低于低对比裁剪点时平滑归零,防止极性翻转噪声。
84
+ // <lang en>Normal polarity (BoW), dark text on light bg; below the low-clip the result rolls off to 0
85
+ // to prevent polarity-flip noise.</lang>
86
+ const sapc = (Math.pow(bgY, SA98G.normBG) - Math.pow(txtY, SA98G.normTXT)) * SA98G.scaleBoW;
87
+ return (sapc < SA98G.loClip ? 0.0 : sapc - SA98G.loBoWoffset) * 100.0;
88
+ }
89
+ // 反极性(WoB):浅字深底,结果恒为负值(极性信息)。
90
+ // <lang en>Reverse polarity (WoB), light text on dark bg; always negative — the polarity carries meaning.</lang>
91
+ const sapc = (Math.pow(bgY, SA98G.revBG) - Math.pow(txtY, SA98G.revTXT)) * SA98G.scaleWoB;
92
+ return (sapc > -SA98G.loClip ? 0.0 : sapc + SA98G.loWoBoffset) * 100.0;
93
+ }
94
+ //# sourceMappingURL=apca.js.map
@@ -36,29 +36,47 @@ export function modifierFor(L, C) {
36
36
  return C > 0.14 ? 'deep' : 'dark';
37
37
  return C > 0.12 ? 'deep' : 'dark';
38
38
  }
39
- // 色相角 → 色相名(12 分区,含棕与品红/粉的明度区分)。
40
- // <lang en>Hue angle → hue name (12 sectors; brown/pink resolved by lightness).</lang>
39
+ // 色相角 → 色相名(含棕与品红/粉的明度区分)。
40
+ // **分区锚点是 OKLCH 色相角,不是 sRGB 色相角**——两者的零点与刻度都不同:
41
+ // 纯红 sRGB 0° / OKLCH 29°,纯黄 60° / 110°,纯绿 120° / 143°,纯蓝 240° / 264°。
42
+ // 早前版本按 sRGB 分区(`<15` 判红等)却传入 OKLCH 角,导致整环错位约 30°:
43
+ // 纯红 `#FF0000` 被叫成"强橙"、纯黄 `#FFFF00` 被叫成"亮绿"。分区锚点即以标准色的 OKLCH 角为准。
44
+ // <lang en>Hue angle → hue name (brown/pink resolved by lightness). **The sector anchors are OKLCH hue angles,
45
+ // not sRGB ones** — the two differ in both origin and spacing: pure red is sRGB 0° but OKLCH 29°, yellow 60° vs
46
+ // 110°, green 120° vs 143°, blue 240° vs 264°. An earlier version used sRGB sectors on OKLCH angles, shifting
47
+ // the whole ring by ~30° so pure red `#FF0000` was named "strong orange" and pure yellow "brilliant green".
48
+ // The anchors below are the OKLCH angles of the canonical hues.</lang>
41
49
  export function hueNameFor(h, L, C) {
42
50
  if (C < 0.04)
43
51
  return L > 0.9 ? 'white' : L > 0.35 ? 'grey' : 'black';
44
52
  const deg = ((h % 360) + 360) % 360;
45
- if (deg < 15 || deg >= 345)
53
+ // 红 29° / 橙 53° / 黄 110° / 绿 143° / 青 195° / 蓝 264° / 紫 294° / 品红 328°。
54
+ // 区间边界取相邻锚点的中点:红↔橙 41、橙↔黄 82、黄↔绿 126、绿↔青 169、青↔蓝 230、蓝↔紫 279、紫↔品红 311。
55
+ // 红与品红在 360/0 处首尾相接:品红锚点 328° 到红锚点 29°,中点 358.5°——
56
+ // 故 ≥358.5 归品红、18–41 归红。这样洋红 `#A2007C`(342°)读作品红而不是"深红"。
57
+ // <lang en>Sector boundaries are midpoints between adjacent anchors: red↔orange 41, orange↔yellow 82,
58
+ // yellow↔green 126, green↔cyan 169, cyan↔blue 230, blue↔purple 279, purple↔magenta 311. Red and magenta
59
+ // meet across 360/0: magenta 328° to red 29° has its midpoint at 358.5°, so ≥358.5 reads magenta and 18–41
60
+ // reads red. That keeps magenta `#A2007C` (342°) out of the red sector.</lang>
61
+ if (deg < 18)
46
62
  return L < 0.45 ? 'brown' : 'red';
47
- if (deg < 45)
48
- return L < 0.45 ? 'brown' : 'orange';
49
- if (deg < 70)
63
+ if (deg < 41)
64
+ return L < 0.45 ? 'brown' : 'red';
65
+ if (deg < 82)
66
+ return L < 0.5 ? 'brown' : 'orange';
67
+ if (deg < 126)
50
68
  return 'yellow';
51
- if (deg < 165)
69
+ if (deg < 169)
52
70
  return 'green';
53
- if (deg < 195)
71
+ if (deg < 230)
54
72
  return 'cyan';
55
- if (deg < 270)
73
+ if (deg < 279)
56
74
  return 'blue';
57
- if (deg < 300)
75
+ if (deg < 311)
58
76
  return 'purple';
59
- if (deg < 315)
77
+ if (deg < 358.5)
60
78
  return L > 0.7 ? 'pink' : 'magenta';
61
- return L > 0.7 ? 'pink' : 'magenta';
79
+ return L < 0.45 ? 'brown' : 'red';
62
80
  }
63
81
  /** @lang zh-CN 由 HEX 生成结构化色名(修饰语+色相,中英双语)。
64
82
  * @lang en Builds a structured bilingual color name (modifier + hue) from hex. */
@@ -5,4 +5,50 @@ export declare function bestOnColor(hex: string): {
5
5
  label: string;
6
6
  ratio: number;
7
7
  };
8
+ /** @lang zh-CN 矩阵输入项:key 为显示键名(角色名/token 名),hex 为色值。 @lang en Matrix input: key is the display label, hex the colour. */
9
+ export interface MatrixEntry {
10
+ key: string;
11
+ hex: string;
12
+ }
13
+ export interface ContrastMatrixResult {
14
+ /** @lang zh-CN 行/列顺序与传入顺序一致。 @lang en Row/column order matches the input order. */
15
+ keys: string[];
16
+ /** @lang zh-CN WCAG 2.x 比值矩阵(对称,对角线为 1)。 @lang en WCAG 2.x ratio matrix (symmetric, unit diagonal). */
17
+ wcag: number[][];
18
+ /** @lang zh-CN APCA Lc 带符号矩阵:行=文字色、列=背景色(APCA 极性有方向性,**不对称**)。 @lang en Signed APCA Lc matrix: row=text colour, column=background (polarity is directional, so **not symmetric**). */
19
+ apca: number[][];
20
+ }
21
+ /**
22
+ * @lang zh-CN 全调色板两两对比度矩阵(`W-tb-P36`):WCAG 2.x 逐对 + APCA Lc 逐对(行=文字/列=背景)。
23
+ * 用途:一眼看出哪些角色对在哪个阈值下不可读——把"逐对断言"升级为"全局可见"。
24
+ * 对角线恒为 1(WCAG)/0(APCA),调用方可直接渲染。
25
+ * @lang en Palette-wide pairwise contrast matrix (`W-tb-P36`): WCAG 2.x per pair plus signed APCA Lc per pair
26
+ * (row=text, column=background). Purpose: make unreadable role pairs visible at a glance instead of relying
27
+ * on scattered assertions. The diagonal is 1 (WCAG) / 0 (APCA), ready to render.
28
+ */
29
+ export declare function contrastMatrix(colors: readonly MatrixEntry[]): ContrastMatrixResult;
30
+ export interface StepForContrastResult {
31
+ /** @lang zh-CN 生成色(保色相/彩度形态,仅调 L,经色域映射)。 @lang en Generated colour (hue/chroma shape kept, only L moved, gamut-mapped). */
32
+ hex: string;
33
+ /** @lang zh-CN 实测 WCAG 比值(与目标的接近程度即 ok 的依据)。 @lang en Measured WCAG ratio (closeness to target drives ok). */
34
+ ratio: number;
35
+ /** @lang zh-CN 移动方向:lighter=比背景亮(深底浅字)/ darker=比背景暗(浅底深字)。 @lang en Direction moved: lighter = brighter than bg (dark bg), darker = dimmer than bg (light bg). */
36
+ direction: 'lighter' | 'darker';
37
+ /** @lang zh-CN 生成色的 OKLCH L。 @lang en OKLCH L of the generated colour. */
38
+ L: number;
39
+ /** @lang zh-CN 是否达到目标(±0.1);false 表示色域/亮度边界限制了可达性。 @lang en Whether the target (±0.1) was met; false means gamut/L bounds limited reachability. */
40
+ ok: boolean;
41
+ }
42
+ /**
43
+ * @lang zh-CN 以对比度为目标反推色值(`W-tb-P36`):保持基色的色相与彩度形态,沿 OKLCH 亮度轴
44
+ * 二分搜索,使 WCAG 比值 ≈ target。与"锚定推导"(`W-tb-P16`)互补:锚定保关系、本函数保目标。
45
+ * 背景较亮 → 向深搜(darker);背景较暗 → 向浅搜(lighter);两侧都试并取更接近目标的一侧。
46
+ * 色域边界(彩度映射后 L 可用范围)可能限制可达性——此时返回可达的最接近值并置 ok:false。
47
+ * @lang en Target-driven colour synthesis (`W-tb-P36`, Leonardo-style inverse): keeps the base hue/chroma shape
48
+ * and bisects along OKLCH lightness until the WCAG ratio ≈ target. Complements anchored derivation
49
+ * (`W-tb-P16`): anchoring preserves relations, this preserves targets. Light bg → search darker; dark bg →
50
+ * search lighter; both halves are probed and the closer match wins. Gamut limits may cap reachability —
51
+ * the nearest reachable value is returned with ok:false.
52
+ */
53
+ export declare function stepForContrast(baseHex: string, bgHex: string, target: number): StepForContrastResult;
8
54
  //# sourceMappingURL=contrast.d.ts.map
@@ -1,4 +1,5 @@
1
- import { hexToRgb, srgbToLinear } from './convert.js';
1
+ import { hexToRgb, srgbToLinear, hexToOklch, gamutMapOklch } from './convert.js';
2
+ import { apcaLc } from './apca.js';
2
3
  // 计算相对亮度(WCAG 定义的线性光加权和,范围约 0..1)。
3
4
  // <lang zh-CN>用于对比度计算;权重对应人眼对 RGB 的敏感度。</lang>
4
5
  // <lang en>Used by contrast; weights reflect human eye sensitivity to RGB channels.</lang>
@@ -26,4 +27,115 @@ export function bestOnColor(hex) {
26
27
  // <lang en>ratio is exposed so the UI can show accessibility metrics.</lang>
27
28
  return white >= dark ? { hex: '#FFFFFF', label: '白色文字', ratio: white } : { hex: '#0F172A', label: '深色文字', ratio: dark };
28
29
  }
30
+ /**
31
+ * @lang zh-CN 全调色板两两对比度矩阵(`W-tb-P36`):WCAG 2.x 逐对 + APCA Lc 逐对(行=文字/列=背景)。
32
+ * 用途:一眼看出哪些角色对在哪个阈值下不可读——把"逐对断言"升级为"全局可见"。
33
+ * 对角线恒为 1(WCAG)/0(APCA),调用方可直接渲染。
34
+ * @lang en Palette-wide pairwise contrast matrix (`W-tb-P36`): WCAG 2.x per pair plus signed APCA Lc per pair
35
+ * (row=text, column=background). Purpose: make unreadable role pairs visible at a glance instead of relying
36
+ * on scattered assertions. The diagonal is 1 (WCAG) / 0 (APCA), ready to render.
37
+ */
38
+ export function contrastMatrix(colors) {
39
+ const keys = colors.map(c => c.key);
40
+ const wcag = colors.map(() => colors.map(() => 1));
41
+ const apca = colors.map(() => colors.map(() => 0));
42
+ // 对称矩阵只算上三角;APCA 具方向性(行=文字色),两个方向都要算。
43
+ // <lang en>The WCAG matrix is symmetric (upper triangle only); APCA is directional (row = text colour),
44
+ // so both directions are computed.</lang>
45
+ for (let i = 0; i < colors.length; i++) {
46
+ wcag[i][i] = 1;
47
+ for (let j = i + 1; j < colors.length; j++) {
48
+ const ratio = contrast(colors[i].hex, colors[j].hex);
49
+ wcag[i][j] = ratio;
50
+ wcag[j][i] = ratio;
51
+ }
52
+ for (let j = 0; j < colors.length; j++) {
53
+ apca[i][j] = i === j ? 0 : apcaLc(colors[i].hex, colors[j].hex);
54
+ }
55
+ }
56
+ return { keys, wcag, apca };
57
+ }
58
+ /**
59
+ * @lang zh-CN 以对比度为目标反推色值(`W-tb-P36`):保持基色的色相与彩度形态,沿 OKLCH 亮度轴
60
+ * 二分搜索,使 WCAG 比值 ≈ target。与"锚定推导"(`W-tb-P16`)互补:锚定保关系、本函数保目标。
61
+ * 背景较亮 → 向深搜(darker);背景较暗 → 向浅搜(lighter);两侧都试并取更接近目标的一侧。
62
+ * 色域边界(彩度映射后 L 可用范围)可能限制可达性——此时返回可达的最接近值并置 ok:false。
63
+ * @lang en Target-driven colour synthesis (`W-tb-P36`, Leonardo-style inverse): keeps the base hue/chroma shape
64
+ * and bisects along OKLCH lightness until the WCAG ratio ≈ target. Complements anchored derivation
65
+ * (`W-tb-P16`): anchoring preserves relations, this preserves targets. Light bg → search darker; dark bg →
66
+ * search lighter; both halves are probed and the closer match wins. Gamut limits may cap reachability —
67
+ * the nearest reachable value is returned with ok:false.
68
+ */
69
+ export function stepForContrast(baseHex, bgHex, target) {
70
+ const base = hexToOklch(baseHex);
71
+ // 在指定半区二分:ratioAt(L) 用与 tonalScale 相同的色域映射,保证结果可显示。
72
+ // <lang en>Bisect within one half; ratioAt uses the same gamut mapping as tonalScale so results are displayable.</lang>
73
+ const ratioAt = (L) => {
74
+ const { hex } = gamutMapOklch(L, base.C, base.h);
75
+ return contrast(hex, bgHex);
76
+ };
77
+ const probe = (direction) => {
78
+ // 半区端点:背景亮时往深走(0 → 背景L 下方),背景暗时往浅走(背景L 上方 → 1)。
79
+ // <lang en>Half bounds: for a light bg descend toward 0; for a dark bg ascend toward 1.</lang>
80
+ const bgL = hexToOklch(bgHex).L;
81
+ const low = direction === 'darker' ? 0.001 : Math.min(bgL + 0.002, 0.999);
82
+ const high = direction === 'darker' ? Math.max(bgL - 0.002, 0.001) : 0.999;
83
+ // 目标比值换算成可比较的亮度:比值单调于本半区,直接二分。
84
+ // <lang en>The ratio is monotonic within this half, so a plain bisection applies.</lang>
85
+ let lo = low, hi = high;
86
+ const bestHexAt = (L) => gamutMapOklch(L, base.C, base.h).hex;
87
+ // 端点比值:决定可达区间 [min, max]。
88
+ // <lang en>Endpoint ratios: they define the reachable interval [min, max].</lang>
89
+ const rLo = contrast(bestHexAt(lo), bgHex), rHi = contrast(bestHexAt(hi), bgHex);
90
+ // 可达性:单调函数在两端点处取到区间最小/最大比值,目标落在两者之间即可达。
91
+ // darker 半区:lo 端比值最大、hi 端≈1;lighter 半区:lo 端≈1、hi 端最大。判据两侧通用。
92
+ // <lang en>Reachability: a monotonic function attains its min/max ratio at the two endpoints, so the target
93
+ // is reachable iff it lies between them — the check is direction-agnostic.</lang>
94
+ const reachable = target >= Math.min(rLo, rHi) && target <= Math.max(rLo, rHi);
95
+ if (!reachable) {
96
+ // 目标不可达:返回更接近目标的端点,并置 ok:false(调用方据此提示"已取最接近值")。
97
+ // <lang en>Target unreachable: return the nearer endpoint with ok:false so callers can say
98
+ // "nearest achievable".</lang>
99
+ const pick = Math.abs(rLo - target) <= Math.abs(rHi - target) ? lo : hi;
100
+ return { hex: bestHexAt(pick), ratio: contrast(bestHexAt(pick), bgHex), direction, L: pick, ok: false };
101
+ }
102
+ // 32 次二分:亮度域 [0,1] 内精度约 1e-9,远超视觉需求。
103
+ // <lang en>32 bisections: ~1e-9 precision on [0,1], far beyond visual need.</lang>
104
+ for (let i = 0; i < 32; i++) {
105
+ const mid = (lo + hi) / 2;
106
+ const r = contrast(bestHexAt(mid), bgHex);
107
+ // 比值随 L 单调(半区内),据此收缩区间。
108
+ // <lang en>Within the half the ratio is monotonic in L, so shrink accordingly.</lang>
109
+ const goLow = r > target ? direction === 'darker' ? false : true : direction === 'darker' ? true : false;
110
+ if (goLow)
111
+ hi = mid;
112
+ else
113
+ lo = mid;
114
+ }
115
+ // 取收缩后更贴近目标的一端,避免舍入偏差。
116
+ // <lang en>Pick whichever converged end is closer to the target to avoid rounding bias.</lang>
117
+ const cands = [lo, hi];
118
+ let best = cands[0];
119
+ for (const c of cands) {
120
+ if (Math.abs(contrast(bestHexAt(c), bgHex) - target) < Math.abs(contrast(bestHexAt(best), bgHex) - target))
121
+ best = c;
122
+ }
123
+ const hex = bestHexAt(best), ratio = contrast(hex, bgHex);
124
+ return { hex, ratio, direction, L: best, ok: Math.abs(ratio - target) <= 0.1 };
125
+ };
126
+ // 先按亮度常识选一侧(背景亮→深字),不可达时再试另一侧,取 ok 或更接近者。
127
+ // <lang en>Try the obvious side first (light bg → dark text); if unreachable, probe the other side and keep
128
+ // the ok result or the closer one.</lang>
129
+ const bgL = hexToOklch(bgHex).L;
130
+ const primaryDirection = bgL >= 0.5 ? 'darker' : 'lighter';
131
+ const primary = probe(primaryDirection);
132
+ if (primary.ok)
133
+ return primary;
134
+ const secondary = probe(primaryDirection === 'darker' ? 'lighter' : 'darker');
135
+ // 两侧都不可达时,取比值更接近目标的一侧。
136
+ // <lang en>If neither side reaches the target, keep the side whose ratio is nearer the target.</lang>
137
+ if (secondary.ok || Math.abs(secondary.ratio - target) < Math.abs(primary.ratio - target))
138
+ return secondary;
139
+ return primary;
140
+ }
29
141
  //# sourceMappingURL=contrast.js.map
@@ -0,0 +1,56 @@
1
+ /** @lang zh-CN 降采样上限(最长边,ADR-014 决策 6)。 @lang en Downsample cap (longest edge, ADR-014 decision 6). */
2
+ export declare const IMAGE_EXTRACT_MAX_DIM = 512;
3
+ /** @lang zh-CN 聚类数(中位切分叶子数)。 @lang en Cluster count (median-cut leaves). */
4
+ export declare const IMAGE_EXTRACT_CLUSTERS = 8;
5
+ /** @lang zh-CN 近色合并阈值(OKLab 距离)。 @lang en Near-colour merge threshold (OKLab distance). */
6
+ export declare const IMAGE_EXTRACT_MERGE_DIST = 0.09;
7
+ /** @lang zh-CN 提取模式。 @lang en Extraction modes. */
8
+ export type ImageExtractMode = 'balanced' | 'vivid' | 'bright' | 'dark';
9
+ /** @lang zh-CN 降采样后的像素输入(宿主经 OffscreenCanvas 提供)。 @lang en Downsampled pixel input (host provides via OffscreenCanvas). */
10
+ export interface ImagePixels {
11
+ data: Uint8ClampedArray;
12
+ width: number;
13
+ height: number;
14
+ }
15
+ export interface ImageCandidate {
16
+ /** @lang zh-CN 候选 HEX。 @lang en Candidate HEX. */
17
+ hex: string;
18
+ /** @lang zh-CN 中文色名(ISCC-NBS 管线)。 @lang en Chinese colour name (ISCC-NBS pipeline). */
19
+ name: string;
20
+ /** @lang zh-CN 英文色名。 @lang en English colour name. */
21
+ nameEn: string;
22
+ /** @lang zh-CN 象素占比(0–1,模式加权后)。 @lang en Pixel share (0–1, after mode weighting). */
23
+ weight: number;
24
+ /** @lang zh-CN 原始计票(未加权,供 UI 显示可信度)。 @lang en Raw vote count (unweighted, for confidence display). */
25
+ population: number;
26
+ }
27
+ export interface ImageExtractResult {
28
+ /** @lang zh-CN 加权排序后的候选(近色已合并;最多 6 条)。 @lang en Candidates sorted by mode weighting (merged; ≤6). */
29
+ candidates: ImageCandidate[];
30
+ /** @lang zh-CN 推荐主色(加权首位)。 @lang en Suggested primary (weighted first). */
31
+ primary: string;
32
+ /** @lang zh-CN 推荐副色(与主色色相差最大且对比达标的候选;无则回退主色的最佳前景)。 @lang en Suggested secondary (largest hue gap with adequate contrast; falls back to the primary's best foreground). */
33
+ secondary: string;
34
+ /** @lang zh-CN 渐变提取:最暗/最亮候选(HEX);不足两条候选时为 null。 @lang en Gradient extraction: darkest/brightest candidates (HEX); null when fewer than two candidates. */
35
+ gradient: {
36
+ start: string;
37
+ end: string;
38
+ } | null;
39
+ }
40
+ /** @lang zh-CN 最近邻降采样:最长边超过 maxDim 时按整数步长抽点(不插值,确定性)。 @lang en Nearest-neighbour downsample: integer stride sampling when the longest edge exceeds maxDim (no interpolation, deterministic). */
41
+ export declare function downsamplePixels(input: ImagePixels, maxDim?: number): ImagePixels;
42
+ /**
43
+ * @lang zh-CN 图片提色主入口:降采样 → 不透明像素 → OKLab 中位切分 → 代表色(桶均值)→
44
+ * 近色合并 → 模式加权排序 → 主/副/渐变推导。纯函数、确定性。
45
+ * @lang en The main extraction entry: downsample → opaque pixels → OKLab median cut → representative colours
46
+ * (bucket means) → near-colour merge → mode-weighted ordering → primary/secondary/gradient. Pure and
47
+ * deterministic.
48
+ */
49
+ export declare function extractImagePalette(input: ImagePixels, mode?: ImageExtractMode): ImageExtractResult;
50
+ /**
51
+ * @lang zh-CN 从提取结果构造渐变方向建议:暗→亮用 135deg(对角),亮→暗用 315deg。
52
+ * @lang en Suggests a gradient direction from the extraction: dark→light uses 135deg (diagonal), the reverse
53
+ * uses 315deg.
54
+ */
55
+ export declare function suggestGradientDirection(start: string, end: string): string;
56
+ //# sourceMappingURL=image-extract.d.ts.map