@sessile/dom 0.0.0-stage → 0.2.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,348 @@
1
+ /**
2
+ * Pure standard CSS optical surface extraction and material composition for `@sessile/dom`.
3
+ *
4
+ * Reads only standard DOM computed styles (`backdrop-filter`, `background-color`,
5
+ * `border-top-*`, `box-shadow`, `border-top-left-radius`, `color-scheme`) without any
6
+ * host-specific CSS custom properties.
7
+ *
8
+ * SPDX-License-Identifier: MPL-2.0
9
+ */
10
+ import { DEFAULT_OPTICAL_MATERIALS, clamp, interpolateCssGlassSurfaceToMaterial, parseCssGlassSurface, parseCssRgba, } from '@sessile/core';
11
+ const DEFAULT_MORPH_ATTRIBUTE = 'data-sessile-morphing';
12
+ const DEFAULT_LIGHT_SOLID = 'rgb(250, 250, 252)';
13
+ const DEFAULT_DARK_SOLID = 'rgb(32, 32, 36)';
14
+ function resolveComputedStyleFn(customFn) {
15
+ if (customFn) {
16
+ return customFn;
17
+ }
18
+ if (typeof globalThis.getComputedStyle === 'function') {
19
+ return (target) => globalThis.getComputedStyle(target);
20
+ }
21
+ return null;
22
+ }
23
+ function resolveThemeMatchMedia(options) {
24
+ if (options && 'matchMedia' in options) {
25
+ return options.matchMedia ?? null;
26
+ }
27
+ if (typeof window !== 'undefined' && typeof window.matchMedia === 'function') {
28
+ return (query) => window.matchMedia(query);
29
+ }
30
+ if (typeof globalThis.matchMedia === 'function') {
31
+ return (query) => globalThis.matchMedia(query);
32
+ }
33
+ return null;
34
+ }
35
+ function parseExactThemeToken(value) {
36
+ if (!value)
37
+ return null;
38
+ const normalized = value.trim().toLowerCase();
39
+ if (normalized === 'light' || normalized === 'dark') {
40
+ return normalized;
41
+ }
42
+ return null;
43
+ }
44
+ /**
45
+ * Resolves the active light/dark theme for `el` using standard DOM attributes,
46
+ * `color-scheme`, `(prefers-color-scheme: light)`, and finally `fallbackTheme`.
47
+ */
48
+ export function resolveElementTheme(el, options) {
49
+ const scopedAttr = el && typeof el.closest === 'function'
50
+ ? parseExactThemeToken(el.closest('[data-theme]')?.getAttribute('data-theme'))
51
+ : parseExactThemeToken(el?.getAttribute?.('data-theme'));
52
+ if (scopedAttr) {
53
+ return scopedAttr;
54
+ }
55
+ const rootEl = typeof document !== 'undefined' ? document.documentElement : null;
56
+ const docAttr = parseExactThemeToken(rootEl?.getAttribute?.('data-theme'));
57
+ if (docAttr) {
58
+ return docAttr;
59
+ }
60
+ const getCs = resolveComputedStyleFn(options?.getComputedStyle);
61
+ if (getCs) {
62
+ if (el) {
63
+ const elScheme = parseExactThemeToken(getCs(el).colorScheme);
64
+ if (elScheme)
65
+ return elScheme;
66
+ }
67
+ if (rootEl && rootEl !== el) {
68
+ const rootScheme = parseExactThemeToken(getCs(rootEl).colorScheme);
69
+ if (rootScheme)
70
+ return rootScheme;
71
+ }
72
+ }
73
+ const matchMedia = resolveThemeMatchMedia(options);
74
+ if (matchMedia) {
75
+ const mql = matchMedia('(prefers-color-scheme: light)');
76
+ if (mql) {
77
+ return mql.matches ? 'light' : 'dark';
78
+ }
79
+ }
80
+ return options?.fallbackTheme ?? 'dark';
81
+ }
82
+ /** Extracts the CSS `blur(<num>px)` (or `blur(0)`) radius from a filter string, or `null`. */
83
+ export function parseCssBackdropBlur(filterStr) {
84
+ if (!filterStr || filterStr === 'none') {
85
+ return null;
86
+ }
87
+ const regex = /blur\(\s*([^)]+)\s*\)/gi;
88
+ let match;
89
+ while ((match = regex.exec(filterStr)) !== null) {
90
+ const token = match[1].trim();
91
+ if (token === '0') {
92
+ return 0;
93
+ }
94
+ if (/^[+-]?(?:\d+\.?\d*|\.\d+)px$/i.test(token)) {
95
+ const parsed = Number.parseFloat(token);
96
+ if (Number.isFinite(parsed) && parsed >= 0) {
97
+ return parsed;
98
+ }
99
+ }
100
+ }
101
+ return null;
102
+ }
103
+ /** Extracts the cumulative `saturate(...)` multiplier from a CSS filter string, or `null`. */
104
+ export function parseCssBackdropSaturate(filterStr) {
105
+ if (!filterStr || filterStr === 'none') {
106
+ return null;
107
+ }
108
+ const regex = /saturate\(\s*([^)]+)\s*\)/gi;
109
+ let match;
110
+ let product = 1;
111
+ let found = false;
112
+ while ((match = regex.exec(filterStr)) !== null) {
113
+ const token = match[1].trim();
114
+ let val = Number.NaN;
115
+ if (token.endsWith('%')) {
116
+ const numPart = token.slice(0, -1).trim();
117
+ if (/^[+-]?(?:\d+\.?\d*|\.\d+)$/.test(numPart)) {
118
+ val = Number.parseFloat(numPart) / 100;
119
+ }
120
+ }
121
+ else if (/^[+-]?(?:\d+\.?\d*|\.\d+)$/.test(token)) {
122
+ val = Number.parseFloat(token);
123
+ }
124
+ if (Number.isFinite(val) && val >= 0) {
125
+ product *= val;
126
+ found = true;
127
+ }
128
+ }
129
+ return found ? product : null;
130
+ }
131
+ /**
132
+ * Reads resting computed glass optical properties from `el` using standard CSS properties only.
133
+ * Temporarily strips `temporarilyClearAttribute` (with transitions suppressed) so resting styles
134
+ * can be sampled cleanly even if an active morph rule overrides visual styles.
135
+ */
136
+ export function readElementGlassSurface(el, options) {
137
+ const getCs = resolveComputedStyleFn(options?.getComputedStyle);
138
+ if (!getCs) {
139
+ throw new Error('getComputedStyle is unavailable in this environment');
140
+ }
141
+ const clearAttr = options?.temporarilyClearAttribute === undefined
142
+ ? DEFAULT_MORPH_ATTRIBUTE
143
+ : options.temporarilyClearAttribute;
144
+ const hasClearAttr = Boolean(clearAttr && el.hasAttribute(clearAttr));
145
+ const prevAttrValue = hasClearAttr && clearAttr ? el.getAttribute(clearAttr) : null;
146
+ const prevTransition = el.style ? el.style.transition : '';
147
+ if (hasClearAttr && clearAttr) {
148
+ if (el.style) {
149
+ el.style.transition = 'none';
150
+ }
151
+ el.removeAttribute(clearAttr);
152
+ }
153
+ let backdropFilter = '';
154
+ let webkitBf = '';
155
+ let borderWidthPx = 0;
156
+ let borderColor = '';
157
+ let boxShadow = '';
158
+ let backgroundColor = '';
159
+ let rawRadius = Number.NaN;
160
+ let theme;
161
+ try {
162
+ const cs = getCs(el);
163
+ const themeOpts = {
164
+ fallbackTheme: options?.fallbackTheme,
165
+ getComputedStyle: getCs,
166
+ };
167
+ if (options && 'matchMedia' in options) {
168
+ themeOpts.matchMedia = options.matchMedia;
169
+ }
170
+ theme = resolveElementTheme(el, themeOpts);
171
+ // Snapshot all computed style fields while the morph attribute is cleared because
172
+ // browser CSSStyleDeclaration instances are live and update as soon as `finally` restores it.
173
+ webkitBf =
174
+ typeof cs.getPropertyValue === 'function'
175
+ ? cs.getPropertyValue('-webkit-backdrop-filter')
176
+ : '';
177
+ backdropFilter = cs.backdropFilter || webkitBf || '';
178
+ borderWidthPx = Number.parseFloat(cs.borderTopWidth) || 0;
179
+ borderColor = cs.borderTopColor || '';
180
+ boxShadow = cs.boxShadow || '';
181
+ backgroundColor = cs.backgroundColor || '';
182
+ rawRadius = Number.parseFloat(cs.borderTopLeftRadius);
183
+ }
184
+ finally {
185
+ if (hasClearAttr && clearAttr) {
186
+ el.setAttribute(clearAttr, prevAttrValue ?? 'true');
187
+ if (el.style) {
188
+ el.style.transition = prevTransition;
189
+ }
190
+ }
191
+ }
192
+ const borderRadiusPx = Number.isFinite(rawRadius) && rawRadius >= 0 ? rawRadius : 0;
193
+ const surface = parseCssGlassSurface({
194
+ backdropFilter,
195
+ borderWidthPx,
196
+ borderColor,
197
+ boxShadow,
198
+ });
199
+ return {
200
+ surface,
201
+ backgroundRgba: parseCssRgba(backgroundColor),
202
+ blurPx: parseCssBackdropBlur(backdropFilter),
203
+ saturation: parseCssBackdropSaturate(backdropFilter),
204
+ borderRadiusPx,
205
+ theme,
206
+ };
207
+ }
208
+ function applyMaterialOverrides(material, overrides) {
209
+ if (!overrides) {
210
+ return material;
211
+ }
212
+ const merged = { ...material };
213
+ if (overrides.bevel !== undefined)
214
+ merged.bevel = overrides.bevel;
215
+ if (overrides.refraction !== undefined)
216
+ merged.refraction = overrides.refraction;
217
+ if (overrides.blur !== undefined)
218
+ merged.blur = overrides.blur;
219
+ if (overrides.dispersion !== undefined)
220
+ merged.dispersion = overrides.dispersion;
221
+ if (overrides.saturation !== undefined)
222
+ merged.saturation = overrides.saturation;
223
+ if (overrides.brightness !== undefined)
224
+ merged.brightness = overrides.brightness;
225
+ if (overrides.contrast !== undefined)
226
+ merged.contrast = overrides.contrast;
227
+ if (overrides.tintRgba !== undefined)
228
+ merged.tintRgba = overrides.tintRgba;
229
+ if (overrides.rimMode !== undefined)
230
+ merged.rimMode = overrides.rimMode;
231
+ if (overrides.rimOpacity !== undefined)
232
+ merged.rimOpacity = overrides.rimOpacity;
233
+ if (overrides.rimWidth !== undefined)
234
+ merged.rimWidth = overrides.rimWidth;
235
+ if (overrides.rimTail !== undefined)
236
+ merged.rimTail = overrides.rimTail;
237
+ if (overrides.rimFocus !== undefined)
238
+ merged.rimFocus = overrides.rimFocus;
239
+ if (overrides.rimAdded !== undefined)
240
+ merged.rimAdded = overrides.rimAdded;
241
+ if (overrides.hairlineWidth !== undefined)
242
+ merged.hairlineWidth = overrides.hairlineWidth;
243
+ if (overrides.hairlineSideAlpha !== undefined)
244
+ merged.hairlineSideAlpha = overrides.hairlineSideAlpha;
245
+ if (overrides.hairlineCornerAlpha !== undefined) {
246
+ merged.hairlineCornerAlpha = overrides.hairlineCornerAlpha;
247
+ }
248
+ if (overrides.hairlineFlatAlpha !== undefined)
249
+ merged.hairlineFlatAlpha = overrides.hairlineFlatAlpha;
250
+ if (overrides.shadowBlur !== undefined)
251
+ merged.shadowBlur = overrides.shadowBlur;
252
+ if (overrides.shadowOffsetY !== undefined)
253
+ merged.shadowOffsetY = overrides.shadowOffsetY;
254
+ if (overrides.shadowAlpha !== undefined)
255
+ merged.shadowAlpha = overrides.shadowAlpha;
256
+ if ('borderWidth' in overrides)
257
+ merged.borderWidth = overrides.borderWidth;
258
+ if ('borderRgba' in overrides)
259
+ merged.borderRgba = overrides.borderRgba;
260
+ if ('rimBottomRatio' in overrides)
261
+ merged.rimBottomRatio = overrides.rimBottomRatio;
262
+ return merged;
263
+ }
264
+ /**
265
+ * Builds a complete `OpticalMaterial` from a measured CSS glass surface and explicit theme/preset defaults.
266
+ * Keeps `veil` (`brightness`/`contrast` affine optics) separate from `OpticalMaterial.contrast`, which
267
+ * represents a signed shader offset rather than a CSS filter multiplier.
268
+ */
269
+ export function buildMaterialFromCssSurface(measured, options) {
270
+ const theme = options?.theme ?? measured.theme;
271
+ const preset = options?.preset ?? 'frosted';
272
+ const base = options?.baseMaterial ?? DEFAULT_OPTICAL_MATERIALS[theme][preset];
273
+ const material = interpolateCssGlassSurfaceToMaterial(base, measured.surface, measured.surface, 1);
274
+ if (measured.blurPx !== null) {
275
+ material.blur = measured.blurPx;
276
+ }
277
+ if (measured.saturation !== null) {
278
+ material.saturation = measured.saturation;
279
+ }
280
+ if (measured.backgroundRgba[3] > 0.001) {
281
+ material.tintRgba = [
282
+ measured.backgroundRgba[0],
283
+ measured.backgroundRgba[1],
284
+ measured.backgroundRgba[2],
285
+ measured.backgroundRgba[3],
286
+ ];
287
+ }
288
+ return applyMaterialOverrides(material, options?.overrides);
289
+ }
290
+ function toByteChannel(channel) {
291
+ if (!Number.isFinite(channel))
292
+ return 0;
293
+ return Math.round(clamp(channel, 0, 1) * 255);
294
+ }
295
+ /** Formats normalized `[0..1]` RGBA channels into a standard CSS `rgba(...)` string. */
296
+ export function formatRgbaCss(rgba) {
297
+ const r = toByteChannel(rgba[0]);
298
+ const g = toByteChannel(rgba[1]);
299
+ const b = toByteChannel(rgba[2]);
300
+ const aRaw = Number.isFinite(rgba[3]) ? clamp(rgba[3], 0, 1) : 0;
301
+ const a = Number(aRaw.toFixed(4));
302
+ return `rgba(${r}, ${g}, ${b}, ${a})`;
303
+ }
304
+ /** Formats normalized `[0..1]` RGBA into an opaque `rgb(...)` background for `'solid'` fallback mode. */
305
+ export function formatOpaqueSolidCss(rgba, theme) {
306
+ if (!Number.isFinite(rgba[3]) || rgba[3] <= 0.001) {
307
+ return theme === 'light' ? DEFAULT_LIGHT_SOLID : DEFAULT_DARK_SOLID;
308
+ }
309
+ const r = toByteChannel(rgba[0]);
310
+ const g = toByteChannel(rgba[1]);
311
+ const b = toByteChannel(rgba[2]);
312
+ return `rgb(${r}, ${g}, ${b})`;
313
+ }
314
+ /** Composes a standard CSS `backdrop-filter` declaration preserving affine brightness/contrast ordering. */
315
+ export function buildBackdropFilterCss({ blurPx, saturation, veil, }) {
316
+ const parts = [];
317
+ if (Number.isFinite(blurPx) && blurPx > 0.01) {
318
+ parts.push(`blur(${blurPx.toFixed(2)}px)`);
319
+ }
320
+ if (saturation !== undefined &&
321
+ Number.isFinite(saturation) &&
322
+ Math.abs(saturation - 1) > 1e-4) {
323
+ parts.push(`saturate(${Number(Math.max(0, saturation).toFixed(3))})`);
324
+ }
325
+ if (veil) {
326
+ const hasBrightness = Number.isFinite(veil.brightness) && Math.abs(veil.brightness - 1) > 1e-4;
327
+ const hasContrast = Number.isFinite(veil.contrast) && Math.abs(veil.contrast - 1) > 1e-4;
328
+ const bToken = hasBrightness
329
+ ? `brightness(${Number(Math.max(0, veil.brightness).toFixed(4))})`
330
+ : null;
331
+ const cToken = hasContrast
332
+ ? `contrast(${Number(Math.max(0, veil.contrast).toFixed(4))})`
333
+ : null;
334
+ if (veil.contrastFirst) {
335
+ if (cToken)
336
+ parts.push(cToken);
337
+ if (bToken)
338
+ parts.push(bToken);
339
+ }
340
+ else {
341
+ if (bToken)
342
+ parts.push(bToken);
343
+ if (cToken)
344
+ parts.push(cToken);
345
+ }
346
+ }
347
+ return parts.length > 0 ? parts.join(' ') : 'none';
348
+ }
@@ -0,0 +1,10 @@
1
+ /**
2
+ * Public entry point for `@sessile/dom`.
3
+ * Framework-agnostic headless Live-DOM glass surface driver built on `@sessile/core`.
4
+ *
5
+ * SPDX-License-Identifier: MPL-2.0
6
+ */
7
+ export { cancelAnimationFrameSafe, createFrameLoop, detectSurfaceCapabilities, measureElementBorderBox, observeElementResize, observeReducedMotion, prefersReducedMotion, resetCapabilityCache, resolveEffectiveRenderMode, scheduleAnimationFrame, supportsSvgBackdropRefraction, type CapabilityEnv, type FrameLoop, type FrameScheduler, type ObserveElementResizeOptions, type SurfaceCapabilities, type SurfaceRenderMode, } from './capabilities.ts';
8
+ export { buildBackdropFilterCss, buildMaterialFromCssSurface, formatOpaqueSolidCss, formatRgbaCss, parseCssBackdropBlur, parseCssBackdropSaturate, readElementGlassSurface, resolveElementTheme, type BuildBackdropFilterCssParams, type BuildMaterialFromCssSurfaceOptions, type MeasuredCssGlassSurface, type ReadElementGlassSurfaceOptions, type ResolveElementThemeOptions, } from './cssSurface.ts';
9
+ export { DEFAULT_MAX_REFRACT_MAP_PIXELS, SVG_NS, computeAutoBezel, createRefractFilterController, resolveEffectiveMapScale, resolveFieldBezel, type RefractFilterConfig, type RefractFilterController, type RefractFilterControllerOptions, type RefractFilterFrame, } from './refractFilter.ts';
10
+ export { GlassSurfaceController, computeAutoSurfaceBounds, computeClampedRefractBounds, createGlassSurfaceController, type GlassSurfaceCapabilities, type GlassSurfaceControllerOptions, type GlassSurfaceElements, type GlassSurfaceFrame, type GlassSurfaceZIndex, type SurfaceFrameProducer, } from './surfaceController.ts';
package/dist/index.js ADDED
@@ -0,0 +1,10 @@
1
+ /**
2
+ * Public entry point for `@sessile/dom`.
3
+ * Framework-agnostic headless Live-DOM glass surface driver built on `@sessile/core`.
4
+ *
5
+ * SPDX-License-Identifier: MPL-2.0
6
+ */
7
+ export { cancelAnimationFrameSafe, createFrameLoop, detectSurfaceCapabilities, measureElementBorderBox, observeElementResize, observeReducedMotion, prefersReducedMotion, resetCapabilityCache, resolveEffectiveRenderMode, scheduleAnimationFrame, supportsSvgBackdropRefraction, } from "./capabilities.js";
8
+ export { buildBackdropFilterCss, buildMaterialFromCssSurface, formatOpaqueSolidCss, formatRgbaCss, parseCssBackdropBlur, parseCssBackdropSaturate, readElementGlassSurface, resolveElementTheme, } from "./cssSurface.js";
9
+ export { DEFAULT_MAX_REFRACT_MAP_PIXELS, SVG_NS, computeAutoBezel, createRefractFilterController, resolveEffectiveMapScale, resolveFieldBezel, } from "./refractFilter.js";
10
+ export { GlassSurfaceController, computeAutoSurfaceBounds, computeClampedRefractBounds, createGlassSurfaceController, } from "./surfaceController.js";
@@ -0,0 +1,71 @@
1
+ /**
2
+ * Headless Route B3 SVG `<filter>` DOM controller for Chromium liquid-glass refraction.
3
+ *
4
+ * Manages an off-screen SVG filter graph driven by `@sessile/core`'s Stored-PNG
5
+ * displacement map (`createRefractMapBuilder`) and Rec.709 color optics matrix
6
+ * (`buildColorOpticsMatrix`), dynamically switching between single-pass displacement
7
+ * and 3-channel RGB chromatic dispersion while self-masking to the displacement map alpha
8
+ * to avoid rectangular `backdrop-filter` bounds leakage.
9
+ *
10
+ * SPDX-License-Identifier: MPL-2.0
11
+ */
12
+ import { type GlassFieldState, type Rect, type RefractionProfileSpec } from '@sessile/core';
13
+ export declare const SVG_NS = "http://www.w3.org/2000/svg";
14
+ export declare const DEFAULT_MAX_REFRACT_MAP_PIXELS = 96000;
15
+ export interface RefractFilterConfig {
16
+ /** Bezel lens rim width in CSS px; `0` selects `computeAutoBezel` from active primitives. */
17
+ bezel?: number;
18
+ /** Dimensionless thickness-to-bezel ratio controlling Snell ray deflection (`0` disables refraction). */
19
+ strength?: number;
20
+ /** Chromatic RGB dispersion delta in px (`0` uses a single displacement map pass). */
21
+ dispersion?: number;
22
+ /** Extra scale factor applied to computed displacement strength (defaults to `1`). */
23
+ scaleMultiplier?: number;
24
+ /** Base resolution multiplier for Stored-PNG displacement maps (defaults to `0.5`). */
25
+ mapScale?: number;
26
+ /** Maximum encoded pixel budget for full-field Stored-PNG maps (`0` disables capping; defaults to `96_000`). */
27
+ maxMapPixels?: number;
28
+ /** Bezel refraction cross-section profile (`'squircle'`, `'circle'`, `'parabolic'`, `'lip'`, or custom height fn). */
29
+ profile?: RefractionProfileSpec;
30
+ /** Index of refraction (`1` = air, `1.5` = glass; defaults to `1.5`). */
31
+ ior?: number;
32
+ /** Allow steep-edge caustic folds (defaults to `false`). */
33
+ caustics?: boolean;
34
+ /** Enable 9-slice tile fast path for single-primitive rounded rects (defaults to `true`). */
35
+ nineSlice?: boolean;
36
+ }
37
+ export interface RefractFilterFrame extends RefractFilterConfig {
38
+ bounds: Rect;
39
+ field: GlassFieldState;
40
+ blurSigma: number;
41
+ saturate: number;
42
+ brightness: number;
43
+ contrast: number;
44
+ contrastFirst?: boolean;
45
+ }
46
+ export interface RefractFilterControllerOptions extends RefractFilterConfig {
47
+ id: string;
48
+ document?: Document;
49
+ mountTarget?: Element | null;
50
+ }
51
+ export interface RefractFilterController {
52
+ readonly id: string;
53
+ readonly svgElement: SVGSVGElement | null;
54
+ readonly mounted: boolean;
55
+ mount(target?: Element | null): boolean;
56
+ updateConfig(config: Partial<RefractFilterConfig>): void;
57
+ updateFrame(frame: RefractFilterFrame): void;
58
+ dispose(): void;
59
+ }
60
+ /**
61
+ * Resolves effective Stored-PNG resolution scale for full-field refraction maps,
62
+ * promoting compact controls (`<= 128px`) to 1:1 and capping encoded pixel area to
63
+ * `maxMapPixels` (`0` disables capping).
64
+ */
65
+ export declare function resolveEffectiveMapScale(boundsWidth: number, boundsHeight: number, requestedMapScale: number, maxMapPixels?: number): number;
66
+ /** Computes automatic lens bezel width (clamped to `[6, 22]` CSS px) from element dimensions. */
67
+ export declare function computeAutoBezel(width: number, height: number): number;
68
+ /** Resolves effective bezel width across all active primitives in an N-primitive glass field. */
69
+ export declare function resolveFieldBezel(requestedBezel: number, field: GlassFieldState): number;
70
+ /** Creates an imperative SVG `<filter>` controller implementing Route B3 self-masked refraction. */
71
+ export declare function createRefractFilterController(options: RefractFilterControllerOptions): RefractFilterController;