shaderfont 0.0.0-stage → 0.5.3

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