Repository navigation
Expand file tree
/
Copy patheditor.js
More file actions
609 lines (598 loc) · 32.3 KB
/
Copy patheditor.js
File metadata and controls
609 lines (598 loc) · 32.3 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
"use strict";
/* ---------- State ---------- */
const GEO = { B: .034, C: .166, F: .52, G: .53, H: .636, I: .97, J: 90, hx: .495 };
const DEFAULTS = {
mode: "solid", c: "#0a2a6c", f1: "#0a2a6c", f2: "#e3202b",
stops: ["#d63a2f", "#ef8a22", "#f4d23c", "#4fae4a", "#2f7fd0"], angle: 180,
bgOn: true, bg: "#ffffff",
outW: 0, outC: "#1c1c1c",
exD: 0, exA: 45, exC: "#1c1c1c",
shX: .02, shY: .03, shB: .02, shC: "#000000", shO: 0,
glS: 0, glC: "#8f82f0", glO: .8,
scan: 0, scanP: .03,
rot: 0, skew: 0, flip: false, anim: "none", dur: 3,
...GEO,
};
/* [min, max, step]; the ranges keep the hole inside the ring */
const RANGE = {
angle: [0, 360, 1], outW: [0, .04, .001], exD: [0, .3, .005], exA: [0, 360, 1],
shX: [-.2, .2, .005], shY: [-.2, .2, .005], shB: [0, .12, .002], shO: [0, 1, .01],
glS: [0, .15, .002], glO: [0, 1, .01], scan: [0, 1, .01], scanP: [.01, .1, .001],
rot: [-180, 180, 1], skew: [-40, 40, 1], dur: [.5, 12, .1],
B: [0, .15, .001], C: [.05, .3, .001], F: [.2, .66, .001], G: [.2, .66, .001],
H: [.5, .8, .001], I: [.92, 1.05, .001], J: [40, 160, 1], hx: [.44, .54, .001],
};
const ENUM = { mode: ["solid", "gradient", "stripes"], anim: ["none", "spin", "pulse", "hue"] };
const solid = (c, bg, f2 = c) => ({ c, f1: c, f2, bg });
const PRESETS = {
classic: ["Blue and red", {}],
solid: ["Solid", solid("#1c1c1c", "#e8e8e7")],
reversed: ["Reversed", solid("#f4f4f2", "#161616")],
rainbow: ["Rainbow", { mode: "stripes", bg: "#c9bfa8" }],
crt: ["Scanlines", { ...solid("#a9a0ff", "#352879"), scan: .4, scanP: .024, glS: .04, glO: .67 }],
chrome: ["Chrome", { mode: "gradient", bg: "#3a3d42", stops: ["#fdfdfd", "#b9bec6", "#6d747e", "#d9dde2", "#8c929b"], shX: 0, shY: .014, shB: .014, shO: .5 }],
outline: ["Outline", { ...solid("#ffffff", "#ffffff"), outW: .008 }],
red: ["White on red", solid("#ffffff", "#e3202b")],
blue: ["On blue", solid("#ffffff", "#0a2a6c", "#e3202b")],
block: ["Block", { ...solid("#f4d23c", "#2f7fd0", "#ffffff"), outW: .01, exD: .1 }],
neon: ["Neon", { ...solid("#12061f", "#12061f"), outW: .012, outC: "#ff5fd2", glS: .035, glC: "#ff2fb9", glO: 1 }],
dusk: ["Dusk", { mode: "gradient", bg: "#1d1330", stops: ["#ffd166", "#ef476f", "#6a3fb5"], scan: .25, scanP: .05 }],
};
const HEX = /^#[0-9a-f]{6}$/i;
/* Everything that reaches CSS/SVG/HTML goes through here (links are untrusted). */
function clean(o) {
const s = structuredClone(DEFAULTS);
if (!o || typeof o !== "object") return s;
for (const k of Object.keys(DEFAULTS)) {
if (!Object.hasOwn(o, k)) continue;
const v = o[k], d = DEFAULTS[k];
if (RANGE[k]) { if (Number.isFinite(v)) s[k] = Math.min(RANGE[k][1], Math.max(RANGE[k][0], v)); }
else if (ENUM[k]) { if (ENUM[k].includes(v)) s[k] = v; }
else if (typeof d === "boolean") { if (typeof v === "boolean") s[k] = v; }
else if (k === "stops") { if (Array.isArray(v) && v.length > 1 && v.length < 9 && v.every(x => typeof x === "string" && HEX.test(x))) s[k] = [...v]; }
else if (typeof v === "string" && HEX.test(v)) s[k] = v;
}
return s;
}
/* ---------- Generators: CSS ---------- */
const n = x => String(+x.toFixed(4));
const alpha = (hex, o) => hex + Math.round(o * 255).toString(16).padStart(2, "0");
const polar = (d, deg) => [d * Math.cos(deg * Math.PI / 180), d * Math.sin(deg * Math.PI / 180)];
/* Effects as groups of drop-shadows: [dx, dy, blur, colour, opacity, cssX, cssY], x A.
Within one filter a browser may re-render the input at every pass (cost 2^n), so each
group gets its own element: the first is .cbm itself, the rest are wrapper spans.
SVG draws outline and extrusion as vectors instead. */
function groups(s) {
const g = [];
if (s.outW) { // a square dilation, then a diamond: together an even octagon
const o = (pairs, k, v) => pairs.map(([x, y]) => {
const css = d => d ? (d > 0 ? `var(${v})` : `calc(-1 * var(${v}))`) : "0px";
return [x * s.outW * k, y * s.outW * k, 0, s.outC, 1, css(x), css(y)];
});
g.push(o([[1, 0], [-1, 0], [0, 1], [0, -1]], .5, "--out-p"), o([[1, 1], [-1, -1], [1, -1], [-1, 1]], .25, "--out-q"));
}
if (s.exD) g.push([32, 32, 16, 8, 4, 2].map(k => { // halving steps that add up to the full depth
const [x, y] = polar(s.exD / k, s.exA); return [x, y, 0, s.exC, 1];
}));
const f = soft(s);
if (f.length) g.push(f);
return g;
}
function soft(s) {
const out = [];
if (s.shO) out.push([s.shX, s.shY, s.shB, s.shC, s.shO]);
if (s.glS && s.glO) out.push([0, 0, s.glS, s.glC, s.glO]);
return out;
}
function cssFill(s) {
const l = [];
const bands = s.stops.map((c, i, a) => `${c} 0 ${n(100 * (i + 1) / a.length)}%`).join(", ");
if (s.mode === "gradient") l.push(`linear-gradient(${n(s.angle)}deg, ${s.stops.join(", ")})`);
else if (s.mode === "stripes") l.push(`linear-gradient(${n(s.angle)}deg, ${bands})`);
const scan = s.scan ? `repeating-linear-gradient(#0000 0 calc(var(--a) * ${n(s.scanP / 2)}), ${alpha("#000000", s.scan)} 0 calc(var(--a) * ${n(s.scanP)})), ` : "";
return s.mode === "solid"
? [scan + `linear-gradient(${s.c} 0 0)`, scan + `linear-gradient(${s.f1} 50%, ${s.f2} 50%)`]
: [scan + l[0], scan + l[0]];
}
function logoCSS(s, guardMotion = true) {
const [fill, flag] = cssFill(s);
const len = v => `var(--a) * ${+v.toFixed(5)}`, zero = v => Math.abs(v) < 1e-6;
const px = v => zero(v) ? "0px" : `round(${len(v)}, 1px)`; // whole px: browsers snap shadow offsets unevenly
const chains = groups(s).map(g => g.map(([x, y, b, c, o, cx, cy]) =>
`drop-shadow(${cx ?? px(x)} ${cy ?? px(y)} ${zero(b) ? "0px" : `calc(${len(b)})`} ${o < 1 ? alpha(c, o) : c})`).join("\n "));
const last = Math.max(0, chains.length - 1), root = last ? `.cbm-fx${last}` : ".cbm";
const fx = i => chains[i] ? `\n filter: var(--fx);` : "";
const outline = s.outW ? `
--out: max(1px, round(${len(s.outW)}, 1px));
--out-q: round(down, var(--out) / 4, 1px);
--out-p: calc(var(--out) - 2 * var(--out-q));` : "";
const tf = [s.rot && `rotate(${n(s.rot)}deg)`, s.skew && `skewX(${n(s.skew)}deg)`, s.flip && "scaleX(-1)"].filter(Boolean).join(" ");
const d = n(s.dur);
const anim = { none: "", spin: `cbm-spin ${d}s linear infinite`, pulse: `cbm-pulse ${d}s ease-in-out infinite alternate`, hue: `cbm-hue ${d}s linear infinite` }[s.anim];
const keys = {
none: "", spin: "@keyframes cbm-spin { to { rotate: y 360deg } }",
pulse: "@keyframes cbm-pulse { to { scale: 1.08 } }",
hue: "@keyframes cbm-hue { from { filter: var(--fx) hue-rotate(0deg) } to { filter: var(--fx) hue-rotate(360deg) } }",
}[s.anim];
const rule = `${root} { animation: ${anim} }`;
return `.cbm {
--B: ${n(s.B)}; --C: ${n(s.C)}; --E: ${n(1 - s.H)}; --F: ${n(s.F)}; --G: ${n(s.G)};
--H: ${n(s.H)}; --I: ${n(s.I)}; --J: ${n(s.J)}deg; --hole-x: ${n(s.hx)};
--fill: ${fill};
--flag-fill: ${flag};
--fx: ${chains[0] || "opacity(1)"};
--a: var(--A, 10rem);${last ? "" : outline}
--w: var(--a);
--h: calc(var(--a) * var(--I));
--cut: calc(var(--a) * var(--H));
--flag-h: calc(var(--a) * var(--C));
--flags-h: calc(var(--a) * (2 * var(--C) + var(--B)));
--flags-y: calc((var(--h) - var(--flags-h)) / 2);
--notch: min(var(--flag-h) / tan(var(--J) / 2), var(--a) * var(--E));
position: relative;
display: inline-block;
flex: none;
width: var(--w);
height: var(--h);${fx(0)}${!last && tf ? `\n transform: ${tf};` : ""}
}
.cbm::before,
.cbm::after {
content: "";
position: absolute;
background-image: var(--fill);
background-repeat: no-repeat;
background-size: calc(var(--w) + 1px) calc(var(--h) + 1px); /* bleed against pixel rounding */
}
.cbm::before {
left: 0;
top: 0;
width: var(--h);
height: var(--h);
border-radius: 50%;
clip-path: inset(0 calc(var(--h) - var(--cut)) 0 0);
--hole: radial-gradient(
calc(var(--a) * var(--G) / 2) calc(var(--a) * var(--F) / 2)
at calc(var(--a) * var(--hole-x)) 50%,
#0000 calc(100% - .5px), #000 calc(100% + .5px));
-webkit-mask: var(--hole);
mask: var(--hole);
}
.cbm::after {
left: var(--cut);
top: var(--flags-y);
width: calc(var(--a) * var(--E));
height: var(--flags-h);
background-image: var(--flag-fill);
background-position: calc(-1 * var(--cut)) calc(-1 * var(--flags-y));
clip-path: polygon(
0 0, 100% 0,
calc(100% - var(--notch)) var(--flag-h), 0 var(--flag-h),
0 calc(100% - var(--flag-h)), calc(100% - var(--notch)) calc(100% - var(--flag-h)),
100% 100%, 0 100%);
}
${chains.slice(1).map((c, i) => `.cbm-fx${i + 1} {
--fx: ${c};
--a: var(--A, 10rem);${i + 1 === last ? outline : ""}
display: inline-grid;
filter: var(--fx);${i + 1 === last && tf ? `\n transform: ${tf};` : ""}
}
`).join("")}${anim ? `${keys}\n${guardMotion ? `@media (prefers-reduced-motion: no-preference) { ${rule} }` : rule}\n` : ""}`;
}
/* [class, class, ...] from the outside in, and the matching HTML */
const layers = s => [...groups(s).slice(1).map((_, i) => `cbm-fx${i + 1}`).reverse(), "cbm"];
const markup = (s, A) => {
const [first, ...rest] = layers(s);
return `<span class="${first}" style="--A: ${A}" role="img" aria-label="Commodore">` + rest.map(c => `<span class="${c}">`).join("") + "</span>".repeat(rest.length + 1);
};
const pageHTML = s => `<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Commodore</title>
<style>
body { margin: 0; min-height: 100vh; display: grid; place-items: center;${s.bgOn ? ` background: ${s.bg};` : ""} }
${logoCSS(s)}</style>
</head>
<body>
${markup(s, "min(60vw, 60vh)")}
</body>
</html>
`;
/* ---------- Generators: SVG ---------- */
const U = 1000; // one A in SVG units
function matrix(s) {
const r = s.rot * Math.PI / 180, k = Math.tan(s.skew * Math.PI / 180), f = s.flip ? -1 : 1;
return (x, y) => {
const X = (x - .5) * f + (y - s.I / 2) * k, Y = y - s.I / 2;
return [X * Math.cos(r) - Y * Math.sin(r) + .5, X * Math.sin(r) + Y * Math.cos(r) + s.I / 2];
};
}
/* Painted area including effects: local (untransformed) and final, x A */
function bounds(s) {
let l = 0, t = 0, r = 0, b = 0;
for (const [x, y, bl] of groups(s).flat()) {
l = Math.max(l, l - x + 3 * bl); r = Math.max(r, r + x + 3 * bl);
t = Math.max(t, t - y + 3 * bl); b = Math.max(b, b + y + 3 * bl);
}
const local = [-l, -t, 1 + r, s.I + b], m = matrix(s);
const p = [[0, 1], [2, 1], [2, 3], [0, 3]].map(([i, j]) => m(local[i], local[j]));
const xs = p.map(q => q[0]), ys = p.map(q => q[1]);
return { local, x0: Math.min(...xs), y0: Math.min(...ys), x1: Math.max(...xs), y1: Math.max(...ys) };
}
function paths(s) {
const u = v => n(v * U), R = s.I / 2, cy = R, rx = s.G / 2, ry = s.F / 2;
const oy = Math.sqrt(Math.max(0, R * R - (s.H - R) ** 2)), big = s.H > R ? 1 : 0;
const q = (s.H - s.hx) / rx;
let ring = `M${u(s.H)} ${u(cy - oy)}A${u(R)} ${u(R)} 0 ${big} 0 ${u(s.H)} ${u(cy + oy)}`;
if (Math.abs(q) < 1) { // the cut passes through the hole
const iy = ry * Math.sqrt(1 - q * q);
ring += `V${u(cy + iy)}A${u(rx)} ${u(ry)} 0 ${q > 0 ? 1 : 0} 1 ${u(s.H)} ${u(cy - iy)}Z`;
} else {
ring += "Z";
if (q >= 1) ring += `M${u(s.hx - rx)} ${u(cy)}a${u(rx)} ${u(ry)} 0 1 1 ${u(2 * rx)} 0a${u(rx)} ${u(ry)} 0 1 1 ${u(-2 * rx)} 0Z`;
}
const E = 1 - s.H, notch = Math.min(s.C / Math.tan(s.J * Math.PI / 360), E);
const y0 = (s.I - 2 * s.C - s.B) / 2, y1 = y0 + s.C, y2 = y1 + s.B, y3 = y2 + s.C;
return [ring,
`M${u(s.H)} ${u(y0)}H${u(1)}L${u(1 - notch)} ${u(y1)}H${u(s.H)}Z`,
`M${u(s.H)} ${u(y2)}H${u(1 - notch)}L${u(1)} ${u(y3)}H${u(s.H)}Z`];
}
function logoSVG(s, { width = 1024, pad = .08, box } = {}) {
const u = v => n(v * U), B = box || bounds(s);
const [x0, y0, x1, y1] = [B.x0 - pad, B.y0 - pad, B.x1 + pad, B.y1 + pad];
const W = x1 - x0, H = y1 - y0, height = Math.max(1, Math.round(width * H / W));
let defs = "", fills = [s.c, s.f1, s.f2];
if (s.mode !== "solid") {
const a = s.angle * Math.PI / 180, dx = Math.sin(a), dy = -Math.cos(a), L = (Math.abs(dx) + s.I * Math.abs(dy)) / 2;
const N = s.stops.length;
const st = s.stops.map((c, i) => s.mode === "gradient"
? `<stop offset="${n(i / (N - 1))}" stop-color="${c}"/>`
: `<stop offset="${n(i / N)}" stop-color="${c}"/><stop offset="${n((i + 1) / N)}" stop-color="${c}"/>`).join("");
defs += `<linearGradient id="fill" gradientUnits="userSpaceOnUse" x1="${u(.5 - dx * L)}" y1="${u(s.I / 2 - dy * L)}" x2="${u(.5 + dx * L)}" y2="${u(s.I / 2 + dy * L)}">${st}</linearGradient>`;
fills = Array(3).fill("url(#fill)");
}
if (s.scan) defs += `<pattern id="scan" patternUnits="userSpaceOnUse" width="${U}" height="${u(s.scanP)}"><rect y="${u(s.scanP / 2)}" width="${U}" height="${u(s.scanP / 2)}" fill="#000" fill-opacity="${n(s.scan)}"/></pattern>`;
const sh = soft(s);
if (sh.length) {
const [l, t, r, b] = B.local, m = .01;
defs += `<filter id="fx" filterUnits="userSpaceOnUse" color-interpolation-filters="sRGB" x="${u(l - m)}" y="${u(t - m)}" width="${u(r - l + 2 * m)}" height="${u(b - t + 2 * m)}">`
+ sh.map(([x, y, bl, c, o]) => `<feDropShadow dx="${u(x)}" dy="${u(y)}" stdDeviation="${u(bl)}" flood-color="${c}" flood-opacity="${n(o)}"/>`).join("") + "</filter>";
}
const p = paths(s);
let back = "";
if (s.outW || s.exD) {
const stroke = c => s.outW ? ` stroke="${c}" stroke-width="${u(2 * s.outW)}" stroke-miterlimit="2"` : "";
const d = p.join("");
if (s.exD) {
defs += `<path id="slab" fill="${s.exC}" fill-rule="evenodd"${stroke(s.exC)} d="${d}"/>`;
const N = Math.ceil(s.exD / .0015);
for (let i = N; i; i--) { const [x, y] = polar(s.exD * i / N, s.exA); back += `<use href="#slab" x="${u(x)}" y="${u(y)}"/>`; }
}
if (s.outW) back += `<path fill="${s.outC}" fill-rule="evenodd"${stroke(s.outC)} d="${d}"/>`;
}
const art = back + p.map((d, i) => `<path fill="${fills[i]}" fill-rule="evenodd" d="${d}"/>`).join("")
+ (s.scan ? `<path fill="url(#scan)" fill-rule="evenodd" d="${p.join("")}"/>` : "");
const cx = u(.5), cy = u(s.I / 2);
const tf = s.rot || s.skew || s.flip
? ` transform="translate(${cx} ${cy}) rotate(${n(s.rot)}) skewX(${n(s.skew)}) scale(${s.flip ? -1 : 1} 1) translate(-${cx} -${cy})"` : "";
return `<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${height}" viewBox="${u(x0)} ${u(y0)} ${u(W)} ${u(H)}" role="img" aria-label="Commodore">`
+ (defs ? `<defs>${defs}</defs>` : "")
+ (s.bgOn ? `<rect x="${u(x0)}" y="${u(y0)}" width="${u(W)}" height="${u(H)}" fill="${s.bg}"/>` : "")
+ `<g${tf}><g${sh.length ? ' filter="url(#fx)"' : ""}>${art}</g></g></svg>`;
}
/* ---------- Page ---------- */
const $ = id => document.getElementById(id);
const el = (tag, props = {}, ...kids) => { const e = Object.assign(document.createElement(tag), props); e.append(...kids); return e; };
const stage = $("stage"), holder = $("holder"), panel = $("panel");
const sheet = document.head.appendChild(el("style"));
let logo, state = clean({}), hist = [], at = -1, syncs = [];
const store = { get: k => { try { return localStorage.getItem(k) } catch { return null } }, set: (k, v) => { try { localStorage.setItem(k, v) } catch {} } };
/* Plain fills preview as the real CSS. Outline and extrusion preview as the SVG export, because
long filter chains repaint too slowly to edit. Zoomed in, blurs come from a cached bitmap
with the sharp vector on top. */
const mode = () => {
const blur = soft(state).length && BASE * view.z > 900;
return blur ? "bitmap" : state.outW || state.exD ? "svg" : "css";
};
const PAD = .02;
function draw() {
drawn = mode();
const motion = state.anim === "none" ? "" : state.anim;
if (drawn === "css") {
sheet.textContent = logoCSS(state, false);
holder.innerHTML = markup(state, BASE + "px");
} else {
sheet.textContent = `@keyframes spin { to { rotate: y 360deg } } @keyframes pulse { to { scale: 1.08 } } @keyframes hue { to { filter: hue-rotate(360deg) } }`;
const flat = { ...state, bgOn: false, ...(drawn === "bitmap" && { shO: 0, glS: 0 }) };
holder.innerHTML = `<div>${logoSVG(flat, { box: bounds(state), pad: PAD })}</div>`;
}
logo = holder.firstElementChild;
if (drawn === "bitmap") {
const me = logo;
image("image/png", { ...state, bgOn: false }, { width: 1400, pad: PAD })
.then(b => {
if (me !== logo) return;
const img = el("img", { alt: "" });
img.onload = img.onerror = () => URL.revokeObjectURL(img.src);
img.src = URL.createObjectURL(b); me.prepend(img);
}).catch(() => {});
}
if (drawn !== "css" && motion) logo.style.animation = `${motion} ${state.dur}s ${motion === "pulse" ? "ease-in-out infinite alternate" : "linear infinite"}`;
}
let drawn;
function render() {
draw();
stage.classList.toggle("clear", !state.bgOn);
stage.style.backgroundColor = state.bgOn ? state.bg : "";
syncs.forEach(f => f());
if (view.auto) fit(); else place();
}
function commit() {
const j = JSON.stringify(state);
if (j !== hist[at]) { hist.length = at + 1; hist.push(j); at++; }
store.set("cbm-editor", j); buttons();
}
function buttons() { $("undo").disabled = at <= 0; $("redo").disabled = at >= hist.length - 1; }
function load(o) { state = clean(o); render(); commit(); }
function step(d) {
if (!hist[at + d]) return;
at += d; state = clean(JSON.parse(hist[at])); render(); store.set("cbm-editor", hist[at]); buttons();
}
let toastT;
function toast(m) { $("toast").textContent = m; $("toast").classList.add("on"); clearTimeout(toastT); toastT = setTimeout(() => $("toast").classList.remove("on"), 2200); }
/* ---------- Zoom and pan ---------- */
const BASE = 320, ZMIN = 2 ** -3.4, ZMAX = 2 ** 4.4;
const view = { z: 1, x: 0, y: 0, auto: true };
function place() {
const A = BASE * view.z;
if (mode() !== drawn) draw();
const vec = drawn !== "css", b = bounds(state), x0 = vec ? b.x0 - PAD : 0, y0 = vec ? b.y0 - PAD : 0;
logo.style.setProperty("--A", A + "px");
if (vec) {
logo.style.width = (b.x1 + PAD - x0) * A + "px"; logo.style.height = (b.y1 + PAD - y0) * A + "px";
logo.style.transformOrigin = `${(.5 - x0) * A}px ${(state.I / 2 - y0) * A}px`;
}
logo.style.left = (x0 - .5) * A + "px"; logo.style.top = (y0 - state.I / 2) * A + "px";
holder.style.transform = `translate(${view.x}px, ${view.y}px)`;
$("zval").textContent = Math.round(view.z * 100) + "%";
$("zrange").value = Math.log2(view.z);
}
function zoomTo(z, px = 0, py = 0) {
z = Math.min(ZMAX, Math.max(ZMIN, z));
const k = z / view.z;
view.x = px - (px - view.x) * k; view.y = py - (py - view.y) * k; view.z = z; view.auto = false; place();
}
function fit() {
const b = bounds(state), w = stage.clientWidth, h = stage.clientHeight - 60;
const z = Math.min(w * .8 / (b.x1 - b.x0), h * .84 / (b.y1 - b.y0)) / BASE;
view.z = Math.min(ZMAX, Math.max(ZMIN, z)); view.auto = true;
view.x = (.5 - (b.x0 + b.x1) / 2) * BASE * view.z;
view.y = (state.I / 2 - (b.y0 + b.y1) / 2) * BASE * view.z - 26; place();
}
const rel = e => { const r = stage.getBoundingClientRect(); return [e.clientX - r.left - r.width / 2, e.clientY - r.top - r.height / 2]; };
stage.addEventListener("wheel", e => {
if (e.target.closest("#zoombar")) return;
e.preventDefault();
zoomTo(view.z * Math.exp(-e.deltaY * (e.deltaMode ? .05 : .0016)), ...rel(e));
}, { passive: false });
const ptr = new Map();
stage.addEventListener("pointerdown", e => {
if (e.target.closest("#zoombar") || e.button) return;
stage.setPointerCapture(e.pointerId); ptr.set(e.pointerId, rel(e)); stage.classList.add("drag");
});
stage.addEventListener("pointermove", e => {
const old = ptr.get(e.pointerId); if (!old) return;
const now = rel(e), others = [...ptr].filter(([id]) => id !== e.pointerId);
if (others.length) { // pinch around the other finger
const o = others[0][1], d0 = Math.hypot(old[0] - o[0], old[1] - o[1]), d1 = Math.hypot(now[0] - o[0], now[1] - o[1]);
if (d0 > 4) zoomTo(view.z * d1 / d0, ...o);
} else { view.x += now[0] - old[0]; view.y += now[1] - old[1]; view.auto = false; place(); }
ptr.set(e.pointerId, now);
});
for (const t of ["pointerup", "pointercancel"]) stage.addEventListener(t, e => { ptr.delete(e.pointerId); if (!ptr.size) stage.classList.remove("drag"); });
stage.addEventListener("dblclick", e => { if (!e.target.closest("#zoombar")) fit(); });
$("zin").onclick = () => zoomTo(view.z * 1.25);
$("zout").onclick = () => zoomTo(view.z / 1.25);
$("zval").onclick = () => zoomTo(1);
$("zfit").onclick = fit;
$("zrange").oninput = e => zoomTo(2 ** +e.target.value);
new ResizeObserver(() => view.auto && fit()).observe(stage);
addEventListener("keydown", e => {
if (e.target.matches("input[type=text], input[type=number], select")) return;
const mod = e.ctrlKey || e.metaKey, k = e.key.toLowerCase();
if (mod && k === "z") { e.preventDefault(); return step(e.shiftKey ? 1 : -1); }
if (mod && k === "y") { e.preventDefault(); return step(1); }
if (mod || e.altKey) return;
if (k === "+" || k === "=") zoomTo(view.z * 1.25);
else if (k === "-") zoomTo(view.z / 1.25);
else if (k === "0") fit();
else if (k === "1") zoomTo(1);
else if (e.target === stage && k.startsWith("arrow")) {
e.preventDefault();
view.x += { arrowleft: 40, arrowright: -40 }[k] || 0; view.y += { arrowup: 40, arrowdown: -40 }[k] || 0;
view.auto = false; place();
}
});
/* ---------- Controls ---------- */
let uid = 0;
function ctl(label, input, ...rest) {
input.id = "k" + uid++;
return el("div", { className: "ctl" }, el("label", { textContent: label, htmlFor: input.id }), input, ...rest);
}
const live = (k, v) => { state[k] = v; state = clean(state); render(); };
function slider(k, label, scale = 1, unit = "") {
const [min, max, stp] = RANGE[k].map(v => +(v * scale).toFixed(6));
const r = el("input", { type: "range", min, max, step: stp }), num = el("input", { type: "number", min, max, step: stp, ariaLabel: label + (unit && ` (${unit})`) });
r.oninput = () => live(k, r.value / scale);
num.onchange = () => { if (num.value !== "") live(k, num.value / scale); else syncs.forEach(f => f()); commit(); };
r.onchange = commit;
syncs.push(() => { r.value = state[k] * scale; num.value = +(state[k] * scale).toFixed(3); });
return ctl(unit ? `${label} (${unit})` : label, r, num);
}
function colorInputs(get, set, label) {
const c = el("input", { type: "color", ariaLabel: label }), t = el("input", { type: "text", maxLength: 7, spellcheck: false, ariaLabel: label + " hex" });
c.oninput = () => set(c.value); c.onchange = commit;
t.onchange = () => {
let v = t.value.trim().replace(/^#?/, "#");
if (/^#[0-9a-f]{3}$/i.test(v)) v = "#" + [...v.slice(1)].map(x => x + x).join("");
if (HEX.test(v)) { set(v.toLowerCase()); commit(); } else t.value = get();
};
const sync = () => { c.value = get(); t.value = get(); };
return [el("div", { className: "color wide" }, c, t), sync, c];
}
function color(k, label) {
const [wrap, sync, c] = colorInputs(() => state[k], v => live(k, v), label);
syncs.push(sync); c.id = "k" + uid++;
return el("div", { className: "ctl" }, el("label", { textContent: label, htmlFor: c.id }), wrap);
}
function check(k, label) {
const i = el("input", { type: "checkbox", className: "chk" });
i.onchange = () => { live(k, i.checked); commit(); };
syncs.push(() => i.checked = state[k]);
return ctl(label, i);
}
function choose(k, label, names) {
const i = el("select", { className: "wide" }, ...Object.entries(names).map(([v, t]) => el("option", { value: v, textContent: t })));
i.onchange = () => { live(k, i.value); commit(); };
syncs.push(() => i.value = state[k]);
return ctl(label, i);
}
const h3 = t => el("h3", { textContent: t });
const note = t => el("p", { className: "note", textContent: t });
function when(test, ...kids) {
const box = el("div", { className: "body", style: "padding:0" }, ...kids);
syncs.push(() => box.hidden = !test()); return box;
}
function stopList() {
const box = el("div", { className: "body", style: "padding:0" });
let count = -1, inner = [];
const build = () => {
count = state.stops.length; inner = [];
box.replaceChildren(...state.stops.map((_, i) => {
const put = v => { const a = [...state.stops]; a[i] = v; live("stops", a); };
const [wrap, sync] = colorInputs(() => state.stops[i], put, "Colour " + (i + 1));
inner.push(sync);
wrap.append(el("button", { type: "button", textContent: "×", ariaLabel: "Remove colour " + (i + 1), disabled: count <= 2,
onclick: () => { live("stops", state.stops.filter((_, j) => j !== i)); commit(); } }));
return el("div", { className: "ctl" }, el("label", { textContent: "Colour " + (i + 1) }), wrap);
}), el("button", { type: "button", textContent: "Add colour", disabled: count >= 8,
onclick: () => { live("stops", [...state.stops, state.stops.at(-1)]); commit(); } }));
};
syncs.push(() => { if (state.stops.length !== count) build(); inner.forEach(f => f()); });
return box;
}
function section(title, open, cls, ...kids) {
panel.append(el("details", { open }, el("summary", { textContent: title }), el("div", { className: "body " + cls }, ...kids)));
}
section("Presets", true, "presets", ...Object.entries(PRESETS).map(([, [name, o]]) => {
const s = clean(o), j = JSON.stringify(s);
const b = el("button", { type: "button", onclick: () => load(o) },
el("img", { alt: "", style: `background:${s.bg}`, src: "data:image/svg+xml," + encodeURIComponent(logoSVG(s, { width: 180, pad: .2 })) }), name);
syncs.push(() => b.setAttribute("aria-pressed", JSON.stringify(state) === j));
return b;
}));
section("Colours", true, "",
choose("mode", "Fill", { solid: "Solid", gradient: "Gradient", stripes: "Stripes" }),
when(() => state.mode === "solid", color("c", "C"), color("f1", "Upper flag"), color("f2", "Lower flag")),
when(() => state.mode !== "solid", slider("angle", "Angle", 1, "°"), stopList()),
h3("Background"), check("bgOn", "Show"), when(() => state.bgOn, color("bg", "Colour")));
section("Effects", false, "",
h3("Outline"), slider("outW", "Width", 100, "%"), color("outC", "Colour"),
h3("Extrude"), slider("exD", "Depth", 100, "%"), slider("exA", "Angle", 1, "°"), color("exC", "Colour"),
h3("Shadow"), slider("shO", "Strength", 100, "%"), slider("shX", "Across", 100, "%"), slider("shY", "Down", 100, "%"), slider("shB", "Blur", 100, "%"), color("shC", "Colour"),
h3("Glow"), slider("glS", "Size", 100, "%"), slider("glO", "Strength", 100, "%"), color("glC", "Colour"),
h3("Scanlines"), slider("scan", "Strength", 100, "%"), slider("scanP", "Spacing", 100, "%"),
note("Sizes are a percentage of A, the logo's width."));
section("Transform and motion", false, "",
slider("rot", "Rotate", 1, "°"), slider("skew", "Slant", 1, "°"), check("flip", "Mirror"),
choose("anim", "Motion", { none: "None", spin: "Spin", pulse: "Pulse", hue: "Colour cycle" }),
when(() => state.anim !== "none", slider("dur", "Duration", 1, "s"), note("Motion is kept in CSS and HTML exports only.")));
section("Proportions", false, "",
slider("B", "B flag gap"), slider("C", "C flag height"), slider("F", "F hole height"), slider("G", "G hole width"),
slider("H", "H cut"), slider("I", "I diameter"), slider("J", "J notch", 1, "°"), slider("hx", "Hole centre"),
note("E, the flag width, is always 1 − H."),
el("button", { type: "button", textContent: "Back to the card's values", onclick: () => load({ ...state, ...GEO }) }));
/* ---------- Export ---------- */
const fmt = el("select", { className: "wide" }, ...Object.entries({ png: "PNG image", webp: "WebP image", jpeg: "JPEG image", svg: "SVG vector", css: "CSS", html: "HTML page" }).map(([v, t]) => el("option", { value: v, textContent: t })));
const size = el("input", { type: "number", className: "wide", min: 16, max: 8192, value: 1024 });
const pad = el("input", { type: "number", className: "wide", min: 0, max: 100, value: 8 });
const raster = () => ["png", "webp", "jpeg"].includes(fmt.value);
const sizeRow = ctl("Width (px)", size), padRow = ctl("Padding (%)", pad), expNote = note("");
const clampNum = (i, d) => Math.min(+i.max, Math.max(+i.min, i.value === "" || !Number.isFinite(+i.value) ? d : +i.value));
const opts = () => ({ width: Math.round(clampNum(size, 1024)), pad: clampNum(pad, 8) / 100 });
function exportUI() {
const text = ["css", "html"].includes(fmt.value);
sizeRow.hidden = padRow.hidden = text;
copyBtn.textContent = raster() ? "Copy as PNG" : "Copy code";
const bg = state.bgOn ? "Includes the background colour." : fmt.value === "jpeg" ? "JPEG has no transparency, so the background will be white." : "Transparent background.";
expNote.textContent = fmt.value === "css" ? "No images or scripts. The HTML it needs is in the first line; set --A to resize." : bg;
}
function image(type, s = state, o = opts()) {
const svg = logoSVG(type === "image/jpeg" && !s.bgOn ? { ...s, bgOn: true, bg: "#ffffff" } : s, o);
const url = URL.createObjectURL(new Blob([svg], { type: "image/svg+xml" }));
const img = new Image();
return new Promise((ok, no) => { img.onload = ok; img.onerror = () => no(new Error("The image could not be drawn.")); img.src = url; })
.then(() => {
const c = el("canvas", { width: img.naturalWidth, height: img.naturalHeight });
c.getContext("2d").drawImage(img, 0, 0);
return new Promise((ok, no) => c.toBlob(b => b ? ok(b) : no(new Error("That size is too large for this browser.")), type, .94));
}).finally(() => URL.revokeObjectURL(url));
}
const code = () => ({ svg: () => logoSVG(state, opts()), css: () => `/* ${markup(state, "20rem")} */\n` + logoCSS(state), html: () => pageHTML(state) })[fmt.value]();
function save(blob, ext) {
const url = URL.createObjectURL(blob);
el("a", { href: url, download: "commodore-logo." + ext }).click();
setTimeout(() => URL.revokeObjectURL(url), 10000);
toast(`Saved commodore-logo.${ext}`);
}
async function copyText(t) {
try { await navigator.clipboard.writeText(t); }
catch {
const a = document.body.appendChild(el("textarea", { value: t, style: "position:fixed;opacity:0" }));
a.select(); const ok = document.execCommand("copy"); a.remove();
if (!ok) throw new Error("The browser blocked copying.");
}
}
const guard = f => async () => { try { await f(); } catch (e) { toast(e.message || "That didn't work."); } };
const saveBtn = el("button", { type: "button", className: "main", textContent: "Download", onclick: guard(async () => {
if (!raster()) return save(new Blob([code()], { type: { svg: "image/svg+xml", css: "text/css", html: "text/html" }[fmt.value] }), fmt.value);
const b = await image("image/" + fmt.value), real = b.type.split("/")[1]; // browsers without WebP encoding return PNG
save(b, real === "jpeg" ? "jpg" : real);
}) });
const copyBtn = el("button", { type: "button", onclick: guard(async () => {
if (raster()) {
if (!navigator.clipboard || !window.ClipboardItem) throw new Error("This browser can't copy images. Use Download.");
await navigator.clipboard.write([new ClipboardItem({ "image/png": image("image/png") })]);
} else await copyText(code());
toast("Copied");
}) });
fmt.onchange = exportUI; syncs.push(exportUI);
section("Export", true, "", ctl("Format", fmt), sizeRow, padRow, expNote, el("div", { className: "row" }, saveBtn, copyBtn));
const keyRow = (k, t) => el("div", { className: "key" }, el("span", {}, ...k.map(x => el("kbd", { textContent: x }))), el("span", { textContent: t }));
section("Keyboard and mouse", false, "",
keyRow(["Scroll"], "Zoom around the pointer"), keyRow(["Drag"], "Pan"), keyRow(["Double-click"], "Fit to view"),
keyRow(["+", "−"], "Zoom in, out"), keyRow(["0"], "Fit to view"), keyRow(["1"], "100%"),
keyRow(["←", "↑", "→", "↓"], "Pan, with the preview focused"),
keyRow(["Ctrl", "Z"], "Undo"), keyRow(["Ctrl", "Shift", "Z"], "Redo"),
note("Your work is saved in this browser. Copy link puts the whole design in a URL."));
$("undo").onclick = () => step(-1);
$("redo").onclick = () => step(1);
$("reset").onclick = () => { load({}); fit(); };
$("share").onclick = guard(async () => {
const diff = Object.fromEntries(Object.entries(state).filter(([k, v]) => JSON.stringify(v) !== JSON.stringify(DEFAULTS[k])));
await copyText(location.href.split("#")[0] + "#s=" + encodeURIComponent(JSON.stringify(diff)));
toast("Link copied");
});
function fromHash() {
const h = location.hash;
try {
if (h.startsWith("#preset=") && Object.hasOwn(PRESETS, h.slice(8))) return PRESETS[h.slice(8)][1];
if (h.startsWith("#s=")) return JSON.parse(decodeURIComponent(h.slice(3)));
} catch { toast("That link couldn't be read."); }
return null;
}
addEventListener("hashchange", () => { const o = fromHash(); if (o) load(o); });
let start = fromHash();
if (!start) try { start = JSON.parse(store.get("cbm-editor")); } catch {}
load(start);