@sessile/core 0.2.0 → 0.3.1
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/dist/contour.js +57 -12
- package/dist/index.d.ts +3 -2
- package/dist/index.js +2 -1
- package/dist/legibility.d.ts +288 -0
- package/dist/legibility.js +569 -0
- package/dist/optics.d.ts +13 -1
- package/dist/optics.js +59 -2
- package/dist/overlayRenderer.d.ts +17 -2
- package/dist/overlayRenderer.js +284 -118
- package/package.json +1 -1
|
@@ -0,0 +1,569 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Adaptive backdrop legibility kernel.
|
|
3
|
+
*
|
|
4
|
+
* The host fixes the foreground (text color, polarity, target contrast); the glass yields.
|
|
5
|
+
* Every quantity here is expressed in sRGB-encoded relative luminance ("encoded luminance"),
|
|
6
|
+
* the domain browsers composite in, so veil-over-backdrop blending stays affine and WCAG
|
|
7
|
+
* bounds convert exactly for neutrals.
|
|
8
|
+
*
|
|
9
|
+
* The per-pixel stage is a luminance-keyed multiplicative film evaluated by the Route B3 SVG
|
|
10
|
+
* filter: `out = c * M(x)` for light text and `1 - out = (1 - c) * M(x)` for dark text. Scaling
|
|
11
|
+
* all channels by one factor keeps hue and saturation (no signed chroma intermediates, no gamut
|
|
12
|
+
* clipping) while absolute chroma converges exactly where luminance is compressed.
|
|
13
|
+
*
|
|
14
|
+
* SPDX-License-Identifier: MPL-2.0
|
|
15
|
+
*/
|
|
16
|
+
import { clamp, lerp, smoothstep } from "./physics.js";
|
|
17
|
+
export const LEGIBILITY_POLICIES = {
|
|
18
|
+
clear: {
|
|
19
|
+
contrast: 3,
|
|
20
|
+
knee: 0.72,
|
|
21
|
+
filmMax: 0.06,
|
|
22
|
+
saturationFloor: 0.88,
|
|
23
|
+
blurBoostPx: 1.5,
|
|
24
|
+
refractionFloor: 0.85,
|
|
25
|
+
edgeGain: 0.35,
|
|
26
|
+
shadowGain: 0.4,
|
|
27
|
+
assumedRisk: 0.3,
|
|
28
|
+
},
|
|
29
|
+
regular: {
|
|
30
|
+
contrast: 4.5,
|
|
31
|
+
knee: 0.7,
|
|
32
|
+
filmMax: 0.14,
|
|
33
|
+
saturationFloor: 0.72,
|
|
34
|
+
blurBoostPx: 3,
|
|
35
|
+
refractionFloor: 0.65,
|
|
36
|
+
edgeGain: 0.6,
|
|
37
|
+
shadowGain: 0.8,
|
|
38
|
+
assumedRisk: 0.5,
|
|
39
|
+
},
|
|
40
|
+
legible: {
|
|
41
|
+
contrast: 7,
|
|
42
|
+
knee: 0.65,
|
|
43
|
+
filmMax: 0.26,
|
|
44
|
+
saturationFloor: 0.55,
|
|
45
|
+
blurBoostPx: 6,
|
|
46
|
+
refractionFloor: 0.4,
|
|
47
|
+
edgeGain: 0.9,
|
|
48
|
+
shadowGain: 1.2,
|
|
49
|
+
assumedRisk: 0.8,
|
|
50
|
+
},
|
|
51
|
+
};
|
|
52
|
+
/**
|
|
53
|
+
* Attack is fast so text never sits on an unsafe backdrop for more than a few frames; hold and
|
|
54
|
+
* release bridge the calm gutters between cards so scrolling across a grid does not strobe.
|
|
55
|
+
*/
|
|
56
|
+
export const LEGIBILITY_SMOOTHING = {
|
|
57
|
+
attackMs: 90,
|
|
58
|
+
holdMs: 240,
|
|
59
|
+
releaseMs: 700,
|
|
60
|
+
// The final snap moves film alpha by at most `filmMax * epsilon` (~0.001), invisible, while
|
|
61
|
+
// letting the frame loop sleep a couple of seconds earlier than a 1e-3 tail would.
|
|
62
|
+
epsilon: 0.004,
|
|
63
|
+
};
|
|
64
|
+
/** Knee fraction used at zero luminance risk. */
|
|
65
|
+
export const LEGIBILITY_CALM_KNEE = 0.9;
|
|
66
|
+
/** Samples in each per-pixel multiplier table (`feFunc* type="table"`). */
|
|
67
|
+
export const LEGIBILITY_TABLE_SIZE = 33;
|
|
68
|
+
/**
|
|
69
|
+
* Filter-graph contract for the per-pixel stage, keyed by polarity.
|
|
70
|
+
* `k` are `feComposite operator="arithmetic"` coefficients with `in` = color, `in2` = multiplier.
|
|
71
|
+
* Light text keys on true luminance (`linearRGB` matrix): sRGB luma underestimates saturated
|
|
72
|
+
* colors (pure red has luma 0.21 but encoded luminance ~0.50) and would leave them unclamped.
|
|
73
|
+
* Dark text keys on sRGB luma, which only ever underestimates, so the lift errs on the safe side
|
|
74
|
+
* and avoids quantizing shadows in an 8-bit linear buffer.
|
|
75
|
+
*/
|
|
76
|
+
export const LEGIBILITY_STAGES = {
|
|
77
|
+
light: { luminanceSpace: 'linearRGB', k: [1, 0, 0, 0] },
|
|
78
|
+
dark: { luminanceSpace: 'sRGB', k: [1, 0, -1, 1] },
|
|
79
|
+
};
|
|
80
|
+
/**
|
|
81
|
+
* Encoded-luminance headroom kept below the exact limit. Covers the residual error of
|
|
82
|
+
* scaling in sRGB space (the transfer curve is not a pure power law), veil blending of colored
|
|
83
|
+
* pixels, and 8-bit filter intermediates; sized by the reference-model sweep in the unit tests.
|
|
84
|
+
*/
|
|
85
|
+
export const LEGIBILITY_LIMIT_MARGIN = 0.008;
|
|
86
|
+
/** Telemetry floats per grid cell: `lumaHigh, lumaLow, channelHigh, channelLow, chroma, detail`. */
|
|
87
|
+
export const TELEMETRY_STRIDE = 6;
|
|
88
|
+
export function srgbToLinear(c) {
|
|
89
|
+
return c <= 0.04045 ? c / 12.92 : Math.pow((c + 0.055) / 1.055, 2.4);
|
|
90
|
+
}
|
|
91
|
+
export function linearToSrgb(l) {
|
|
92
|
+
return l <= 0.0031308 ? l * 12.92 : 1.055 * Math.pow(l, 1 / 2.4) - 0.055;
|
|
93
|
+
}
|
|
94
|
+
/** WCAG 2 relative luminance of a normalized sRGB color. */
|
|
95
|
+
/** Rec. 709 weights applied to the encoded sRGB channels; a lower bound on encoded luminance. */
|
|
96
|
+
export function srgbLuma(r, g, b) {
|
|
97
|
+
return 0.2126 * r + 0.7152 * g + 0.0722 * b;
|
|
98
|
+
}
|
|
99
|
+
export function relativeLuminance(r, g, b) {
|
|
100
|
+
return 0.2126 * srgbToLinear(r) + 0.7152 * srgbToLinear(g) + 0.0722 * srgbToLinear(b);
|
|
101
|
+
}
|
|
102
|
+
/** WCAG 2 contrast ratio between two relative luminances. */
|
|
103
|
+
export function contrastRatio(a, b) {
|
|
104
|
+
const hi = Math.max(a, b);
|
|
105
|
+
const lo = Math.min(a, b);
|
|
106
|
+
return (hi + 0.05) / (lo + 0.05);
|
|
107
|
+
}
|
|
108
|
+
/** Resolves the host declaration into a polarity and an encoded-luminance limit. */
|
|
109
|
+
export function resolveLegibilityGoal(target) {
|
|
110
|
+
const policy = LEGIBILITY_POLICIES[target.tier ?? 'regular'];
|
|
111
|
+
const contrast = target.contrast !== undefined && Number.isFinite(target.contrast)
|
|
112
|
+
? Math.max(1, target.contrast)
|
|
113
|
+
: policy.contrast;
|
|
114
|
+
const fg = target.foreground;
|
|
115
|
+
const lf = relativeLuminance(fg[0] ?? 0, fg[1] ?? 0, fg[2] ?? 0);
|
|
116
|
+
const ceiling = (lf + 0.05) / contrast - 0.05;
|
|
117
|
+
const floor = contrast * (lf + 0.05) - 0.05;
|
|
118
|
+
const polarity = target.polarity ?? (ceiling >= 1 - floor ? 'light' : 'dark');
|
|
119
|
+
const limit = polarity === 'light' ? ceiling : floor;
|
|
120
|
+
return {
|
|
121
|
+
polarity,
|
|
122
|
+
contrast,
|
|
123
|
+
policy,
|
|
124
|
+
perceivedLimit: linearToSrgb(clamp(limit, 0, 1)),
|
|
125
|
+
};
|
|
126
|
+
}
|
|
127
|
+
/**
|
|
128
|
+
* Converts the perceived limit into a limit on the backdrop under a veil of `veilRgba`,
|
|
129
|
+
* expressed in "risk space" `u` (`u = x` for light text, `u = 1 - x` for dark) so both
|
|
130
|
+
* polarities share one ceiling curve. Returns `>= 1` when no compression is needed and `<= 0`
|
|
131
|
+
* when the veil alone violates the goal.
|
|
132
|
+
*/
|
|
133
|
+
function backdropCeiling(goal, veilRgba) {
|
|
134
|
+
const a = clamp(veilRgba[3] ?? 0, 0, 1);
|
|
135
|
+
const r = clamp(veilRgba[0] ?? 0, 0, 1);
|
|
136
|
+
const g = clamp(veilRgba[1] ?? 0, 0, 1);
|
|
137
|
+
const b = clamp(veilRgba[2] ?? 0, 0, 1);
|
|
138
|
+
// Bound the veil by its extreme channel: blending happens per channel, so a saturated tint
|
|
139
|
+
// over a complementary backdrop composites far darker (or brighter) than its luminance implies.
|
|
140
|
+
const light = goal.polarity === 'light';
|
|
141
|
+
const veil = light ? Math.max(r, g, b) : Math.min(r, g, b);
|
|
142
|
+
const p = light
|
|
143
|
+
? goal.perceivedLimit - LEGIBILITY_LIMIT_MARGIN
|
|
144
|
+
: goal.perceivedLimit + LEGIBILITY_LIMIT_MARGIN;
|
|
145
|
+
if (a >= 0.999) {
|
|
146
|
+
const ok = light ? veil <= p : veil >= p;
|
|
147
|
+
return ok ? 1 : -1;
|
|
148
|
+
}
|
|
149
|
+
const limit = (p - a * veil) / (1 - a);
|
|
150
|
+
return light ? limit : 1 - limit;
|
|
151
|
+
}
|
|
152
|
+
const IDENTITY_VEIL_OPTICS = { brightness: 1, contrast: 1, contrastFirst: false };
|
|
153
|
+
function veilAffineScale(optics) {
|
|
154
|
+
return Math.max(0, optics.brightness * optics.contrast);
|
|
155
|
+
}
|
|
156
|
+
/**
|
|
157
|
+
* Host optics as the CSS `backdrop-filter` path renders them: two filter functions in order, each
|
|
158
|
+
* clamped to `[0, 1]`. Folding them into one affine would miss the clip between them (contrast
|
|
159
|
+
* can saturate white before a dimming brightness), and only this path relies on the estimate;
|
|
160
|
+
* the per-pixel stage clamps absolute pixel values after the filter's own color matrix.
|
|
161
|
+
*/
|
|
162
|
+
function applyVeilOptics(optics, x) {
|
|
163
|
+
const b = Math.max(0, optics.brightness);
|
|
164
|
+
const c = Math.max(0, optics.contrast);
|
|
165
|
+
return optics.contrastFirst
|
|
166
|
+
? clamp(b * clamp(c * x + 0.5 * (1 - c), 0, 1), 0, 1)
|
|
167
|
+
: clamp(c * clamp(b * x, 0, 1) + 0.5 * (1 - c), 0, 1);
|
|
168
|
+
}
|
|
169
|
+
/**
|
|
170
|
+
* Extreme of `applyVeilOptics(x) - x` over `[lo, hi]`. The map is piecewise linear, so the
|
|
171
|
+
* extreme sits at an endpoint or at one of its (at most three) clip kinks.
|
|
172
|
+
*/
|
|
173
|
+
function opticsDeviation(optics, lo, hi, upper) {
|
|
174
|
+
const b = Math.max(0, optics.brightness);
|
|
175
|
+
const c = Math.max(0, optics.contrast);
|
|
176
|
+
const k = 0.5 * (1 - c);
|
|
177
|
+
let k1 = Number.NaN;
|
|
178
|
+
let k2 = Number.NaN;
|
|
179
|
+
let k3 = Number.NaN;
|
|
180
|
+
if (optics.contrastFirst) {
|
|
181
|
+
if (c > 0) {
|
|
182
|
+
k1 = -k / c;
|
|
183
|
+
k2 = (1 - k) / c;
|
|
184
|
+
if (b > 0)
|
|
185
|
+
k3 = (1 / b - k) / c;
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
else if (b > 0) {
|
|
189
|
+
k1 = 1 / b;
|
|
190
|
+
if (c > 0) {
|
|
191
|
+
k2 = -k / c / b;
|
|
192
|
+
k3 = (1 - k) / c / b;
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
let best = applyVeilOptics(optics, lo) - lo;
|
|
196
|
+
best = deviationAt(optics, hi, lo, hi, best, upper);
|
|
197
|
+
best = deviationAt(optics, k1, lo, hi, best, upper);
|
|
198
|
+
best = deviationAt(optics, k2, lo, hi, best, upper);
|
|
199
|
+
return deviationAt(optics, k3, lo, hi, best, upper);
|
|
200
|
+
}
|
|
201
|
+
function deviationAt(optics, x, lo, hi, best, upper) {
|
|
202
|
+
if (!(x >= lo && x <= hi))
|
|
203
|
+
return best;
|
|
204
|
+
const d = applyVeilOptics(optics, x) - x;
|
|
205
|
+
return upper ? Math.max(best, d) : Math.min(best, d);
|
|
206
|
+
}
|
|
207
|
+
/**
|
|
208
|
+
* Maps backdrop telemetry to `[0, 1]` risk per channel for the given goal and base veil.
|
|
209
|
+
* Telemetry describes the raw page, but the glass shows it after the host's `optics`, and the
|
|
210
|
+
* fallback correction runs after those optics too. The optics clip each channel, so a colored
|
|
211
|
+
* pixel's output luminance is not a function of its input luminance. It is bounded instead:
|
|
212
|
+
* - by the optics applied to its extreme channel, since luminance lies between min and max
|
|
213
|
+
* channel and the optics are monotonic;
|
|
214
|
+
* - by `L + D`, where `D` is the extreme of `f(x) - x` over its channel range. The dark tail is
|
|
215
|
+
* sRGB luma, a weighted mean of the channels, so this holds exactly; the bright tail is
|
|
216
|
+
* encoded luminance, a translated power mean, which by Minkowski's inequality moves no
|
|
217
|
+
* further than a shift applied to every channel.
|
|
218
|
+
* Both bounds are exact for neutral pixels and collapse to `L` under identity optics, so the
|
|
219
|
+
* estimate stays continuous as the host's optics change. Chroma and gradients scale by the
|
|
220
|
+
* affine slope.
|
|
221
|
+
*
|
|
222
|
+
* `saturation` is the host's `saturate()`, which runs first: `x' = luma + s * (x - luma)` per
|
|
223
|
+
* channel, then clipped. Desaturating never clips, keeps sRGB luma and (by Jensen) never raises
|
|
224
|
+
* encoded luminance, so only `s > 1` matters; there each clipped channel moves by at most
|
|
225
|
+
* `(s - 1)` times the channel spread, a bounded shift that widens the channel range and the
|
|
226
|
+
* luminance tails by the same amount. The legibility response only ever lowers saturation, so
|
|
227
|
+
* the host's value bounds the effective one.
|
|
228
|
+
*/
|
|
229
|
+
export function computeBackdropRisk(telemetry, goal, veilRgba, out, optics = IDENTITY_VEIL_OPTICS, saturation = 1) {
|
|
230
|
+
const s = veilAffineScale(optics);
|
|
231
|
+
const ceiling = backdropCeiling(goal, veilRgba);
|
|
232
|
+
const rawHigh = clamp(telemetry.lumaHigh, 0, 1);
|
|
233
|
+
const rawLow = clamp(telemetry.lumaLow, 0, 1);
|
|
234
|
+
const rawChannelHigh = clamp(Math.max(telemetry.channelHigh ?? rawHigh, rawHigh), 0, 1);
|
|
235
|
+
const rawChannelLow = clamp(Math.min(telemetry.channelLow ?? rawLow, rawLow), 0, 1);
|
|
236
|
+
const shift = Math.max(0, saturation - 1) * (rawChannelHigh - rawChannelLow);
|
|
237
|
+
const high = rawHigh + shift;
|
|
238
|
+
const low = rawLow - shift;
|
|
239
|
+
const channelHigh = Math.min(1, rawChannelHigh + shift);
|
|
240
|
+
const channelLow = Math.max(0, rawChannelLow - shift);
|
|
241
|
+
const tail = goal.polarity === 'light'
|
|
242
|
+
? Math.min(high + Math.max(0, opticsDeviation(optics, channelLow, channelHigh, true)), applyVeilOptics(optics, channelHigh))
|
|
243
|
+
: 1 -
|
|
244
|
+
Math.max(low + Math.min(0, opticsDeviation(optics, channelLow, channelHigh, false)), applyVeilOptics(optics, channelLow));
|
|
245
|
+
if (ceiling >= 1) {
|
|
246
|
+
out.luma = 0;
|
|
247
|
+
}
|
|
248
|
+
else {
|
|
249
|
+
const knee = Math.max(0, ceiling) * goal.policy.knee;
|
|
250
|
+
out.luma = clamp((tail - knee) / Math.max(1e-6, 1 - knee), 0, 1);
|
|
251
|
+
}
|
|
252
|
+
out.chroma = smoothstep(0.12, 0.45, s * telemetry.chroma);
|
|
253
|
+
out.detail = smoothstep(0.04, 0.22, s * telemetry.detail);
|
|
254
|
+
return out;
|
|
255
|
+
}
|
|
256
|
+
export function createLegibilityParams() {
|
|
257
|
+
const table = new Float32Array(LEGIBILITY_TABLE_SIZE);
|
|
258
|
+
table.fill(1);
|
|
259
|
+
return {
|
|
260
|
+
polarity: 'light',
|
|
261
|
+
table,
|
|
262
|
+
tableRevision: 0,
|
|
263
|
+
veilRgba: new Float32Array(4),
|
|
264
|
+
blurBoostPx: 0,
|
|
265
|
+
refractionScale: 1,
|
|
266
|
+
saturationScale: 1,
|
|
267
|
+
hairlineScale: 1,
|
|
268
|
+
shadowScale: 1,
|
|
269
|
+
fallbackVeil: { brightness: 1, contrast: 1, contrastFirst: false },
|
|
270
|
+
backdropLimit: 1,
|
|
271
|
+
feasible: true,
|
|
272
|
+
};
|
|
273
|
+
}
|
|
274
|
+
/**
|
|
275
|
+
* Writes `material` with the edge response applied into `out` and returns it. Only alphas scale:
|
|
276
|
+
* blur radii and offsets feed surface bounds, so moving them would resize the overlay mid-flight.
|
|
277
|
+
* Static surfaces and morph overlays both draw through this, so one response yields one edge.
|
|
278
|
+
*/
|
|
279
|
+
export function compensateLegibilityEdges(material, params, out) {
|
|
280
|
+
Object.assign(out, material);
|
|
281
|
+
// Object.assign never clears optional keys a previous material set and this one omits.
|
|
282
|
+
out.borderWidth = material.borderWidth;
|
|
283
|
+
out.borderRgba = material.borderRgba;
|
|
284
|
+
out.rimBottomRatio = material.rimBottomRatio;
|
|
285
|
+
out.bevelProfile = material.bevelProfile;
|
|
286
|
+
out.lightAngle = material.lightAngle;
|
|
287
|
+
out.lightElevation = material.lightElevation;
|
|
288
|
+
out.rimShade = material.rimShade;
|
|
289
|
+
out.hairlineSideAlpha = clamp(material.hairlineSideAlpha * params.hairlineScale, 0, 1);
|
|
290
|
+
out.hairlineCornerAlpha = clamp(material.hairlineCornerAlpha * params.hairlineScale, 0, 1);
|
|
291
|
+
out.hairlineFlatAlpha = clamp(material.hairlineFlatAlpha * params.hairlineScale, 0, 1);
|
|
292
|
+
out.rimOpacity = clamp(material.rimOpacity * params.hairlineScale, 0, 1);
|
|
293
|
+
out.shadowAlpha = clamp(material.shadowAlpha * params.shadowScale, 0, 1);
|
|
294
|
+
return out;
|
|
295
|
+
}
|
|
296
|
+
/**
|
|
297
|
+
* Soft-knee ceiling in risk space: identity below `knee`, then a rational shoulder whose slope is
|
|
298
|
+
* continuous at the knee and which lands exactly on `ceiling` at `u = 1`, so the guarantee holds
|
|
299
|
+
* for the brightest possible pixel without flattening mid-tones.
|
|
300
|
+
*/
|
|
301
|
+
function softCeiling(u, knee, ceiling) {
|
|
302
|
+
if (u <= knee)
|
|
303
|
+
return u;
|
|
304
|
+
const s = (1 - knee) / (ceiling - knee);
|
|
305
|
+
const t = (u - knee) / (1 - knee);
|
|
306
|
+
return knee + (ceiling - knee) * ((s * t) / (1 + (s - 1) * t));
|
|
307
|
+
}
|
|
308
|
+
function multiplierAt(u, knee, ceiling) {
|
|
309
|
+
if (ceiling >= 1 || u <= knee)
|
|
310
|
+
return 1;
|
|
311
|
+
return ceiling > 0 ? softCeiling(u, knee, ceiling) / u : 0;
|
|
312
|
+
}
|
|
313
|
+
/**
|
|
314
|
+
* Solves the material response for the smoothed `risk` and writes it into `out`.
|
|
315
|
+
* Allocation-free; returns `true` when any output changed.
|
|
316
|
+
*/
|
|
317
|
+
export function resolveLegibilityParams(goal, risk, baseVeilRgba, out) {
|
|
318
|
+
const policy = goal.policy;
|
|
319
|
+
const light = goal.polarity === 'light';
|
|
320
|
+
let changed = out.polarity !== goal.polarity;
|
|
321
|
+
out.polarity = goal.polarity;
|
|
322
|
+
// The film reuses the host tint's hue pushed toward the safe extreme; mixing toward a neutral
|
|
323
|
+
// mid-gray is what makes compressed glass read as dirty.
|
|
324
|
+
const filmAlpha = policy.filmMax * Math.max(risk.luma, 0.6 * risk.detail);
|
|
325
|
+
const baseA = clamp(baseVeilRgba[3] ?? 0, 0, 1);
|
|
326
|
+
const alpha = filmAlpha + baseA * (1 - filmAlpha);
|
|
327
|
+
const veil = out.veilRgba;
|
|
328
|
+
for (let i = 0; i < 3; i++) {
|
|
329
|
+
const tint = clamp(baseVeilRgba[i] ?? 0, 0, 1);
|
|
330
|
+
const film = light ? tint * 0.15 : 1 - (1 - tint) * 0.15;
|
|
331
|
+
const v = alpha > 0 ? (filmAlpha * film + baseA * (1 - filmAlpha) * tint) / alpha : tint;
|
|
332
|
+
changed ||= Math.abs(veil[i] - v) > 1e-4;
|
|
333
|
+
veil[i] = v;
|
|
334
|
+
}
|
|
335
|
+
changed ||= Math.abs(veil[3] - alpha) > 1e-4;
|
|
336
|
+
veil[3] = alpha;
|
|
337
|
+
const rawCeiling = backdropCeiling(goal, veil);
|
|
338
|
+
out.feasible = rawCeiling > 0;
|
|
339
|
+
const ceiling = clamp(rawCeiling, 0, 1);
|
|
340
|
+
out.backdropLimit = light ? ceiling : 1 - ceiling;
|
|
341
|
+
const knee = ceiling * lerp(LEGIBILITY_CALM_KNEE, policy.knee, risk.luma);
|
|
342
|
+
// The table is only republished when some entry moves by half an 8-bit step, so a slowly
|
|
343
|
+
// releasing smoother does not rewrite filter attributes every frame.
|
|
344
|
+
const table = out.table;
|
|
345
|
+
const last = table.length - 1;
|
|
346
|
+
let tableChanged = false;
|
|
347
|
+
for (let i = 0; i <= last && !tableChanged; i++) {
|
|
348
|
+
const u = light ? i / last : 1 - i / last;
|
|
349
|
+
tableChanged = Math.abs(table[i] - multiplierAt(u, knee, ceiling)) > 0.5 / 255;
|
|
350
|
+
}
|
|
351
|
+
if (tableChanged) {
|
|
352
|
+
for (let i = 0; i <= last; i++) {
|
|
353
|
+
table[i] = multiplierAt(light ? i / last : 1 - i / last, knee, ceiling);
|
|
354
|
+
}
|
|
355
|
+
out.tableRevision += 1;
|
|
356
|
+
changed = true;
|
|
357
|
+
}
|
|
358
|
+
// Paths without a per-pixel filter can only scale the whole backdrop. The tail estimate
|
|
359
|
+
// inverts `computeBackdropRisk`, so the affine follows the same smoothed signal.
|
|
360
|
+
const baseCeiling = backdropCeiling(goal, baseVeilRgba);
|
|
361
|
+
const baseKnee = clamp(baseCeiling, 0, 1) * policy.knee;
|
|
362
|
+
const tail = baseKnee + risk.luma * (1 - baseKnee);
|
|
363
|
+
const scale = ceiling >= 1 || tail <= ceiling ? 1 : ceiling / tail;
|
|
364
|
+
// Light text: x -> scale * x. Dark text: x -> scale * x + 1 - scale, written contrast-first as
|
|
365
|
+
// b * (c * x + 0.5 * (1 - c)) with b = 2 - scale; the contrast step stays inside [0, 1] and
|
|
366
|
+
// b times its maximum is exactly 1, so neither stage clamps.
|
|
367
|
+
const fallback = out.fallbackVeil;
|
|
368
|
+
const brightness = light ? scale : 2 - scale;
|
|
369
|
+
const contrast = light ? 1 : scale / brightness;
|
|
370
|
+
if (fallback.contrastFirst === light ||
|
|
371
|
+
Math.abs(fallback.brightness - brightness) > 1e-4 ||
|
|
372
|
+
Math.abs(fallback.contrast - contrast) > 1e-4) {
|
|
373
|
+
fallback.brightness = brightness;
|
|
374
|
+
fallback.contrast = contrast;
|
|
375
|
+
fallback.contrastFirst = !light;
|
|
376
|
+
changed = true;
|
|
377
|
+
}
|
|
378
|
+
changed = assign(out, 'blurBoostPx', policy.blurBoostPx * risk.detail) || changed;
|
|
379
|
+
changed = assign(out, 'refractionScale', lerp(1, policy.refractionFloor, risk.detail)) || changed;
|
|
380
|
+
changed = assign(out, 'saturationScale', lerp(1, policy.saturationFloor, risk.chroma)) || changed;
|
|
381
|
+
changed =
|
|
382
|
+
assign(out, 'hairlineScale', 1 + policy.edgeGain * Math.max(risk.luma, risk.detail)) || changed;
|
|
383
|
+
changed = assign(out, 'shadowScale', 1 + policy.shadowGain * risk.luma) || changed;
|
|
384
|
+
return changed;
|
|
385
|
+
}
|
|
386
|
+
function assign(out, key, value) {
|
|
387
|
+
if (Math.abs(out[key] - value) <= 1e-4)
|
|
388
|
+
return false;
|
|
389
|
+
out[key] = value;
|
|
390
|
+
return true;
|
|
391
|
+
}
|
|
392
|
+
export function createTelemetryAccumulator() {
|
|
393
|
+
let weight = 0;
|
|
394
|
+
let high = 0;
|
|
395
|
+
let low = 0;
|
|
396
|
+
let channelHigh = 0;
|
|
397
|
+
let channelLow = 0;
|
|
398
|
+
let chroma = 0;
|
|
399
|
+
let detail = 0;
|
|
400
|
+
const push = (h, l, ch, cl, c, d, w) => {
|
|
401
|
+
if (!(w > 0))
|
|
402
|
+
return;
|
|
403
|
+
const hh = clamp(h, 0, 1);
|
|
404
|
+
const ll = 1 - clamp(l, 0, 1);
|
|
405
|
+
// Luminance lies between a pixel's extreme channels; inconsistent input falls back to neutral.
|
|
406
|
+
const chh = Math.max(hh, clamp(ch, 0, 1));
|
|
407
|
+
const cll = Math.max(ll, 1 - clamp(cl, 0, 1));
|
|
408
|
+
weight += w;
|
|
409
|
+
high += w * hh * hh;
|
|
410
|
+
low += w * ll * ll;
|
|
411
|
+
channelHigh += w * chh * chh;
|
|
412
|
+
channelLow += w * cll * cll;
|
|
413
|
+
chroma += w * clamp(c, 0, 1);
|
|
414
|
+
detail += w * clamp(d, 0, 1);
|
|
415
|
+
};
|
|
416
|
+
return {
|
|
417
|
+
get weight() {
|
|
418
|
+
return weight;
|
|
419
|
+
},
|
|
420
|
+
reset() {
|
|
421
|
+
weight = high = low = channelHigh = channelLow = chroma = detail = 0;
|
|
422
|
+
},
|
|
423
|
+
add(t, w) {
|
|
424
|
+
push(t.lumaHigh, t.lumaLow, t.channelHigh ?? t.lumaHigh, t.channelLow ?? t.lumaLow, t.chroma, t.detail, w);
|
|
425
|
+
},
|
|
426
|
+
addRecord(data, offset, w) {
|
|
427
|
+
push(data[offset], data[offset + 1], data[offset + 2], data[offset + 3], data[offset + 4], data[offset + 5], w);
|
|
428
|
+
},
|
|
429
|
+
resolve(out) {
|
|
430
|
+
if (!(weight > 0))
|
|
431
|
+
return false;
|
|
432
|
+
out.lumaHigh = Math.sqrt(high / weight);
|
|
433
|
+
out.lumaLow = 1 - Math.sqrt(low / weight);
|
|
434
|
+
out.channelHigh = Math.sqrt(channelHigh / weight);
|
|
435
|
+
out.channelLow = 1 - Math.sqrt(channelLow / weight);
|
|
436
|
+
out.chroma = chroma / weight;
|
|
437
|
+
out.detail = detail / weight;
|
|
438
|
+
return true;
|
|
439
|
+
},
|
|
440
|
+
};
|
|
441
|
+
}
|
|
442
|
+
const HISTOGRAM_BINS = 64;
|
|
443
|
+
/**
|
|
444
|
+
* Measures a `cols x rows` telemetry grid from straight (non-premultiplied) RGBA bytes.
|
|
445
|
+
* Runs once per source image, never per frame; callers obtain pixels through normal
|
|
446
|
+
* same-origin or CORS-approved channels only.
|
|
447
|
+
*/
|
|
448
|
+
export function measureTelemetryGrid(rgba, width, height, cols, rows) {
|
|
449
|
+
const w = Math.max(1, Math.floor(width));
|
|
450
|
+
const h = Math.max(1, Math.floor(height));
|
|
451
|
+
const gc = Math.max(1, Math.floor(cols));
|
|
452
|
+
const gr = Math.max(1, Math.floor(rows));
|
|
453
|
+
const data = new Float32Array(gc * gr * TELEMETRY_STRIDE);
|
|
454
|
+
const lum = new Float32Array(w * h);
|
|
455
|
+
const luma = new Float32Array(w * h);
|
|
456
|
+
const maxPx = new Float32Array(w * h);
|
|
457
|
+
const minPx = new Float32Array(w * h);
|
|
458
|
+
for (let i = 0; i < w * h; i++) {
|
|
459
|
+
const r = (rgba[i * 4] ?? 0) / 255;
|
|
460
|
+
const g = (rgba[i * 4 + 1] ?? 0) / 255;
|
|
461
|
+
const b = (rgba[i * 4 + 2] ?? 0) / 255;
|
|
462
|
+
lum[i] = linearToSrgb(relativeLuminance(r, g, b));
|
|
463
|
+
luma[i] = srgbLuma(r, g, b);
|
|
464
|
+
maxPx[i] = Math.max(r, g, b);
|
|
465
|
+
minPx[i] = Math.min(r, g, b);
|
|
466
|
+
}
|
|
467
|
+
const hist = new Uint32Array(HISTOGRAM_BINS);
|
|
468
|
+
const lumaHist = new Uint32Array(HISTOGRAM_BINS);
|
|
469
|
+
const maxHist = new Uint32Array(HISTOGRAM_BINS);
|
|
470
|
+
const minHist = new Uint32Array(HISTOGRAM_BINS);
|
|
471
|
+
for (let cy = 0; cy < gr; cy++) {
|
|
472
|
+
const y0 = Math.floor((cy * h) / gr);
|
|
473
|
+
const y1 = Math.max(y0 + 1, Math.floor(((cy + 1) * h) / gr));
|
|
474
|
+
for (let cx = 0; cx < gc; cx++) {
|
|
475
|
+
const x0 = Math.floor((cx * w) / gc);
|
|
476
|
+
const x1 = Math.max(x0 + 1, Math.floor(((cx + 1) * w) / gc));
|
|
477
|
+
hist.fill(0);
|
|
478
|
+
lumaHist.fill(0);
|
|
479
|
+
maxHist.fill(0);
|
|
480
|
+
minHist.fill(0);
|
|
481
|
+
let count = 0;
|
|
482
|
+
let chroma = 0;
|
|
483
|
+
let gradient = 0;
|
|
484
|
+
for (let y = y0; y < y1; y++) {
|
|
485
|
+
for (let x = x0; x < x1; x++) {
|
|
486
|
+
const i = y * w + x;
|
|
487
|
+
const l = lum[i];
|
|
488
|
+
hist[histogramBin(l)] += 1;
|
|
489
|
+
lumaHist[histogramBin(luma[i])] += 1;
|
|
490
|
+
maxHist[histogramBin(maxPx[i])] += 1;
|
|
491
|
+
minHist[histogramBin(minPx[i])] += 1;
|
|
492
|
+
chroma += maxPx[i] - minPx[i];
|
|
493
|
+
// Gradients stay inside the cell so a card edge on a cell border is not counted as detail.
|
|
494
|
+
const right = x + 1 < x1 ? lum[i + 1] : l;
|
|
495
|
+
const down = y + 1 < y1 ? lum[i + w] : l;
|
|
496
|
+
gradient += Math.abs(right - l) + Math.abs(down - l);
|
|
497
|
+
count += 1;
|
|
498
|
+
}
|
|
499
|
+
}
|
|
500
|
+
const o = (cy * gc + cx) * TELEMETRY_STRIDE;
|
|
501
|
+
data[o] = percentileFromHistogram(hist, count, 0.95);
|
|
502
|
+
data[o + 1] = percentileFromHistogram(lumaHist, count, 0.05);
|
|
503
|
+
// Bin bounds rather than centers keep the channel extremes conservative after quantization.
|
|
504
|
+
data[o + 2] = Math.max(data[o], percentileFromHistogram(maxHist, count, 0.95, 1));
|
|
505
|
+
data[o + 3] = Math.min(data[o + 1], percentileFromHistogram(minHist, count, 0.05, 0));
|
|
506
|
+
data[o + 4] = chroma / count;
|
|
507
|
+
data[o + 5] = Math.min(1, (gradient / count) * 4);
|
|
508
|
+
}
|
|
509
|
+
}
|
|
510
|
+
return { cols: gc, rows: gr, data };
|
|
511
|
+
}
|
|
512
|
+
function histogramBin(v) {
|
|
513
|
+
return Math.min(HISTOGRAM_BINS - 1, Math.max(0, Math.floor(v * HISTOGRAM_BINS)));
|
|
514
|
+
}
|
|
515
|
+
/** `edge` places the result inside the matching bin: `0.5` its center, `0` / `1` its bounds. */
|
|
516
|
+
function percentileFromHistogram(hist, count, q, edge = 0.5) {
|
|
517
|
+
const target = q * count;
|
|
518
|
+
let acc = 0;
|
|
519
|
+
for (let i = 0; i < hist.length; i++) {
|
|
520
|
+
acc += hist[i];
|
|
521
|
+
if (acc >= target)
|
|
522
|
+
return (i + edge) / hist.length;
|
|
523
|
+
}
|
|
524
|
+
return 1;
|
|
525
|
+
}
|
|
526
|
+
export function createAsymmetricSmoother(channels, options) {
|
|
527
|
+
const values = new Float32Array(channels);
|
|
528
|
+
const holdLeft = new Float32Array(channels);
|
|
529
|
+
const holdMs = Math.max(0, options.holdMs ?? 0);
|
|
530
|
+
const attackMs = Math.max(1e-3, options.attackMs);
|
|
531
|
+
const releaseMs = Math.max(1e-3, options.releaseMs);
|
|
532
|
+
const epsilon = Math.max(0, options.epsilon ?? 1e-3);
|
|
533
|
+
holdLeft.fill(holdMs);
|
|
534
|
+
return {
|
|
535
|
+
values,
|
|
536
|
+
step(target, dtMs) {
|
|
537
|
+
const dt = Number.isFinite(dtMs) && dtMs > 0 ? dtMs : 0;
|
|
538
|
+
let settled = true;
|
|
539
|
+
for (let i = 0; i < channels; i++) {
|
|
540
|
+
const goal = target[i] ?? 0;
|
|
541
|
+
let v = values[i];
|
|
542
|
+
if (goal >= v - epsilon) {
|
|
543
|
+
holdLeft[i] = holdMs;
|
|
544
|
+
if (goal > v)
|
|
545
|
+
v += (goal - v) * (1 - Math.exp(-dt / attackMs));
|
|
546
|
+
}
|
|
547
|
+
else {
|
|
548
|
+
const releaseDt = Math.max(0, dt - holdLeft[i]);
|
|
549
|
+
holdLeft[i] = Math.max(0, holdLeft[i] - dt);
|
|
550
|
+
v += (goal - v) * (1 - Math.exp(-releaseDt / releaseMs));
|
|
551
|
+
}
|
|
552
|
+
if (Math.abs(goal - v) <= epsilon) {
|
|
553
|
+
v = goal;
|
|
554
|
+
}
|
|
555
|
+
else {
|
|
556
|
+
settled = false;
|
|
557
|
+
}
|
|
558
|
+
values[i] = v;
|
|
559
|
+
}
|
|
560
|
+
return settled;
|
|
561
|
+
},
|
|
562
|
+
reset(next) {
|
|
563
|
+
for (let i = 0; i < channels; i++) {
|
|
564
|
+
values[i] = typeof next === 'number' ? next : (next[i] ?? 0);
|
|
565
|
+
}
|
|
566
|
+
holdLeft.fill(holdMs);
|
|
567
|
+
},
|
|
568
|
+
};
|
|
569
|
+
}
|
package/dist/optics.d.ts
CHANGED
|
@@ -68,8 +68,20 @@ export declare function buildCircularBevelTable(bezel: number, blurStd?: number,
|
|
|
68
68
|
export declare function buildColorOpticsMatrix(saturate: number, brightness: number, contrast: number, contrastFirst?: boolean): string;
|
|
69
69
|
/** Encodes a contour SVG path as an inline Data URL for use as an `feImage` alpha mask. */
|
|
70
70
|
export declare function buildContourAlphaDataUrl(contourPath: string, width: number, height: number): string;
|
|
71
|
-
/**
|
|
71
|
+
/**
|
|
72
|
+
* Parses a browser-computed `rgb(...)`, `rgba(...)`, `color(srgb ...)`, `oklab(...)` or
|
|
73
|
+
* `oklch(...)` string into normalized `[0..1]` sRGB RGBA.
|
|
74
|
+
*/
|
|
72
75
|
export declare function parseCssRgba(color: string): [number, number, number, number];
|
|
76
|
+
/**
|
|
77
|
+
* Like `parseCssRgba`, but returns `null` instead of transparent black for anything it cannot
|
|
78
|
+
* resolve (`var()`, percentage `color(srgb ...)` channels, other color spaces), so callers can
|
|
79
|
+
* tell a real transparent color from an unsupported one.
|
|
80
|
+
*
|
|
81
|
+
* Browsers serialize `color-mix()` and alpha-modified theme colors (Tailwind's `text-white/90`)
|
|
82
|
+
* as `oklab()` / `oklch()`, so a host reading computed styles meets these routinely.
|
|
83
|
+
*/
|
|
84
|
+
export declare function tryParseCssRgba(color: string): [number, number, number, number] | null;
|
|
73
85
|
/** Extracts `brightness(...)` and `contrast(...)` affine composition from a CSS filter string. */
|
|
74
86
|
export declare function parseCssFilterOptics(filterStr: string): BackdropVeilOptics;
|
|
75
87
|
/** Linearly interpolates two backdrop veil optics states in 1D affine `(scale, offset)` space. */
|
package/dist/optics.js
CHANGED
|
@@ -104,8 +104,22 @@ export function buildContourAlphaDataUrl(contourPath, width, height) {
|
|
|
104
104
|
const svgDoc = `<svg xmlns="http://www.w3.org/2000/svg" width="${w}" height="${h}" viewBox="0 0 ${w} ${h}"><path d="${contourPath}" fill="white"/></svg>`;
|
|
105
105
|
return `data:image/svg+xml;charset=utf-8,${encodeURIComponent(svgDoc)}`;
|
|
106
106
|
}
|
|
107
|
-
/**
|
|
107
|
+
/**
|
|
108
|
+
* Parses a browser-computed `rgb(...)`, `rgba(...)`, `color(srgb ...)`, `oklab(...)` or
|
|
109
|
+
* `oklch(...)` string into normalized `[0..1]` sRGB RGBA.
|
|
110
|
+
*/
|
|
108
111
|
export function parseCssRgba(color) {
|
|
112
|
+
return tryParseCssRgba(color) ?? [0, 0, 0, 0];
|
|
113
|
+
}
|
|
114
|
+
/**
|
|
115
|
+
* Like `parseCssRgba`, but returns `null` instead of transparent black for anything it cannot
|
|
116
|
+
* resolve (`var()`, percentage `color(srgb ...)` channels, other color spaces), so callers can
|
|
117
|
+
* tell a real transparent color from an unsupported one.
|
|
118
|
+
*
|
|
119
|
+
* Browsers serialize `color-mix()` and alpha-modified theme colors (Tailwind's `text-white/90`)
|
|
120
|
+
* as `oklab()` / `oklch()`, so a host reading computed styles meets these routinely.
|
|
121
|
+
*/
|
|
122
|
+
export function tryParseCssRgba(color) {
|
|
109
123
|
const trimmed = color.trim().toLowerCase();
|
|
110
124
|
if (!trimmed || trimmed === 'none' || trimmed === 'transparent') {
|
|
111
125
|
return [0, 0, 0, 0];
|
|
@@ -121,6 +135,34 @@ export function parseCssRgba(color) {
|
|
|
121
135
|
return [r, g, b, clamp(a, 0, 1)];
|
|
122
136
|
}
|
|
123
137
|
}
|
|
138
|
+
const okMatch = trimmed.match(/^ok(lab|lch)\(\s*([^)]+)\s*\)$/);
|
|
139
|
+
if (okMatch) {
|
|
140
|
+
const [channels, alphaRaw] = okMatch[2].split('/');
|
|
141
|
+
const parts = channels.trim().split(/\s+/);
|
|
142
|
+
if (parts.length === 3) {
|
|
143
|
+
const polar = okMatch[1] === 'lch';
|
|
144
|
+
// Percent references: L 100% = 1, a/b/C 100% = 0.4 (CSS Color 4).
|
|
145
|
+
const num = (token, percentScale) => token === 'none' ? 0 : token.endsWith('%') ? (parseFloat(token) / 100) * percentScale : parseFloat(token);
|
|
146
|
+
const l = num(parts[0], 1);
|
|
147
|
+
let a = num(parts[1], 0.4);
|
|
148
|
+
let b = num(parts[2], 0.4);
|
|
149
|
+
if (polar) {
|
|
150
|
+
const hue = ((parts[2] === 'none' ? 0 : parseFloat(parts[2])) * Math.PI) / 180;
|
|
151
|
+
b = a * Math.sin(hue);
|
|
152
|
+
a = a * Math.cos(hue);
|
|
153
|
+
}
|
|
154
|
+
const alphaToken = alphaRaw?.trim();
|
|
155
|
+
const alpha = alphaToken === undefined || alphaToken === 'none'
|
|
156
|
+
? 1
|
|
157
|
+
: alphaToken.endsWith('%')
|
|
158
|
+
? parseFloat(alphaToken) / 100
|
|
159
|
+
: parseFloat(alphaToken);
|
|
160
|
+
if ([l, a, b, alpha].every(Number.isFinite)) {
|
|
161
|
+
const [r, g, bl] = oklabToSrgb(l, a, b);
|
|
162
|
+
return [r, g, bl, clamp(alpha, 0, 1)];
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
}
|
|
124
166
|
const rgbMatch = trimmed.match(/^rgba?\(\s*([^)]+)\s*\)$/);
|
|
125
167
|
if (rgbMatch) {
|
|
126
168
|
const body = rgbMatch[1].replace(/\//g, ' ').trim();
|
|
@@ -140,7 +182,22 @@ export function parseCssRgba(color) {
|
|
|
140
182
|
}
|
|
141
183
|
}
|
|
142
184
|
}
|
|
143
|
-
return
|
|
185
|
+
return null;
|
|
186
|
+
}
|
|
187
|
+
/** OKLab to gamma-encoded sRGB (Björn Ottosson's matrices); out-of-gamut channels are clipped. */
|
|
188
|
+
function oklabToSrgb(l, a, b) {
|
|
189
|
+
const lc = (l + 0.3963377774 * a + 0.2158037573 * b) ** 3;
|
|
190
|
+
const mc = (l - 0.1055613458 * a - 0.0638541728 * b) ** 3;
|
|
191
|
+
const sc = (l - 0.0894841775 * a - 1.291485548 * b) ** 3;
|
|
192
|
+
const encode = (linear) => {
|
|
193
|
+
const x = clamp(linear, 0, 1);
|
|
194
|
+
return x <= 0.0031308 ? 12.92 * x : 1.055 * x ** (1 / 2.4) - 0.055;
|
|
195
|
+
};
|
|
196
|
+
return [
|
|
197
|
+
encode(4.0767416621 * lc - 3.3077115913 * mc + 0.2309699292 * sc),
|
|
198
|
+
encode(-1.2684380046 * lc + 2.6097574011 * mc - 0.3413193965 * sc),
|
|
199
|
+
encode(-0.0041960863 * lc - 0.7034186147 * mc + 1.707614701 * sc),
|
|
200
|
+
];
|
|
144
201
|
}
|
|
145
202
|
const VEIL_SINGULAR_EPS = 1e-6;
|
|
146
203
|
function veilOpticsToAffine(veil) {
|