@labpics/colors 0.8.0 → 0.9.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.
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # @labpics/colors
2
2
 
3
- Адаптивные цветовые роли для дизайн-системы. Получает фоновый цвет и тему — возвращает полный набор ролей (`--lab-label-primary`, `--lab-icon`, `--lab-border-base`, …). CSS-переменные несут готовое значение `oklch(L% C H)` (для полупрозрачных ролей — `oklch(L% C H / A)`); сырой `#RRGGBB` остаётся данными роли (`roles.<ключ>.hex`). Ядро написано на Rust и скомпилировано в WebAssembly; пакет не имеет runtime-зависимостей.
3
+ Агностичный контраст-движок для дизайн-систем. Получает фоновый цвет и тему — возвращает полный набор цветовых ролей **вашей** системы. Словарь ролей не встроен в пакет: его задаёт конфиг дизайн-системы (`ThemeConfig`), загружаемый через `loadConfig`; имена вида `--lab-label-primary`, `--lab-border-base` в примерах ниже — из конфига дизайн-системы labui. CSS-переменные несут готовое значение `oklch(L% C H)` (для полупрозрачных ролей — `oklch(L% C H / A)`); сырой `#RRGGBB` остаётся данными роли (`roles.<ключ>.hex`). Ядро написано на Rust и скомпилировано в WebAssembly; пакет не имеет runtime-зависимостей.
4
4
 
5
5
  Ядро возвращает **данные**, не затрагивает DOM. Три вспомогательные функции переводят эти данные в живые CSS-переменные: `applyTheme` (разовое применение), `watchTheme` (реактивное — обновляется при изменении фона) и `adaptTheme` (плавная адаптация для фона, меняющегося каждый кадр).
6
6
 
@@ -28,13 +28,15 @@ npm run build # → pkg/ (wasm + JS-обёртка + .d.ts)
28
28
 
29
29
  ```ts
30
30
  import init, { LabColors, applyTheme } from "@labpics/colors";
31
+ import dsConfig from "./theme.config.json"; // паспорт вашей дизайн-системы (ThemeConfig)
31
32
 
32
- await init(); // загрузить WASM-модуль (один раз)
33
- const engine = new LabColors(); // движок по умолчанию
33
+ await init(); // загрузить WASM-модуль (один раз)
34
+ const engine = new LabColors(); // пустой движок: словаря ролей ещё нет
35
+ engine.loadConfig(JSON.stringify(dsConfig)); // без этого шага resolveTheme отклонится: config_required
34
36
 
35
37
  const result = engine.resolveTheme("#FFFFFF", "light");
36
- // result.vars → { "--lab-label-primary": "oklch(14.79140% 0.012878 284.717)",
37
- // "--lab-icon": "oklch(66.97448% 0.014606 285.999)", ... }
38
+ // result.vars → готовые CSS-значения по ролям ВАШЕГО конфига:
39
+ // { "--lab-label-primary": "oklch(<L>% <C> <H>)", … }
38
40
  // result.roles → детали каждой роли (css, hex, контраст, флаги)
39
41
 
40
42
  applyTheme(document.documentElement, result); // записать все --lab-* в элемент
@@ -49,6 +51,7 @@ import init, { LabColors, watchTheme } from "@labpics/colors";
49
51
 
50
52
  await init();
51
53
  const colors = new LabColors();
54
+ colors.loadConfig(JSON.stringify(dsConfig)); // конфиг дизайн-системы (см. квик-старт)
52
55
 
53
56
  const panel = document.querySelector(".panel") as HTMLElement;
54
57
  const watcher = watchTheme(panel, { colors, theme: "light" });
@@ -73,6 +76,7 @@ import init, { LabColors, adaptTheme, effectiveBackground } from "@labpics/color
73
76
 
74
77
  await init();
75
78
  const colors = new LabColors();
79
+ colors.loadConfig(JSON.stringify(dsConfig)); // конфиг дизайн-системы (см. квик-старт)
76
80
 
77
81
  const surface = document.querySelector(".hero") as HTMLElement;
78
82
  const adaptive = adaptTheme(surface, {
@@ -114,7 +118,7 @@ adaptTheme(hero, {
114
118
 
115
119
  ### `new LabColors()`
116
120
 
117
- Создаёт движок с таблицей ролей и условиями наблюдения по умолчанию. Повторные одинаковые вызовы `resolveTheme` обслуживаются из внутреннего кэша.
121
+ Создаёт движок **без** словаря ролей: до `loadConfig` любой вызов `resolveTheme` отклоняется ошибкой `config_required`. Повторные одинаковые вызовы `resolveTheme` обслуживаются из внутреннего кэша (кэш-пространство привязано к отпечатку конфига).
118
122
 
119
123
  ---
120
124
 
@@ -147,6 +151,7 @@ type RoleResult = SolvedColor | TranslucentRole | NoneRole | UnreachableRole;
147
151
 
148
152
  | Код ошибки | Причина |
149
153
  |------------|---------|
154
+ | `config_required` | конфиг ещё не загружен (`loadConfig` не вызывался) |
150
155
  | `invalid_background` | `bgHex` не является `#RGB` или `#RRGGBB` |
151
156
  | `unknown_theme` | `theme` не входит в список допустимых |
152
157
 
@@ -154,7 +159,7 @@ type RoleResult = SolvedColor | TranslucentRole | NoneRole | UnreachableRole;
154
159
 
155
160
  ### `engine.loadConfig(json): string`
156
161
 
157
- Загружает конфиг дизайн-системы (JSON по типу `ThemeConfig`) — главная фича конфиг-границы: движок начинает эмитить роли и подтон конфига вместо встроенной таблицы. Полный preflight: невалидный конфиг отклоняется структурной ошибкой `invalid_config: …` и НЕ меняет состояние. Возвращает отпечаток конфига — 16 hex-символов; разные конфиги дают разные отпечатки и разные кэш-пространства.
162
+ Загружает конфиг дизайн-системы (JSON по типу `ThemeConfig`; схема — в репозитории: `docs/decisions/0001-config-boundary.md`, TS-типы — в поставляемом `labcolors.d.ts`). Это **единственный** источник словаря ролей — встроенной таблицы в движке нет: до загрузки конфига `resolveTheme` отклоняется ошибкой `config_required`. Полный preflight: невалидный конфиг отклоняется структурной ошибкой `invalid_config: …` и НЕ меняет состояние. Возвращает отпечаток конфига — 16 hex-символов; разные конфиги дают разные отпечатки и разные кэш-пространства.
158
163
 
159
164
  ---
160
165
 
@@ -164,6 +169,12 @@ type RoleResult = SolvedColor | TranslucentRole | NoneRole | UnreachableRole;
164
169
 
165
170
  ---
166
171
 
172
+ ### `engine.recheckContrastMulti(bgHexes, fgHexes, theme): Float64Array`
173
+
174
+ Батч-вариант `recheckContrast` для меняющегося фона (градиент / картинка / bg-blur / стекло): проверяет один набор `fgHexes` сразу против НЕСКОЛЬКИХ сэмплов фона `bgHexes` за один вызов, разделяя прямой ход модели каждого переднего плана между всеми сэмплами (он от фона не зависит). Байт-в-байт равен N отдельным вызовам `recheckContrast`, пара за парой — это закреплено parity-тестом границы, — только быстрее: ~2.5× на 3 сэмплах. Возвращает плоский background-major `Float64Array`: сэмпл `s`, цвет `i` лежит в `(s · fgHexes.length + i) · 2` (`lc`) и `+1` (`wcagRatio`). Именно этим вызовом `adaptTheme` схлопывает worst-case цикл по сэмплам в одно обращение к движку; на одном сэмпле выигрыша нет — контроллер остаётся на `recheckContrast`.
175
+
176
+ ---
177
+
167
178
  ### `engine.muddiness(hex): number` · `engine.confidence(hex): number`
168
179
 
169
180
  `muddiness` — оценка «грязи» цвета `hex` в диапазоне `[0, 1]` (Закон Грязи). `confidence` — надёжность этой оценки: `0` означает, что оценке нельзя доверять (у границы решения или серого фронтира), выше — увереннее. Верхний потолок — деталь калибровки, не контракт: не хардкодить.
package/adapt-theme.d.ts CHANGED
@@ -3,8 +3,15 @@
3
3
  import type { LabColors, ThemeName } from "./pkg/labcolors.js";
4
4
 
5
5
  export interface AdaptThemeOptions {
6
- /** An initialised engine — needs `resolveTheme` AND `recheckContrast`. */
7
- colors: Pick<LabColors, "resolveTheme" | "recheckContrast">;
6
+ /**
7
+ * An initialised engine — needs `resolveTheme` AND `recheckContrast`.
8
+ * `recheckContrastMulti` is optional: when present, a multi-sample backdrop
9
+ * is rechecked in ONE batched call per frame (byte-identical to the
10
+ * per-sample loop, locked by the wasm boundary parity test); when absent,
11
+ * the controller falls back to N `recheckContrast` calls.
12
+ */
13
+ colors: Pick<LabColors, "resolveTheme" | "recheckContrast"> &
14
+ Partial<Pick<LabColors, "recheckContrastMulti">>;
8
15
  theme: ThemeName;
9
16
  /**
10
17
  * Explicit effective background, overriding the ancestor-composite. A single
package/adapt-theme.js CHANGED
@@ -215,16 +215,33 @@ export function adaptTheme(element, options) {
215
215
  // frame and previously rebuilt this identical array from `roles` each time.
216
216
  let fgsCache = [];
217
217
 
218
+ // Batch path (many samples): collapse the shared per-foreground CAM16 forward
219
+ // across every sample into ONE engine call. `recheckContrastMulti` returns a
220
+ // background-major flat buffer where sample `s`, foreground `i` sits at
221
+ // `(s * stride + i) * 2` (Lc) — the batched analogue of the per-sample loop's
222
+ // `flat[2 * i]`. Byte-identical to N `recheckContrast` calls (locked by the
223
+ // wasm boundary parity test), so the worst-margin / breach / worstIdx decision
224
+ // below is bit-for-bit the same as the fallback loop.
225
+ const canBatch =
226
+ typeof colors.recheckContrastMulti === "function";
227
+
218
228
  const recheckSamples = (samples) => {
219
229
  let breached = false;
220
230
  let worstIdx = 0;
221
231
  let worstMargin = Infinity;
232
+ const stride = fgsCache.length;
233
+ const batch =
234
+ canBatch && samples.length > 1
235
+ ? colors.recheckContrastMulti(samples, fgsCache, theme)
236
+ : null;
222
237
  for (let s = 0; s < samples.length; s++) {
223
- const flat = colors.recheckContrast(samples[s], fgsCache, theme);
238
+ // Per-sample flat buffer, or a background-major window into the batch one.
239
+ const flat = batch ? null : colors.recheckContrast(samples[s], fgsCache, theme);
240
+ const base = s * stride;
224
241
  let sampleMargin = Infinity;
225
242
  for (let i = 0; i < roles.length; i++) {
226
243
  const want = Math.abs(roles[i].lc) * (1 - dropFraction);
227
- const lcNow = Math.abs(flat[2 * i]);
244
+ const lcNow = Math.abs(batch ? batch[(base + i) * 2] : flat[2 * i]);
228
245
  if (lcNow < want) breached = true;
229
246
  const margin = want > 0 ? lcNow / want : Infinity;
230
247
  if (margin < sampleMargin) sampleMargin = margin;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@labpics/colors",
3
- "version": "0.8.0",
3
+ "version": "0.9.0",
4
4
  "description": "Framework-agnostic contrast engine: resolve accessible, perceptually-anchored colour roles for any background. WASM core, zero runtime dependencies.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -204,22 +204,6 @@ export interface ResolvedTheme {
204
204
  export class LabColors {
205
205
  free(): void;
206
206
  [Symbol.dispose](): void;
207
- /**
208
- * PROTOTYPE — NOT part of the public API (unlisted, `_`-prefixed; may change
209
- * or be removed without notice). Recheck one foreground set against MANY
210
- * background samples in a single call. The reactive controller's worst-case
211
- * loop rechecks the same foregrounds against every sample of a varying
212
- * backdrop; the dominant per-foreground CAM16 forward is background-
213
- * independent, so this shares it across all samples instead of recomputing it
214
- * per `recheckContrast` call.
215
- *
216
- * Returns a flat, background-major `Float64Array`: sample `s`, foreground `i`
217
- * is at `(s * fgHexes.length + i) * 2` (`lc`) and `+1` (`wcagRatio`). The
218
- * values are byte-identical to calling `recheckContrast(bgHexes[s], fgHexes,
219
- * theme)` for each `s`. Wiring the runtime to it is an OWNER decision (it
220
- * changes the controller↔engine call shape); it is measured, not adopted.
221
- */
222
- _recheckContrastMulti(bg_hexes: string[], fg_hexes: string[], theme: string): Float64Array;
223
207
  /**
224
208
  * Загрузить конфиг дизайн-системы (JSON по типу `ThemeConfig` из `.d.ts`).
225
209
  *
@@ -256,6 +240,20 @@ export class LabColors {
256
240
  * an unknown theme.
257
241
  */
258
242
  recheckContrast(bg_hex: string, fg_hexes: string[], theme: string): Float64Array;
243
+ /**
244
+ * Recheck one foreground set against MANY background samples in a single
245
+ * call. The reactive controller's worst-case loop rechecks the same
246
+ * foregrounds against every sample of a varying backdrop (gradient / image /
247
+ * bg-blur / glass); the dominant per-foreground CAM16 forward is background-
248
+ * independent, so this shares it across all samples instead of recomputing it
249
+ * per `recheckContrast` call — a measured ~2.6x on the multi-sample recheck.
250
+ *
251
+ * Returns a flat, background-major `Float64Array`: sample `s`, foreground `i`
252
+ * is at `(s * fgHexes.length + i) * 2` (`lc`) and `+1` (`wcagRatio`). The
253
+ * values are byte-identical to calling `recheckContrast(bgHexes[s], fgHexes,
254
+ * theme)` for each `s`.
255
+ */
256
+ recheckContrastMulti(bg_hexes: string[], fg_hexes: string[], theme: string): Float64Array;
259
257
  /**
260
258
  * Resolve every role for `bgHex` under `theme` (`"light" | "dark" |
261
259
  * "light-ic" | "dark-ic"`).
@@ -275,11 +273,11 @@ export type InitInput = RequestInfo | URL | Response | BufferSource | WebAssembl
275
273
  export interface InitOutput {
276
274
  readonly memory: WebAssembly.Memory;
277
275
  readonly __wbg_labcolors_free: (a: number, b: number) => void;
278
- readonly labcolors__recheckContrastMulti: (a: number, b: number, c: number, d: number, e: number, f: number, g: number, h: number) => void;
279
276
  readonly labcolors_loadConfig: (a: number, b: number, c: number, d: number) => void;
280
277
  readonly labcolors_muddiness: (a: number, b: number, c: number, d: number) => void;
281
278
  readonly labcolors_new: () => number;
282
279
  readonly labcolors_recheckContrast: (a: number, b: number, c: number, d: number, e: number, f: number, g: number, h: number) => void;
280
+ readonly labcolors_recheckContrastMulti: (a: number, b: number, c: number, d: number, e: number, f: number, g: number, h: number) => void;
283
281
  readonly labcolors_resolveTheme: (a: number, b: number, c: number, d: number, e: number, f: number) => void;
284
282
  readonly __wbindgen_export: (a: number, b: number) => number;
285
283
  readonly __wbindgen_export2: (a: number, b: number, c: number, d: number) => number;
package/pkg/labcolors.js CHANGED
@@ -17,49 +17,6 @@ export class LabColors {
17
17
  const ptr = this.__destroy_into_raw();
18
18
  wasm.__wbg_labcolors_free(ptr, 0);
19
19
  }
20
- /**
21
- * PROTOTYPE — NOT part of the public API (unlisted, `_`-prefixed; may change
22
- * or be removed without notice). Recheck one foreground set against MANY
23
- * background samples in a single call. The reactive controller's worst-case
24
- * loop rechecks the same foregrounds against every sample of a varying
25
- * backdrop; the dominant per-foreground CAM16 forward is background-
26
- * independent, so this shares it across all samples instead of recomputing it
27
- * per `recheckContrast` call.
28
- *
29
- * Returns a flat, background-major `Float64Array`: sample `s`, foreground `i`
30
- * is at `(s * fgHexes.length + i) * 2` (`lc`) and `+1` (`wcagRatio`). The
31
- * values are byte-identical to calling `recheckContrast(bgHexes[s], fgHexes,
32
- * theme)` for each `s`. Wiring the runtime to it is an OWNER decision (it
33
- * changes the controller↔engine call shape); it is measured, not adopted.
34
- * @param {string[]} bg_hexes
35
- * @param {string[]} fg_hexes
36
- * @param {string} theme
37
- * @returns {Float64Array}
38
- */
39
- _recheckContrastMulti(bg_hexes, fg_hexes, theme) {
40
- try {
41
- const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);
42
- const ptr0 = passArrayJsValueToWasm0(bg_hexes, wasm.__wbindgen_export);
43
- const len0 = WASM_VECTOR_LEN;
44
- const ptr1 = passArrayJsValueToWasm0(fg_hexes, wasm.__wbindgen_export);
45
- const len1 = WASM_VECTOR_LEN;
46
- const ptr2 = passStringToWasm0(theme, wasm.__wbindgen_export, wasm.__wbindgen_export2);
47
- const len2 = WASM_VECTOR_LEN;
48
- wasm.labcolors__recheckContrastMulti(retptr, this.__wbg_ptr, ptr0, len0, ptr1, len1, ptr2, len2);
49
- var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);
50
- var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);
51
- var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);
52
- var r3 = getDataViewMemory0().getInt32(retptr + 4 * 3, true);
53
- if (r3) {
54
- throw takeObject(r2);
55
- }
56
- var v4 = getArrayF64FromWasm0(r0, r1).slice();
57
- wasm.__wbindgen_export4(r0, r1 * 8, 8);
58
- return v4;
59
- } finally {
60
- wasm.__wbindgen_add_to_stack_pointer(16);
61
- }
62
- }
63
20
  /**
64
21
  * Загрузить конфиг дизайн-системы (JSON по типу `ThemeConfig` из `.d.ts`).
65
22
  *
@@ -173,6 +130,47 @@ export class LabColors {
173
130
  wasm.__wbindgen_add_to_stack_pointer(16);
174
131
  }
175
132
  }
133
+ /**
134
+ * Recheck one foreground set against MANY background samples in a single
135
+ * call. The reactive controller's worst-case loop rechecks the same
136
+ * foregrounds against every sample of a varying backdrop (gradient / image /
137
+ * bg-blur / glass); the dominant per-foreground CAM16 forward is background-
138
+ * independent, so this shares it across all samples instead of recomputing it
139
+ * per `recheckContrast` call — a measured ~2.6x on the multi-sample recheck.
140
+ *
141
+ * Returns a flat, background-major `Float64Array`: sample `s`, foreground `i`
142
+ * is at `(s * fgHexes.length + i) * 2` (`lc`) and `+1` (`wcagRatio`). The
143
+ * values are byte-identical to calling `recheckContrast(bgHexes[s], fgHexes,
144
+ * theme)` for each `s`.
145
+ * @param {string[]} bg_hexes
146
+ * @param {string[]} fg_hexes
147
+ * @param {string} theme
148
+ * @returns {Float64Array}
149
+ */
150
+ recheckContrastMulti(bg_hexes, fg_hexes, theme) {
151
+ try {
152
+ const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);
153
+ const ptr0 = passArrayJsValueToWasm0(bg_hexes, wasm.__wbindgen_export);
154
+ const len0 = WASM_VECTOR_LEN;
155
+ const ptr1 = passArrayJsValueToWasm0(fg_hexes, wasm.__wbindgen_export);
156
+ const len1 = WASM_VECTOR_LEN;
157
+ const ptr2 = passStringToWasm0(theme, wasm.__wbindgen_export, wasm.__wbindgen_export2);
158
+ const len2 = WASM_VECTOR_LEN;
159
+ wasm.labcolors_recheckContrastMulti(retptr, this.__wbg_ptr, ptr0, len0, ptr1, len1, ptr2, len2);
160
+ var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);
161
+ var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);
162
+ var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);
163
+ var r3 = getDataViewMemory0().getInt32(retptr + 4 * 3, true);
164
+ if (r3) {
165
+ throw takeObject(r2);
166
+ }
167
+ var v4 = getArrayF64FromWasm0(r0, r1).slice();
168
+ wasm.__wbindgen_export4(r0, r1 * 8, 8);
169
+ return v4;
170
+ } finally {
171
+ wasm.__wbindgen_add_to_stack_pointer(16);
172
+ }
173
+ }
176
174
  /**
177
175
  * Resolve every role for `bgHex` under `theme` (`"light" | "dark" |
178
176
  * "light-ic" | "dark-ic"`).
Binary file
@@ -2,11 +2,11 @@
2
2
  /* eslint-disable */
3
3
  export const memory: WebAssembly.Memory;
4
4
  export const __wbg_labcolors_free: (a: number, b: number) => void;
5
- export const labcolors__recheckContrastMulti: (a: number, b: number, c: number, d: number, e: number, f: number, g: number, h: number) => void;
6
5
  export const labcolors_loadConfig: (a: number, b: number, c: number, d: number) => void;
7
6
  export const labcolors_muddiness: (a: number, b: number, c: number, d: number) => void;
8
7
  export const labcolors_new: () => number;
9
8
  export const labcolors_recheckContrast: (a: number, b: number, c: number, d: number, e: number, f: number, g: number, h: number) => void;
9
+ export const labcolors_recheckContrastMulti: (a: number, b: number, c: number, d: number, e: number, f: number, g: number, h: number) => void;
10
10
  export const labcolors_resolveTheme: (a: number, b: number, c: number, d: number, e: number, f: number) => void;
11
11
  export const __wbindgen_export: (a: number, b: number) => number;
12
12
  export const __wbindgen_export2: (a: number, b: number, c: number, d: number) => number;