-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFontLabOnline.html
More file actions
750 lines (675 loc) · 47.7 KB
/
FontLabOnline.html
File metadata and controls
750 lines (675 loc) · 47.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
<!DOCTYPE html>
<html lang="en" data-theme="light">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Enhanced Typography Playground</title>
<meta name="color-scheme" content="light dark">
<style>
/* ===== CSS RESET (modern minimal) ===== */
*, *::before, *::after { box-sizing: border-box; }
html, body { height: 100%; }
body { margin: 0; font-family: system-ui, -apple-system, Segoe UI, Roboto, Inter, Arial, sans-serif; line-height: 1.5; }
img, svg { display: block; max-width: 100%; }
button, input, select, textarea { font: inherit; }
/* ===== THEME TOKENS ===== */
:root {
--bg: #f4f6f8; /* page background */
--panel: #ffffff; /* surface */
--text: #111418; /* primary text */
--muted: #5b6068; /* secondary text */
--accent: #6b8afd; /* primary accent */
--accent-2: #13c6a8; /* secondary accent */
--danger: #e5484d; /* error */
--ok: #18a957; /* success */
--border: #dde1e7;
--shadow: 0 6px 18px rgba(0,0,0,.08);
--radius: 14px;
--mono: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace;
}
[data-theme="dark"] {
--bg: #0f1216;
--panel: #171b21;
--text: #e8eaee;
--muted: #b2b9c3;
--accent: #8aa4ff;
--accent-2: #2bd8b8;
--border: #2a313b;
--shadow: 0 10px 30px rgba(0,0,0,.35);
}
body { background: radial-gradient(1200px 800px at 20% -10%, rgba(107,138,253,.12), transparent 60%), radial-gradient(1200px 800px at 120% 120%, rgba(43,216,184,.12), transparent 60%), var(--bg); color: var(--text); }
/* ===== LAYOUT ===== */
.app {
display: grid;
grid-template-columns: 360px 1fr;
grid-template-rows: auto 1fr auto;
grid-template-areas: "header header" "controls preview" "code code";
gap: 16px; padding: 16px; max-width: 1400px; margin: 0 auto; min-height: 100vh;
}
header.appbar { grid-area: header; display: flex; align-items: center; justify-content: space-between; background: var(--panel); box-shadow: var(--shadow); border: 1px solid var(--border); padding: 12px 16px; border-radius: var(--radius); }
.brand { display: flex; align-items: center; gap: 12px; }
.brand .logo { width: 28px; height: 28px; border-radius: 8px; background: linear-gradient(135deg, var(--accent), var(--accent-2)); box-shadow: inset 0 0 20px rgba(255,255,255,.25); }
.brand h1 { font-size: 18px; margin: 0; }
.toolbar { display: flex; align-items: center; gap: 8px; }
.btn { display: inline-flex; align-items: center; gap: .5rem; border: 1px solid var(--border); background: var(--panel); color: var(--text); padding: 8px 12px; border-radius: 10px; cursor: pointer; box-shadow: var(--shadow); }
.btn.primary { border-color: color-mix(in oklab, var(--accent) 40%, var(--border)); background: linear-gradient(180deg, color-mix(in oklab, var(--accent) 25%, #fff 0%), color-mix(in oklab, var(--accent) 7%, #000 100%)); color: #fff; }
.btn.ghost { background: transparent; box-shadow: none; }
.btn:active { transform: translateY(1px); }
.panel { background: var(--panel); border: 1px solid var(--border); border-radius: var(--radius); box-shadow: var(--shadow); }
.controls { grid-area: controls; padding: 14px; display: grid; gap: 12px; grid-template-columns: 1fr; align-content: start; }
.group { border: 1px dashed var(--border); border-radius: 12px; padding: 10px; }
.group h2 { font-size: 14px; margin: 0 0 8px; color: var(--muted); text-transform: uppercase; letter-spacing: .06em; }
.row { display: grid; grid-template-columns: 130px 1fr auto; gap: 8px; align-items: center; margin: 6px 0; }
.row label { font-size: 12px; color: var(--muted); }
.row input[type="text"], .row input[type="number"], .row input[type="color"], .row select, .row textarea { width: 100%; padding: 8px 10px; border-radius: 8px; border: 1px solid var(--border); background: color-mix(in oklab, var(--panel) 90%, #000 10%); color: var(--text); resize: vertical; }
.row input[type="range"] { width: 100%; }
.row .mini { font-size: 12px; color: var(--muted); }
.preview { grid-area: preview; position: relative; display: grid; grid-template-rows: auto 1fr; }
.canvas { position: relative; overflow: hidden; padding: 28px; min-height: 360px; border-radius: var(--radius); border: 1px solid var(--border); background: conic-gradient(from 180deg at 50% 120%, color-mix(in oklab, var(--panel) 92%, #000 8%), color-mix(in oklab, var(--panel) 88%, #fff 12%)); }
#previewBlock { position: relative; margin: 0 auto; padding: var(--padY, 0) var(--padX, 0); max-width: var(--maxw, 70ch); text-align: var(--align, left); }
#previewText { margin: 0; transition: all .18s ease; text-wrap: balance; }
.gradient-text { background: linear-gradient(90deg, var(--grad-a, #6b8afd), var(--grad-b, #13c6a8)); -webkit-background-clip: text; background-clip: text; color: transparent; }
.stroke-on { -webkit-text-stroke: var(--stroke-w, 1px) var(--stroke-c, #000); }
.shadow-on { text-shadow: var(--shadow-v, 0 1px 2px rgba(0,0,0,.25)); }
.baseline { position: absolute; inset: 0; pointer-events: none; background-size: 100% var(--base, 24px); background-image: linear-gradient(to bottom, color-mix(in oklab, var(--accent) 25%, transparent) 1px, transparent 1px); opacity: .35; display: none; }
.baseline.on { display: block; }
.metrics { display: flex; gap: 12px; flex-wrap: wrap; padding: 10px 12px; font-size: 12px; color: var(--muted); }
.badge { padding: 2px 8px; border-radius: 999px; border: 1px solid var(--border); background: var(--panel); }
.badge.pass { border-color: color-mix(in oklab, var(--ok) 55%, var(--border)); color: var(--ok); }
.badge.fail { border-color: color-mix(in oklab, var(--danger) 55%, var(--border)); color: var(--danger); }
.code { grid-area: code; display: grid; grid-template-rows: auto 1fr; }
.tabs { display: flex; gap: 8px; padding: 8px; border-bottom: 1px solid var(--border); }
.tabs .tab { padding: 8px 10px; border-radius: 8px; border: 1px solid var(--border); background: var(--panel); cursor: pointer; }
.tabs .tab.active { outline: 2px solid color-mix(in oklab, var(--accent) 50%, transparent); }
.editor { display: none; }
.editor.active { display: block; }
pre { margin: 0; padding: 12px; font-family: var(--mono); overflow: auto; max-height: 56vh; white-space: pre; border-bottom-left-radius: var(--radius); border-bottom-right-radius: var(--radius); }
/* ===== Animations (presets) ===== */
@keyframes fadeIn { from { opacity: 0; transform: translateY(6px);} to { opacity: 1; transform: none; } }
@keyframes rotate { from { transform: rotate(0); } to { transform: rotate(360deg);} }
@keyframes bounce { 0%, 100% { transform: translateY(0);} 50% { transform: translateY(-8px);} }
@keyframes typewriter { from { width: 0; } to { width: 100%; } }
.help { font-size: 12px; color: var(--muted); }
/* Responsive */
@media (max-width: 980px) {
.app { grid-template-columns: 1fr; grid-template-areas: "header" "preview" "controls" "code"; }
.canvas { min-height: 280px; }
}
</style>
</head>
<body>
<div class="app">
<header class="appbar panel">
<div class="brand">
<div class="logo" aria-hidden="true"></div>
<h1>Enhanced Typography Playground</h1>
</div>
<div class="toolbar">
<button class="btn" id="themeToggle" title="Toggle light/dark">🌗 Theme</button>
<button class="btn" id="gridToggle" title="Toggle baseline grid">📏 Baseline</button>
<button class="btn" id="randomize">🎲 Randomize</button>
<button class="btn" id="savePreset">💾 Save</button>
<button class="btn" id="loadPreset">📂 Load</button>
<button class="btn" id="exportHTML" title="Download standalone .html">⬇️ Export .html</button>
</div>
</header>
<!-- ===== Controls ===== -->
<section class="controls panel" id="controls">
<div class="group">
<h2>Content</h2>
<div class="row">
<label for="customText">Text</label>
<textarea id="customText" rows="3">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Variable fonts, ligatures, and gradients—oh my.</textarea>
<span class="mini">Multi-line supported</span>
</div>
<div class="row">
<label for="elementTag">Element</label>
<select id="elementTag">
<option value="p"><p></option>
<option value="h1"><h1></option>
<option value="h2"><h2></option>
<option value="h3"><h3></option>
<option value="a"><a> (link)</option>
<option value="button"><button></option>
</select>
<span></span>
</div>
<div class="row">
<label for="hyperlink">Hyperlink (if link)</label>
<input type="text" id="hyperlink" placeholder="https://example.com" value="">
<span class="mini">Sanitized</span>
</div>
</div>
<div class="group">
<h2>Font & Variable Axes</h2>
<div class="row">
<label for="fontSelector">Font family</label>
<select id="fontSelector"></select>
<button class="btn ghost" id="reloadFonts" title="(Re)load web fonts">↻</button>
</div>
<div class="row"><label for="fontSize">Font size (px)</label><input type="range" id="fontSize" min="10" max="200" value="48"><input type="number" id="fontSizeN" min="10" max="200" value="48"></div>
<div class="row"><label for="fontWeight">Weight</label><input type="range" id="fontWeight" min="100" max="900" step="1" value="700"><input type="number" id="fontWeightN" min="1" max="1000" value="700"></div>
<div class="row"><label for="fontStyle">Style</label><select id="fontStyle"><option value="normal">normal</option><option value="italic">italic</option></select><span></span></div>
<div class="row"><label for="lineHeight">Line height</label><input type="range" id="lineHeight" min="0.8" max="2.2" step="0.01" value="1.2"><input type="number" id="lineHeightN" step="0.01" value="1.2"></div>
<div class="row"><label for="letterSpacing">Letter spacing (em)</label><input type="range" id="letterSpacing" min="-0.1" max="0.5" step="0.001" value="0"><input type="number" id="letterSpacingN" step="0.001" value="0"></div>
<div class="row"><label for="wordSpacing">Word spacing (px)</label><input type="range" id="wordSpacing" min="0" max="30" step="0.5" value="0"><input type="number" id="wordSpacingN" step="0.5" value="0"></div>
<div class="row"><label for="maxWidth">Max width (ch)</label><input type="range" id="maxWidth" min="20" max="100" value="70"><input type="number" id="maxWidthN" min="10" max="120" value="70"></div>
<div class="row"><label for="paddingX">Padding X (px)</label><input type="range" id="paddingX" min="0" max="80" value="0"><input type="number" id="paddingXN" min="0" max="160" value="0"></div>
<div class="row"><label for="paddingY">Padding Y (px)</label><input type="range" id="paddingY" min="0" max="80" value="0"><input type="number" id="paddingYN" min="0" max="160" value="0"></div>
<!-- Variable font axes (conditional UI) -->
<div id="axesContainer" class="help">Select a variable font to enable axes controls.</div>
</div>
<div class="group">
<h2>Decoration & Effects</h2>
<div class="row"><label for="textColor">Text color</label><input type="color" id="textColor" value="#111418"><span></span></div>
<div class="row"><label for="bgColor">Background</label><input type="color" id="bgColor" value="#ffffff"><span></span></div>
<div class="row"><label for="useGradient">Gradient fill</label><select id="useGradient"><option value="off">off</option><option value="text">text only</option><option value="background">background</option></select><span></span></div>
<div class="row"><label for="gradA">Gradient A</label><input type="color" id="gradA" value="#6b8afd"><span></span></div>
<div class="row"><label for="gradB">Gradient B</label><input type="color" id="gradB" value="#13c6a8"><span></span></div>
<div class="row"><label for="strokeWidth">Text stroke (px)</label><input type="range" id="strokeWidth" min="0" max="8" value="0"><input type="number" id="strokeWidthN" min="0" max="16" value="0"></div>
<div class="row"><label for="strokeColor">Stroke color</label><input type="color" id="strokeColor" value="#000000"><span></span></div>
<div class="row"><label for="shadowCSS">Text shadow</label><input type="text" id="shadowCSS" placeholder="e.g. 0 2px 6px rgba(0,0,0,.35)" value=""><span class="mini">comma‑separate for multiple</span></div>
<div class="row"><label for="decoration">Decoration</label><select id="decoration"><option value="none">none</option><option value="underline">underline</option><option value="overline">overline</option><option value="line-through">line-through</option></select><span></span></div>
<div class="row"><label for="decorationStyle">Deco style</label><select id="decorationStyle"><option>solid</option><option>double</option><option>dot</option><option>dashed</option><option>wavy</option></select><span></span></div>
<div class="row"><label for="decorationColor">Deco color</label><input type="color" id="decorationColor" value="#111418"><span></span></div>
<div class="row"><label for="decorationThickness">Deco thickness</label><input type="range" id="decorationThickness" min="0" max="12" value="0"><input type="number" id="decorationThicknessN" min="0" max="24" value="0"></div>
<div class="row"><label for="underlineOffset">Underline offset</label><input type="range" id="underlineOffset" min="0" max="16" value="0"><input type="number" id="underlineOffsetN" min="0" max="32" value="0"></div>
</div>
<div class="group">
<h2>Layout & Behavior</h2>
<div class="row"><label for="textAlign">Align</label><select id="textAlign"><option>left</option><option>center</option><option>right</option><option>justify</option></select><span></span></div>
<div class="row"><label for="writingMode">Writing mode</label><select id="writingMode"><option value="horizontal-tb">horizontal-tb</option><option value="vertical-rl">vertical-rl</option><option value="vertical-lr">vertical-lr</option></select><span></span></div>
<div class="row"><label for="columns">Columns</label><input type="range" id="columns" min="1" max="4" value="1"><input type="number" id="columnsN" min="1" max="6" value="1"></div>
<div class="row"><label for="hyphenate">Hyphenation</label><select id="hyphenate"><option value="auto">auto</option><option value="manual">manual</option><option value="none">none</option></select><span></span></div>
<div class="row"><label for="langAttr">Language</label><input type="text" id="langAttr" value="en"><span class="mini">for hyphenation</span></div>
<div class="row"><label for="animationPreset">Animation</label><select id="animationPreset"><option value="none">none</option><option value="fadeIn">fadeIn</option><option value="rotate">rotate</option><option value="bounce">bounce</option><option value="typewriter">typewriter</option></select><span></span></div>
<div class="row"><label for="duration">Anim duration (ms)</label><input type="range" id="duration" min="200" max="5000" step="50" value="1000"><input type="number" id="durationN" value="1000"></div>
<div class="row"><label for="iteration">Iterations</label><input type="number" id="iteration" min="1" value="1"><span class="mini">or "infinite"</span></div>
</div>
<div class="group">
<h2>OpenType features</h2>
<div class="row"><label for="ligatures">Ligatures</label><select id="ligatures"><option value="normal">normal</option><option value="none">none</option><option value="discretionary-ligatures">discretionary-ligatures</option><option value="historical-ligatures">historical-ligatures</option></select><span></span></div>
<div class="row"><label for="numeric">Numeric</label><select id="numeric"><option value="normal">normal</option><option value="oldstyle-nums">oldstyle‑nums</option><option value="lining-nums">lining‑nums</option><option value="tabular-nums">tabular‑nums</option><option value="proportional-nums">proportional‑nums</option><option value="slashed-zero">slashed‑zero</option><option value="ordinal">ordinal</option><option value="diagonal-fractions">diagonal‑fractions</option></select><span></span></div>
</div>
<div class="group">
<h2>Utilities</h2>
<div class="row"><label>JS sandbox</label><button class="btn" id="openSandbox">▶ Run</button><span class="mini">isolated iframe</span></div>
<div class="row"><label>Preset JSON</label><button class="btn" id="exportPreset">⬇ Export</button><button class="btn" id="importPreset">⬆ Import</button></div>
<div class="row"><label>Snapshot</label><button class="btn" id="exportPNG">🖼️ PNG</button><button class="btn" id="exportSVG">🔤 SVG</button></div>
</div>
</section>
<!-- ===== Preview ===== -->
<section class="preview">
<div class="canvas panel" id="canvas">
<div class="baseline" id="baseline"></div>
<div id="previewBlock" lang="en">
<p id="previewText">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Variable fonts, ligatures, and gradients—oh my.</p>
</div>
</div>
<div class="metrics" id="metrics"></div>
</section>
<!-- ===== Code output tabs ===== -->
<section class="code panel">
<div class="tabs">
<button class="tab active" data-target="htmlOut">HTML</button>
<button class="tab" data-target="cssOut">CSS</button>
<button class="tab" data-target="jsOut">JS</button>
<button class="btn" id="copyActive">📋 Copy</button>
</div>
<div class="editor active" id="htmlOut"><pre></pre></div>
<div class="editor" id="cssOut"><pre></pre></div>
<div class="editor" id="jsOut"><pre></pre></div>
</section>
</div>
<!-- ===== Sandboxed JS Runner ===== -->
<template id="sandboxTemplate">
<html><head><meta charset="utf-8"/><style>html,body{margin:0;padding:8px;font:12px/1.4 var(--mono,ui-monospace,monospace);background:#0b1020;color:#e6e8ef}#log{white-space:pre-wrap;border:1px solid #223;min-height:120px;padding:8px;border-radius:8px;background:#0e1530}textarea{width:100%;box-sizing:border-box;min-height:120px;border-radius:8px;border:1px solid #223;background:#0e1530;color:#e6e8ef;padding:8px}button{margin:8px 0;padding:6px 10px;border-radius:8px;border:1px solid #334;background:#13204a;color:#fff;cursor:pointer}</style></head>
<body>
<h3>Sandboxed JavaScript Runner</h3>
<textarea id="code">// console output appears below\nconsole.log('Hello from sandbox')</textarea>
<div>
<button id="run">Run ▶</button>
<button id="clear">Clear</button>
</div>
<div id="log" aria-live="polite"></div>
<script>
(function(){
const logEl = document.getElementById('log');
function writeLine(msg){ logEl.textContent += msg + "\n"; }
// Proxy console
const orig = console.log; console.log = function(){ orig.apply(console, arguments); writeLine(Array.from(arguments).map(v=>typeof v==='object'?JSON.stringify(v):String(v)).join(' ')); };
const runBtn = document.getElementById('run');
const clearBtn = document.getElementById('clear');
runBtn.addEventListener('click', ()=>{
const code = document.getElementById('code').value;
try { new Function(code)(); } catch(e){ writeLine('Error: '+e.message); }
});
clearBtn.addEventListener('click', ()=>{ logEl.textContent=''; });
})();
</script>
</body></html>
</template>
<script>
(function(){
// ===== Fonts (web-safe + curated variable fonts) =====
const FONTS = [
{label:'System UI', css:"system-ui, -apple-system, Segoe UI, Roboto, Arial, sans-serif"},
{label:'Georgia', css:'Georgia, serif'},
{label:'Times New Roman', css:'"Times New Roman", Times, serif'},
{label:'Garamond', css:'Garamond, serif'},
{label:'Courier New', css:'"Courier New", Courier, monospace'},
{label:'Inter (var)', css:'InterVariable, Inter, system-ui, sans-serif', google:"Inter:slnt,wght@-10..0,100..900" , axes:{wght:[100,900,1], slnt:[-10,0,1]}},
{label:'Roboto Flex (var)', css:'"Roboto Flex", system-ui, sans-serif', google:"Roboto+Flex:opsz,wght,GRAD,slnt,wdth@8..144,100..1000,-200..150,-10..0,25..151", axes:{wght:[100,1000,1], wdth:[25,151,1], slnt:[-10,0,1], opsz:[8,144,1], GRAD:[-200,150,1]}},
{label:'Recursive (var)', css:'Recursive, system-ui, sans-serif', google:"Recursive:CASL,CRSV,MONO,slnt,wght@0..1,0..1,0..1,-15..0,300..1000", axes:{wght:[300,1000,1], slnt:[-15,0,1], MONO:[0,1,.01], CASL:[0,1,.01], CRSV:[0,1,.01]}},
{label:'Source Serif 4 (var)', css:'"Source Serif 4", Georgia, serif', google:"Source+Serif+4:opsz,wght@8..60,200..900", axes:{wght:[200,900,1], opsz:[8,60,1]}},
];
// Inject Google Fonts link for selected families on demand (no API key required)
function ensureGoogleFonts(){
const fontsToLoad = new Set();
const sel = document.getElementById('fontSelector');
const opt = FONTS[sel.selectedIndex];
if (opt && opt.google) fontsToLoad.add(opt.google);
if (!fontsToLoad.size) return;
const href = 'https://fonts.googleapis.com/css2?' + Array.from(fontsToLoad).map(f=>`family=${f}`).join('&') + '&display=swap';
let link = document.getElementById('gf');
if (!link) { link = document.createElement('link'); link.id='gf'; link.rel='stylesheet'; document.head.appendChild(link); }
link.href = href;
}
// ===== DOM refs =====
const el = (id)=>document.getElementById(id);
const previewBlock = el('previewBlock');
const previewText = el('previewText');
const baseline = el('baseline');
const metrics = el('metrics');
// Populate font selector
const fontSelector = el('fontSelector');
FONTS.forEach(f=>{ const o = document.createElement('option'); o.textContent = f.label; fontSelector.appendChild(o); });
// ===== State & helpers =====
const state = {
elementTag:'p',
text: el('customText').value,
href: '',
fontIdx: 0,
size: 48,
weight: 700,
style: 'normal',
lineHeight: 1.2,
letterSpacing: 0,
wordSpacing: 0,
maxWidth: 70,
padX: 0,
padY: 0,
color: '#111418',
bg: '#ffffff',
gradMode: 'off', gradA: '#6b8afd', gradB: '#13c6a8',
strokeW: 0, strokeC: '#000000',
shadow: '',
deco: 'none', decoStyle: 'solid', decoColor: '#111418', decoThick: 0, underlineOffset: 0,
align: 'left', writingMode:'horizontal-tb', cols:1, hyphens:'auto', lang:'en',
anim:'none', duration:1000, iteration:1,
lig:'normal', numeric:'normal',
axes:{}
};
function clamp(n, min, max){ return Math.min(max, Math.max(min, n)); }
// URL sanitizer for href
function sanitizeURL(u){ try{ const url = new URL(u); const ok = ['http:','https:','mailto:','tel:'].includes(url.protocol); return ok ? u : ''; } catch{ return ''; } }
// Contrast calculations (WCAG 2.1)
function hexToRgb(h){ const r = parseInt(h.slice(1,3),16), g = parseInt(h.slice(3,5),16), b = parseInt(h.slice(5,7),16); return [r,g,b]; }
function relLuminance([r,g,b]){ const f=x=>{x/=255; return x<=0.03928? x/12.92 : Math.pow((x+0.055)/1.055, 2.4)}; const [R,G,B]=[f(r),f(g),f(b)]; return 0.2126*R+0.7152*G+0.0722*B; }
function contrastRatio(fg,bg){ const L1 = relLuminance(hexToRgb(fg)); const L2 = relLuminance(hexToRgb(bg)); const [Lmax,Lmin] = L1>L2 ? [L1,L2] : [L2,L1]; return (Lmax+0.05)/(Lmin+0.05); }
// Variable axes UI
const axesContainer = el('axesContainer');
function buildAxesUI(){
axesContainer.innerHTML = '';
const selected = FONTS[state.fontIdx];
if (!selected.axes){ axesContainer.textContent = 'Select a variable font to enable axes controls.'; return; }
Object.entries(selected.axes).forEach(([axis,[min,max,step]])=>{
const row = document.createElement('div'); row.className='row';
const label = document.createElement('label'); label.textContent = axis;
const range = document.createElement('input'); range.type='range'; range.min=min; range.max=max; range.step=step; range.value = state.axes[axis] ?? max;
const num = document.createElement('input'); num.type='number'; num.min=min; num.max=max; num.step=step; num.value = range.value;
range.addEventListener('input', ()=>{ num.value = range.value; state.axes[axis] = parseFloat(range.value); update(); });
num.addEventListener('input', ()=>{ range.value = num.value; state.axes[axis] = parseFloat(num.value); update(); });
row.append(label, range, num); axesContainer.appendChild(row);
});
}
// Bind controls
function bind(id, key, transform=(v)=>v){ const c = el(id); const n = el(id+'N'); const handler = ()=>{ state[key] = transform(c.value); if(n) n.value=c.value; update(); }; c.addEventListener('input', handler); if(n) n.addEventListener('input', ()=>{ c.value = n.value; handler(); }); }
// Content
el('customText').addEventListener('input', ()=>{ state.text = el('customText').value; update(); });
el('elementTag').addEventListener('change', ()=>{ state.elementTag = el('elementTag').value; update(); });
el('hyperlink').addEventListener('input', ()=>{ state.href = sanitizeURL(el('hyperlink').value); update(); });
// Font + core metrics
fontSelector.addEventListener('change', ()=>{ state.fontIdx = fontSelector.selectedIndex; ensureGoogleFonts(); buildAxesUI(); update(); });
el('reloadFonts').addEventListener('click', ()=>{ ensureGoogleFonts(); });
bind('fontSize','size', v=>clamp(parseInt(v,10)||48,10,200));
bind('fontWeight','weight', v=>clamp(parseInt(v,10)||400,1,1000));
bind('fontStyle','style');
bind('lineHeight','lineHeight', parseFloat);
bind('letterSpacing','letterSpacing', parseFloat);
bind('wordSpacing','wordSpacing', parseFloat);
bind('maxWidth','maxWidth', v=>clamp(parseInt(v,10)||70,10,120));
bind('paddingX','padX', v=>parseInt(v,10)||0);
bind('paddingY','padY', v=>parseInt(v,10)||0);
// Effects & decoration
bind('textColor','color');
bind('bgColor','bg');
el('useGradient').addEventListener('change', ()=>{ state.gradMode = el('useGradient').value; update(); });
bind('gradA','gradA');
bind('gradB','gradB');
bind('strokeWidth','strokeW', v=>parseInt(v,10)||0);
bind('strokeColor','strokeC');
el('shadowCSS').addEventListener('input', ()=>{ state.shadow = el('shadowCSS').value; update(); });
el('decoration').addEventListener('change', ()=>{ state.deco = el('decoration').value; update(); });
el('decorationStyle').addEventListener('change', ()=>{ state.decoStyle = el('decorationStyle').value; update(); });
bind('decorationColor','decoColor');
bind('decorationThickness','decoThick', v=>parseInt(v,10)||0);
bind('underlineOffset','underlineOffset', v=>parseInt(v,10)||0);
// Layout & behavior
el('textAlign').addEventListener('change', ()=>{ state.align = el('textAlign').value; update(); });
el('writingMode').addEventListener('change', ()=>{ state.writingMode = el('writingMode').value; update(); });
bind('columns','cols', v=>parseInt(v,10)||1);
el('hyphenate').addEventListener('change', ()=>{ state.hyphens = el('hyphenate').value; update(); });
el('langAttr').addEventListener('input', ()=>{ state.lang = el('langAttr').value || 'en'; update(); });
el('animationPreset').addEventListener('change', ()=>{ state.anim = el('animationPreset').value; update(); });
bind('duration','duration', v=>parseInt(v,10)||1000);
el('iteration').addEventListener('input', ()=>{ state.iteration = el('iteration').value; update(); });
// OpenType
el('ligatures').addEventListener('change', ()=>{ state.lig = el('ligatures').value; update(); });
el('numeric').addEventListener('change', ()=>{ state.numeric = el('numeric').value; update(); });
// Toggles
el('themeToggle').addEventListener('click', ()=>{ const t = document.documentElement.getAttribute('data-theme'); document.documentElement.setAttribute('data-theme', t==='dark'?'light':'dark'); });
el('gridToggle').addEventListener('click', ()=>{ baseline.classList.toggle('on'); update(); });
// Randomize
el('randomize').addEventListener('click', ()=>{
const rc = ()=>`#${Math.floor(Math.random()*16777215).toString(16).padStart(6,'0')}`;
state.color = rc(); el('textColor').value = state.color;
state.bg = rc(); el('bgColor').value = state.bg;
state.gradA = rc(); el('gradA').value = state.gradA;
state.gradB = rc(); el('gradB').value = state.gradB;
state.weight = Math.floor(100+Math.random()*800); el('fontWeight').value = state.weight; el('fontWeightN').value = state.weight;
update();
});
// Presets
const PRESET_KEY = 'typography-playground-presets-v2';
function savePreset(){
const name = prompt('Preset name?');
if(!name) return;
const all = JSON.parse(localStorage.getItem(PRESET_KEY)||'{}');
all[name] = state;
localStorage.setItem(PRESET_KEY, JSON.stringify(all));
alert('Saved preset: '+name);
}
function loadPreset(){
const all = JSON.parse(localStorage.getItem(PRESET_KEY)||'{}');
const names = Object.keys(all);
if(!names.length) return alert('No presets saved');
const name = prompt('Load which preset?\n'+names.join('\n'));
if(!name || !all[name]) return;
Object.assign(state, all[name]);
// reflect state into controls
fontSelector.selectedIndex = state.fontIdx;
ensureGoogleFonts(); buildAxesUI();
const reflect = (id, val)=>{ const c = el(id); const n = el(id+'N'); if(c){ c.value = val } if(n){ n.value = val } };
reflect('fontSize', state.size); reflect('fontWeight', state.weight); reflect('fontStyle', state.style);
reflect('fontSizeN', state.size); reflect('fontWeightN', state.weight);
reflect('lineHeight', state.lineHeight); reflect('lineHeightN', state.lineHeight);
reflect('letterSpacing', state.letterSpacing); reflect('letterSpacingN', state.letterSpacing);
reflect('wordSpacing', state.wordSpacing); reflect('wordSpacingN', state.wordSpacing);
reflect('maxWidth', state.maxWidth); reflect('maxWidthN', state.maxWidth);
reflect('paddingX', state.padX); reflect('paddingXN', state.padX);
reflect('paddingY', state.padY); reflect('paddingYN', state.padY);
el('textColor').value = state.color; el('bgColor').value = state.bg;
el('useGradient').value = state.gradMode; el('gradA').value = state.gradA; el('gradB').value = state.gradB;
el('strokeWidth').value = state.strokeW; el('strokeWidthN').value = state.strokeW; el('strokeColor').value = state.strokeC;
el('shadowCSS').value = state.shadow;
el('decoration').value = state.deco; el('decorationStyle').value = state.decoStyle; el('decorationColor').value = state.decoColor; el('decorationThickness').value = state.decoThick; el('underlineOffset').value = state.underlineOffset; el('underlineOffsetN').value = state.underlineOffset;
el('textAlign').value = state.align; el('writingMode').value = state.writingMode; el('columns').value = state.cols; el('columnsN').value = state.cols; el('hyphenate').value = state.hyphens; el('langAttr').value = state.lang;
el('animationPreset').value = state.anim; el('duration').value = state.duration; el('durationN').value = state.duration; el('iteration').value = state.iteration;
el('ligatures').value = state.lig; el('numeric').value = state.numeric;
el('customText').value = state.text; el('elementTag').value = state.elementTag; el('hyperlink').value = state.href;
update();
}
el('savePreset').addEventListener('click', savePreset);
el('loadPreset').addEventListener('click', loadPreset);
el('exportPreset').addEventListener('click', ()=>{
const blob = new Blob([JSON.stringify(state,null,2)], {type:'application/json'});
const a = document.createElement('a'); a.href = URL.createObjectURL(blob); a.download = 'typography-preset.json'; a.click();
});
el('importPreset').addEventListener('click', ()=>{
const input = document.createElement('input'); input.type='file'; input.accept='application/json';
input.onchange = ()=>{
const file = input.files[0]; if(!file) return;
file.text().then(txt=>{ Object.assign(state, JSON.parse(txt)); loadPreset(); });
};
input.click();
});
// Baseline grid sync
function syncBaseline(){ baseline.style.setProperty('--base', Math.max(12, Math.round(state.size*state.lineHeight/4))+'px'); }
// Build preview element (switching tag safely)
function renderPreviewElement(){
const parent = previewBlock; const current = previewText;
if (current.tagName.toLowerCase() === state.elementTag) return current;
const next = document.createElement(state.elementTag);
next.id = 'previewText';
next.textContent = current.textContent;
current.replaceWith(next);
return next;
}
function applyText(){
const node = renderPreviewElement();
const selectedFont = FONTS[state.fontIdx];
// content
node.textContent = state.text;
node.removeAttribute('href'); node.removeAttribute('role'); node.removeAttribute('target'); node.removeAttribute('rel');
if (state.elementTag === 'a' && state.href){
node.textContent = state.text || state.href;
node.setAttribute('href', state.href);
node.setAttribute('role','link');
node.setAttribute('target','_blank');
node.setAttribute('rel','noopener noreferrer');
node.style.cursor = 'pointer';
}
// baseline container props
previewBlock.style.setProperty('--maxw', state.maxWidth+'ch');
previewBlock.style.setProperty('--padX', state.padX+'px');
previewBlock.style.setProperty('--padY', state.padY+'px');
previewBlock.style.setProperty('--align', state.align);
previewBlock.style.writingMode = state.writingMode;
previewBlock.style.columnCount = String(state.cols);
previewBlock.lang = state.lang;
// text styles
const style = node.style;
style.fontFamily = selectedFont.css;
style.fontSize = state.size+'px';
style.fontWeight = state.weight;
style.fontStyle = state.style;
style.lineHeight = state.lineHeight;
style.letterSpacing = state.letterSpacing+'em';
style.wordSpacing = state.wordSpacing+'px';
style.color = state.gradMode==='text' ? 'transparent' : state.color;
style.background = '';
style.removeProperty('-webkit-text-stroke');
node.classList.toggle('gradient-text', state.gradMode==='text');
node.classList.toggle('shadow-on', !!state.shadow);
node.classList.toggle('stroke-on', state.strokeW>0);
node.style.setProperty('--stroke-w', state.strokeW+'px');
node.style.setProperty('--stroke-c', state.strokeC);
node.style.setProperty('--shadow-v', state.shadow || '');
// Gradients
if (state.gradMode==='text'){
node.style.setProperty('--grad-a', state.gradA);
node.style.setProperty('--grad-b', state.gradB);
}
previewBlock.style.background = state.gradMode==='background' ? `linear-gradient(135deg, ${state.gradA}, ${state.gradB})` : state.bg;
// Decoration
const decoColor = state.decoColor;
style.textDecorationLine = state.deco;
style.textDecorationStyle = state.decoStyle;
style.textDecorationColor = decoColor;
if (state.deco !== 'none' && state.decoThick>0) style.textDecorationThickness = state.decoThick+'px'; else style.removeProperty('text-decoration-thickness');
if (state.deco==='underline' && state.underlineOffset>0) style.textUnderlineOffset = state.underlineOffset+'px'; else style.removeProperty('text-underline-offset');
// Hyphenation
previewBlock.style.hyphens = state.hyphens;
// OpenType features
style.fontVariantLigatures = state.lig; // ligatures
style.fontVariantNumeric = state.numeric; // numbers
// Variable axes (font-variation-settings)
const axes = FONTS[state.fontIdx].axes;
if (axes){
const entries = Object.entries(axes).map(([axis])=>`"${axis}" ${state.axes[axis] ?? axes[axis][1]}`);
// also ensure weight maps to wght if exists
if (axes.wght) {
const has = entries.some(s=>s.startsWith('"wght"'));
if (!has) entries.push(`"wght" ${state.weight}`);
}
style.fontVariationSettings = entries.join(', ');
} else {
style.removeProperty('font-variation-settings');
}
// Animation
const dur = state.duration+'ms';
if (state.anim==='none') { style.animation = 'none'; node.style.width=''; }
else if (state.anim==='typewriter') { style.animation = `typewriter ${dur} steps(40,end) ${state.iteration}`; style.whiteSpace='nowrap'; style.overflow='hidden'; style.display='inline-block'; node.style.width='0'; setTimeout(()=>{ node.style.width='100%'; }, 0); }
else { style.animation = `${state.anim} ${dur} ease ${state.iteration}`; }
// container shadows vs text
previewBlock.style.boxShadow = '0 0 0 transparent';
}
// Metrics + WCAG badges
function updateMetrics(){
const ratio = contrastRatio(state.gradMode==='text'? '#000000': state.color, state.gradMode==='background' ? '#ffffff' : state.bg);
const isLarge = state.size >= 24 || (state.size >= 18.66 && state.weight >= 700); // WCAG "large text" threshold
const AA = isLarge ? 3 : 4.5; const AAA = isLarge ? 4.5 : 7;
const passAA = ratio >= AA; const passAAA = ratio >= AAA;
metrics.innerHTML = '';
const items = [
['Size', state.size+'px'],
['Line', state.lineHeight.toFixed(2)],
['Weight', state.weight],
['Contrast', ratio.toFixed(2)+' : 1'],
['AA', passAA? 'Pass':'Fail', passAA],
['AAA', passAAA? 'Pass':'Fail', passAAA]
];
items.forEach(([k,v,ok])=>{
const b = document.createElement('span'); b.className='badge'+(ok===undefined? '' : ok? ' pass':' fail'); b.textContent = `${k}: ${v}`; metrics.appendChild(b);
});
}
// Code generation
const outHTML = document.querySelector('#htmlOut pre');
const outCSS = document.querySelector('#cssOut pre');
const outJS = document.querySelector('#jsOut pre');
function generateCode(){
const selectedFont = FONTS[state.fontIdx];
const tag = state.elementTag;
const text = state.text.replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>');
const isLink = tag==='a' && state.href;
const linkAttr = isLink ? ` href="${state.href}" target="_blank" rel="noopener noreferrer"` : '';
const html = `<${tag} id="previewText"${linkAttr}>${text}</${tag}>`;
const gradBG = state.gradMode==='background' ? `background: linear-gradient(135deg, ${state.gradA}, ${state.gradB});` : `background: ${state.bg};`;
const gradTEXT = state.gradMode==='text' ? `background: linear-gradient(90deg, ${state.gradA}, ${state.gradB});\n -webkit-background-clip: text;\n background-clip: text;\n color: transparent;` : `color: ${state.color};`;
const decoT = (state.deco!=='none' && state.decoThick>0)? `\n text-decoration-thickness: ${state.decoThick}px;` : '';
const uo = (state.deco==='underline' && state.underlineOffset>0)? `\n text-underline-offset: ${state.underlineOffset}px;` : '';
const axes = FONTS[state.fontIdx].axes; let axisStr = '';
if (axes){
const entries = Object.entries(axes).map(([axis])=>`"${axis}" ${state.axes[axis] ?? axes[axis][1]}`);
if (axes.wght && !entries.some(s=>s.startsWith('"wght"'))) entries.push(`"wght" ${state.weight}`);
axisStr = `\n font-variation-settings: ${entries.join(', ')};`;
}
const css = `#previewBlock {\n max-width: ${state.maxWidth}ch;\n padding: ${state.padY}px ${state.padX}px;\n text-align: ${state.align};\n writing-mode: ${state.writingMode};\n column-count: ${state.cols};\n ${gradBG}\n}\n\n#previewText {\n font-family: ${selectedFont.css};\n font-size: ${state.size}px;\n font-weight: ${state.weight};\n font-style: ${state.style};\n line-height: ${state.lineHeight};\n letter-spacing: ${state.letterSpacing}em;\n word-spacing: ${state.wordSpacing}px;\n ${gradTEXT}\n text-decoration-line: ${state.deco};\n text-decoration-style: ${state.decoStyle};\n text-decoration-color: ${state.decoColor};${decoT}${uo}\n -webkit-text-stroke: ${state.strokeW}px ${state.strokeC};\n text-shadow: ${state.shadow || 'none'};\n font-variant-ligatures: ${state.lig};\n font-variant-numeric: ${state.numeric};${axisStr}\n animation: ${state.anim==='none' ? 'none' : `${state.anim} ${state.duration}ms ease ${state.iteration}`};\n}`;
const js = `// No library required; ensure the font is available (optional)\n// <link rel=\"stylesheet\" href=\"https://fonts.googleapis.com/css2?family=${encodeURIComponent(selectedFont.google||'Inter:slnt,wght@-10..0,100..900')}\&display=swap\">\n`;
outHTML.textContent = html;
outCSS.textContent = css;
outJS.textContent = js;
}
// Tabs + copy
document.querySelectorAll('.tab').forEach(btn=>{
btn.addEventListener('click', ()=>{
document.querySelectorAll('.tab').forEach(b=>b.classList.remove('active'));
document.querySelectorAll('.editor').forEach(e=>e.classList.remove('active'));
btn.classList.add('active');
document.getElementById(btn.dataset.target).classList.add('active');
});
});
el('copyActive').addEventListener('click', ()=>{
const active = document.querySelector('.editor.active pre');
navigator.clipboard.writeText(active.textContent).then(()=>{ el('copyActive').textContent='✅ Copied'; setTimeout(()=>el('copyActive').textContent='📋 Copy', 1200); });
});
// Export HTML (standalone snapshot)
el('exportHTML').addEventListener('click', ()=>{
const doc = `<!DOCTYPE html><html lang="${state.lang}"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>Typography Snippet</title><link rel="preconnect" href="https://fonts.googleapis.com"><link rel="preconnect" href="https://fonts.gstatic.com" crossorigin><link id="gf" rel="stylesheet" href="https://fonts.googleapis.com/css2?family=${encodeURIComponent(FONTS[state.fontIdx].google||'Inter:slnt,wght@-10..0,100..900')}&display=swap"><style>${document.querySelector('#cssOut pre').textContent}\n@keyframes fadeIn{from{opacity:0;transform:translateY(6px)}to{opacity:1;transform:none}}@keyframes rotate{from{transform:rotate(0)}to{transform:rotate(360deg)}}@keyframes bounce{0%,100%{transform:translateY(0)}50%{transform:translateY(-8px)}}@keyframes typewriter{from{width:0}to{width:100%}}</style></head><body><div id="previewBlock">${document.querySelector('#htmlOut pre').textContent}</div></body></html>`;
const blob = new Blob([doc], {type:'text/html'});
const a = document.createElement('a'); a.href = URL.createObjectURL(blob); a.download='typography-snippet.html'; a.click();
});
// Export PNG (basic canvas render of text effects)
el('exportPNG').addEventListener('click', ()=>{
const W = 1600; const P = 80; // width & padding
const canvas = document.createElement('canvas'); canvas.width=W; canvas.height = Math.max(400, Math.ceil(state.size*state.lineHeight* (state.text.split(/\n/).length + 4)));
const ctx = canvas.getContext('2d');
// background
if (state.gradMode==='background'){
const g = ctx.createLinearGradient(0,0,W,canvas.height);
g.addColorStop(0, state.gradA); g.addColorStop(1, state.gradB);
ctx.fillStyle = g; ctx.fillRect(0,0,W,canvas.height);
} else { ctx.fillStyle = state.bg; ctx.fillRect(0,0,W,canvas.height); }
// text
const fontStack = FONTS[state.fontIdx].css.split(',')[0];
const weight = state.weight; const style = state.style;
ctx.font = `${style} ${weight} ${state.size}px ${fontStack}`;
ctx.textBaseline = 'top';
const lines = state.text.split(/\n/);
const lineH = state.size*state.lineHeight;
let y = P;
if (state.gradMode==='text'){
const gg = ctx.createLinearGradient(P, P, W-P, P);
gg.addColorStop(0, state.gradA); gg.addColorStop(1, state.gradB);
ctx.fillStyle = gg;
} else { ctx.fillStyle = state.color; }
if (state.strokeW>0){ ctx.lineWidth = state.strokeW; ctx.strokeStyle = state.strokeC; }
// very simple shadow: first value only
if (state.shadow){
const m = state.shadow.match(/(-?\d+)\s+(-?\d+)\s+(\d+)/);
if (m){ ctx.shadowOffsetX=parseInt(m[1],10); ctx.shadowOffsetY=parseInt(m[2],10); ctx.shadowBlur=parseInt(m[3],10); ctx.shadowColor = '#00000080'; }
}
lines.forEach(line=>{
const x = P;
if (state.strokeW>0) ctx.strokeText(line, x, y);
ctx.fillText(line, x, y);
y += lineH;
});
const a = document.createElement('a'); a.href = canvas.toDataURL('image/png'); a.download='typography.png'; a.click();
});
// Export SVG (vector text with styles subset)
el('exportSVG').addEventListener('click', ()=>{
const safeText = state.text.replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>');
const w = 1600; const lh = state.size*state.lineHeight; const lines = safeText.split(/\n/);
const h = Math.max(400, Math.ceil(lh*(lines.length+2)));
const y0 = 80 + state.size; let y = y0;
const fill = state.gradMode==='text' ? `url(#grad1)` : state.color;
const stroke = state.strokeW>0 ? `stroke="${state.strokeC}" stroke-width="${state.strokeW}"` : '';
const grad = state.gradMode==='text' ? `<defs><linearGradient id="grad1" x1="0" y1="0" x2="1" y2="0"><stop offset="0%" stop-color="${state.gradA}"/><stop offset="100%" stop-color="${state.gradB}"/></linearGradient></defs>` : '';
const textEls = lines.map(line=>{ const t = `<text x="80" y="${(y+=lh)}" font-family="${FONTS[state.fontIdx].css.split(',')[0].replace(/\"/g,'')}" font-size="${state.size}" font-weight="${state.weight}" fill="${fill}" ${stroke}>${line}</text>`; return t; }).join('\n');
const svg = `<?xml version="1.0" encoding="UTF-8"?><svg xmlns="http://www.w3.org/2000/svg" width="${w}" height="${h}" viewBox="0 0 ${w} ${h}">${grad}<rect width="100%" height="100%" fill="${state.gradMode==='background'?'' : state.bg}"/>${textEls}</svg>`;
const blob = new Blob([svg], {type:'image/svg+xml'});
const a = document.createElement('a'); a.href = URL.createObjectURL(blob); a.download='typography.svg'; a.click();
});
// Sandbox window
el('openSandbox').addEventListener('click', ()=>{
const tpl = document.getElementById('sandboxTemplate').innerHTML;
const win = window.open('', '_blank', 'noopener,noreferrer,width=640,height=520');
win.document.open(); win.document.write(tpl); win.document.close();
});
// Tabs init + font init + first render
ensureGoogleFonts();
buildAxesUI();
function update(){ applyText(); syncBaseline(); updateMetrics(); generateCode(); }
// Initial draw + gentle poll to catch font load
update();
const interval = setInterval(update, 1000); // keep original feature: periodic refresh
setTimeout(()=>clearInterval(interval), 120000); // stop after 2 minutes to save CPU
// Persist UI state between reloads
window.addEventListener('beforeunload', ()=>{ localStorage.setItem('typography-playground-last', JSON.stringify(state)); });
(function restore(){ const s = localStorage.getItem('typography-playground-last'); if(!s) return; try{ Object.assign(state, JSON.parse(s)); }catch{} })();
})();
</script>
</body>
</html>