excalideck 0.0.1 → 0.2.1

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,617 @@
1
+ // excalideck player — every frame in an .excalidraw file is a slide; shapes morph between them.
2
+ import { loadScene as parseScene, match, zoomAnchor, attachPos, TRANSITIONS, APPEARS } from "../src/scene.js";
3
+ {
4
+ const $ = (s) => document.querySelector(s);
5
+ const canvas = $("#c"), ctx = canvas.getContext("2d");
6
+ const gen = rough.generator();
7
+
8
+ // ── small utilities ─────────────────────────────────────────────────────────
9
+ const clamp = (v, a = 0, b = 1) => Math.max(a, Math.min(b, v));
10
+ const lerp = (a, b, t) => a + (b - a) * t;
11
+ const ease = (t) => (t < 0.5 ? 4 * t * t * t : 1 - Math.pow(-2 * t + 2, 3) / 2);
12
+ const easeOut = (t) => 1 - Math.pow(1 - t, 3);
13
+ const backOut = (t) => { const c = 1.6; return 1 + (c + 1) * Math.pow(t - 1, 3) + c * Math.pow(t - 1, 2); };
14
+ const norm = (s) => String(s).toLowerCase().replace(/\s+/g, " ").trim();
15
+ const FONTS = { 1: "Virgil", 2: "Helvetica, Arial, sans-serif", 3: '"Cascadia Code", Menlo, monospace',
16
+ 5: "Excalifont, Virgil", 6: "Nunito, sans-serif", 7: '"Lilita One", sans-serif',
17
+ 8: '"Comic Shanns", "Comic Sans MS", cursive', 9: '"Liberation Sans", Arial, sans-serif' };
18
+ const fontCss = (fam, size) => `${size}px ${FONTS[fam] || FONTS[5]}`;
19
+
20
+ const colorCache = new Map();
21
+ function col(c) {
22
+ if (!c || c === "transparent") return [0, 0, 0, 0];
23
+ if (colorCache.has(c)) return colorCache.get(c);
24
+ let r = 0, g = 0, b = 0, a = 1, m;
25
+ const h = c.replace("#", "");
26
+ if (/^[0-9a-f]{3,8}$/i.test(h) && c[0] === "#") {
27
+ const full = h.length <= 4 ? h.split("").map((x) => x + x).join("") : h;
28
+ r = parseInt(full.slice(0, 2), 16); g = parseInt(full.slice(2, 4), 16); b = parseInt(full.slice(4, 6), 16);
29
+ if (full.length === 8) a = parseInt(full.slice(6, 8), 16) / 255;
30
+ } else if ((m = c.match(/rgba?\(([^)]+)\)/))) {
31
+ [r, g, b, a = 1] = m[1].split(",").map(Number);
32
+ } else { // named colour → let the canvas normalise it
33
+ ctx.fillStyle = "#000"; ctx.fillStyle = c; return col(ctx.fillStyle);
34
+ }
35
+ const v = [r, g, b, a]; colorCache.set(c, v); return v;
36
+ }
37
+ const rgba = (c, mul = 1) => `rgba(${c[0] | 0},${c[1] | 0},${c[2] | 0},${c[3] * mul})`;
38
+ function lerpCol(a, b, t) {
39
+ if (a[3] === 0) a = [b[0], b[1], b[2], 0];
40
+ if (b[3] === 0) b = [a[0], a[1], a[2], 0];
41
+ return [lerp(a[0], b[0], t), lerp(a[1], b[1], t), lerp(a[2], b[2], t), lerp(a[3], b[3], t)];
42
+ }
43
+
44
+ const measureCache = new Map();
45
+ function measure(font, text) {
46
+ const k = font + "|" + text;
47
+ let w = measureCache.get(k);
48
+ if (w === undefined) { ctx.font = font; w = ctx.measureText(text).width; measureCache.set(k, w); }
49
+ return w;
50
+ }
51
+
52
+ // ── animatable state ────────────────────────────────────────────────────────
53
+ const stateOf = (it) => ({ x: it.x, y: it.y, w: it.w, h: it.h, angle: it.angle, op: it.op, stroke: col(it.stroke),
54
+ bg: col(it.bg), sw: it.sw, rough: it.rough, pts: it.pts, k: 1 });
55
+
56
+ function equalize(a, b) {
57
+ const grow = (p, n) => { p = p.map((q) => q.slice()); while (p.length < n) {
58
+ let bi = 0, bl = -1; for (let i = 0; i < p.length - 1; i++) { const l = Math.hypot(p[i + 1][0] - p[i][0], p[i + 1][1] - p[i][1]); if (l > bl) { bl = l; bi = i; } }
59
+ p.splice(bi + 1, 0, [(p[bi][0] + p[bi + 1][0]) / 2, (p[bi][1] + p[bi + 1][1]) / 2]); } return p; };
60
+ const n = Math.max(a.length, b.length);
61
+ return [grow(a, n), grow(b, n)];
62
+ }
63
+
64
+ function lerpState(a, b, t, eq) {
65
+ const s = { x: lerp(a.x, b.x, t), y: lerp(a.y, b.y, t), w: lerp(a.w, b.w, t), h: lerp(a.h, b.h, t),
66
+ angle: lerp(a.angle, b.angle, t), op: lerp(a.op, b.op, t), stroke: lerpCol(a.stroke, b.stroke, t),
67
+ bg: lerpCol(a.bg, b.bg, t), sw: lerp(a.sw, b.sw, t), rough: lerp(a.rough, b.rough, t), k: lerp(a.k, b.k, t), pts: null };
68
+ if (a.pts && b.pts) {
69
+ const [pa, pb] = eq || (a.pts.length === b.pts.length ? [a.pts, b.pts] : equalize(a.pts, b.pts));
70
+ s.pts = pa.map((p, i) => [lerp(p[0], pb[i][0], t), lerp(p[1], pb[i][1], t)]);
71
+ } else s.pts = b.pts || a.pts;
72
+ return s;
73
+ }
74
+
75
+ // uniform scale about point `from`, moved to `to` (used by pop and by zoom)
76
+ function xform(st, from, to, s, strokeToo) {
77
+ const m = ([x, y]) => [to[0] + (x - from[0]) * s, to[1] + (y - from[1]) * s];
78
+ const c = m([st.x + st.w / 2, st.y + st.h / 2]);
79
+ return { ...st, w: st.w * s, h: st.h * s, x: c[0] - (st.w * s) / 2, y: c[1] - (st.h * s) / 2,
80
+ pts: st.pts && st.pts.map(m), k: st.k * s, sw: strokeToo ? clamp(st.sw * s, 0.4, 14) : st.sw };
81
+ }
82
+ const center = (st) => [st.x + st.w / 2, st.y + st.h / 2];
83
+
84
+ // ── building a transition timeline ──────────────────────────────────────────
85
+ function buildTransition(A, B, mode, appear, speed, stagger) {
86
+ const sp = speed;
87
+ if (mode === "camera" || mode === "cut") return { mode, A, B, dur: mode === "cut" ? 0 : 1900 * sp };
88
+ let pairs = mode === "fade" ? [...A.items.map((a) => ({ a, b: null })), ...B.items.map((b) => ({ a: null, b }))] : match(A, B);
89
+ for (const p of pairs) {
90
+ if (p.a) p.sa = stateOf(p.a);
91
+ if (p.b) p.sb = stateOf(p.b);
92
+ if (p.spawn) p.sa = stateOf(p.spawn);
93
+ if (p.sa?.pts && p.sb?.pts && p.sa.pts.length !== p.sb.pts.length) p.eq = equalize(p.sa.pts, p.sb.pts);
94
+ }
95
+ let Z = null;
96
+ if (mode === "zoom") { // anchor = the matched shape whose size changes the most
97
+ const p = zoomAnchor(pairs);
98
+ if (p) Z = { cA: center(p.sa), cB: center(p.sb), s: Math.sqrt((p.b.w * p.b.h) / Math.max(1, p.a.w * p.a.h)) };
99
+ else mode = "morph";
100
+ }
101
+ const M0 = 150 * sp, MD = 1000 * sp;
102
+ const hasMorph = pairs.some((p) => p.a && p.b);
103
+ const enters = [];
104
+ for (const p of pairs) {
105
+ if (p.a && p.b) Object.assign(p, { kind: "morph", t0: M0, dur: MD });
106
+ else if (p.a) Object.assign(p, mode === "fade" ? { kind: "exit", t0: 0, dur: 500 * sp } : Z ? { kind: "exit", t0: M0, dur: MD } : { kind: "exit", t0: 0, dur: 450 * sp });
107
+ else { p.kind = p.spawn ? "spawn" : "enter"; enters.push(p); }
108
+ }
109
+ if (mode === "fade") for (const p of enters) Object.assign(p, { t0: 380 * sp, dur: 520 * sp });
110
+ else if (Z) for (const p of enters) Object.assign(p, p.spawn ? { t0: M0, dur: MD } : { t0: M0 + 60 * sp, dur: MD });
111
+ else {
112
+ const reading = (p) => { const s = p.sb; const c = s.pts ? s.pts.reduce((m, q) => [m[0] + q[0] / s.pts.length, m[1] + q[1] / s.pts.length], [0, 0]) : center(s); return c[0] + c[1] * 0.35; };
113
+ enters.sort((x, y) => reading(x) - reading(y));
114
+ const shapes = enters.filter((p) => !p.b.pts), lines = enters.filter((p) => p.b.pts);
115
+ const base = hasMorph ? 650 * sp : 120 * sp;
116
+ const gap = stagger ? Math.min(110, 1300 / Math.max(1, shapes.length)) * sp : 0;
117
+ const dShape = (appear === "draw" ? 950 : 560) * sp, dLine = (appear === "draw" ? 650 : 450) * sp;
118
+ shapes.forEach((p, i) => Object.assign(p, { t0: base + i * gap, dur: p.spawn ? 800 * sp : dShape }));
119
+ const ready = new Map(shapes.map((p) => [p.b.id, p.t0 + p.dur * 0.7]));
120
+ lines.forEach((p, i) => {
121
+ const own = base + (i * gap) / 2;
122
+ const deps = [p.b.startId, p.b.endId].map((id) => ready.get(id) ?? 0);
123
+ Object.assign(p, { t0: Math.max(own, ...deps), dur: p.spawn ? 700 * sp : dLine });
124
+ });
125
+ }
126
+ pairs.sort((x, y) => (x.b ? x.b.z : x.a.z - 0.5) - (y.b ? y.b.z : y.a.z - 0.5));
127
+ const dur = Math.max(0, ...pairs.map((p) => p.t0 + p.dur));
128
+ const byA = new Map(), byB = new Map();
129
+ for (const p of pairs) { if (p.a) byA.set(p.a.id, p); if (p.b) byB.set(p.b.id, p); }
130
+ return { mode, A, B, pairs, Z, appear, dur, byA, byB };
131
+ }
132
+
133
+ function staticOf(slide) {
134
+ if (slide._static) return slide._static;
135
+ const pairs = slide.items.slice().sort((a, b) => a.z - b.z).map((b) => ({ a: null, b, sb: stateOf(b), kind: "static", t0: 0, dur: 1 }));
136
+ return (slide._static = { mode: "static", pairs, byA: new Map(), byB: new Map(pairs.map((p) => [p.b.id, p])), dur: 0 });
137
+ }
138
+
139
+ // ── evaluating a pair at time T ─────────────────────────────────────────────
140
+ function evaluate(tr, p, T) {
141
+ const u = clamp((T - p.t0) / (p.dur || 1)), e = ease(u);
142
+ const out = { prog: 1, fillA: 1, labelA: 1, clip: 1, mix: 1 };
143
+ if (p.kind === "static") { out.st = p.sb; return out; }
144
+ if (p.kind === "morph") { out.st = lerpState(p.sa, p.sb, e, p.eq); out.mix = e; return out; }
145
+ if (p.kind === "spawn") { out.st = lerpState(p.sa, p.sb, e, p.eq); out.st.op *= clamp(u * 3); return out; }
146
+ const st0 = p.kind === "exit" ? p.sa : p.sb;
147
+ if (tr.Z) {
148
+ const Z = tr.Z;
149
+ // zooming in: the rest flies off-screen, so fade early; zooming out: detail shrinks home, so fade late
150
+ const [f0, f1] = Z.s > 1 ? [0.15, 0.55] : [0.5, 0.4];
151
+ if (p.kind === "exit") { out.st = lerpState(st0, xform(st0, Z.cA, Z.cB, Z.s, true), e); out.st.op *= 1 - clamp((u - f0) / f1); }
152
+ else { out.st = lerpState(xform(st0, Z.cB, Z.cA, 1 / Z.s, true), st0, e); out.st.op *= clamp((u - 0.2) / 0.5); }
153
+ return out;
154
+ }
155
+ const style = tr.mode === "fade" ? "fade" : tr.appear;
156
+ if (p.kind === "exit") {
157
+ out.st = { ...st0, op: st0.op * (1 - easeOut(u)) };
158
+ if (style === "pop") out.st = xform(out.st, center(st0), center(st0), 1 - 0.15 * u);
159
+ if (style === "rise") out.st = xform(out.st, [0, 0], [0, -24 * u], 1);
160
+ return out;
161
+ }
162
+ // enter
163
+ if (style === "draw" || (style === "pop" && p.b.pts)) {
164
+ out.st = st0; out.prog = easeOut(u); out.fillA = clamp((u - 0.5) / 0.4); out.labelA = clamp((u - 0.6) / 0.35);
165
+ out.clip = easeOut(u);
166
+ if (p.b.type === "text" || p.b.type === "image") { out.st = { ...st0, op: st0.op * clamp(u * 1.6) }; }
167
+ } else if (style === "pop") {
168
+ out.st = xform(st0, center(st0), center(st0), 0.35 + 0.65 * backOut(u)); out.st.op *= clamp(u * 2.5);
169
+ } else if (style === "rise") {
170
+ out.st = xform(st0, [0, 0], [0, 36 * (1 - easeOut(u))], 1); out.st.op *= easeOut(u);
171
+ } else { out.st = { ...st0, op: st0.op * easeOut(u) }; }
172
+ return out;
173
+ }
174
+
175
+ // ── drawing ─────────────────────────────────────────────────────────────────
176
+ const drawableCache = new Map();
177
+ function adjustRough(type, st, round) {
178
+ const r = st.rough;
179
+ if (type === "arrow" || type === "line") return r;
180
+ const mx = Math.max(st.w, st.h), mn = Math.min(st.w, st.h);
181
+ if ((mn >= 20 && mx >= 50) || mn >= 15 || (round && type === "rectangle")) return r;
182
+ return Math.min(r / (mx < 10 ? 3 : 2), 2.5);
183
+ }
184
+
185
+ function drawableFor(it, type, st) {
186
+ const hasFill = st.bg[3] > 0.001 && (type !== "line" || it.closed) && type !== "arrow";
187
+ const r5 = (v) => Math.round(v * 2) / 2;
188
+ const ptsKey = st.pts ? st.pts.map((p) => r5(p[0]) + "," + r5(p[1])).join(";") : "";
189
+ const key = [it.seed, type, r5(st.w), r5(st.h), r5(st.sw), r5(st.rough * 4), it.strokeStyle, it.fillStyle, hasFill, it.round, ptsKey, it.heads?.join()].join("|");
190
+ let d = drawableCache.get(key);
191
+ if (d) return d;
192
+ if (drawableCache.size > 4000) drawableCache.clear();
193
+ const dashed = it.strokeStyle !== "solid";
194
+ const o = { seed: it.seed, roughness: adjustRough(type, st, it.round), strokeWidth: dashed ? st.sw + 0.5 : st.sw,
195
+ fillWeight: st.sw / 2, hachureGap: st.sw * 4, disableMultiStroke: dashed, preserveVertices: st.rough < 2,
196
+ stroke: "#000", fill: hasFill ? "#000" : undefined, fillStyle: it.fillStyle === "solid" ? "solid" : it.fillStyle, curveFitting: 1 };
197
+ const w = Math.max(1, st.w), h = Math.max(1, st.h);
198
+ const shapes = [];
199
+ if (type === "rectangle") {
200
+ if (it.round) {
201
+ const x = Math.min(w, h), fixed = it.roundValue ?? 32, rr = x <= fixed / 0.25 ? x * 0.25 : fixed;
202
+ shapes.push(gen.path(`M ${rr} 0 L ${w - rr} 0 Q ${w} 0, ${w} ${rr} L ${w} ${h - rr} Q ${w} ${h}, ${w - rr} ${h} L ${rr} ${h} Q 0 ${h}, 0 ${h - rr} L 0 ${rr} Q 0 0, ${rr} 0`, o));
203
+ } else shapes.push(gen.rectangle(0, 0, w, h, o));
204
+ } else if (type === "ellipse") shapes.push(gen.ellipse(w / 2, h / 2, w, h, o));
205
+ else if (type === "diamond") shapes.push(gen.polygon([[w / 2, 0], [w, h / 2], [w / 2, h], [0, h / 2]], o));
206
+ else if (type === "arrow" || type === "line") {
207
+ const pts = st.pts;
208
+ if (it.closed && hasFill) shapes.push(gen.polygon(pts, o));
209
+ else if (it.round && pts.length > 2) shapes.push(gen.curve(pts, o));
210
+ else shapes.push(gen.linearPath(pts, o));
211
+ if (type === "arrow") {
212
+ const heads = [];
213
+ if (it.heads?.[1]) heads.push(arrowhead(pts.at(-1), pts.at(-2), it.heads[1], o));
214
+ if (it.heads?.[0]) heads.push(arrowhead(pts[0], pts[1], it.heads[0], o));
215
+ d = { body: shapes, heads: heads.flat() };
216
+ drawableCache.set(key, d); return d;
217
+ }
218
+ }
219
+ d = { body: shapes, heads: [] };
220
+ drawableCache.set(key, d);
221
+ return d;
222
+ }
223
+
224
+ function arrowhead(tip, prev, kind, o) {
225
+ if (!prev) return [];
226
+ const [x2, y2] = tip, [x1, y1] = prev, len = Math.hypot(x2 - x1, y2 - y1) || 1;
227
+ const size = Math.min(kind === "arrow" ? 25 : 15, len * 0.5), ang = ((kind === "arrow" ? 20 : 25) * Math.PI) / 180;
228
+ const bx = x2 - ((x2 - x1) / len) * size, by = y2 - ((y2 - y1) / len) * size;
229
+ const rot = (a) => [x2 + (bx - x2) * Math.cos(a) - (by - y2) * Math.sin(a), y2 + (bx - x2) * Math.sin(a) + (by - y2) * Math.cos(a)];
230
+ const [p3, p4] = [rot(ang), rot(-ang)];
231
+ const ho = { ...o, fill: undefined, strokeLineDash: undefined, disableMultiStroke: false };
232
+ if (kind === "triangle" || kind === "triangle_outline") return [{ g: gen.polygon([tip, p3, p4], { ...ho, fill: kind === "triangle" ? "#000" : undefined, fillStyle: "solid" }) }];
233
+ if (kind === "bar") { const px = -(y2 - y1) / len * 10, py = (x2 - x1) / len * 10; return [{ g: gen.line(x2 + px, y2 + py, x2 - px, y2 - py, ho) }]; }
234
+ if (kind === "dot" || kind === "circle" || kind === "circle_outline") return [{ g: gen.ellipse(x2 - ((x2 - x1) / len) * 6, y2 - ((y2 - y1) / len) * 6, 12, 12, { ...ho, fill: kind === "circle_outline" ? undefined : "#000", fillStyle: "solid" }) }];
235
+ return [{ g: gen.line(p3[0], p3[1], x2, y2, ho) }, { g: gen.line(p4[0], p4[1], x2, y2, ho) }];
236
+ }
237
+
238
+ // rough "ops" → Path2D, optionally only the first `prog` of the stroke (for draw-on)
239
+ function bezLen(x0, y0, a) { const chord = Math.hypot(a[4] - x0, a[5] - y0); const net = Math.hypot(a[0] - x0, a[1] - y0) + Math.hypot(a[2] - a[0], a[3] - a[1]) + Math.hypot(a[4] - a[2], a[5] - a[3]); return (chord + net) / 2; }
240
+ function opsToPath(ops, prog = 1) {
241
+ const p = new Path2D();
242
+ let total = 0, cx = 0, cy = 0;
243
+ const lens = ops.map((o) => {
244
+ let l = 0;
245
+ if (o.op === "lineTo") l = Math.hypot(o.data[0] - cx, o.data[1] - cy);
246
+ else if (o.op === "bcurveTo") l = bezLen(cx, cy, o.data);
247
+ const d = o.data; cx = d[d.length - 2]; cy = d[d.length - 1]; total += l; return l;
248
+ });
249
+ let budget = prog >= 1 ? Infinity : total * prog; cx = cy = 0;
250
+ for (let i = 0; i < ops.length; i++) {
251
+ const o = ops[i], d = o.data;
252
+ if (o.op === "move") { p.moveTo(d[0], d[1]); cx = d[0]; cy = d[1]; continue; }
253
+ if (lens[i] <= budget) {
254
+ if (o.op === "lineTo") p.lineTo(d[0], d[1]); else p.bezierCurveTo(d[0], d[1], d[2], d[3], d[4], d[5]);
255
+ budget -= lens[i]; cx = d[d.length - 2]; cy = d[d.length - 1]; continue;
256
+ }
257
+ const t = budget / (lens[i] || 1);
258
+ if (o.op === "lineTo") p.lineTo(lerp(cx, d[0], t), lerp(cy, d[1], t));
259
+ else { // de Casteljau split
260
+ const L = (a, b) => [lerp(a[0], b[0], t), lerp(a[1], b[1], t)];
261
+ const P0 = [cx, cy], P1 = [d[0], d[1]], P2 = [d[2], d[3]], P3 = [d[4], d[5]];
262
+ const a = L(P0, P1), b = L(P1, P2), c = L(P2, P3), ab = L(a, b), bc = L(b, c), m = L(ab, bc);
263
+ p.bezierCurveTo(a[0], a[1], ab[0], ab[1], m[0], m[1]);
264
+ }
265
+ break;
266
+ }
267
+ return p;
268
+ }
269
+
270
+ function paint(drawable, strokeC, fillC, prog, fillA, dash) {
271
+ const o = drawable.options;
272
+ for (const set of drawable.sets) {
273
+ if (set.type === "path") {
274
+ ctx.strokeStyle = strokeC; ctx.lineWidth = o.strokeWidth; ctx.setLineDash(dash || []);
275
+ ctx.lineCap = "round"; ctx.lineJoin = "round"; ctx.stroke(opsToPath(set.ops, prog));
276
+ } else if (fillA > 0) {
277
+ ctx.save(); ctx.globalAlpha *= fillA; ctx.setLineDash([]);
278
+ if (set.type === "fillPath") { ctx.fillStyle = fillC; ctx.fill(opsToPath(set.ops), "evenodd"); }
279
+ else { ctx.strokeStyle = fillC; ctx.lineWidth = o.fillWeight > 0 ? o.fillWeight : o.strokeWidth / 2; ctx.stroke(opsToPath(set.ops)); }
280
+ ctx.restore();
281
+ }
282
+ }
283
+ }
284
+
285
+ function drawBody(it, type, st, alpha, ev) {
286
+ if (st.op * alpha <= 0.002) return;
287
+ ctx.save();
288
+ ctx.globalAlpha = clamp(st.op * alpha);
289
+ if (st.angle && !st.pts) { const c = center(st); ctx.translate(c[0], c[1]); ctx.rotate(st.angle); ctx.translate(-c[0], -c[1]); }
290
+ if (type === "image") { if (it.img?.complete) ctx.drawImage(it.img, st.x, st.y, st.w, st.h); ctx.restore(); return; }
291
+ if (type === "freedraw") {
292
+ ctx.strokeStyle = rgba(st.stroke); ctx.lineWidth = st.sw * 1.6 * st.k; ctx.lineCap = ctx.lineJoin = "round";
293
+ const pts = st.pts, n = Math.max(2, Math.floor(pts.length * ev.prog));
294
+ ctx.beginPath(); ctx.moveTo(pts[0][0], pts[0][1]);
295
+ for (let i = 1; i < n - 1; i++) ctx.quadraticCurveTo(pts[i][0], pts[i][1], (pts[i][0] + pts[i + 1][0]) / 2, (pts[i][1] + pts[i + 1][1]) / 2);
296
+ if (pts[n - 1]) ctx.lineTo(pts[n - 1][0], pts[n - 1][1]);
297
+ ctx.stroke(); ctx.restore(); return;
298
+ }
299
+ const d = drawableFor(it, type, st);
300
+ if (!st.pts) ctx.translate(st.x, st.y);
301
+ const dash = it.strokeStyle === "dashed" ? [8, 8 + st.sw] : it.strokeStyle === "dotted" ? [1.5, 6 + st.sw] : null;
302
+ const sc = rgba(st.stroke), fc = rgba(st.bg[3] > 0 ? st.bg : st.stroke);
303
+ for (const g of d.body) paint(g, sc, fc, ev.prog, ev.fillA, dash);
304
+ const headA = ev.prog >= 1 ? 1 : clamp((ev.prog - 0.85) / 0.15);
305
+ if (headA > 0) { ctx.globalAlpha *= headA; for (const h of d.heads) paint(h.g, sc, sc, 1, 1, null); }
306
+ ctx.restore();
307
+ }
308
+
309
+ function layoutLines(T, box, fs, pad, valign) {
310
+ const lines = T.text.split("\n"), font = fontCss(T.fam, fs), lh = fs * T.lh;
311
+ const blockH = lines.length * lh;
312
+ const top = valign === "top" ? box.y + pad : valign === "bottom" ? box.y + box.h - pad - blockH : box.y + (box.h - blockH) / 2;
313
+ return { font, fs, lines: lines.map((t, i) => {
314
+ const w = measure(font, t);
315
+ const x = T.align === "left" ? box.x + pad : T.align === "right" ? box.x + box.w - pad - w : box.x + (box.w - w) / 2;
316
+ return { t, x, y: top + (i + 0.5) * lh, w };
317
+ }) };
318
+ }
319
+ function lerpLayout(a, b, t, fam) {
320
+ const fs = lerp(a.fs, b.fs, t);
321
+ return { font: fontCss(fam, fs), fs, lines: a.lines.map((l, i) => ({ t: l.t, x: lerp(l.x, b.lines[i].x, t), y: lerp(l.y, b.lines[i].y, t), w: lerp(l.w, b.lines[i].w, t) })) };
322
+ }
323
+ function fillLines(L, color, alpha, knockout) {
324
+ if (alpha <= 0.002) return;
325
+ ctx.save(); ctx.globalAlpha = clamp(alpha); ctx.font = L.font; ctx.textBaseline = "middle";
326
+ if (knockout) { ctx.fillStyle = scene.bg; for (const l of L.lines) ctx.fillRect(l.x - 4, l.y - L.fs * 0.62, l.w + 8, L.fs * 1.24); }
327
+ ctx.fillStyle = color;
328
+ for (const l of L.lines) ctx.fillText(l.t, l.x, l.y);
329
+ ctx.restore();
330
+ }
331
+ function midpoint(pts) {
332
+ if (pts.length % 2 === 1) return pts[(pts.length - 1) / 2];
333
+ const a = pts[pts.length / 2 - 1], b = pts[pts.length / 2];
334
+ return [(a[0] + b[0]) / 2, (a[1] + b[1]) / 2];
335
+ }
336
+ const labelBox = (it, st) => (st.pts ? (() => { const m = midpoint(st.pts); return { x: m[0], y: m[1], w: 0, h: 0 }; })() : st);
337
+ const layoutLabel = (L, it, st) => layoutLines({ ...L, align: it.pts ? "center" : L.align }, labelBox(it, st), L.fs * st.k, it.pts ? 0 : 5, it.pts ? "middle" : L.valign);
338
+
339
+ function drawLabels(p, ev) {
340
+ const st = ev.st, A = p.a?.label, B = (p.b || p.spawn)?.label;
341
+ const itB = p.b || p.a, knock = !!itB.pts;
342
+ const alpha = st.op * ev.labelA;
343
+ if (p.kind === "morph" && A && B && A.text === B.text) {
344
+ const la = layoutLabel(A, p.a, p.sa), lb = layoutLabel(B, p.b, p.sb);
345
+ const L = itB.pts ? layoutLabel(B, p.b, st) : lerpLayout(la, lb, ev.mix, B.fam);
346
+ fillLines(L, rgba(lerpCol(col(A.color), col(B.color), ev.mix)), alpha * lerp(A.op, B.op, ev.mix), knock);
347
+ return;
348
+ }
349
+ if (p.kind === "morph") {
350
+ if (A) fillLines(layoutLabel(A, p.a, st), A.color, alpha * A.op * (1 - ev.mix), knock);
351
+ if (B) fillLines(layoutLabel(B, p.b, st), B.color, alpha * B.op * ev.mix, knock);
352
+ return;
353
+ }
354
+ const L = p.b ? B : A; const it = p.b || p.a;
355
+ if (L) fillLines(layoutLabel(L, it, st), L.color, alpha * L.op, knock);
356
+ }
357
+
358
+ function drawText(p, ev) {
359
+ const it = p.b || p.a, st = ev.st, T = it.text;
360
+ let L;
361
+ if (p.kind === "morph") L = lerpLayout(layoutLines(p.a.text, p.sa, p.a.text.fs * p.sa.k, 0, "top"), layoutLines(T, p.sb, T.fs * p.sb.k, 0, "top"), ev.mix, T.fam);
362
+ else L = layoutLines(T, st, T.fs * st.k, 0, "top");
363
+ ctx.save();
364
+ if (ev.clip < 1) { ctx.beginPath(); ctx.rect(st.x - 20, st.y - 20, (st.w + 40) * ev.clip, st.h + 40); ctx.clip(); }
365
+ fillLines(L, rgba(st.stroke), st.op, false);
366
+ ctx.restore();
367
+ }
368
+
369
+ function renderTransition(tr, T) {
370
+ const evs = new Map();
371
+ for (const p of tr.pairs) if (!(p.b || p.a).pts) evs.set(p, evaluate(tr, p, T));
372
+ // arrows: re-glue each end to wherever its shape currently is
373
+ const stFor = (map, id) => { const q = map.get(id); return q && evs.get(q)?.st; };
374
+ for (const p of tr.pairs) {
375
+ const it = p.b || p.a;
376
+ if (!it.pts) continue;
377
+ const ev = evaluate(tr, p, T);
378
+ if (it.type !== "freedraw") {
379
+ const pts = ev.st.pts.map((q) => q.slice());
380
+ for (const [end, idx] of [["startAttach", 0], ["endAttach", pts.length - 1]]) {
381
+ const fromA = p.a?.[end] && stFor(tr.byA, p.a[end].id), fromB = p.b?.[end] && stFor(tr.byB, p.b[end].id);
382
+ const pa = fromA ? attachPos(p.a[end], fromA) : null, pb = fromB ? attachPos(p.b[end], fromB) : null;
383
+ let q = null;
384
+ if (p.kind === "morph") {
385
+ // if this end is moving onto a shape that is only now appearing, wait for that shape
386
+ const tgt = p.b?.[end] && tr.byB.get(p.b[end].id);
387
+ const w = ev.mix * (tgt && tgt.kind === "enter" ? ease(clamp((T - tgt.t0) / (tgt.dur || 1))) : 1);
388
+ const from = pa || pts[idx];
389
+ q = pb ? [lerp(from[0], pb[0], w), lerp(from[1], pb[1], w)] : pa;
390
+ } else q = pb || pa;
391
+ if (q) pts[idx] = q;
392
+ }
393
+ ev.st = { ...ev.st, pts };
394
+ }
395
+ evs.set(p, ev);
396
+ }
397
+ for (const p of tr.pairs) {
398
+ const ev = evs.get(p), it = p.b || p.a;
399
+ if (it.type === "text") { drawText(p, ev); continue; }
400
+ if (p.kind === "morph" && p.a.type !== p.b.type && !it.pts) {
401
+ drawBody(p.a, p.a.type, ev.st, 1 - ev.mix, ev); drawBody(p.b, p.b.type, ev.st, ev.mix, ev);
402
+ } else drawBody(it, it.type, ev.st, 1, ev);
403
+ drawLabels(p, ev);
404
+ }
405
+ }
406
+
407
+ let scene = null;
408
+
409
+ // ── camera / view ───────────────────────────────────────────────────────────
410
+ let dpr = 1;
411
+ function setView(r) {
412
+ const cw = canvas.width, ch = canvas.height;
413
+ const s = Math.min(cw / r.w, ch / r.h);
414
+ ctx.setTransform(s, 0, 0, s, (cw - r.w * s) / 2 - r.x * s, (ch - r.h * s) / 2 - r.y * s);
415
+ return s;
416
+ }
417
+ function clear() { ctx.setTransform(1, 0, 0, 1, 0, 0); ctx.fillStyle = scene ? scene.bg : "#fff"; ctx.fillRect(0, 0, canvas.width, canvas.height); }
418
+ const rectOf = (s) => ({ x: s.x, y: s.y, w: s.w, h: s.h });
419
+ function overviewRect() {
420
+ const S = scene.slides, x = Math.min(...S.map((s) => s.x)), y = Math.min(...S.map((s) => s.y));
421
+ const X = Math.max(...S.map((s) => s.x + s.w)), Y = Math.max(...S.map((s) => s.y + s.h)), pad = 120;
422
+ return { x: x - pad, y: y - pad, w: X - x + 2 * pad, h: Y - y + 2 * pad };
423
+ }
424
+ function flyRect(a, b, t) {
425
+ const e = ease(t);
426
+ const ca = [a.x + a.w / 2, a.y + a.h / 2], cb = [b.x + b.w / 2, b.y + b.h / 2];
427
+ const d = Math.hypot(cb[0] - ca[0], cb[1] - ca[1]);
428
+ const bump = 1 + Math.min(1.6, (d / Math.max(a.w, b.w)) * 0.5) * Math.sin(Math.PI * e);
429
+ const w = Math.exp(lerp(Math.log(a.w), Math.log(b.w), e)) * bump, h = Math.exp(lerp(Math.log(a.h), Math.log(b.h), e)) * bump;
430
+ const c = [lerp(ca[0], cb[0], e), lerp(ca[1], cb[1], e)];
431
+ return { x: c[0] - w / 2, y: c[1] - h / 2, w, h };
432
+ }
433
+ function drawWorld(view) {
434
+ setView(view);
435
+ const base = ctx.getTransform();
436
+ for (const s of scene.slides) {
437
+ if (s.x > view.x + view.w || s.x + s.w < view.x || s.y > view.y + view.h || s.y + s.h < view.y) continue;
438
+ ctx.setTransform(base); ctx.translate(s.x, s.y);
439
+ if (overview) { ctx.save(); ctx.strokeStyle = "rgba(0,0,0,.12)"; ctx.lineWidth = 3; ctx.strokeRect(0, 0, s.w, s.h); ctx.restore(); }
440
+ renderTransition(staticOf(s), 0);
441
+ }
442
+ }
443
+
444
+ // ── state, navigation, render loop ──────────────────────────────────────────
445
+ let idx = 0, anim = null, overview = false, ovAnim = null;
446
+ const over = { mode: null, appear: null, speed: 1 };
447
+ const SPEEDS = [1, 2, 4, 0.6];
448
+
449
+ function settingsFor(target, from) {
450
+ const s = target > from ? scene.slides[target] : scene.slides[from];
451
+ return { mode: over.mode || s.mode || "morph", appear: over.appear || s.appear || "fade", speed: (s.speed || 1) * over.speed, stagger: s.stagger };
452
+ }
453
+ function go(to) {
454
+ if (!scene) return;
455
+ to = clamp(to, 0, scene.slides.length - 1);
456
+ if (overview) { closeOverview(to); return; }
457
+ if (to === idx && !anim) return;
458
+ const from = anim ? anim.to : idx;
459
+ if (to === from) return;
460
+ const s = settingsFor(to, from);
461
+ anim = { tr: buildTransition(scene.slides[from], scene.slides[to], s.mode, s.appear, s.speed, s.stagger), t0: performance.now(), from, to };
462
+ idx = to;
463
+ hud(true);
464
+ history.replaceState(null, "", `${location.search}#${idx + 1}`);
465
+ requestDraw();
466
+ }
467
+ function replay() {
468
+ if (idx === 0) return;
469
+ const to = idx; idx = idx - 1; anim = null; go(to);
470
+ }
471
+
472
+ function openOverview() { overview = true; ovAnim = { a: rectOf(scene.slides[idx]), b: overviewRect(), t0: performance.now(), dur: 1200 }; anim = null; requestDraw(); hud(true); }
473
+ function closeOverview(to) {
474
+ const fromR = currentWorldRect(); overview = false;
475
+ idx = to; ovAnim = { a: fromR, b: rectOf(scene.slides[idx]), t0: performance.now(), dur: 1200 };
476
+ history.replaceState(null, "", `${location.search}#${idx + 1}`);
477
+ requestDraw(); hud(true);
478
+ }
479
+ function currentWorldRect() {
480
+ if (ovAnim) { const t = clamp((performance.now() - ovAnim.t0) / ovAnim.dur); return flyRect(ovAnim.a, ovAnim.b, t); }
481
+ return overview ? overviewRect() : rectOf(scene.slides[idx]);
482
+ }
483
+
484
+ let raf = 0;
485
+ function requestDraw() { if (!raf) raf = requestAnimationFrame(draw); }
486
+ function draw(now) {
487
+ raf = 0;
488
+ if (!scene) return;
489
+ clear();
490
+ let more = false;
491
+ if (ovAnim) {
492
+ const t = clamp((now - ovAnim.t0) / ovAnim.dur);
493
+ drawWorld(flyRect(ovAnim.a, ovAnim.b, t));
494
+ if (t < 1) more = true; else ovAnim = null;
495
+ } else if (overview) {
496
+ drawWorld(overviewRect());
497
+ } else if (anim) {
498
+ const T = now - anim.t0, tr = anim.tr;
499
+ const done = T >= tr.dur;
500
+ if (done) anim = null;
501
+ if (done || tr.mode === "cut") { setView({ x: 0, y: 0, w: tr.B.w, h: tr.B.h }); renderTransition(staticOf(tr.B), 0); }
502
+ else if (tr.mode === "camera") drawWorld(flyRect(rectOf(tr.A), rectOf(tr.B), T / tr.dur));
503
+ else {
504
+ const t = ease(clamp(T / tr.dur));
505
+ setView({ x: 0, y: 0, w: lerp(tr.A.w, tr.B.w, t), h: lerp(tr.A.h, tr.B.h, t) });
506
+ renderTransition(tr, T);
507
+ }
508
+ more = !done;
509
+ } else {
510
+ const s = scene.slides[idx];
511
+ setView({ x: 0, y: 0, w: s.w, h: s.h });
512
+ renderTransition(staticOf(s), 0);
513
+ }
514
+ if (more) requestDraw();
515
+ }
516
+
517
+ function resize() {
518
+ dpr = window.devicePixelRatio || 1;
519
+ canvas.width = Math.round(innerWidth * dpr); canvas.height = Math.round(innerHeight * dpr);
520
+ canvas.style.width = innerWidth + "px"; canvas.style.height = innerHeight + "px";
521
+ requestDraw();
522
+ }
523
+ addEventListener("resize", resize);
524
+
525
+ // ── HUD, keys, file loading ─────────────────────────────────────────────────
526
+ let hudT;
527
+ function hud(show) {
528
+ const el = $("#hud");
529
+ if (!scene) return;
530
+ const s = scene.slides[idx], set = settingsFor(idx, Math.max(0, idx - 1));
531
+ const ov = [over.mode && `T: ${over.mode}`, over.appear && `A: ${over.appear}`, over.speed !== 1 && `S: ×${over.speed}`].filter(Boolean);
532
+ el.innerHTML = `<b>${idx + 1}/${scene.slides.length}</b> ${esc(s.title)}` +
533
+ (idx > 0 ? ` <span>· in: ${set.mode}${set.mode === "morph" || set.mode === "zoom" ? " + " + set.appear : ""}</span>` : "") +
534
+ (ov.length ? ` <em>override ${ov.join(" · ")}</em>` : "");
535
+ el.classList.add("show");
536
+ clearTimeout(hudT);
537
+ if (!ov.length) hudT = setTimeout(() => el.classList.remove("show"), 2200);
538
+ }
539
+ const esc = (s) => s.replace(/[&<>]/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;" })[c]);
540
+ function toast(msg) { const el = $("#toast"); el.textContent = msg; el.classList.add("show"); clearTimeout(el._t); el._t = setTimeout(() => el.classList.remove("show"), 1600); }
541
+ const cycle = (list, v) => list[(list.indexOf(v) + 1) % list.length];
542
+
543
+ addEventListener("keydown", (e) => {
544
+ if (e.metaKey || e.ctrlKey || e.altKey || !scene) return;
545
+ const k = e.key;
546
+ if (k === "ArrowRight" || k === "PageDown" || k === "ArrowDown" || (k === " " && !e.shiftKey)) go((anim ? anim.to : idx) + 1);
547
+ else if (k === "ArrowLeft" || k === "PageUp" || k === "ArrowUp" || k === "Backspace" || (k === " " && e.shiftKey)) go((anim ? anim.to : idx) - 1);
548
+ else if (k === "Home") go(0);
549
+ else if (k === "End") go(scene.slides.length - 1);
550
+ else if (/^[0-9]$/.test(k)) go((k === "0" ? 10 : +k) - 1);
551
+ else if (k === "o" || k === "O" || k === "Escape") { if (overview) closeOverview(idx); else if (k !== "Escape") openOverview(); }
552
+ else if (k === "t" || k === "T") { over.mode = cycle([null, ...TRANSITIONS], over.mode); toast(`transition: ${over.mode || "as named in each frame"}`); hud(true); }
553
+ else if (k === "a" || k === "A") { over.appear = cycle([null, ...APPEARS], over.appear); toast(`appear: ${over.appear || "as named in each frame"}`); hud(true); }
554
+ else if (k === "s" || k === "S") { over.speed = cycle(SPEEDS, over.speed); toast(`speed ×${over.speed}${over.speed > 1 ? " (slow motion)" : ""}`); hud(true); }
555
+ else if (k === "r" || k === "R") replay();
556
+ else if (k === "f" || k === "F") document.fullscreenElement ? document.exitFullscreen() : document.documentElement.requestFullscreen();
557
+ else if (k === "h" || k === "H" || k === "?") $("#help").hidden = !$("#help").hidden;
558
+ else if (k === "l" || k === "L") $("#file").click();
559
+ else return;
560
+ e.preventDefault();
561
+ });
562
+ canvas.addEventListener("click", (e) => {
563
+ if (!scene) return;
564
+ if (overview) { // click a frame to fly there
565
+ const v = overviewRect(), s = Math.min(canvas.width / v.w, canvas.height / v.h);
566
+ const wx = (e.clientX * dpr - (canvas.width - v.w * s) / 2) / s + v.x, wy = (e.clientY * dpr - (canvas.height - v.h * s) / 2) / s + v.y;
567
+ const hit = scene.slides.findIndex((sl) => wx >= sl.x && wx <= sl.x + sl.w && wy >= sl.y && wy <= sl.y + sl.h);
568
+ if (hit >= 0) closeOverview(hit);
569
+ return;
570
+ }
571
+ go((anim ? anim.to : idx) + (e.shiftKey ? -1 : 1));
572
+ });
573
+
574
+ const params = new URLSearchParams(location.search);
575
+ const STATIC = params.has("static"); // ?static&frame=N → no animation, no HUD (used by `excalideck render`)
576
+ async function useData(data, name, keepPlace) {
577
+ await Promise.all(["Excalifont", "Virgil"].map((f) => document.fonts.load(`20px ${f}`).catch(() => {})));
578
+ measureCache.clear(); drawableCache.clear();
579
+ const keep = keepPlace && scene ? idx : null;
580
+ scene = parseScene(data, { image: (id, f) => { if (!f) return null; const im = new Image(); im.onload = () => requestDraw(); im.src = f.dataURL; return im; } });
581
+ const h = parseInt(params.get("frame") || location.hash.slice(1), 10);
582
+ idx = keep ?? (h > 0 ? clamp(h - 1, 0, scene.slides.length - 1) : 0);
583
+ anim = null; ovAnim = null; if (keep === null) overview = false;
584
+ if (idx === 0 && keep === null && !STATIC) { // build the first slide in from nothing
585
+ const s0 = scene.slides[0], empty = { items: [], w: s0.w, h: s0.h };
586
+ anim = { tr: buildTransition(empty, s0, "morph", over.appear || s0.appear || "fade", (s0.speed || 1) * over.speed, s0.stagger), t0: performance.now() + 300, from: 0, to: 0 };
587
+ }
588
+ $("#drop").hidden = true;
589
+ document.title = name || "excalideck";
590
+ if (!STATIC && keep === null) hud(true);
591
+ requestDraw();
592
+ readyResolve(scene.slides.length);
593
+ }
594
+ let readyResolve; const ready = new Promise((r) => (readyResolve = r));
595
+ async function loadFile(file) {
596
+ try { await useData(JSON.parse(await file.text()), file.name); toast(`loaded ${file.name}`); }
597
+ catch (err) { toast("couldn't read that file"); console.error(err); }
598
+ }
599
+ $("#file").addEventListener("change", (e) => e.target.files[0] && loadFile(e.target.files[0]));
600
+ addEventListener("dragover", (e) => { e.preventDefault(); document.body.classList.add("dragging"); });
601
+ addEventListener("dragleave", () => document.body.classList.remove("dragging"));
602
+ addEventListener("drop", (e) => { e.preventDefault(); document.body.classList.remove("dragging"); const f = e.dataTransfer.files[0]; if (f) loadFile(f); });
603
+
604
+ resize();
605
+ const src = params.get("file") || "../examples/snapline/snapline.excalidraw";
606
+ let lastText = "";
607
+ const fetchDeck = () => fetch(src, { cache: "no-store" }).then((r) => { if (!r.ok) throw new Error(r.status); return r.text(); });
608
+ fetchDeck().then((t) => { lastText = t; return useData(JSON.parse(t), src.split("/").pop()); })
609
+ .catch(() => { $("#drop").hidden = false; readyResolve(0); });
610
+ if (params.has("watch")) setInterval(async () => { // live reload: keep your place when the file changes
611
+ try { const t = await fetchDeck(); if (t !== lastText) { lastText = t; await useData(JSON.parse(t), src.split("/").pop(), true); toast("reloaded"); } } catch {}
612
+ }, 1000);
613
+ if (STATIC) document.body.classList.add("static");
614
+
615
+ window.__deck = { go, ready, get idx() { return idx; }, get count() { return scene?.slides.length ?? 0; },
616
+ get busy() { return !!anim || !!ovAnim; }, over };
617
+ }
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2019 Preet Shihn
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.