@margoengine/cutscene 0.0.0-stage → 1.0.0

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.
package/dist/editor.js ADDED
@@ -0,0 +1,514 @@
1
+ import { d as e, n as t, t as n } from "./cutscene-WWP9-stS.js";
2
+ import { MargoError as r } from "@margoengine/math/errors";
3
+ import { EditHistory as i } from "@margoengine/inspector/history";
4
+ //#region src/editor.ts
5
+ var a = "@markers", o = (e) => Number(e.toFixed(9)), s = (e, t) => {
6
+ if (!Number.isFinite(e)) throw RangeError(`${t} must be a finite number of seconds; pass a number`);
7
+ }, c = (e) => e.time ?? e.start, l = (e) => String(e.text ?? e.sound ?? e.clip ?? e.camera ?? e.timeline ?? e.name ?? "clip"), u = class u {
8
+ get doc() {
9
+ if (!this.root) return this.data;
10
+ let e = this.root.doc, t = e.timelines && Object.hasOwn(e.timelines, this.scopeName) ? e.timelines[this.scopeName] : void 0;
11
+ if (!t) throw new r("state", "Nested timeline was removed; reopen an existing timeline");
12
+ return {
13
+ format: "margo-cutscene",
14
+ version: 1,
15
+ ...t,
16
+ timelines: e.timelines
17
+ };
18
+ }
19
+ set doc(e) {
20
+ if (!this.root) this.data = e;
21
+ else {
22
+ let { duration: t, tracks: n, markers: r } = e;
23
+ this.root.doc.timelines[this.scopeName] = {
24
+ duration: t,
25
+ tracks: n,
26
+ ...r ? { markers: r } : {}
27
+ };
28
+ }
29
+ }
30
+ constructor(e, { tracks: t = [], history: r = new i(200, 0) } = {}) {
31
+ this.listeners = /* @__PURE__ */ new Set(), this.open = null, this.types = t, this.checks = new Map(t.map((e) => [e.type, e])), this.data = JSON.parse(JSON.stringify(new n(e, { tracks: t }).document)), this.history = r;
32
+ }
33
+ get duration() {
34
+ return this.doc.duration;
35
+ }
36
+ get document() {
37
+ return JSON.parse(JSON.stringify(this.doc));
38
+ }
39
+ toJSON() {
40
+ return this.document;
41
+ }
42
+ save() {
43
+ return JSON.stringify(this.doc, null, 2);
44
+ }
45
+ cutscene() {
46
+ return new n(this.document, { tracks: this.types });
47
+ }
48
+ on(e, t) {
49
+ if (e !== "change") throw RangeError(`TimelineModel has no '${String(e)}' event; use 'change'`);
50
+ return this.root ? this.root.on(e, (e) => {
51
+ let n = this.root.doc.timelines;
52
+ n && Object.hasOwn(n, this.scopeName) && t(e);
53
+ }) : (this.listeners.add(t), () => void this.listeners.delete(t));
54
+ }
55
+ nested(e) {
56
+ let t = this.root ?? this, n = t.doc.timelines, r = n && Object.hasOwn(n, e) ? n[e] : void 0;
57
+ if (!r) throw RangeError(`No nested timeline '${e}'; choose a timeline clip's definition`);
58
+ let i = new u({
59
+ ...t.document,
60
+ ...r
61
+ }, {
62
+ tracks: this.types,
63
+ history: t.history
64
+ });
65
+ return i.root = t, i.scopeName = e, i;
66
+ }
67
+ setTimeline(e, t) {
68
+ let n = this.root ?? this, r = JSON.parse(JSON.stringify(t));
69
+ return n.edit("Set nested timeline", !1, () => {
70
+ Object.defineProperty(n.doc.timelines ??= {}, e, {
71
+ value: r,
72
+ writable: !0,
73
+ enumerable: !0,
74
+ configurable: !0
75
+ });
76
+ });
77
+ }
78
+ get rows() {
79
+ let e = this.doc.tracks.map((e) => {
80
+ let [t, n] = d(e);
81
+ return {
82
+ track: e.id,
83
+ type: e.type,
84
+ label: e.target ?? e.id,
85
+ keyable: e.type === "event" || n === "key" && !!t,
86
+ items: (t ?? []).map((t, r) => ({
87
+ track: e.id,
88
+ index: r,
89
+ kind: n,
90
+ time: c(t),
91
+ duration: n === "clip" ? t.duration : 0,
92
+ label: n === "clip" ? l(t) : n === "event" ? String(t.name) : ""
93
+ }))
94
+ };
95
+ });
96
+ return e.push({
97
+ track: a,
98
+ type: "marker",
99
+ label: "Markers",
100
+ keyable: !0,
101
+ items: (this.doc.markers ?? []).map((e, t) => ({
102
+ track: a,
103
+ index: t,
104
+ kind: "marker",
105
+ time: e.time,
106
+ duration: 0,
107
+ label: e.name
108
+ }))
109
+ }), e;
110
+ }
111
+ addKey(e, t, n = {}) {
112
+ if (s(t, "Key time"), t < 0 || t > this.duration) throw RangeError(`Key time ${t} is outside the timeline; pass 0 to its duration`);
113
+ if (e === "@markers" || this.track(e).type === "event") return this.addItem(e, {
114
+ name: e === "@markers" ? "marker" : "event",
115
+ ...n,
116
+ time: t
117
+ });
118
+ let r = this.track(e);
119
+ if (!r.keys) throw RangeError(`Track '${e}' holds clips, not keys; use addItem with the clip's fields`);
120
+ return this.addItem(e, {
121
+ ...this.sampled(r, t),
122
+ ...n,
123
+ time: t
124
+ });
125
+ }
126
+ addItem(e, t) {
127
+ let n = JSON.parse(JSON.stringify(t)), r = -1;
128
+ return this.edit("Add", !0, () => {
129
+ let t = this.list(e, !0);
130
+ t.push(n), f(t), r = t.indexOf(n);
131
+ }), {
132
+ track: e,
133
+ index: r
134
+ };
135
+ }
136
+ addTrack(e) {
137
+ let t = JSON.parse(JSON.stringify(e));
138
+ this.edit("Add track", !0, () => {
139
+ this.doc.tracks.push(t);
140
+ });
141
+ }
142
+ moveItems(e, t) {
143
+ s(t, "Move");
144
+ let n = e.map((e) => ({
145
+ ref: e,
146
+ item: this.item(e)
147
+ }));
148
+ if (!n.length || t === 0) return [...e];
149
+ let r = t;
150
+ for (let { item: e } of n) {
151
+ let t = c(e), n = t + (e.duration ?? 0);
152
+ r = Math.max(-t, Math.min(this.duration - n, r));
153
+ }
154
+ return r === 0 || !this.edit("Move", !1, () => {
155
+ for (let { item: e } of n) e.start === void 0 ? e.time = o(e.time + r) : e.start = o(e.start + r);
156
+ for (let e of new Set(n.map(({ ref: e }) => e.track))) f(this.list(e));
157
+ }) ? [...e] : n.map(({ ref: e, item: t }) => ({
158
+ track: e.track,
159
+ index: this.list(e.track).indexOf(t)
160
+ }));
161
+ }
162
+ setItem(e, t) {
163
+ let n = this.item(e);
164
+ return this.edit("Set", !1, () => {
165
+ for (let [e, r] of Object.entries(t)) r === void 0 ? delete n[e] : n[e] = JSON.parse(JSON.stringify(r));
166
+ });
167
+ }
168
+ updateItem(e, t) {
169
+ let n = this.item(e);
170
+ return this.edit("Set", !1, () => {
171
+ for (let [e, r] of Object.entries(t)) r === void 0 ? delete n[e] : n[e] = JSON.parse(JSON.stringify(r));
172
+ f(this.list(e.track));
173
+ }) ? {
174
+ track: e.track,
175
+ index: this.list(e.track).indexOf(n)
176
+ } : void 0;
177
+ }
178
+ deleteItems(e) {
179
+ let t = e.map((e) => ({
180
+ ref: e,
181
+ item: this.item(e)
182
+ }));
183
+ return !t.length || this.edit("Delete", !1, () => {
184
+ for (let { ref: e, item: n } of t) {
185
+ let t = this.list(e.track);
186
+ t.splice(t.indexOf(n), 1);
187
+ }
188
+ });
189
+ }
190
+ setDuration(e) {
191
+ return s(e, "Duration"), this.edit("Set duration", !1, () => {
192
+ this.doc = {
193
+ ...this.doc,
194
+ duration: e
195
+ };
196
+ });
197
+ }
198
+ begin(e) {
199
+ if (this.root) this.root.begin(e);
200
+ else {
201
+ if (this.open) throw new r("state", "An edit is already open; call commit() before begin()");
202
+ this.open = {
203
+ label: e,
204
+ before: this.snapshot()
205
+ };
206
+ }
207
+ }
208
+ commit() {
209
+ if (this.root) {
210
+ this.root.commit();
211
+ return;
212
+ }
213
+ if (!this.open) throw new r("state", "No edit is open; call begin() first");
214
+ let { label: e, before: t } = this.open;
215
+ this.open = null, this.remember(e, t);
216
+ }
217
+ undo() {
218
+ this.history.undo();
219
+ }
220
+ redo() {
221
+ this.history.redo();
222
+ }
223
+ snap(e, { step: t = .1, reach: n = .05, ignore: r = [], times: i = [] } = {}) {
224
+ s(e, "Snap time");
225
+ let a = new Set(r.map((e) => `${e.track}\0${e.index}`)), c = e, l = n, u = (t) => {
226
+ let n = Math.abs(t - e);
227
+ n > l || (l = n, c = t);
228
+ };
229
+ if (n > 0) {
230
+ for (let e of i) u(e);
231
+ u(0), u(this.duration);
232
+ for (let e of this.rows) for (let t of e.items) a.has(`${t.track}\0${t.index}`) || (u(t.time), t.duration && u(t.time + t.duration));
233
+ }
234
+ return c !== e || !(t > 0) ? c : Math.min(this.duration, Math.max(0, o(Math.round(e / t) * t)));
235
+ }
236
+ track(e) {
237
+ let t = this.doc.tracks.find((t) => t.id === e);
238
+ if (!t) throw RangeError(`No track '${e}' in this cutscene; use a row's track`);
239
+ return t;
240
+ }
241
+ list(e, t = !1) {
242
+ if (e === "@markers") return t && !this.doc.markers && (this.doc = {
243
+ ...this.doc,
244
+ markers: []
245
+ }), this.doc.markers ?? [];
246
+ let [n] = d(this.track(e));
247
+ if (!n) throw RangeError(`Track '${e}' holds nothing to edit here; use a row with items`);
248
+ return n;
249
+ }
250
+ item(e) {
251
+ let t = this.list(e.track)[e.index];
252
+ if (!t) throw RangeError(`No item ${e.index} on track '${e.track}'; use refs the last edit gave`);
253
+ return t;
254
+ }
255
+ sampled(e, t) {
256
+ let n = this.cutscene().evaluate(t);
257
+ if (e.type === "camera") {
258
+ let { position: e, target: t, fov: r, roll: i } = n.camera ?? {};
259
+ return {
260
+ position: e,
261
+ target: t,
262
+ fov: r,
263
+ roll: i
264
+ };
265
+ }
266
+ return e.type === "transform" ? { ...n.transforms[e.target] } : e.type === "property" ? { value: n.properties[e.target]?.[e.property] } : this.checks.get(e.type)?.sampleKey?.(e, t) ?? {};
267
+ }
268
+ snapshot() {
269
+ return JSON.stringify(this.doc);
270
+ }
271
+ restore(e, t) {
272
+ this.doc = JSON.parse(e), this.changed(t);
273
+ }
274
+ changed(e) {
275
+ for (let t of [...this.listeners]) t(e);
276
+ }
277
+ remember(e, t) {
278
+ let n = this.snapshot();
279
+ n !== t && this.history.record({
280
+ label: e,
281
+ undo: () => this.restore(t, e),
282
+ redo: () => this.restore(n, e)
283
+ });
284
+ }
285
+ edit(n, r, i) {
286
+ let a = this.root ?? this, o = a.snapshot();
287
+ try {
288
+ i();
289
+ } catch (e) {
290
+ throw a.doc = JSON.parse(o), e;
291
+ }
292
+ let s = e(a.doc, t, a.checks);
293
+ if (s.length) {
294
+ if (a.doc = JSON.parse(o), r) throw RangeError(`${n} refused: ${s[0].path}: ${s[0].message}; use a value the document allows`);
295
+ return !1;
296
+ }
297
+ return a.open || a.remember(n, o), a.changed(n), !0;
298
+ }
299
+ };
300
+ function d(e) {
301
+ return e.keys ? [e.keys, "key"] : e.events ? [e.events, "event"] : [e.clips, "clip"];
302
+ }
303
+ var f = (e) => void e.sort((e, t) => c(e) - c(t)), p = 10, m = 2e3, h = 1.25, g = [
304
+ .05,
305
+ .1,
306
+ .25,
307
+ .5,
308
+ 1,
309
+ 2,
310
+ 5,
311
+ 10,
312
+ 30,
313
+ 60,
314
+ 120,
315
+ 300,
316
+ 600
317
+ ], _ = 60, v = "\n.mtl{--bg:#16181d;--panel:#1f2229;--line:#3a3f4a;--text:#e6e8ec;--dim:#a9afbb;--accent:#f2b134;--clip:#2f6f8f;\n background:var(--bg);color:var(--text);font:13px/1.4 system-ui,sans-serif;display:flex;flex-direction:column;min-height:120px;\n border:1px solid var(--line);outline-offset:-2px;touch-action:none;user-select:none}\n.mtl button{font:inherit;color:inherit}\n.mtl-bar{display:flex;gap:4px;align-items:center;padding:4px;background:var(--panel);border-bottom:1px solid var(--line);flex-wrap:wrap}\n.mtl-bar button{min-height:28px;min-width:28px;padding:0 8px;background:transparent;border:1px solid var(--line);border-radius:3px;cursor:pointer}\n.mtl-bar button[aria-pressed=true]{background:var(--accent);color:#16181d;border-color:var(--accent)}\n.mtl-bar button:disabled{opacity:.45;cursor:default}\n.mtl-time{margin-left:auto;font-variant-numeric:tabular-nums;padding:0 8px}\n.mtl-body{display:flex;flex:1;min-height:0;overflow-y:auto}\n.mtl-names{flex:0 0 130px;border-right:1px solid var(--line);background:var(--panel)}\n.mtl-name{height:28px;line-height:28px;padding:0 8px;border-bottom:1px solid var(--line);overflow:hidden;white-space:nowrap;text-overflow:ellipsis;color:var(--dim);cursor:pointer}\n.mtl-name[data-current]{color:var(--text);box-shadow:inset 3px 0 var(--accent)}\n.mtl-head{height:24px;line-height:24px;border-bottom:1px solid var(--line)}\n.mtl-scroll{flex:1;overflow-x:auto;overflow-y:hidden;position:relative}\n.mtl-inner{position:relative}\n.mtl-ruler{height:24px;position:relative;border-bottom:1px solid var(--line);cursor:ew-resize;overflow:hidden}\n.mtl-tick{position:absolute;top:0;bottom:0;border-left:1px solid var(--line);padding-left:3px;font-size:11px;color:var(--dim);pointer-events:none}\n.mtl-lane{height:28px;position:relative;border-bottom:1px solid var(--line)}\n.mtl-item{position:absolute;top:3px;height:21px;padding:0;background:var(--clip);border:1px solid transparent;border-radius:3px;cursor:grab;overflow:hidden;white-space:nowrap;text-overflow:ellipsis;font-size:11px;text-align:left}\n.mtl-item[data-kind=key],.mtl-item[data-kind=event],.mtl-item[data-kind=marker]{width:13px;margin-left:-7px;background:var(--dim);transform:rotate(45deg) scale(.72)}\n.mtl-item[data-kind=event],.mtl-item[data-kind=marker]{border-radius:50%;transform:none;top:7px;height:13px}\n.mtl-item[aria-pressed=true]{background:var(--accent);color:#16181d;border-color:#fff}\n.mtl-play{position:absolute;top:0;bottom:0;width:1px;background:var(--accent);pointer-events:none}\n.mtl :focus-visible{outline:2px solid #fff;outline-offset:1px}\n", y = class {
318
+ constructor(e, t = {}) {
319
+ this.bar = {}, this.listeners = /* @__PURE__ */ new Map(), this.playhead = 0, this.picked = [], this.drag = null, this.holding = !1, this.disposed = !1, this.abort = new AbortController();
320
+ let { parent: n, zoom: r = 100, step: i = .1, snap: a = !0, fileName: o = "cutscene.json", ...s } = t;
321
+ if (!(r >= p && r <= m)) throw RangeError(`Timeline zoom must be ${p} to ${m}; pass pixels a second`);
322
+ if (!(i > 0) || !Number.isFinite(i)) throw RangeError("Timeline step must be above 0; pass seconds");
323
+ this.model = e instanceof u ? e : new u(e, s), this.pixels = r, this.step = i, this.snapping = a, this.fileName = o, this.row = this.model.rows.find((e) => e.keyable)?.track ?? "@markers";
324
+ let c = (e, t, n) => {
325
+ let r = window.document.createElement(e);
326
+ return r.className = t, n?.append(r), r;
327
+ }, l = this.element = c("div", "mtl");
328
+ l.tabIndex = 0, l.setAttribute("role", "application"), l.setAttribute("aria-label", "Cutscene timeline"), c("style", "", l).textContent = v;
329
+ let d = c("div", "mtl-bar", l);
330
+ d.setAttribute("role", "toolbar"), d.setAttribute("aria-label", "Timeline tools");
331
+ let f = (e, t, n) => {
332
+ let r = c("button", "", d);
333
+ return r.type = "button", r.textContent = e, r.title = t, r.setAttribute("aria-label", t), r.addEventListener("click", n, { signal: this.abort.signal }), r;
334
+ };
335
+ this.bar.key = f("Key", "Add key at the playhead", () => this.addKey()), this.bar.undo = f("Undo", "Undo", () => this.history("undo")), this.bar.redo = f("Redo", "Redo", () => this.history("redo")), this.bar.snap = f("Snap", "Snap to the grid and to other items", () => {
336
+ this.snapping = !this.snapping, this.toolbar();
337
+ }), f("-", "Zoom out", () => this.zoom = this.pixels / h), f("+", "Zoom in", () => this.zoom = this.pixels * h), f("Export", "Save the document as a JSON file", () => this.download()), this.bar.time = c("span", "mtl-time", d), this.bar.time.setAttribute("aria-live", "off");
338
+ let g = c("div", "mtl-body", l);
339
+ this.names = c("div", "mtl-names", g), this.scroll = c("div", "mtl-scroll", g), this.inner = c("div", "mtl-inner", this.scroll), this.ruler = c("div", "mtl-ruler", this.inner), this.ruler.tabIndex = 0, this.ruler.setAttribute("role", "slider"), this.ruler.setAttribute("aria-label", "Playhead"), this.ruler.setAttribute("aria-valuemin", "0"), this.lanes = c("div", "", this.inner), this.head = c("div", "mtl-play", this.inner);
340
+ let _ = this.abort.signal;
341
+ l.addEventListener("pointerdown", (e) => this.press(e), { signal: _ }), l.addEventListener("pointermove", (e) => this.pointerMove(e), { signal: _ }), l.addEventListener("pointerup", (e) => this.release(e), { signal: _ }), l.addEventListener("pointercancel", (e) => this.release(e), { signal: _ }), l.addEventListener("keydown", (e) => this.key(e), { signal: _ }), l.addEventListener("wheel", (e) => this.wheel(e), {
342
+ passive: !1,
343
+ signal: _
344
+ }), this.unsubscribe = this.model.on("change", (e) => {
345
+ this.holding || this.draw(), this.emit("change", e);
346
+ }), this.draw(), n?.append(l);
347
+ }
348
+ get time() {
349
+ return this.playhead;
350
+ }
351
+ set time(e) {
352
+ if (!Number.isFinite(e)) throw RangeError("Timeline time must be a finite number of seconds; pass a number");
353
+ this.playhead = Math.min(this.model.duration, Math.max(0, e)), this.place();
354
+ }
355
+ get zoom() {
356
+ return this.pixels;
357
+ }
358
+ set zoom(e) {
359
+ if (!Number.isFinite(e)) throw RangeError("Timeline zoom must be a finite number; pass pixels a second");
360
+ this.pixels = Math.min(m, Math.max(p, e)), this.draw();
361
+ }
362
+ get selection() {
363
+ return this.picked;
364
+ }
365
+ set selection(e) {
366
+ this.picked = [...e], this.draw(), this.emit("select", this.picked);
367
+ }
368
+ on(e, t) {
369
+ let n = this.listeners.get(e);
370
+ return n || this.listeners.set(e, n = /* @__PURE__ */ new Set()), n.add(t), () => void n.delete(t);
371
+ }
372
+ dispose() {
373
+ this.disposed || (this.disposed = !0, this.abort.abort(), this.unsubscribe(), this.listeners.clear(), this.element.remove());
374
+ }
375
+ [Symbol.dispose]() {
376
+ this.dispose();
377
+ }
378
+ emit(e, t) {
379
+ for (let n of [...this.listeners.get(e) ?? []]) n(t);
380
+ }
381
+ toolbar() {
382
+ this.bar.undo.disabled = !this.model.history.undoCount, this.bar.redo.disabled = !this.model.history.redoCount, this.bar.snap.setAttribute("aria-pressed", String(this.snapping)), this.bar.time.textContent = `${this.playhead.toFixed(2)} s`;
383
+ }
384
+ place() {
385
+ this.head.style.left = `${this.playhead * this.pixels}px`, this.ruler.setAttribute("aria-valuenow", this.playhead.toFixed(2)), this.ruler.setAttribute("aria-valuetext", `${this.playhead.toFixed(2)} seconds`), this.toolbar();
386
+ }
387
+ draw() {
388
+ let { rows: e, duration: t } = this.model, n = window.document.activeElement, r = n?.dataset?.track !== void 0 && n.closest(".mtl") === this.element, i = window.document.createDocumentFragment(), a = window.document.createDocumentFragment(), o = new Set(this.picked.map((e) => `${e.track}\0${e.index}`)), s = t * this.pixels;
389
+ this.inner.style.width = `${s + _}px`, this.ruler.setAttribute("aria-valuemax", String(t)), this.ruler.textContent = "";
390
+ let c = g.find((e) => e * this.pixels >= _) ?? g.at(-1);
391
+ for (let e = 0; e * c <= t + 1e-9; e++) {
392
+ let t = window.document.createElement("div");
393
+ t.className = "mtl-tick", t.style.left = `${e * c * this.pixels}px`, t.textContent = `${Number((e * c).toFixed(2))}`, this.ruler.append(t);
394
+ }
395
+ let l = window.document.createElement("div");
396
+ l.className = "mtl-head", i.append(l);
397
+ for (let t of e) {
398
+ let e = window.document.createElement("div");
399
+ e.className = "mtl-name", e.textContent = t.label, e.title = `${t.type}: ${t.label}`, e.dataset.row = t.track, t.track === this.row && (e.dataset.current = ""), i.append(e);
400
+ let n = window.document.createElement("div");
401
+ n.className = "mtl-lane", n.dataset.row = t.track, n.setAttribute("role", "group"), n.setAttribute("aria-label", `${t.type} ${t.label}`);
402
+ for (let e of t.items) {
403
+ let r = window.document.createElement("button");
404
+ r.type = "button", r.className = "mtl-item", r.dataset.kind = e.kind, r.dataset.track = e.track, r.dataset.index = String(e.index), r.style.left = `${e.time * this.pixels}px`, e.kind === "clip" && (r.style.width = `${Math.max(4, e.duration * this.pixels)}px`, r.textContent = e.label), r.setAttribute("aria-pressed", String(o.has(`${e.track}\0${e.index}`))), r.setAttribute("aria-label", `${e.kind} ${e.label} at ${e.time.toFixed(2)} seconds on ${t.label}`.replace(" ", " ")), n.append(r);
405
+ }
406
+ a.append(n);
407
+ }
408
+ this.names.replaceChildren(i), this.lanes.replaceChildren(a), this.place(), r && this.picked[0] ? this.itemElement(this.picked[0])?.focus() : r && this.element.focus();
409
+ }
410
+ itemElement({ track: e, index: t }) {
411
+ return this.lanes.querySelector(`[data-track="${CSS.escape(e)}"][data-index="${t}"]`);
412
+ }
413
+ timeAt(e) {
414
+ return (e.clientX - this.inner.getBoundingClientRect().left) / this.pixels;
415
+ }
416
+ snapped(e, t = []) {
417
+ return this.snapping ? this.model.snap(e, {
418
+ step: this.step,
419
+ reach: 8 / this.pixels,
420
+ ignore: t,
421
+ times: t.length ? [this.playhead] : []
422
+ }) : e;
423
+ }
424
+ seek(e) {
425
+ this.time = e, this.emit("seek", this.playhead);
426
+ }
427
+ press(e) {
428
+ if (e.button !== 0 || this.drag) return;
429
+ let t = e.target, n = t.closest(".mtl-item"), r = t.closest("[data-row]")?.dataset.row;
430
+ if (r !== void 0 && r !== this.row) {
431
+ this.row = r;
432
+ for (let e of this.names.querySelectorAll(".mtl-name")) e.dataset.row === r ? e.dataset.current = "" : delete e.dataset.current;
433
+ }
434
+ if (n) {
435
+ let t = {
436
+ track: n.dataset.track,
437
+ index: Number(n.dataset.index)
438
+ }, r = this.picked.some((e) => e.track === t.track && e.index === t.index);
439
+ if (e.shiftKey || e.ctrlKey || e.metaKey ? this.selection = r ? this.picked.filter((e) => e.track !== t.track || e.index !== t.index) : [...this.picked, t] : r || (this.selection = [t]), !this.picked.length) return;
440
+ let i = this.model.rows.flatMap((e) => e.items).find((e) => e.track === t.track && e.index === t.index);
441
+ this.grab(e, "items", this.timeAt(e), i.time), this.model.begin("Move"), this.itemElement(t)?.focus();
442
+ } else this.ruler.contains(t) ? (this.grab(e, "scrub", 0, 0), this.ruler.focus(), this.seek(this.snapped(this.timeAt(e)))) : this.scroll.contains(t) && (this.picked.length && (this.selection = []), this.seek(this.snapped(this.timeAt(e))));
443
+ }
444
+ grab(e, t, n, r) {
445
+ this.element.setPointerCapture(e.pointerId), e.preventDefault(), this.drag = {
446
+ pointer: e.pointerId,
447
+ kind: t,
448
+ from: n,
449
+ origin: r,
450
+ applied: 0
451
+ };
452
+ }
453
+ pointerMove(e) {
454
+ let t = this.drag;
455
+ if (!t || e.pointerId !== t.pointer) return;
456
+ if (t.kind === "scrub") {
457
+ this.seek(this.snapped(this.timeAt(e)));
458
+ return;
459
+ }
460
+ let n = this.snapped(t.origin + this.timeAt(e) - t.from, this.picked);
461
+ t.applied += this.shift(n - t.origin - t.applied);
462
+ }
463
+ shift(e) {
464
+ let t = () => {
465
+ let { track: e, index: t } = this.picked[0];
466
+ return this.model.rows.find((t) => t.track === e).items[t].time;
467
+ }, n = t();
468
+ return this.holding = !0, this.picked = this.model.moveItems(this.picked, e), this.holding = !1, this.draw(), t() - n;
469
+ }
470
+ release(e) {
471
+ let t = this.drag;
472
+ t && e.pointerId === t.pointer && (this.drag = null, this.element.hasPointerCapture(e.pointerId) && this.element.releasePointerCapture(e.pointerId), t.kind === "items" && (this.model.commit(), this.draw(), this.emit("select", this.picked)));
473
+ }
474
+ history(e) {
475
+ this.drag || (this.picked.length && (this.selection = []), this.model[e]());
476
+ }
477
+ addKey() {
478
+ let e = this.model.rows.find((e) => e.track === this.row);
479
+ e?.keyable && (this.selection = [this.model.addKey(e.track, this.playhead)], this.itemElement(this.picked[0])?.focus());
480
+ }
481
+ nudge(e, t) {
482
+ let n = e * this.step * (t ? 10 : 1);
483
+ this.picked.length ? (this.shift(n), this.emit("select", this.picked)) : this.seek(o(this.playhead + n));
484
+ }
485
+ key(e) {
486
+ let { key: t } = e, n = e.ctrlKey || e.metaKey, r = t.toLowerCase();
487
+ if (n && r === "z") this.history(e.shiftKey ? "redo" : "undo");
488
+ else if (n && r === "y") this.history("redo");
489
+ else if (n || e.altKey) return;
490
+ else if (t === "ArrowLeft") this.nudge(-1, e.shiftKey);
491
+ else if (t === "ArrowRight") this.nudge(1, e.shiftKey);
492
+ else if (t === "Home") this.seek(0);
493
+ else if (t === "End") this.seek(this.model.duration);
494
+ else if (r === "k") this.addKey();
495
+ else if (t === "Delete" || t === "Backspace") this.picked.length && this.model.deleteItems(this.picked) && (this.selection = []);
496
+ else if (t === "+" || t === "=") this.zoom = this.pixels * h;
497
+ else if (t === "-") this.zoom = this.pixels / h;
498
+ else if (t === "Escape") this.selection = [];
499
+ else return;
500
+ e.preventDefault();
501
+ }
502
+ wheel(e) {
503
+ if (!e.ctrlKey && !e.metaKey) return;
504
+ e.preventDefault();
505
+ let t = this.timeAt(e), n = e.clientX - this.scroll.getBoundingClientRect().left;
506
+ this.zoom = this.pixels * (e.deltaY < 0 ? h : 1 / h), this.scroll.scrollLeft = t * this.pixels - n;
507
+ }
508
+ download() {
509
+ let e = URL.createObjectURL(new Blob([this.model.save()], { type: "application/json" })), t = window.document.createElement("a");
510
+ t.href = e, t.download = this.fileName, t.click(), URL.revokeObjectURL(e);
511
+ }
512
+ };
513
+ //#endregion
514
+ export { a as MARKERS, y as TimelineEditor, u as TimelineModel };
@@ -0,0 +1,162 @@
1
+ // @ts-ignore optional peer: its types apply when it is installed
2
+ import { type TextSize, type Ui } from '@margoengine/ui';
3
+ /** One caption: shown from `start` (inclusive) to `end` (exclusive), in film seconds. */
4
+ export interface FilmCue {
5
+ start: number;
6
+ end: number;
7
+ /** The text. Newlines break lines. */
8
+ text: string;
9
+ }
10
+ /**
11
+ * A cue as a film may hold it: a {@link FilmCue}, a `[start, end, text]` tuple, or a cue of
12
+ * `@margoengine/text/captions` (`{ start, end, lines }`, lines joined by newlines).
13
+ */
14
+ export type FilmCueInput = FilmCue | readonly [start: number, end: number, text: string] | {
15
+ readonly start: number;
16
+ readonly end: number;
17
+ readonly lines: readonly string[];
18
+ };
19
+ /** One chapter of a film. */
20
+ export interface FilmChapter {
21
+ /** Film second the chapter starts. */
22
+ start: number;
23
+ /** Number on the card. Default the chapter's position in the list, counted from `firstNumber`. */
24
+ number?: number;
25
+ /** Chapter title, the large line of the card. */
26
+ title: string;
27
+ /** Place and date line under the title, such as `'Fauld, Staffordshire, 1944'`. Default none. */
28
+ place?: string;
29
+ /** Show a card for this chapter. Default true; a cold open sets false. */
30
+ card?: boolean;
31
+ /** Seconds the card stays up, fades included. Default the spec's `chapterHold`. */
32
+ hold?: number;
33
+ }
34
+ /** The closing card. */
35
+ export interface FilmClosing {
36
+ /** Film second the card starts to fade in. */
37
+ start: number;
38
+ /** Lines of the card, top to bottom, each with its own size and colour. Default {@link defaultClosingLines}. */
39
+ lines?: readonly FilmTitleLine[];
40
+ }
41
+ /** One line of text on a card. */
42
+ export interface FilmTitleLine {
43
+ text: string;
44
+ /** Default `'body'`. */
45
+ size?: TextSize;
46
+ /** `#rrggbb[aa]` or a theme colour role. Default `'#fff5e8'`. */
47
+ color?: string;
48
+ }
49
+ /** Everything {@link filmTitlesAt} and {@link FilmTitles} read. */
50
+ export interface FilmTitlesSpec {
51
+ /** Film title, shown on the default closing card. */
52
+ title: string;
53
+ /** Captions. Order does not matter; where two overlap, the one that starts first shows. Default none. */
54
+ cues?: readonly FilmCueInput[];
55
+ /** Chapters in film order. Default none. */
56
+ chapters?: readonly FilmChapter[];
57
+ /** The "of" number on cards (`03 / 13`). Default the highest chapter number. */
58
+ chapterCount?: number;
59
+ /** Number of the first chapter when chapters carry no `number`. Default 0 (a cold open is chapter 00). */
60
+ firstNumber?: number;
61
+ /** Seconds a chapter card stays up, fades included. Default 4. */
62
+ chapterHold?: number;
63
+ /** Closing card, or none. Default none. */
64
+ closing?: FilmClosing;
65
+ /** Seconds a caption or card takes to fade in. Default 0.22. */
66
+ fadeIn?: number;
67
+ /** Seconds a caption or card takes to fade out. Default 0.24. */
68
+ fadeOut?: number;
69
+ /** Seconds the closing card takes to fade in. Default 1. */
70
+ closingFade?: number;
71
+ }
72
+ /** What shows at one film time. A new object each call. */
73
+ export interface FilmTitlesState {
74
+ /** The caption on screen, or null. */
75
+ caption: {
76
+ text: string;
77
+ opacity: number;
78
+ } | null;
79
+ /** The chapter card on screen, or null. `label` is `'03 / 13'`. */
80
+ chapter: {
81
+ index: number;
82
+ label: string;
83
+ title: string;
84
+ place: string | null;
85
+ opacity: number;
86
+ } | null;
87
+ /** Opacity of the closing card, 0 when there is none. */
88
+ closing: number;
89
+ }
90
+ /** The closing card's lines when the spec gives none: a credit, the film title and a call to subscribe. */
91
+ export declare function defaultClosingLines(title: string): FilmTitleLine[];
92
+ /** Checks a spec and resolves it; {@link filmTitlesAt} and {@link FilmTitles} call it, so a bad spec fails at once. */
93
+ export declare function checkFilmTitles(spec: FilmTitlesSpec): void;
94
+ /**
95
+ * What a film shows at film second `t`: the caption with its fade, the chapter card with its fade and the closing
96
+ * card's opacity. Pure: the same spec and time give the same state, whatever was asked before.
97
+ *
98
+ * @example
99
+ * const state = filmTitlesAt({ title: 'Fauld', cues: [[1, 4, 'November 1944.']] }, 2);
100
+ * state.caption; // { text: 'November 1944.', opacity: 1 }
101
+ */
102
+ export declare function filmTitlesAt(spec: FilmTitlesSpec, t: number): FilmTitlesState;
103
+ /** Looks of {@link FilmTitles}. Every field has a default matched to a 1920 by 1080 reference UI. */
104
+ export interface FilmTitlesStyle {
105
+ /** Caption text size. Default 39. */
106
+ captionSize?: TextSize;
107
+ /** Caption text colour. Default `'#faf4e7'`. */
108
+ captionColor?: string;
109
+ /** Panel colour behind captions and cards. Default `'#111a23cf'`. */
110
+ background?: string;
111
+ /** Chapter number size. Default 30. */
112
+ numberSize?: TextSize;
113
+ /** Chapter title size. Default 64. */
114
+ titleSize?: TextSize;
115
+ /** Place and date line size. Default 32. */
116
+ placeSize?: TextSize;
117
+ /** Margin of the caption panel from the bottom-left corner, `[top, right, bottom, left]`. Default `[0, 0, 74, 97]`. */
118
+ captionMargin?: [number, number, number, number];
119
+ /** Margin of the chapter and closing cards, `[top, right, bottom, left]`. Default `[0, 0, 200, 98]`. */
120
+ cardMargin?: [number, number, number, number];
121
+ }
122
+ /**
123
+ * Captions, chapter cards and a closing card drawn with `@margoengine/ui` on film time. Call `update(t)` with the film
124
+ * second each frame (or once per captured frame); the widgets only change when what shows changes.
125
+ *
126
+ * @example
127
+ * import { Ui, UiRenderer } from '@margoengine/ui';
128
+ * import { parseSrt } from '@margoengine/text/captions';
129
+ * import { FilmTitles } from '@margoengine/cutscene/film-titles';
130
+ *
131
+ * const ui = new Ui({ scale: { reference: [1920, 1080], match: 0.5 } });
132
+ * UiRenderer.attach(engine, ui);
133
+ * using titles = new FilmTitles(ui, {
134
+ * title: 'Fauld',
135
+ * cues: parseSrt(srtText).cues,
136
+ * chapters: [{ start: 0, title: 'Cold open', card: false }, { start: 43, title: 'Gentle country', place: 'Fauld, 1944' }],
137
+ * closing: { start: 880 },
138
+ * });
139
+ * engine.onFrame(() => titles.update(filmTime));
140
+ */
141
+ export declare class FilmTitles implements Disposable {
142
+ /** The spec this draws. */
143
+ readonly spec: FilmTitlesSpec;
144
+ /** What the last `update` showed. */
145
+ state: FilmTitlesState;
146
+ private readonly ui;
147
+ private readonly widgets;
148
+ private readonly caption;
149
+ private readonly captionPanel;
150
+ private readonly number;
151
+ private readonly title;
152
+ private readonly place;
153
+ private readonly card;
154
+ private readonly closing;
155
+ private disposed;
156
+ constructor(ui: Ui, spec: FilmTitlesSpec, style?: FilmTitlesStyle);
157
+ /** Shows what the film shows at second `t` and returns it. */
158
+ update(t: number): FilmTitlesState;
159
+ /** Removes the widgets from the UI. Safe to call twice. */
160
+ dispose(): void;
161
+ [Symbol.dispose](): void;
162
+ }