shaderfont 0.0.0-stage → 0.5.4

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,1379 @@
1
+ import {
2
+ DragEffect,
3
+ GestureTag,
4
+ activeGesture,
5
+ assertGestureTransition,
6
+ clamp,
7
+ createElasticTransform,
8
+ createErosionField,
9
+ createMaskField,
10
+ dampedSpringFactor,
11
+ dissolveProgress,
12
+ hashText,
13
+ idleGesture,
14
+ numberOption,
15
+ pressedGesture,
16
+ resolveDragEffect,
17
+ resolveShaderPreset,
18
+ restoringGesture,
19
+ selectedGesture
20
+ } from "./core.js";
21
+ import { createMaskRenderer } from "./mask-renderer.js";
22
+ import { SHADER_FONT_DEFAULTS } from "./options.js";
23
+ import { isProceduralShader } from "./presets.js";
24
+ import { materialDimensions } from "./material-core.js";
25
+ import { createMaterialRenderer } from "./material-renderer.js";
26
+ import { rendererError } from "./webgl-surface.js";
27
+ import { createRevealField, revealSample } from "./reveal-core.js";
28
+ import { createRevealRenderer } from "./reveal-renderer.js";
29
+ import { createPaintLayout, projectSelectionRects } from "./paint-layout.js";
30
+ import { createSelectionIndicator } from "./selection-indicator.js";
31
+ import { selectionWithin } from "./selection-range.js";
32
+ import { observeSelectionDrag } from "./selection-gesture.js";
33
+
34
+ const STYLE_ID = "shader-font-component-styles";
35
+ const MASK_STEPS = 144;
36
+ const MAX_MASK_PIXELS = 131_072;
37
+ const DRAG_THRESHOLD = 5;
38
+ const DEFAULT_DISSOLVE_MS = 2400;
39
+ const DEFAULT_RESTORE_MS = 1800;
40
+ const SHAKE_RESTORE_MS = 180;
41
+ const ELASTIC_RESTORE_MS = 900;
42
+ const DEFAULT_COLORS = Object.freeze({
43
+ primary: SHADER_FONT_DEFAULTS.primary,
44
+ secondary: SHADER_FONT_DEFAULTS.secondary,
45
+ accent: SHADER_FONT_DEFAULTS.accent
46
+ });
47
+
48
+ const COMPONENT_STYLES = `
49
+ shader-font,
50
+ shaderfont {
51
+ --sf-x: 0px;
52
+ --sf-y: 0px;
53
+ --sf-effect-x: 0px;
54
+ --sf-effect-y: 0px;
55
+ --sf-effect-rotate: 0deg;
56
+ --sf-effect-scale-x: 1;
57
+ --sf-effect-scale-y: 1;
58
+ --sf-shake-small: 1px;
59
+ --sf-shake-large: 3px;
60
+ --sf-shake-neg-small: -1px;
61
+ --sf-shake-neg-large: -3px;
62
+ --sf-shake-angle: .45deg;
63
+ --sf-shake-neg-angle: -.45deg;
64
+ --sf-fade: 1;
65
+ --_sf-primary: ${DEFAULT_COLORS.primary};
66
+ --_sf-secondary: ${DEFAULT_COLORS.secondary};
67
+ --_sf-accent: ${DEFAULT_COLORS.accent};
68
+ --_sf-author-primary: initial;
69
+ --_sf-author-secondary: initial;
70
+ --_sf-author-accent: initial;
71
+ display: inline;
72
+ box-decoration-break: slice;
73
+ -webkit-box-decoration-break: slice;
74
+ max-width: 100%;
75
+ vertical-align: baseline;
76
+ color: transparent;
77
+ -webkit-text-fill-color: transparent;
78
+ background:
79
+ var(--sf-burn-edge-image, none),
80
+ repeating-linear-gradient(
81
+ 180deg,
82
+ var(--_sf-author-accent, var(--sf-accent, var(--_sf-accent))) 0 2px,
83
+ var(--_sf-author-secondary, var(--sf-secondary, var(--_sf-secondary))) 2px 4px,
84
+ var(--_sf-author-primary, var(--sf-primary, var(--_sf-primary))) 4px 5px,
85
+ var(--_sf-author-accent, var(--sf-accent, var(--_sf-accent))) 5px 7px
86
+ ),
87
+ linear-gradient(
88
+ 135deg,
89
+ var(--_sf-author-primary, var(--sf-primary, var(--_sf-primary))) 0%,
90
+ var(--_sf-author-accent, var(--sf-accent, var(--_sf-accent))) 38%,
91
+ var(--_sf-author-secondary, var(--sf-secondary, var(--_sf-secondary))) 72%,
92
+ var(--_sf-author-primary, var(--sf-primary, var(--_sf-primary))) 100%
93
+ );
94
+ background-size: 100% 100%, 100% 7px, 100% 100%;
95
+ background-clip: text;
96
+ -webkit-background-clip: text;
97
+ background-blend-mode: normal;
98
+ text-shadow:
99
+ -.018em 0 color-mix(in srgb, var(--_sf-author-primary, var(--sf-primary, var(--_sf-primary))) 70%, transparent),
100
+ .018em 0 color-mix(in srgb, var(--_sf-author-secondary, var(--sf-secondary, var(--_sf-secondary))) 62%, transparent);
101
+ filter: none;
102
+ transform:
103
+ translate3d(var(--sf-x), var(--sf-y), 0)
104
+ translate3d(var(--sf-effect-x), var(--sf-effect-y), 0)
105
+ rotate(var(--sf-effect-rotate))
106
+ scale(var(--sf-effect-scale-x), var(--sf-effect-scale-y));
107
+ transform-origin: center;
108
+ opacity: var(--sf-fade);
109
+ caret-color: var(--_sf-author-primary, var(--sf-primary, var(--_sf-primary)));
110
+ -webkit-mask-repeat: no-repeat;
111
+ mask-repeat: no-repeat;
112
+ -webkit-mask-position: 0 0;
113
+ mask-position: 0 0;
114
+ -webkit-mask-size: 100% 100%;
115
+ mask-size: 100% 100%;
116
+ animation:
117
+ shader-font-scan var(--sf-scan-duration, 1.8s) linear infinite,
118
+ shader-font-outline-jitter var(--sf-jitter-duration, 1.35s) steps(1, end) infinite;
119
+ }
120
+
121
+ shader-font[data-drag-effect="move"], shaderfont[data-drag-effect="move"],
122
+ shader-font[data-drag-effect="shake"], shaderfont[data-drag-effect="shake"],
123
+ shader-font[data-drag-effect="elastic"], shaderfont[data-drag-effect="elastic"] {
124
+ display: inline-block;
125
+ cursor: grab;
126
+ touch-action: none;
127
+ }
128
+ shader-font[block], shaderfont[block] { display: block; }
129
+ shader-font.is-dragging, shaderfont.is-dragging { cursor: grabbing; user-select: none; }
130
+ shader-font.is-effect-active, shader-font.is-dragging {
131
+ will-change: transform, mask-image;
132
+ }
133
+ shader-font[interaction="none"] { pointer-events: none; }
134
+ shader-font[contenteditable]:focus {
135
+ outline: 1px solid color-mix(in srgb, var(--_sf-author-primary, var(--sf-primary, var(--_sf-primary))) 38%, transparent);
136
+ outline-offset: .16em;
137
+ }
138
+ shader-font::selection, shaderfont::selection {
139
+ color: HighlightText;
140
+ -webkit-text-fill-color: HighlightText;
141
+ background: Highlight;
142
+ text-shadow: none;
143
+ }
144
+ .shaderfont-selection-indicator {
145
+ position: fixed;
146
+ inset: 0;
147
+ pointer-events: none;
148
+ user-select: none;
149
+ }
150
+ .shaderfont-selection-indicator > span {
151
+ position: absolute;
152
+ pointer-events: none;
153
+ box-sizing: border-box;
154
+ outline: 1px solid Highlight;
155
+ background: color-mix(in srgb, Highlight 24%, transparent);
156
+ }
157
+
158
+ shader-font[data-shader="none"],
159
+ shaderfont[data-shader="none"] {
160
+ color: inherit;
161
+ -webkit-text-fill-color: currentColor;
162
+ background: none;
163
+ background-clip: border-box;
164
+ -webkit-background-clip: border-box;
165
+ background-blend-mode: normal;
166
+ text-shadow: none;
167
+ filter: none;
168
+ animation: none;
169
+ }
170
+
171
+ shader-font[data-shader]:not([data-shader="none"]):not([data-shader="hologram"]) {
172
+ color: inherit;
173
+ -webkit-text-fill-color: currentColor;
174
+ background: none;
175
+ background-clip: text;
176
+ -webkit-background-clip: text;
177
+ text-shadow: none;
178
+ filter: none;
179
+ animation: none;
180
+ }
181
+ shader-font[data-shader]:not([data-shader="none"]):not([data-shader="hologram"])[data-material-status="ready"] {
182
+ color: transparent;
183
+ -webkit-text-fill-color: transparent;
184
+ background-image: var(--sf-burn-edge-image, none), var(--sf-material-image);
185
+ background-size: 100% 100%;
186
+ background-repeat: no-repeat;
187
+ background-blend-mode: normal;
188
+ }
189
+ shader-font[data-shader="none"][data-reveal-status="ready"] {
190
+ color: inherit;
191
+ -webkit-text-fill-color: transparent;
192
+ background-image: var(--sf-burn-edge-image), linear-gradient(currentColor, currentColor);
193
+ background-size: 100% 100%;
194
+ background-repeat: no-repeat;
195
+ background-clip: text;
196
+ -webkit-background-clip: text;
197
+ }
198
+ shader-font[data-renderer-status="error"] {
199
+ color: inherit;
200
+ -webkit-text-fill-color: currentColor;
201
+ background: none;
202
+ text-shadow: none;
203
+ filter: none;
204
+ }
205
+ shader-font[data-shader-paused="true"] { animation-play-state: paused !important; }
206
+
207
+ shader-font[data-drag-effect="shake"].is-effect-active,
208
+ shaderfont[data-drag-effect="shake"].is-effect-active {
209
+ animation:
210
+ shader-font-scan 1.8s linear infinite,
211
+ shader-font-outline-jitter 1.35s steps(1, end) infinite,
212
+ shader-font-drag-shake 115ms steps(2, end) infinite;
213
+ }
214
+
215
+ shader-font[data-shader="none"][data-drag-effect="shake"].is-effect-active,
216
+ shaderfont[data-shader="none"][data-drag-effect="shake"].is-effect-active {
217
+ animation: shader-font-drag-shake 115ms steps(2, end) infinite;
218
+ }
219
+ shader-font[data-shader]:not([data-shader="none"]):not([data-shader="hologram"])[data-drag-effect="shake"].is-effect-active {
220
+ animation: shader-font-drag-shake 115ms steps(2, end) infinite;
221
+ }
222
+
223
+ @keyframes shader-font-scan { to { background-position: 0 0, 0 7px, 0 0; } }
224
+ @keyframes shader-font-outline-jitter {
225
+ 0%, 100% { text-shadow: -.018em 0 var(--_sf-author-primary, var(--sf-primary, var(--_sf-primary))), .018em 0 var(--_sf-author-secondary, var(--sf-secondary, var(--_sf-secondary))); }
226
+ 14% { text-shadow: -.052em -.004em var(--_sf-author-primary, var(--sf-primary, var(--_sf-primary))), .026em .003em var(--_sf-author-secondary, var(--sf-secondary, var(--_sf-secondary))); }
227
+ 31% { text-shadow: .024em 0 var(--_sf-author-primary, var(--sf-primary, var(--_sf-primary))), -.036em 0 var(--_sf-author-secondary, var(--sf-secondary, var(--_sf-secondary))); }
228
+ 48% { text-shadow: -.028em .005em var(--_sf-author-primary, var(--sf-primary, var(--_sf-primary))), .058em -.003em var(--_sf-author-secondary, var(--sf-secondary, var(--_sf-secondary))); }
229
+ 67% { text-shadow: -.062em 0 var(--_sf-author-primary, var(--sf-primary, var(--_sf-primary))), .032em .004em var(--_sf-author-secondary, var(--sf-secondary, var(--_sf-secondary))); }
230
+ 83% { text-shadow: .036em -.003em var(--_sf-author-primary, var(--sf-primary, var(--_sf-primary))), -.022em .003em var(--_sf-author-secondary, var(--sf-secondary, var(--_sf-secondary))); }
231
+ }
232
+ @keyframes shader-font-drag-shake {
233
+ 0%, 100% { translate: var(--sf-shake-neg-small) var(--sf-shake-small); rotate: var(--sf-shake-neg-angle); }
234
+ 25% { translate: var(--sf-shake-large) var(--sf-shake-neg-small); rotate: var(--sf-shake-angle); }
235
+ 50% { translate: var(--sf-shake-neg-large) var(--sf-shake-neg-small); rotate: var(--sf-shake-angle); }
236
+ 75% { translate: var(--sf-shake-small) var(--sf-shake-small); rotate: var(--sf-shake-neg-angle); }
237
+ }
238
+
239
+ @media (prefers-reduced-motion: reduce) {
240
+ shader-font, shaderfont { animation: none !important; translate: none; rotate: none; }
241
+ }
242
+ `;
243
+
244
+ let installedStyleNonce;
245
+
246
+ function styleError(code) {
247
+ return Object.assign(new Error(code), { code });
248
+ }
249
+
250
+ function ensureStyles(styleNonce = installedStyleNonce) {
251
+ if (styleNonce !== undefined && (typeof styleNonce !== "string" || !styleNonce || /\s/.test(styleNonce))) {
252
+ throw styleError("INVALID_STYLE_NONCE");
253
+ }
254
+ const existing = document.getElementById(STYLE_ID);
255
+ if (existing) {
256
+ if (existing.tagName !== "STYLE" || existing.textContent !== COMPONENT_STYLES) {
257
+ throw styleError("STYLES_CONFLICT");
258
+ }
259
+ if (existing.sheet && !existing.sheet.disabled) {
260
+ if (styleNonce && existing.nonce === styleNonce) installedStyleNonce = styleNonce;
261
+ return;
262
+ }
263
+ if (!styleNonce) throw styleError("STYLES_BLOCKED");
264
+ existing.remove();
265
+ }
266
+ const style = document.createElement("style");
267
+ style.id = STYLE_ID;
268
+ if (styleNonce) style.nonce = styleNonce;
269
+ style.textContent = COMPONENT_STYLES;
270
+ document.head.append(style);
271
+ if (!style.sheet || style.sheet.disabled) {
272
+ style.remove();
273
+ throw styleError("STYLES_BLOCKED");
274
+ }
275
+ installedStyleNonce = styleNonce;
276
+ }
277
+
278
+ function colorOrDefault(element, attribute) {
279
+ const value = element.getAttribute(attribute)?.trim();
280
+ return value && CSS.supports("color", value) ? value : DEFAULT_COLORS[attribute];
281
+ }
282
+
283
+ function numberAttribute(element, name, fallback, minimum, maximum) {
284
+ return numberOption(element.getAttribute(name), fallback, minimum, maximum);
285
+ }
286
+
287
+ function ownedSelection(element) {
288
+ return selectionWithin(element, document);
289
+ }
290
+
291
+ function selectionGeometry(element) {
292
+ const owned = ownedSelection(element);
293
+ if (!owned) return null;
294
+ const viewportRects = Array.from(owned.range.getClientRects());
295
+ const rects = projectSelectionRects(measurePaintLayout(element), viewportRects);
296
+ if (rects.length === 0) return null;
297
+ return { regions: rects, viewportRects };
298
+ }
299
+
300
+ function measurePaintLayout(element) {
301
+ const bounds = element.getBoundingClientRect();
302
+ const computed = getComputedStyle(element);
303
+ const inline = computed.display === "inline";
304
+ return createPaintLayout(bounds, inline ? Array.from(element.getClientRects()) : [], inline, computed.direction);
305
+ }
306
+
307
+ function sameRegions(left, right) {
308
+ if (left.length !== right.length) return false;
309
+ return left.every((region, index) => {
310
+ const other = right[index];
311
+ return ["x", "y", "width", "height"].every(key => Math.abs(region[key] - other[key]) < 0.01);
312
+ });
313
+ }
314
+
315
+ export class ShaderFont extends HTMLElement {
316
+ static get observedAttributes() {
317
+ return ["shader", "renderer", "primary", "secondary", "accent", "speed", "scale", "resolution", "softness", "flow", "roughness", "dissolve-ms", "restore-ms", "interaction", "drag-effect", "block", "reveal-effect", "reveal-ms", "reveal-interval-ms"];
318
+ }
319
+
320
+ constructor() {
321
+ super();
322
+ this.gesture = idleGesture();
323
+ this.offsetX = 0;
324
+ this.offsetY = 0;
325
+ this.gestureWidth = 120;
326
+ this.dissolve = 0;
327
+ this.effectProgress = 0;
328
+ this.elasticMotion = createElasticTransform(0, 0, 1);
329
+ this.restoreToken = 0;
330
+ this.restoreTimer = 0;
331
+ this.restoreFrame = 0;
332
+ this.dissolveFrame = 0;
333
+ this.dissolveStartedAt = null;
334
+ this.selectionDirty = true;
335
+ this.selectionRegions = [];
336
+ this.selectionIndicator = createSelectionIndicator(this,
337
+ () => { const owned = ownedSelection(this); return owned ? Array.from(owned.range.getClientRects()) : []; },
338
+ error => this.reportRendererError(error, "selection"));
339
+ this.maskGeometry = null;
340
+ this.maskField = null;
341
+ this.maskTexture = null;
342
+ this.maskSurface = null;
343
+ this.rendererError = null;
344
+ this.materialSurface = null;
345
+ this.materialGeometry = null;
346
+ this.materialInput = null;
347
+ this.materialDirty = true;
348
+ this.materialFrame = 0;
349
+ this.materialElapsed = 0;
350
+ this.materialLastTime = null;
351
+ this.materialLastPaint = null;
352
+ this.dissolveMaskImage = "none";
353
+ this.revealMaskImage = "none";
354
+ this.revealSurface = null;
355
+ this.revealField = null;
356
+ this.revealFrame = 0;
357
+ this.revealTimer = 0;
358
+ this.revealElapsed = 0;
359
+ this.revealLastTime = null;
360
+ this.revealLastPaint = null;
361
+ this.revealProgress = 1;
362
+ this.inViewport = false;
363
+ this.motionQuery = matchMedia("(prefers-reduced-motion: reduce)");
364
+ this.onMaterialPlaybackChange = () => {
365
+ if (document.hidden) this.selectionIndicator.clear();
366
+ else if (this.gesture.tag === GestureTag.ACTIVE || this.gesture.tag === GestureTag.SELECTED) this.captureSelectionRegions();
367
+ this.syncMaterialPlayback();
368
+ this.syncRevealPlayback();
369
+ };
370
+ this.visibilityObserver = new IntersectionObserver(entries => {
371
+ const entry = entries.find(entry => entry.target === this);
372
+ if (!entry) return;
373
+ this.inViewport = entry.isIntersecting;
374
+ if (!entry.isIntersecting) this.selectionIndicator.clear();
375
+ else if (this.gesture.tag === GestureTag.ACTIVE || this.gesture.tag === GestureTag.SELECTED) this.captureSelectionRegions();
376
+ this.syncMaterialPlayback();
377
+ this.syncRevealPlayback();
378
+ });
379
+ this.renderedMaskStep = -1;
380
+ this.resizeObserver = new ResizeObserver(() => {
381
+ this.invalidateMask();
382
+ this.invalidateMaterial();
383
+ this.invalidateReveal();
384
+ });
385
+ this.textObserver = new MutationObserver(() => {
386
+ this.resetInteractionForOptionChange();
387
+ this.invalidateMask();
388
+ this.invalidateMaterial();
389
+ this.invalidateReveal();
390
+ });
391
+ this.onPointerDown = this.onPointerDown.bind(this);
392
+ this.onPointerMove = this.onPointerMove.bind(this);
393
+ this.onPointerEnd = this.onPointerEnd.bind(this);
394
+ this.onDragStart = this.onDragStart.bind(this);
395
+ this.onSelectionChange = this.onSelectionChange.bind(this);
396
+ this.onWindowBlur = this.onWindowBlur.bind(this);
397
+ this.selectionDrag = null;
398
+ }
399
+
400
+ connectedCallback() {
401
+ try {
402
+ ensureStyles();
403
+ this.dataset.styleStatus = "ready";
404
+ delete this.dataset.styleError;
405
+ } catch (error) {
406
+ this.dataset.styleStatus = "error";
407
+ this.dataset.styleError = error.code ?? "STYLE_INSTALL_FAILED";
408
+ return;
409
+ }
410
+ this.applyAttributes();
411
+ if (this.dataset.shaderFontBound === "true") return;
412
+ this.dataset.shaderFontBound = "true";
413
+ this.dataset.shaderFontState = this.gesture.tag;
414
+ this.addEventListener("pointerdown", this.onPointerDown);
415
+ this.addEventListener("dragstart", this.onDragStart);
416
+ window.addEventListener("pointermove", this.onPointerMove, { passive: false });
417
+ window.addEventListener("pointerup", this.onPointerEnd);
418
+ window.addEventListener("pointercancel", this.onPointerEnd);
419
+ document.addEventListener("selectionchange", this.onSelectionChange);
420
+ this.selectionDrag = observeSelectionDrag(document, pointer => this.adoptSelectionDrag(pointer, true));
421
+ window.addEventListener("blur", this.onWindowBlur);
422
+ this.resizeObserver.observe(this);
423
+ // Non-replaced inline boxes do not emit useful ResizeObserver sizes.
424
+ let container = this.parentElement;
425
+ while (container && ["inline", "contents"].includes(getComputedStyle(container).display)) container = container.parentElement;
426
+ if (container) this.resizeObserver.observe(container);
427
+ this.textObserver.observe(this, { childList: true, characterData: true, subtree: true });
428
+ document.addEventListener("visibilitychange", this.onMaterialPlaybackChange);
429
+ this.motionQuery.addEventListener("change", this.onMaterialPlaybackChange);
430
+ this.visibilityObserver.observe(this);
431
+ }
432
+
433
+ disconnectedCallback() {
434
+ this.selectionDrag?.dispose();
435
+ this.selectionDrag = null;
436
+ this.stopRevealClock(true);
437
+ this.clearRevealPaint();
438
+ this.revealField = null;
439
+ this.stopMaterialClock(true);
440
+ this.materialGeometry = null;
441
+ this.materialInput = null;
442
+ this.materialDirty = true;
443
+ this.inViewport = false;
444
+ this.visibilityObserver.disconnect();
445
+ document.removeEventListener("visibilitychange", this.onMaterialPlaybackChange);
446
+ this.motionQuery.removeEventListener("change", this.onMaterialPlaybackChange);
447
+ this.resetInteractionForOptionChange();
448
+ this.maskGeometry = null;
449
+ this.maskTexture = null;
450
+ this.maskField = null;
451
+ this.disposeMaskRenderer();
452
+ this.removeEventListener("pointerdown", this.onPointerDown);
453
+ this.removeEventListener("dragstart", this.onDragStart);
454
+ window.removeEventListener("pointermove", this.onPointerMove);
455
+ window.removeEventListener("pointerup", this.onPointerEnd);
456
+ window.removeEventListener("pointercancel", this.onPointerEnd);
457
+ document.removeEventListener("selectionchange", this.onSelectionChange);
458
+ window.removeEventListener("blur", this.onWindowBlur);
459
+ this.resizeObserver.disconnect();
460
+ this.textObserver.disconnect();
461
+ delete this.dataset.shaderFontBound;
462
+ }
463
+
464
+ attributeChangedCallback(name, oldValue, newValue) {
465
+ if (!this.isConnected) return;
466
+ this.applyAttributes();
467
+ if (oldValue !== newValue && (name === "drag-effect" || name === "interaction")) {
468
+ this.resetInteractionForOptionChange();
469
+ }
470
+ if (oldValue !== newValue && ["drag-effect", "block"].includes(name)) {
471
+ this.invalidateMask();
472
+ this.invalidateMaterial();
473
+ this.invalidateReveal();
474
+ }
475
+ if (oldValue !== newValue && name === "renderer") {
476
+ this.resetInteractionForOptionChange();
477
+ this.disposeMaskRenderer();
478
+ this.clearRendererError();
479
+ this.stopMaterialClock(true);
480
+ this.stopRevealClock(true);
481
+ }
482
+ if (oldValue !== newValue && name === "shader") {
483
+ this.stopMaterialClock(true);
484
+ this.clearRendererError();
485
+ }
486
+ if (["shader", "renderer", "primary", "secondary", "accent", "speed", "scale", "resolution", "softness"].includes(name)) {
487
+ this.invalidateMaterial();
488
+ }
489
+ if (name === "flow" || name === "roughness") this.invalidateMask();
490
+ if (["reveal-effect", "reveal-ms", "reveal-interval-ms"].includes(name) && oldValue !== newValue) {
491
+ this.restartReveal();
492
+ } else if (name === "resolution") this.invalidateReveal();
493
+ else if (name === "renderer" || name === "shader") this.syncRevealPlayback();
494
+ }
495
+
496
+ applyAttributes() {
497
+ for (const name of Object.keys(DEFAULT_COLORS)) {
498
+ const value = this.getAttribute(name)?.trim();
499
+ if (value && CSS.supports("color", value)) this.style.setProperty(`--_sf-author-${name}`, value);
500
+ else this.style.removeProperty(`--_sf-author-${name}`);
501
+ }
502
+ this.dataset.shader = this.shaderPreset();
503
+ this.dataset.dragEffect = this.dragEffect();
504
+ this.dataset.renderer = this.rendererKind();
505
+ this.dataset.revealEffect = this.getAttribute("reveal-effect") ?? SHADER_FONT_DEFAULTS.revealEffect;
506
+ const speed = numberAttribute(this, "speed", SHADER_FONT_DEFAULTS.speed, 0, 4);
507
+ this.style.setProperty("--sf-scan-duration", `${1.8 / Math.max(0.01, speed)}s`);
508
+ this.style.setProperty("--sf-jitter-duration", `${1.35 / Math.max(0.01, speed)}s`);
509
+ }
510
+
511
+ shaderPreset() {
512
+ return resolveShaderPreset(this.getAttribute("shader"));
513
+ }
514
+
515
+ interactionMode() {
516
+ const value = this.getAttribute("interaction") ?? "select";
517
+ if (value === "none") return "none";
518
+ const effect = this.dragEffect();
519
+ if (this.rendererError && effect === DragEffect.DISSOLVE) return "none";
520
+ if (effect === DragEffect.NONE) return "none";
521
+ return effect === DragEffect.DISSOLVE ? "select" : "direct";
522
+ }
523
+
524
+ dragEffect() {
525
+ return resolveDragEffect(this.getAttribute("drag-effect"), this.getAttribute("interaction") ?? "select");
526
+ }
527
+
528
+ rendererKind() {
529
+ return this.getAttribute("renderer") ?? SHADER_FONT_DEFAULTS.renderer;
530
+ }
531
+
532
+ disposeMaskRenderer() {
533
+ this.maskSurface?.dispose();
534
+ this.maskSurface = null;
535
+ this.renderedMaskStep = -1;
536
+ }
537
+
538
+ clearRendererError() {
539
+ this.rendererError = null;
540
+ delete this.dataset.rendererError;
541
+ this.dataset.rendererStatus = "idle";
542
+ this.materialDirty = true;
543
+ }
544
+
545
+ reportRendererError(error, phase = "mask") {
546
+ this.stopRevealClock(true);
547
+ this.clearRevealPaint();
548
+ this.dataset.revealState = "error";
549
+ this.stopMaterialClock(true);
550
+ this.dataset.materialStatus = "error";
551
+ this.dataset.shaderPaused = "true";
552
+ this.cancelRestore();
553
+ this.stopDissolveClock();
554
+ const state = this.gesture;
555
+ if ((state.tag === GestureTag.PRESSED || state.tag === GestureTag.ACTIVE) && this.hasPointerCapture(state.pointerId)) {
556
+ this.releasePointerCapture(state.pointerId);
557
+ }
558
+ this.disposeMaskRenderer();
559
+ this.resetTransientEffect();
560
+ this.clearSelectionRegions();
561
+ this.classList.remove("is-dragging");
562
+ this.rendererError = error;
563
+ this.dataset.rendererStatus = "error";
564
+ this.dataset.rendererError = error.code ?? "MASK_RENDER_FAILED";
565
+ this.transitionTo(idleGesture());
566
+ this.publishProgress(0, DragEffect.DISSOLVE);
567
+ this.dispatchEvent(new CustomEvent("shaderfont-error", {
568
+ bubbles: true,
569
+ detail: { renderer: this.rendererKind(), code: this.dataset.rendererError, message: error.message, phase }
570
+ }));
571
+ }
572
+
573
+ invalidateMaterial() {
574
+ this.materialGeometry = null;
575
+ this.materialInput = null;
576
+ this.materialDirty = true;
577
+ this.syncMaterialPlayback();
578
+ }
579
+
580
+ stopMaterialClock(dispose = false) {
581
+ if (this.materialFrame) cancelAnimationFrame(this.materialFrame);
582
+ this.materialFrame = 0;
583
+ this.materialLastTime = null;
584
+ this.materialLastPaint = null;
585
+ if (dispose) {
586
+ this.materialSurface?.dispose();
587
+ this.materialSurface = null;
588
+ }
589
+ }
590
+
591
+ syncMaterialPlayback() {
592
+ const speed = numberAttribute(this, "speed", SHADER_FONT_DEFAULTS.speed, 0, 4);
593
+ const outside = !this.isConnected || !this.inViewport || document.hidden;
594
+ const paused = outside || speed === 0 || this.motionQuery.matches || !!this.rendererError;
595
+ this.dataset.shaderPaused = String(paused);
596
+ if (!isProceduralShader(this.shaderPreset())) {
597
+ this.stopMaterialClock(true);
598
+ this.dataset.materialStatus = "idle";
599
+ this.style.setProperty("--sf-material-image", "none");
600
+ return;
601
+ }
602
+ if (outside || this.rendererError) {
603
+ this.stopMaterialClock(this.materialSurface?.kind === "webgl");
604
+ return;
605
+ }
606
+ if (paused) {
607
+ this.stopMaterialClock();
608
+ if (this.materialDirty || !this.materialSurface) this.paintMaterial();
609
+ return;
610
+ }
611
+ if (this.materialFrame) return;
612
+ const tick = now => {
613
+ this.materialFrame = 0;
614
+ if (!this.isConnected || !this.inViewport || document.hidden || this.rendererError) return;
615
+ if (this.motionQuery.matches) {
616
+ this.syncMaterialPlayback();
617
+ return;
618
+ }
619
+ const speed = numberAttribute(this, "speed", SHADER_FONT_DEFAULTS.speed, 0, 4);
620
+ if (this.materialLastTime !== null) this.materialElapsed += Math.max(0, now - this.materialLastTime) / 1000 * speed;
621
+ this.materialLastTime = now;
622
+ if (this.materialDirty || this.materialLastPaint === null || now - this.materialLastPaint >= 1000 / 30) {
623
+ if (!this.paintMaterial()) return;
624
+ this.materialLastPaint = now;
625
+ }
626
+ this.materialFrame = requestAnimationFrame(tick);
627
+ };
628
+ this.materialFrame = requestAnimationFrame(tick);
629
+ }
630
+
631
+ paintMaterial() {
632
+ try {
633
+ if (!this.materialGeometry) {
634
+ const rect = measurePaintLayout(this);
635
+ const resolution = numberAttribute(this, "resolution", SHADER_FONT_DEFAULTS.resolution, 0.25, 1);
636
+ this.materialGeometry = { ...materialDimensions(rect.width, rect.height, resolution), aspect: Math.max(1, rect.width) / Math.max(1, rect.height) };
637
+ }
638
+ const { width, height, aspect } = this.materialGeometry;
639
+ if (!this.materialSurface || this.materialSurface.canvas.width !== width || this.materialSurface.canvas.height !== height) {
640
+ this.materialSurface?.dispose();
641
+ this.materialSurface = createMaterialRenderer(this.rendererKind(), width, height, error => this.reportRendererError(error, "material"));
642
+ }
643
+ if (!this.materialInput) {
644
+ const computed = getComputedStyle(this);
645
+ const colors = ["primary", "secondary", "accent"].map(name => {
646
+ const color = computed.getPropertyValue(`--_sf-author-${name}`).trim()
647
+ || computed.getPropertyValue(`--sf-${name}`).trim() || colorOrDefault(this, name);
648
+ if (!/^#[0-9a-f]{6}$/i.test(color)) throw rendererError("INVALID_MATERIAL_COLOR", "Procedural materials require six-digit hex colors");
649
+ return [1, 3, 5].map(index => Number.parseInt(color.slice(index, index + 2), 16) / 255);
650
+ });
651
+ this.materialInput = {
652
+ shader: this.shaderPreset(), aspect, colors, speed: 1,
653
+ scale: numberAttribute(this, "scale", SHADER_FONT_DEFAULTS.scale, 0.25, 4),
654
+ softness: numberAttribute(this, "softness", SHADER_FONT_DEFAULTS.softness, 0, 1), time: this.materialElapsed
655
+ };
656
+ }
657
+ // Playback owns accumulated, speed-scaled time, including pauses.
658
+ this.materialInput.time = this.materialElapsed;
659
+ const image = this.materialSurface.render(this.materialInput);
660
+ this.style.setProperty("--sf-material-image", `url("${image}")`);
661
+ this.dataset.materialStatus = "ready";
662
+ this.materialDirty = false;
663
+ return true;
664
+ } catch (error) {
665
+ this.reportRendererError(error, "material");
666
+ return false;
667
+ }
668
+ }
669
+
670
+ /** This is the only writer of mask-image; neither effect can erase the other. */
671
+ commitMasks() {
672
+ const layers = [this.dissolveMaskImage, this.revealMaskImage].filter(image => image !== "none");
673
+ if (layers.length > 1 && !CSS.supports("mask-composite", "intersect")
674
+ && !CSS.supports("-webkit-mask-composite", "source-in")) {
675
+ throw rendererError("MASK_COMPOSITION_UNAVAILABLE", "This browser cannot intersect reveal and selection masks");
676
+ }
677
+ const mask = layers.length ? layers.join(", ") : "none";
678
+ this.style.webkitMaskImage = mask;
679
+ this.style.maskImage = mask;
680
+ this.style.webkitMaskComposite = layers.length > 1 ? "source-in" : "source-over";
681
+ this.style.maskComposite = layers.length > 1 ? "intersect" : "add";
682
+ }
683
+
684
+ clearRevealPaint() {
685
+ this.revealMaskImage = "none";
686
+ this.style.setProperty("--sf-burn-edge-image", "none");
687
+ this.dataset.revealStatus = "idle";
688
+ this.revealProgress = 1;
689
+ this.commitMasks();
690
+ }
691
+
692
+ stopRevealClock(dispose = false) {
693
+ if (this.revealLastTime !== null) this.revealElapsed += Math.max(0, performance.now() - this.revealLastTime);
694
+ this.revealLastTime = null;
695
+ if (this.revealFrame) cancelAnimationFrame(this.revealFrame);
696
+ if (this.revealTimer) clearTimeout(this.revealTimer);
697
+ this.revealFrame = this.revealTimer = 0;
698
+ this.revealLastPaint = null;
699
+ if (dispose) {
700
+ this.revealSurface?.dispose();
701
+ this.revealSurface = null;
702
+ }
703
+ }
704
+
705
+ invalidateReveal() {
706
+ this.revealField = null;
707
+ this.revealLastPaint = null;
708
+ this.syncRevealPlayback();
709
+ }
710
+
711
+ restartReveal() {
712
+ this.stopRevealClock(true);
713
+ this.revealElapsed = 0;
714
+ this.revealField = null;
715
+ this.clearRevealPaint();
716
+ this.syncRevealPlayback();
717
+ }
718
+
719
+ syncRevealPlayback() {
720
+ const effect = this.dataset.revealEffect;
721
+ if (effect === "none" || this.rendererError || this.motionQuery.matches) {
722
+ this.stopRevealClock(true);
723
+ this.clearRevealPaint();
724
+ this.dataset.revealState = this.rendererError ? "error" : this.motionQuery.matches ? "reduced-motion" : "idle";
725
+ return;
726
+ }
727
+ if (effect !== "burn") {
728
+ this.reportRendererError(rendererError("INVALID_REVEAL_EFFECT", `Unknown reveal effect: ${effect}`), "reveal");
729
+ return;
730
+ }
731
+ if (!this.isConnected || !this.inViewport || document.hidden) {
732
+ this.stopRevealClock(this.revealSurface?.kind === "webgl");
733
+ this.dataset.revealState = "paused";
734
+ return;
735
+ }
736
+ if (this.revealFrame || this.revealTimer) return;
737
+ const tick = now => {
738
+ this.revealFrame = 0;
739
+ if (this.motionQuery.matches) {
740
+ this.syncRevealPlayback();
741
+ return;
742
+ }
743
+ if (!this.isConnected || !this.inViewport || document.hidden || this.rendererError) return;
744
+ if (this.revealLastTime !== null) this.revealElapsed += Math.max(0, now - this.revealLastTime);
745
+ this.revealLastTime = now;
746
+ const duration = numberAttribute(this, "reveal-ms", SHADER_FONT_DEFAULTS.revealMs, 200, 10000);
747
+ const interval = numberAttribute(this, "reveal-interval-ms", SHADER_FONT_DEFAULTS.revealIntervalMs, 0, 60000);
748
+ const sample = revealSample(this.revealElapsed, duration, interval);
749
+ this.dataset.revealState = sample.phase;
750
+ if (sample.phase !== "burning") {
751
+ this.clearRevealPaint();
752
+ this.revealSurface?.dispose();
753
+ this.revealSurface = null;
754
+ if (sample.phase === "holding") {
755
+ this.revealTimer = window.setTimeout(() => {
756
+ this.revealTimer = 0;
757
+ tick(performance.now());
758
+ }, Math.ceil(sample.remainingMs));
759
+ } else this.revealLastTime = null;
760
+ return;
761
+ }
762
+ if (this.revealLastPaint === null || now - this.revealLastPaint >= 1000 / 30) {
763
+ if (!this.paintReveal(sample.progress)) return;
764
+ this.revealLastPaint = now;
765
+ }
766
+ this.revealFrame = requestAnimationFrame(tick);
767
+ };
768
+ this.revealFrame = requestAnimationFrame(tick);
769
+ }
770
+
771
+ paintReveal(progress) {
772
+ try {
773
+ if (!this.revealField) {
774
+ const rect = measurePaintLayout(this);
775
+ const resolution = numberAttribute(this, "resolution", SHADER_FONT_DEFAULTS.resolution, 0.25, 1);
776
+ const { width, height } = materialDimensions(rect.width, rect.height, resolution);
777
+ this.revealField = createRevealField(width, height, hashText(this.textContent ?? ""));
778
+ }
779
+ const { width, height } = this.revealField;
780
+ if (!this.revealSurface || this.revealSurface.canvas.width !== width || this.revealSurface.canvas.height !== height) {
781
+ this.revealSurface?.dispose();
782
+ this.revealSurface = createRevealRenderer(this.rendererKind(), width, height, error => this.reportRendererError(error, "reveal"));
783
+ }
784
+ const images = this.revealSurface.render(this.revealField, progress);
785
+ this.revealMaskImage = `url("${images.mask}")`;
786
+ this.style.setProperty("--sf-burn-edge-image", `url("${images.edge}")`);
787
+ this.dataset.revealStatus = "ready";
788
+ this.revealProgress = progress;
789
+ this.commitMasks();
790
+ return true;
791
+ } catch (error) {
792
+ this.reportRendererError(error, "reveal");
793
+ return false;
794
+ }
795
+ }
796
+
797
+ resetInteractionForOptionChange() {
798
+ this.cancelRestore();
799
+ this.stopDissolveClock();
800
+ const state = this.gesture;
801
+ const hadInteraction = state.tag !== GestureTag.IDLE || this.dissolve > 0;
802
+ if ((state.tag === GestureTag.PRESSED || state.tag === GestureTag.ACTIVE) && this.hasPointerCapture(state.pointerId)) {
803
+ this.releasePointerCapture(state.pointerId);
804
+ }
805
+ this.classList.remove("is-dragging", "is-effect-active");
806
+ this.resetTransientEffect();
807
+ this.clearSelectionRegions();
808
+ if (this.maskSurface?.kind === "webgl") this.disposeMaskRenderer();
809
+ const owned = ownedSelection(this);
810
+ if (owned && hadInteraction && this.contains(owned.selection.anchorNode) && this.contains(owned.selection.focusNode)) {
811
+ owned.selection.removeAllRanges();
812
+ }
813
+ this.transitionTo(idleGesture());
814
+ this.publishProgress(0, this.dragEffect());
815
+ }
816
+
817
+ selectionFlow() {
818
+ const value = this.getAttribute("flow") ?? "reading";
819
+ if (value === "random" || value === "ltr" || value === "rtl") return value;
820
+ return "reading";
821
+ }
822
+
823
+ transitionTo(next) {
824
+ this.gesture = assertGestureTransition(this.gesture, next);
825
+ this.dataset.shaderFontState = next.tag;
826
+ this.dispatchEvent(new CustomEvent("shaderfont-state", {
827
+ bubbles: true,
828
+ detail: { state: next.tag, mode: next.mode ?? null, effect: next.effect ?? this.dragEffect() }
829
+ }));
830
+ }
831
+
832
+ onPointerDown(event) {
833
+ const mode = this.interactionMode();
834
+ if (mode === "none" || (event.pointerType === "mouse" && event.button !== 0)) return;
835
+ if (this.gesture.tag === GestureTag.PRESSED || this.gesture.tag === GestureTag.ACTIVE) return;
836
+ const effect = this.dragEffect();
837
+ this.cancelRestore();
838
+ this.stopDissolveClock();
839
+ if (this.dissolve === 0 || effect !== DragEffect.DISSOLVE) {
840
+ this.resetTransientEffect();
841
+ this.clearSelectionRegions();
842
+ }
843
+ const rect = this.getBoundingClientRect();
844
+ this.gestureWidth = Math.max(120, rect.width);
845
+ this.style.transformOrigin = `${event.clientX - rect.left}px ${event.clientY - rect.top}px`;
846
+ this.transitionTo(pressedGesture(
847
+ mode,
848
+ event.pointerId,
849
+ event.clientX,
850
+ event.clientY,
851
+ this.offsetX,
852
+ this.offsetY,
853
+ effect
854
+ ));
855
+ if (mode === "select" && !event.shiftKey) ownedSelection(this)?.selection.removeAllRanges();
856
+ if (mode === "direct") {
857
+ event.preventDefault();
858
+ this.setPointerCapture(event.pointerId);
859
+ }
860
+ }
861
+
862
+ onDragStart(event) {
863
+ if (this.interactionMode() === "select") event.preventDefault();
864
+ }
865
+
866
+ onPointerMove(event) {
867
+ let state = this.gesture;
868
+ if ((state.tag !== GestureTag.PRESSED && state.tag !== GestureTag.ACTIVE) || event.pointerId !== state.pointerId) return;
869
+ const dx = event.clientX - state.startX;
870
+ const dy = event.clientY - state.startY;
871
+ const distance = Math.hypot(dx, dy);
872
+ if (state.tag === GestureTag.PRESSED) {
873
+ if (distance < DRAG_THRESHOLD) return;
874
+ state = activeGesture(state);
875
+ this.transitionTo(state);
876
+ if (state.mode === "direct") this.classList.add("is-dragging");
877
+ if (state.effect === DragEffect.DISSOLVE) {
878
+ this.resetTransientEffect();
879
+ this.clearSelectionRegions();
880
+ }
881
+ }
882
+
883
+ if (state.effect === DragEffect.DISSOLVE) {
884
+ this.selectionDirty = true;
885
+ this.startDissolveClock();
886
+ return;
887
+ }
888
+
889
+ const width = this.gestureWidth;
890
+ const travelled = clamp(distance / (width * 0.82), 0, 1);
891
+ if (state.effect === DragEffect.MOVE) {
892
+ event.preventDefault();
893
+ this.offsetX = state.baseX + dx;
894
+ this.offsetY = state.baseY + dy;
895
+ this.style.setProperty("--sf-x", `${this.offsetX}px`);
896
+ this.style.setProperty("--sf-y", `${this.offsetY}px`);
897
+ this.publishProgress(travelled, state.effect);
898
+ return;
899
+ }
900
+ if (state.effect === DragEffect.SHAKE) {
901
+ event.preventDefault();
902
+ this.setShake(travelled);
903
+ return;
904
+ }
905
+ if (state.effect === DragEffect.ELASTIC) {
906
+ event.preventDefault();
907
+ this.setElastic(createElasticTransform(dx, dy, width));
908
+ return;
909
+ }
910
+ }
911
+
912
+ onPointerEnd(event) {
913
+ const state = this.gesture;
914
+ if ((state.tag !== GestureTag.PRESSED && state.tag !== GestureTag.ACTIVE) || event.pointerId !== state.pointerId) return;
915
+ this.classList.remove("is-dragging");
916
+ if (this.hasPointerCapture(event.pointerId)) this.releasePointerCapture(event.pointerId);
917
+ this.finishGesture(state, event.type === "pointercancel");
918
+ }
919
+
920
+ onWindowBlur() {
921
+ const state = this.gesture;
922
+ if (state.tag !== GestureTag.PRESSED && state.tag !== GestureTag.ACTIVE) return;
923
+ this.classList.remove("is-dragging");
924
+ if (this.hasPointerCapture(state.pointerId)) this.releasePointerCapture(state.pointerId);
925
+ this.finishGesture(state, true);
926
+ }
927
+
928
+ onSelectionChange() {
929
+ if (!ownedSelection(this)) this.selectionIndicator.clear();
930
+ const pointer = this.selectionDrag?.getDrag();
931
+ if (pointer) this.adoptSelectionDrag(pointer);
932
+ if (this.gesture.tag === GestureTag.ACTIVE && this.gesture.effect === DragEffect.DISSOLVE) {
933
+ this.selectionDirty = true;
934
+ this.startDissolveClock();
935
+ return;
936
+ }
937
+ if (this.gesture.tag !== GestureTag.SELECTED) return;
938
+ if (ownedSelection(this)) {
939
+ this.selectionDirty = true;
940
+ this.startDissolveClock();
941
+ return;
942
+ }
943
+ this.stopDissolveClock();
944
+ this.restoreDissolve();
945
+ }
946
+
947
+ adoptSelectionDrag(pointer, finished = false) {
948
+ if (this.interactionMode() !== "select" || this.dragEffect() !== DragEffect.DISSOLVE) return;
949
+ if (![GestureTag.IDLE, GestureTag.RESTORING, GestureTag.SELECTED].includes(this.gesture.tag)) return;
950
+ if (!ownedSelection(this)) return;
951
+ this.cancelRestore();
952
+ this.stopDissolveClock();
953
+ this.resetTransientEffect();
954
+ this.clearSelectionRegions();
955
+ this.selectionDirty = true;
956
+ this.transitionTo(pressedGesture("select", pointer.pointerId, pointer.startX, pointer.startY, this.offsetX, this.offsetY, DragEffect.DISSOLVE));
957
+ this.transitionTo(activeGesture(this.gesture));
958
+ if (finished) this.transitionTo(selectedGesture(DragEffect.DISSOLVE));
959
+ this.startDissolveClock();
960
+ }
961
+
962
+ finishGesture(state, cancelled = false) {
963
+ if (state.effect === DragEffect.MOVE) {
964
+ this.effectProgress = 0;
965
+ this.publishProgress(0, state.effect);
966
+ this.transitionTo(idleGesture());
967
+ return;
968
+ }
969
+ if (state.effect === DragEffect.SHAKE) {
970
+ this.restoreShake();
971
+ return;
972
+ }
973
+ if (state.effect === DragEffect.ELASTIC) {
974
+ this.restoreElastic();
975
+ return;
976
+ }
977
+ const hasSelection = this.captureSelectionRegions();
978
+ if (this.dissolveStartedAt !== null && hasSelection) {
979
+ const duration = numberAttribute(this, "dissolve-ms", DEFAULT_DISSOLVE_MS, 200, 10_000);
980
+ if (!this.setDissolve(dissolveProgress(performance.now() - this.dissolveStartedAt, duration))) return;
981
+ }
982
+ if (!cancelled && state.tag === GestureTag.ACTIVE && hasSelection && ownedSelection(this)) {
983
+ this.transitionTo(selectedGesture(DragEffect.DISSOLVE));
984
+ this.startDissolveClock();
985
+ return;
986
+ }
987
+ this.stopDissolveClock();
988
+ this.restoreDissolve();
989
+ }
990
+
991
+ startDissolveClock() {
992
+ if (this.dissolveFrame !== 0) return;
993
+ const tick = now => {
994
+ this.dissolveFrame = 0;
995
+ const state = this.gesture;
996
+ if ((state.tag !== GestureTag.ACTIVE && state.tag !== GestureTag.SELECTED) || state.effect !== DragEffect.DISSOLVE) return;
997
+ if (this.selectionDirty) {
998
+ if (!this.captureSelectionRegions()) this.clearSelectionRegions();
999
+ this.selectionDirty = false;
1000
+ }
1001
+ const hasSelection = this.selectionRegions.length > 0 && ownedSelection(this);
1002
+ if (!hasSelection) {
1003
+ if (state.tag === GestureTag.SELECTED) {
1004
+ this.stopDissolveClock();
1005
+ this.restoreDissolve();
1006
+ } else {
1007
+ this.setDissolve(0);
1008
+ this.dissolveStartedAt = null;
1009
+ this.dissolveFrame = requestAnimationFrame(tick);
1010
+ }
1011
+ return;
1012
+ }
1013
+ this.dissolveStartedAt ??= now;
1014
+ const duration = numberAttribute(this, "dissolve-ms", DEFAULT_DISSOLVE_MS, 200, 10_000);
1015
+ const progress = dissolveProgress(now - this.dissolveStartedAt, duration);
1016
+ if (!this.setDissolve(progress)) return;
1017
+ this.dissolveFrame = progress < 1 ? requestAnimationFrame(tick) : 0;
1018
+ };
1019
+ this.dissolveFrame = requestAnimationFrame(tick);
1020
+ }
1021
+
1022
+ stopDissolveClock() {
1023
+ if (this.dissolveFrame !== 0) cancelAnimationFrame(this.dissolveFrame);
1024
+ this.dissolveFrame = 0;
1025
+ this.dissolveStartedAt = null;
1026
+ }
1027
+
1028
+ captureSelectionRegions() {
1029
+ const geometry = selectionGeometry(this);
1030
+ if (!geometry) { this.selectionIndicator.clear(); return false; }
1031
+ const { regions, viewportRects } = geometry;
1032
+ if (this.interactionMode() === "select" && this.inViewport && !document.hidden) {
1033
+ try { this.selectionIndicator.update(viewportRects); }
1034
+ catch (error) { this.reportRendererError(error, "selection"); return false; }
1035
+ }
1036
+ if (sameRegions(this.selectionRegions, regions)) return true;
1037
+ this.selectionRegions = regions;
1038
+ this.maskField = null;
1039
+ this.renderedMaskStep = -1;
1040
+ return true;
1041
+ }
1042
+
1043
+ clearSelectionRegions() {
1044
+ this.selectionIndicator.clear();
1045
+ if (this.selectionRegions.length > 0) {
1046
+ this.selectionRegions = [];
1047
+ this.maskField = null;
1048
+ this.renderedMaskStep = -1;
1049
+ }
1050
+ }
1051
+
1052
+ invalidateMask() {
1053
+ this.maskGeometry = null;
1054
+ this.maskField = null;
1055
+ this.renderedMaskStep = -1;
1056
+ this.selectionDirty = true;
1057
+ if (this.dissolve > 0) {
1058
+ if (ownedSelection(this)) this.captureSelectionRegions();
1059
+ this.setDissolve(this.dissolve);
1060
+ }
1061
+ }
1062
+
1063
+ prepareMask() {
1064
+ if (this.maskField) return this.maskField;
1065
+ if (!this.maskGeometry) this.maskGeometry = this.measureMask();
1066
+ const { width, height, scaleX, scaleY, lineHeight, direction, flow, roughness, seed } = this.maskGeometry;
1067
+ if (!this.maskTexture || this.maskTexture.width !== width || this.maskTexture.height !== height || this.maskTexture.seed !== seed) {
1068
+ this.maskTexture = { width, height, seed, texture: createErosionField(width, height, { seed }) };
1069
+ }
1070
+ const regions = this.selectionRegions.map(region => ({
1071
+ x: region.x * scaleX,
1072
+ y: region.y * scaleY,
1073
+ width: region.width * scaleX,
1074
+ height: region.height * scaleY
1075
+ }));
1076
+ this.maskField = createMaskField(width, height, {
1077
+ lineHeight, direction, flow, roughness, seed, regions, texture: this.maskTexture.texture
1078
+ });
1079
+ if (!this.maskSurface || this.maskSurface.canvas.width !== width || this.maskSurface.canvas.height !== height) {
1080
+ this.disposeMaskRenderer();
1081
+ this.maskSurface = createMaskRenderer(this.rendererKind(), width, height, error => this.reportRendererError(error));
1082
+ this.dataset.rendererStatus = "ready";
1083
+ }
1084
+ return this.maskField;
1085
+ }
1086
+
1087
+ measureMask() {
1088
+ const rect = measurePaintLayout(this);
1089
+ const scale = Math.min(1, 768 / Math.max(1, rect.width), 384 / Math.max(1, rect.height),
1090
+ Math.sqrt(MAX_MASK_PIXELS / Math.max(1, rect.width * rect.height)));
1091
+ const width = Math.max(1, Math.floor(rect.width * scale));
1092
+ const height = Math.max(1, Math.floor(rect.height * scale));
1093
+ const scaleX = width / Math.max(1, rect.width);
1094
+ const scaleY = height / Math.max(1, rect.height);
1095
+ const computed = getComputedStyle(this);
1096
+ const rawLineHeight = Number.parseFloat(computed.lineHeight);
1097
+ const rawFontSize = Number.parseFloat(computed.fontSize) || 16;
1098
+ const lineHeight = Math.min(height, Math.max(1, (Number.isFinite(rawLineHeight) ? rawLineHeight : rawFontSize * 1.2) * scaleY));
1099
+ const flow = this.selectionFlow();
1100
+ const direction = flow === "rtl"
1101
+ ? "rtl"
1102
+ : flow === "ltr"
1103
+ ? "ltr"
1104
+ : computed.direction === "rtl" ? "rtl" : "ltr";
1105
+ const roughness = numberAttribute(this, "roughness", 0.26, 0, 0.48);
1106
+ const seed = hashText(this.textContent ?? "");
1107
+ return { width, height, scaleX, scaleY, lineHeight, direction, flow, roughness, seed };
1108
+ }
1109
+
1110
+ setDissolve(progress) {
1111
+ this.dissolve = clamp(progress, 0, 1);
1112
+ const step = Math.round(this.dissolve * MASK_STEPS);
1113
+ if (step === 0 || this.selectionRegions.length === 0) {
1114
+ this.dissolveMaskImage = "none";
1115
+ this.commitMasks();
1116
+ this.renderedMaskStep = -1;
1117
+ } else if (this.renderedMaskStep !== step) {
1118
+ try {
1119
+ const field = this.prepareMask();
1120
+ const mask = `url("${this.maskSurface.render(field, step / MASK_STEPS)}")`;
1121
+ this.dissolveMaskImage = mask;
1122
+ this.commitMasks();
1123
+ this.renderedMaskStep = step;
1124
+ } catch (error) {
1125
+ this.reportRendererError(error);
1126
+ return false;
1127
+ }
1128
+ }
1129
+ this.classList.toggle("is-effect-active", this.dissolve > 0.001);
1130
+ this.publishProgress(this.dissolve, DragEffect.DISSOLVE);
1131
+ return true;
1132
+ }
1133
+
1134
+ publishProgress(progress, effect = this.dragEffect()) {
1135
+ this.effectProgress = clamp(progress, 0, 1);
1136
+ this.dispatchEvent(new CustomEvent("shaderfont-progress", {
1137
+ bubbles: true,
1138
+ detail: {
1139
+ dissolve: this.dissolve,
1140
+ progress: this.effectProgress,
1141
+ effect,
1142
+ state: this.gesture.tag,
1143
+ x: this.offsetX,
1144
+ y: this.offsetY
1145
+ }
1146
+ }));
1147
+ }
1148
+
1149
+ setShake(progress) {
1150
+ const amount = clamp(progress, 0, 1);
1151
+ const small = 0.7 + amount * 2.1;
1152
+ const large = 1.8 + amount * 5.2;
1153
+ const angle = 0.25 + amount * 1.15;
1154
+ this.style.setProperty("--sf-shake-small", `${small.toFixed(2)}px`);
1155
+ this.style.setProperty("--sf-shake-large", `${large.toFixed(2)}px`);
1156
+ this.style.setProperty("--sf-shake-neg-small", `${(-small).toFixed(2)}px`);
1157
+ this.style.setProperty("--sf-shake-neg-large", `${(-large).toFixed(2)}px`);
1158
+ this.style.setProperty("--sf-shake-angle", `${angle.toFixed(2)}deg`);
1159
+ this.style.setProperty("--sf-shake-neg-angle", `${(-angle).toFixed(2)}deg`);
1160
+ this.classList.add("is-effect-active");
1161
+ this.publishProgress(amount, DragEffect.SHAKE);
1162
+ }
1163
+
1164
+ applyElasticMotion(motion) {
1165
+ this.elasticMotion = motion;
1166
+ this.style.setProperty("--sf-effect-x", `${motion.x.toFixed(3)}px`);
1167
+ this.style.setProperty("--sf-effect-y", `${motion.y.toFixed(3)}px`);
1168
+ this.style.setProperty("--sf-effect-rotate", `${motion.rotate.toFixed(3)}deg`);
1169
+ this.style.setProperty("--sf-effect-scale-x", motion.scaleX.toFixed(4));
1170
+ this.style.setProperty("--sf-effect-scale-y", motion.scaleY.toFixed(4));
1171
+ }
1172
+
1173
+ setElastic(motion) {
1174
+ this.classList.add("is-effect-active");
1175
+ this.applyElasticMotion(motion);
1176
+ this.publishProgress(motion.amount, DragEffect.ELASTIC);
1177
+ }
1178
+
1179
+ resetMotionVariables() {
1180
+ this.classList.remove("is-effect-active");
1181
+ this.style.setProperty("--sf-effect-x", "0px");
1182
+ this.style.setProperty("--sf-effect-y", "0px");
1183
+ this.style.setProperty("--sf-effect-rotate", "0deg");
1184
+ this.style.setProperty("--sf-effect-scale-x", "1");
1185
+ this.style.setProperty("--sf-effect-scale-y", "1");
1186
+ this.elasticMotion = createElasticTransform(0, 0, 1);
1187
+ }
1188
+
1189
+ resetTransientEffect() {
1190
+ this.dissolve = 0;
1191
+ this.effectProgress = 0;
1192
+ this.dissolveMaskImage = "none";
1193
+ this.commitMasks();
1194
+ this.renderedMaskStep = -1;
1195
+ this.resetMotionVariables();
1196
+ }
1197
+
1198
+ cancelRestore() {
1199
+ this.restoreToken += 1;
1200
+ if (this.restoreFrame !== 0) cancelAnimationFrame(this.restoreFrame);
1201
+ this.restoreFrame = 0;
1202
+ if (this.restoreTimer !== 0) {
1203
+ clearTimeout(this.restoreTimer);
1204
+ this.restoreTimer = 0;
1205
+ }
1206
+ }
1207
+
1208
+ completeMotionRestore(token, effect) {
1209
+ if (token !== this.restoreToken || this.gesture.tag !== GestureTag.RESTORING || this.gesture.token !== token) return;
1210
+ if (this.restoreTimer !== 0) {
1211
+ clearTimeout(this.restoreTimer);
1212
+ this.restoreTimer = 0;
1213
+ }
1214
+ if (this.restoreFrame !== 0) cancelAnimationFrame(this.restoreFrame);
1215
+ this.restoreFrame = 0;
1216
+ this.resetMotionVariables();
1217
+ this.publishProgress(0, effect);
1218
+ this.transitionTo(idleGesture());
1219
+ }
1220
+
1221
+ restoreShake() {
1222
+ const initial = this.effectProgress;
1223
+ this.cancelRestore();
1224
+ const token = this.restoreToken;
1225
+ this.classList.remove("is-effect-active");
1226
+ if (initial <= 0.001) {
1227
+ this.resetMotionVariables();
1228
+ this.publishProgress(0, DragEffect.SHAKE);
1229
+ this.transitionTo(idleGesture());
1230
+ return;
1231
+ }
1232
+ this.transitionTo(restoringGesture(token));
1233
+ const reduceMotion = matchMedia("(prefers-reduced-motion: reduce)").matches;
1234
+ const duration = reduceMotion ? 0 : SHAKE_RESTORE_MS;
1235
+ this.restoreTimer = window.setTimeout(
1236
+ () => this.completeMotionRestore(token, DragEffect.SHAKE),
1237
+ duration
1238
+ );
1239
+ }
1240
+
1241
+ restoreElastic() {
1242
+ const initial = this.elasticMotion;
1243
+ const initialProgress = this.effectProgress;
1244
+ this.cancelRestore();
1245
+ const token = this.restoreToken;
1246
+ if (initialProgress <= 0.001) {
1247
+ this.resetMotionVariables();
1248
+ this.publishProgress(0, DragEffect.ELASTIC);
1249
+ this.transitionTo(idleGesture());
1250
+ return;
1251
+ }
1252
+
1253
+ const reduceMotion = matchMedia("(prefers-reduced-motion: reduce)").matches;
1254
+ const duration = reduceMotion
1255
+ ? 100
1256
+ : numberAttribute(this, "restore-ms", ELASTIC_RESTORE_MS, 100, 10_000);
1257
+ this.transitionTo(restoringGesture(token));
1258
+ this.restoreTimer = window.setTimeout(
1259
+ () => this.completeMotionRestore(token, DragEffect.ELASTIC),
1260
+ duration + 100
1261
+ );
1262
+ const startedAt = performance.now();
1263
+ const tick = now => {
1264
+ if (token !== this.restoreToken || this.gesture.tag !== GestureTag.RESTORING || this.gesture.token !== token) return;
1265
+ const elapsed = clamp((now - startedAt) / duration, 0, 1);
1266
+ const factor = reduceMotion ? 1 - elapsed : dampedSpringFactor(elapsed);
1267
+ this.applyElasticMotion({
1268
+ x: initial.x * factor,
1269
+ y: initial.y * factor,
1270
+ rotate: initial.rotate * factor,
1271
+ scaleX: 1 + (initial.scaleX - 1) * factor,
1272
+ scaleY: 1 + (initial.scaleY - 1) * factor,
1273
+ amount: initialProgress * (1 - elapsed)
1274
+ });
1275
+ this.publishProgress(initialProgress * (1 - elapsed), DragEffect.ELASTIC);
1276
+ if (elapsed < 1) this.restoreFrame = requestAnimationFrame(tick);
1277
+ else this.completeMotionRestore(token, DragEffect.ELASTIC);
1278
+ };
1279
+ this.restoreFrame = requestAnimationFrame(tick);
1280
+ }
1281
+
1282
+ completeRestore(token) {
1283
+ if (token !== this.restoreToken || this.gesture.tag !== GestureTag.RESTORING || this.gesture.token !== token) return;
1284
+ if (this.restoreTimer !== 0) {
1285
+ clearTimeout(this.restoreTimer);
1286
+ this.restoreTimer = 0;
1287
+ }
1288
+ if (this.restoreFrame !== 0) cancelAnimationFrame(this.restoreFrame);
1289
+ this.restoreFrame = 0;
1290
+ this.setDissolve(0);
1291
+ this.clearSelectionRegions();
1292
+ if (this.maskSurface?.kind === "webgl") this.disposeMaskRenderer();
1293
+ this.transitionTo(idleGesture());
1294
+ }
1295
+
1296
+ restoreDissolve() {
1297
+ this.selectionIndicator.clear();
1298
+ this.stopDissolveClock();
1299
+ const initial = this.dissolve;
1300
+ this.cancelRestore();
1301
+ const token = this.restoreToken;
1302
+ if (initial <= 0.001) {
1303
+ this.transitionTo(idleGesture());
1304
+ this.setDissolve(0);
1305
+ this.clearSelectionRegions();
1306
+ return;
1307
+ }
1308
+
1309
+ const reduceMotion = matchMedia("(prefers-reduced-motion: reduce)").matches;
1310
+ const duration = reduceMotion ? 80 : numberAttribute(this, "restore-ms", DEFAULT_RESTORE_MS, 100, 10_000);
1311
+ this.transitionTo(restoringGesture(token));
1312
+ this.restoreTimer = window.setTimeout(() => this.completeRestore(token), duration + 100);
1313
+ const startedAt = performance.now();
1314
+ const tick = now => {
1315
+ if (token !== this.restoreToken || this.gesture.tag !== GestureTag.RESTORING || this.gesture.token !== token) return;
1316
+ const elapsed = clamp((now - startedAt) / duration, 0, 1);
1317
+ const eased = elapsed * elapsed * (3 - 2 * elapsed);
1318
+ if (!this.setDissolve(initial * (1 - eased))) return;
1319
+ if (elapsed < 1) this.restoreFrame = requestAnimationFrame(tick);
1320
+ else this.completeRestore(token);
1321
+ };
1322
+ this.restoreFrame = requestAnimationFrame(tick);
1323
+ }
1324
+
1325
+ resetPosition() {
1326
+ this.cancelRestore();
1327
+ this.stopDissolveClock();
1328
+ const state = this.gesture;
1329
+ if ((state.tag === GestureTag.PRESSED || state.tag === GestureTag.ACTIVE) && this.hasPointerCapture(state.pointerId)) {
1330
+ this.releasePointerCapture(state.pointerId);
1331
+ }
1332
+ this.classList.remove("is-dragging", "is-effect-active");
1333
+ this.transitionTo(idleGesture());
1334
+ this.offsetX = 0;
1335
+ this.offsetY = 0;
1336
+ this.style.setProperty("--sf-x", "0px");
1337
+ this.style.setProperty("--sf-y", "0px");
1338
+ this.resetTransientEffect();
1339
+ this.disposeMaskRenderer();
1340
+ this.clearRendererError();
1341
+ this.syncMaterialPlayback();
1342
+ this.restartReveal();
1343
+ this.publishProgress(0, this.dragEffect());
1344
+ this.clearSelectionRegions();
1345
+ }
1346
+ }
1347
+
1348
+ export function upgradeLegacyShaderfont(root = document) {
1349
+ const aliases = [];
1350
+ if (root instanceof Element && root.matches("shaderfont")) aliases.push(root);
1351
+ if (typeof root.querySelectorAll === "function") aliases.push(...root.querySelectorAll("shaderfont"));
1352
+ return aliases.map(alias => {
1353
+ const replacement = document.createElement("shader-font");
1354
+ for (const attribute of alias.attributes) replacement.setAttribute(attribute.name, attribute.value);
1355
+ while (alias.firstChild) replacement.append(alias.firstChild);
1356
+ alias.replaceWith(replacement);
1357
+ return replacement;
1358
+ });
1359
+ }
1360
+
1361
+ let aliasObserver;
1362
+
1363
+ export function registerShaderFontElement({ legacyAliases = false, styleNonce } = {}) {
1364
+ ensureStyles(styleNonce);
1365
+ if (!customElements.get("shader-font")) customElements.define("shader-font", ShaderFont);
1366
+ // Only the legacy script API needs a document-wide alias observer.
1367
+ if (legacyAliases && !aliasObserver) {
1368
+ upgradeLegacyShaderfont();
1369
+ aliasObserver = new MutationObserver(records => {
1370
+ for (const record of records) {
1371
+ for (const node of record.addedNodes) {
1372
+ if (node.nodeType === Node.ELEMENT_NODE) upgradeLegacyShaderfont(node);
1373
+ }
1374
+ }
1375
+ });
1376
+ aliasObserver.observe(document.documentElement, { childList: true, subtree: true });
1377
+ }
1378
+ return customElements.get("shader-font");
1379
+ }