-
-
Notifications
You must be signed in to change notification settings - Fork 51
Expand file tree
/
Copy pathapp.js
More file actions
4597 lines (4518 loc) · 194 KB
/
Copy pathapp.js
File metadata and controls
4597 lines (4518 loc) · 194 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* ═══════════════════════════════════════════════════════════════════════════
FableCut — a browser-based non-linear video editor
Works standalone (open index.html) or connected to server.js, which adds
persistent projects (project.json), a media library folder, and a REST API
so external tools (e.g. Claude Code) can edit the timeline programmatically.
═══════════════════════════════════════════════════════════════════════════ */
"use strict";
/* ── Constants ─────────────────────────────────────────────────────────── */
const TRACKS = [
{ id: "V3", kind: "video", h: 44, color: "#ffd166" },
{ id: "V2", kind: "video", h: 58, color: "#7b6cff" },
{ id: "V1", kind: "video", h: 58, color: "#4f8cff" },
{ id: "A1", kind: "audio", h: 42, color: "#7ec249" },
{ id: "A2", kind: "audio", h: 42, color: "#5a9e3a" },
{ id: "A3", kind: "audio", h: 42, color: "#4a8a2f" },
{ id: "A4", kind: "audio", h: 42, color: "#3a7226" },
];
/* Three timeline density presets. L matches the original track heights (with thumbs).
S is compact solid-color rows; M is in between. */
const TRACK_SIZE_PRESETS = {
s: { thumbs: false, h: { V3: 26, V2: 26, V1: 26, A1: 22, A2: 22, A3: 22, A4: 22 } },
m: { thumbs: true, h: { V3: 36, V2: 44, V1: 44, A1: 32, A2: 32, A3: 32, A4: 32 } },
l: { thumbs: true, h: { V3: 44, V2: 58, V1: 58, A1: 42, A2: 42, A3: 42, A4: 42 } },
};
const TRACK_SIZE_KEY = "fablecut-track-size";
const LAST_TRANS_KEY = { in: "fablecut-last-trans-in", out: "fablecut-last-trans-out" };
const DEFAULT_LAST_TRANS = { type: "fade", duration: 1 };
const RULER_H = 26;
const SNAP_PX = 8;
const MIN_DUR = 0.05;
const ZOOM_MIN = 1;
const ZOOM_MAX = 300;
const TIMELINE_PAD_SEC = 15; // trailing empty seconds in the scrollable content
const DEFAULT_PROPS = {
x: 0, y: 0, scale: 1, rotation: 0, opacity: 1, volume: 1,
speed: 1, // playback rate (video/audio)
brightness: 100, contrast: 100, saturation: 100, hue: 0,
blur: 0, grayscale: 0, sepia: 0, invert: 0,
temperature: 0, tint: 0, vignette: 0, // color grade extensions
filterPreset: "none", // named look, see FILTER_PRESETS
fit: "contain", // contain | cover | stretch | none
cropL: 0, cropT: 0, cropR: 0, cropB: 0, // % trimmed off each source edge
flipH: false, flipV: false,
cornerRadius: 0, // px, rounded corners (PiP look)
blend: "normal", // canvas blend mode
chromaKey: "", chromaTolerance: 26, chromaSoftness: 12, // green-screen key
bgRemove: false, // AI person cut-out (MediaPipe)
shake: 0, shakeSpeed: 8, // handheld/impact camera shake (px)
rgbSplit: 0, // chromatic aberration (px)
grain: 0, // film grain (%)
text: "Title", fontSize: 72, color: "#ffffff", color2: "", font: "Segoe UI",
bold: true, italic: false, weight: 0, align: "center",
letterSpacing: 0, lineHeight: 1.2, uppercase: false, textShadow: 12,
glow: 0, glowColor: "", // neon glow (glowColor defaults to fill)
textAnim: "none", wordRate: 0.15, direction: "auto",
strokeWidth: 0, strokeColor: "#000000", bgColor: "#000000", bgOpacity: 0,
boxW: 0, boxH: 0, // text box (px); 0 = hug content. Resize handles edit these.
boxFit: false, // false = wrap at fixed fontSize; true = scale font to fit box
vAlign: "middle", // top | middle | bottom — vertical align of the text block in the box
};
const ANIMATABLE = ["x", "y", "scale", "rotation", "opacity", "volume", "speed",
"brightness", "contrast", "saturation", "hue", "blur", "grayscale", "sepia", "invert",
"temperature", "tint", "vignette", "cornerRadius", "shake", "rgbSplit", "grain",
"fontSize", "letterSpacing", "glow"];
const TRANSITIONS = ["none", "fade", "slide-left", "slide-right", "slide-up", "slide-down",
"zoom", "wipe", "wipe-right", "wipe-up", "wipe-down", "iris", "spin", "blur", "whip",
"glitch", "pop"];
const TEXT_ANIMS = ["none", "typewriter", "word-pop", "word-slide", "karaoke",
"letter-pop", "wave", "bounce", "shake",
"clip-reveal", "zoom-in", "font-cut", "rise-mask"];
const BLEND_MODES = ["normal", "multiply", "screen", "overlay", "lighter", "soft-light",
"hard-light", "color-dodge", "darken", "lighten", "difference"];
/* Named looks. % props multiply against the clip's own value, additive props add. */
const FILTER_PRESETS = {
none: {},
cinematic: { contrast: 112, saturation: 118, temperature: -10, vignette: 28 },
"teal-orange": { contrast: 115, saturation: 125, temperature: -18, hue: -8, vignette: 22 },
noir: { grayscale: 100, contrast: 128, brightness: 96, vignette: 45 },
vintage: { sepia: 42, contrast: 92, brightness: 106, saturation: 88, temperature: 12, vignette: 30 },
faded: { contrast: 84, brightness: 110, saturation: 82 },
warm: { temperature: 28, brightness: 103, saturation: 108 },
cold: { temperature: -28, saturation: 104 },
pop: { saturation: 152, contrast: 116 },
dreamy: { brightness: 109, saturation: 112, blur: 0.6, temperature: 8 },
retro: { saturation: 130, hue: -6, contrast: 106, sepia: 15 },
"bw-soft": { grayscale: 100, contrast: 95, brightness: 108 },
cyberpunk: { saturation: 140, hue: 12, contrast: 118, temperature: -15, vignette: 25 },
sunset: { temperature: 24, tint: 6, brightness: 105, saturation: 116, contrast: 104, vignette: 20 },
midnight: { temperature: -24, brightness: 88, contrast: 122, saturation: 94, vignette: 38 },
};
const SYSTEM_FONTS = ["Segoe UI", "Arial", "Georgia", "Impact", "Courier New",
"Trebuchet MS", "Verdana", "Times New Roman", "Comic Sans MS", "Consolas"];
const GOOGLE_FONTS = ["Anton", "Archivo Black", "Abril Fatface", "Barlow", "Bebas Neue",
"Caveat", "Inter", "Lobster", "Montserrat", "Oswald", "Pacifico", "Permanent Marker",
"Playfair Display", "Poppins", "Roboto", "Roboto Condensed", "Teko"];
/* ── Title styles: cohesive one-tap looks. Each bundles a DIFFERENT font,
placement and animation, so titles vary instead of all looking basic.
Agents can reproduce a look by writing the same props directly. ── */
const FONT_CUT_DEFAULT = ["Anton", "Bebas Neue", "Archivo Black", "Oswald", "Impact"];
const STYLE_RESET = { // decorative props a style owns; reset before applying
color2: "", glow: 0, glowColor: "", strokeWidth: 0, bgColor: "#000000", bgOpacity: 0,
rotation: 0, letterSpacing: 0, uppercase: false, italic: false, textShadow: 12,
fontCutSet: undefined, align: "center",
};
const TITLE_STYLES = {
plain: { label: "Plain", place: "center", props: { font: "Segoe UI", fontSize: 72, bold: true, color: "#ffffff", textAnim: "none" } },
impact: { label: "Impact", place: "lower", props: { font: "Anton", fontSize: 96, bold: false, uppercase: true, color: "#ffffff", textShadow: 22, textAnim: "word-pop" } },
elegant: { label: "Elegant", place: "center", props: { font: "Playfair Display", fontSize: 88, bold: false, color: "#ffffff", color2: "#ffd166", letterSpacing: 2, textAnim: "clip-reveal" } },
kinetic: { label: "Kinetic cut", place: "center", props: { font: "Bebas Neue", fontSize: 120, bold: false, uppercase: true, color: "#ffd166", letterSpacing: 3, textAnim: "font-cut", fontCutSet: ["Anton", "Bebas Neue", "Archivo Black", "Oswald"] } },
neon: { label: "Neon", place: "center", props: { font: "Bebas Neue", fontSize: 104, bold: false, uppercase: true, color: "#ffffff", glow: 60, glowColor: "#22d3ee", textAnim: "wave" } },
handwritten: { label: "Handwritten", place: "lower-left", props: { font: "Caveat", fontSize: 92, bold: false, color: "#ffffff", rotation: -4, textAnim: "word-slide" } },
serifDrop: { label: "Serif drop", place: "center", props: { font: "Abril Fatface", fontSize: 96, bold: false, color: "#ffffff", textShadow: 18, textAnim: "zoom-in" } },
subtitle: { label: "Subtitle", place: "lower", props: { font: "Roboto", fontSize: 52, bold: false, color: "#ffffff", bgColor: "#000000", bgOpacity: 0.5, textAnim: "karaoke" } },
boldRise: { label: "Bold rise", place: "lower", props: { font: "Archivo Black", fontSize: 92, bold: false, uppercase: true, color: "#ffffff", textAnim: "rise-mask" } },
luxury: { label: "Luxury", place: "center", props: { font: "Cinzel", fontSize: 88, bold: false, uppercase: true, color: "#faf0dc", color2: "#c9a227", letterSpacing: 6, textAnim: "clip-reveal" } },
};
const STYLE_CYCLE = ["impact", "elegant", "kinetic", "neon", "handwritten", "serifDrop", "boldRise", "luxury"];
const AUDIO_EXT = /\.(mp3|wav|ogg|m4a|aac|flac|mpeg)$/i;
const VIDEO_EXT = /\.(mp4|webm|mov|mkv|m4v)$/i;
const IMAGE_EXT = /\.(png|jpe?g|gif|webp|avif)$/i;
const ASPECT_PRESETS = [
{ label: "16:9 · 1280×720", w: 1280, h: 720 },
{ label: "16:9 · 1920×1080", w: 1920, h: 1080 },
{ label: "9:16 · Reel 1080×1920", w: 1080, h: 1920 },
{ label: "4:5 · IG 1080×1350", w: 1080, h: 1350 },
{ label: "1:1 · 1080×1080", w: 1080, h: 1080 },
];
const WAVE_PEAKS_PER_SEC = 50;
const TRACK_IDS = new Set(TRACKS.map((t) => t.id));
/* ── State ─────────────────────────────────────────────────────────────── */
const project = {
name: "Untitled Project",
width: 1280, height: 720, fps: 30,
background: "#000000",
revision: 0,
media: [], // {id, name, kind:'video'|'audio'|'image', src, duration, width?, height?}
clips: [], // {id, mediaId, kind, track, start, in, duration, name, props:{}}
markers: [], // {t, label?} — beat/cue markers on the ruler; snap targets
inPoint: null, // timeline work-area IN (seconds), or null
outPoint: null, // timeline work-area OUT (seconds), or null
disabledTracks: [], // track ids (V4…A3) hidden from preview/export when listed
};
const state = {
time: 0, playing: false, pps: 60, snap: true,
previewRate: 1, // playback speed for PREVIEW only — never affects export
selId: null, // primary selection (drives the inspector)
selIds: new Set(), // full multi-selection (includes selId)
trackSize: "l", // s | m | l — timeline track density preset
connected: false, exporting: false,
rendering: false, // fast (server/ffmpeg) export in progress
guides: false, // safe-area overlay on the monitor
ffmpeg: false, // server reports ffmpeg available
dirtyTimeline: true, gesture: false,
workAreaPlay: false, // when true, play + Home/End stay inside IN/OUT
binTab: "project", // project | elements | sfx | svg
disabledTracks: new Set(), // mirror of project.disabledTracks for fast lookup
transFocus: null, // "in" | "out" — inspector transition row highlighted
};
function normalizeDisabledTracks(raw) {
if (raw == null) return [];
const arr = Array.isArray(raw) ? raw : [];
return [...new Set(arr.filter((id) => TRACK_IDS.has(id)))].sort();
}
function isTrackEnabled(id) {
return !state.disabledTracks.has(id);
}
function syncTrackDisabledUI(id) {
const on = isTrackEnabled(id);
const head = els.trackHeaders.querySelector(`.track-head[data-track="${id}"]`);
const row = els.tracks.querySelector(`.track[data-track="${id}"]`);
if (head) {
head.classList.toggle("disabled", !on);
const btn = head.querySelector(".track-toggle");
if (btn) {
btn.setAttribute("aria-pressed", on ? "true" : "false");
btn.title = on ? "Disable track" : "Enable track";
}
}
if (row) row.classList.toggle("disabled", !on);
}
function syncAllTrackDisabledUI() {
for (const t of TRACKS) syncTrackDisabledUI(t.id);
}
function toggleTrackEnabled(id) {
if (!TRACK_IDS.has(id)) return;
if (state.disabledTracks.has(id)) state.disabledTracks.delete(id);
else state.disabledTracks.add(id);
project.disabledTracks = [...state.disabledTracks].sort();
syncTrackDisabledUI(id);
scheduleSave();
}
const runtime = {
clipEls: new Map(), // clipId -> HTMLMediaElement
clipGain: new Map(), // clipId -> GainNode
mediaAux: new Map(), // mediaId -> {img?, thumb?, svgText?, svgAnimated?}
audioBufs: new Map(), // mediaId -> Promise<AudioBuffer> (waveforms + export mix)
wavePeaks: new Map(), // mediaId -> {channels: Float32Array[], max: Float32Array} | Float32Array (legacy) | null (pending)
library: {}, // dir -> [{name, rel, src, size}] cached /api/library results
customFonts: [], // family names loaded from /library/fonts
googleLoaded: new Set(),
undo: [], redo: [],
audio: null, // {ctx, master, recDest, meter?, meterReady?}
saveTimer: null, pendingSync: false,
sfxPreview: null, // <audio> element for library sound previews
};
/* ── DOM ───────────────────────────────────────────────────────────────── */
const $ = (id) => document.getElementById(id);
const els = {
binList: $("binList"), binEmpty: $("binEmpty"), fileInput: $("fileInput"),
binTabs: $("binTabs"), libList: $("libList"), toast: $("toast"),
preview: $("preview"), tcCurrent: $("tcCurrent"), tcTotal: $("tcTotal"),
btnPlay: $("btnPlay"), inspector: $("inspector"),
trackHeaders: $("trackHeaders"), timelineScroll: $("timelineScroll"),
tracksContent: $("tracksContent"), tracks: $("tracks"), playhead: $("playhead"),
ruler: $("ruler"), zoomSlider: $("zoomSlider"), btnSnap: $("btnSnap"),
exportOverlay: $("exportOverlay"), exportProgress: $("exportProgress"),
exportTitle: $("exportTitle"), exportNote: $("exportNote"),
projectName: $("projectName"), monitorRes: $("monitorRes"),
aspectSel: $("aspectSel"), btnGuides: $("btnGuides"), safeOverlay: $("safeOverlay"),
btnSpeed: $("btnSpeed"),
monitorStage: $("monitorStage"),
exportSetup: $("exportSetup"), engineFast: $("engineFast"), engineRealtime: $("engineRealtime"),
};
const ctx2d = els.preview.getContext("2d");
/* ── Utils ─────────────────────────────────────────────────────────────── */
const uid = () => Math.random().toString(36).slice(2, 9);
const clamp = (v, a, b) => Math.min(b, Math.max(a, v));
function escapeHtml(s) {
return String(s ?? "")
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/"/g, """)
.replace(/'/g, "'");
}
function fmt(t) {
t = Math.max(0, t);
const m = Math.floor(t / 60), s = Math.floor(t % 60),
f = Math.floor((t % 1) * project.fps);
const p = (n) => String(n).padStart(2, "0");
return `${p(m)}:${p(s)}:${p(f)}`;
}
const getMedia = (id) => project.media.find((m) => m.id === id);
const getClip = (id) => project.clips.find((c) => c.id === id);
const clipEnd = (c) => c.start + c.duration;
function projDur() {
return project.clips.reduce((mx, c) => Math.max(mx, clipEnd(c)), 0);
}
const trackOf = (c) => TRACKS.find((t) => t.id === c.track);
const clipSpeed = (c) => clamp(+(c.props?.speed) || 1, 0.1, 8);
/* ── Speed ramps (time remapping) ──
`speed` is keyframable: media time = in + ∫ speed(t) dt over the clip.
The integral is sampled once per unique speed curve and cached. */
const speedIntCache = new Map(); // clipId -> {key, cum: Float32Array, step}
function kfChannel(c, key, local, fallback) {
const kfs = c.keyframes?.[key];
if (!Array.isArray(kfs) || !kfs.length) return fallback;
if (local <= kfs[0].t) return kfs[0].v;
if (local >= kfs[kfs.length - 1].t) return kfs[kfs.length - 1].v;
for (let i = 0; i < kfs.length - 1; i++) {
const a = kfs[i], b = kfs[i + 1];
if (local >= a.t && local <= b.t) {
const u = (local - a.t) / Math.max(1e-6, b.t - a.t);
const ez = EASE[b.ease || "ease-in-out"] || EASE.linear;
return a.v + (b.v - a.v) * ez(u);
}
}
return fallback;
}
function hasSpeedRamp(c) {
return Array.isArray(c.keyframes?.speed) && c.keyframes.speed.length > 0;
}
function mediaTimeAt(c, t) {
const base = clipSpeed(c);
const local = clamp(t - c.start, 0, c.duration);
if (!hasSpeedRamp(c)) return c.in + local * base;
const key = JSON.stringify(c.keyframes.speed) + "|" + c.duration.toFixed(4) + "|" + base;
let e = speedIntCache.get(c.id);
if (!e || e.key !== key) {
const step = 1 / 120;
const n = Math.max(2, Math.ceil(c.duration / step) + 1);
const cum = new Float32Array(n);
let prev = clamp(kfChannel(c, "speed", 0, base), 0.1, 8);
for (let i = 1; i < n; i++) {
const lt = Math.min(c.duration, i * step);
const cur = clamp(kfChannel(c, "speed", lt, base), 0.1, 8);
cum[i] = cum[i - 1] + ((prev + cur) / 2) * (lt - (i - 1) * step);
prev = cur;
}
e = { key, cum, step };
speedIntCache.set(c.id, e);
}
const idx = Math.min(e.cum.length - 1, local / e.step);
const i0 = Math.floor(idx), frac = idx - i0;
const v = i0 >= e.cum.length - 1 ? e.cum[e.cum.length - 1]
: e.cum[i0] + (e.cum[i0 + 1] - e.cum[i0]) * frac;
return c.in + v;
}
let toastTimer = null;
function toast(msg) {
if (!els.toast) return;
els.toast.textContent = msg;
els.toast.classList.add("show");
clearTimeout(toastTimer);
toastTimer = setTimeout(() => els.toast.classList.remove("show"), 3200);
}
/* True when keyboard events should go to a text-entry control (not range/checkbox). */
function isTypingTarget(el) {
if (!el || el === document.body || el === document.documentElement) return false;
const tag = el.tagName;
if (tag === "TEXTAREA" || tag === "SELECT") return true;
if (tag === "INPUT") {
const t = (el.type || "text").toLowerCase();
return !["range", "checkbox", "radio", "button", "submit", "reset", "color", "file", "hidden"].includes(t);
}
return !!el.isContentEditable;
}
/* ═══════════════════════ SERVER SYNC (optional) ═══════════════════════ */
async function connectServer() {
try {
const res = await fetch("/api/project", { cache: "no-store" });
if (!res.ok) throw 0;
const data = await res.json();
applyProject(data);
state.connected = true;
els.projectName.textContent = project.name + " · 🟢 connected";
listenSSE();
fetch("/api/export/ffmpeg").then((r) => r.json())
.then((j) => { state.ffmpeg = !!j.available; }).catch(() => { });
} catch {
state.connected = false;
els.projectName.textContent = project.name + " · ⚪ local session";
}
await probeMissingMeta();
}
const TIMELINE_START_TIME = 0.000; // composition timeline start (seconds)
function normalizeWorkArea(i, o, t0 = TIMELINE_START_TIME) {
let inPoint = (i != null && isFinite(i)) ? Math.max(t0, +i) : null;
let outPoint = (o != null && isFinite(o)) ? Math.max(t0, +o) : null;
if (inPoint != null && outPoint != null && outPoint <= inPoint) {
inPoint = null;
outPoint = null;
}
return { inPoint, outPoint };
}
function applyProject(data) {
const wa = normalizeWorkArea(data.inPoint, data.outPoint);
const disabledTracks = normalizeDisabledTracks(data.disabledTracks);
Object.assign(project, {
name: data.name || "Untitled Project",
width: data.width || 1280, height: data.height || 720, fps: data.fps || 30,
background: data.background || "#000000",
revision: data.revision || 0,
media: data.media || [], clips: data.clips || [],
markers: (data.markers || []).filter((m) => m && isFinite(m.t)).sort((a, b) => a.t - b.t),
inPoint: wa.inPoint,
outPoint: wa.outPoint,
disabledTracks,
});
state.disabledTracks = new Set(disabledTracks);
for (const c of project.clips) {
c.props = { ...DEFAULT_PROPS, ...(c.props || {}) };
if (c.keyframes) for (const arr of Object.values(c.keyframes))
if (Array.isArray(arr)) arr.sort((a, b) => a.t - b.t);
if (c.kind === "text") ensureFont(c.props.font);
}
// AV links aren't always on disk (older saves / agents) — rebuild from matching timing.
relinkClips();
// reset runtime playback elements so they rebuild against new data
for (const el of runtime.clipEls.values()) { try { el.pause(); el.src = ""; } catch { } }
runtime.clipEls.clear(); runtime.clipGain.clear();
els.preview.width = project.width; els.preview.height = project.height;
els.monitorRes.textContent = `${project.width} × ${project.height} · ${project.fps}fps`;
syncAspectSel();
pruneSelection(); // keep the selection across external reloads where possible
state.dirtyTimeline = true;
renderBin(); renderInspector();
updateWorkArea();
syncTrimIOButton();
syncAllTrackDisabledUI();
}
function scheduleSave() {
state.dirtyTimeline = true;
if (!state.connected) return;
clearTimeout(runtime.saveTimer);
runtime.saveTimer = setTimeout(async () => {
runtime.saveTimer = null;
project.revision++;
const body = JSON.stringify(projectJSON(), null, 2);
try {
const res = await fetch("/api/project", { method: "PUT", headers: { "Content-Type": "application/json" }, body });
if (res.status === 409) {
// an external tool saved a newer revision while this change was pending
await syncFromServer(true);
toast("Project was updated externally — your last change may need redoing.");
}
} catch { }
}, 400);
}
function projectJSON() {
const { name, width, height, fps, background, revision, media, clips, markers, inPoint, outPoint, disabledTracks } = project;
return {
name, width, height, fps, background, revision,
media: media.filter((m) => !m.transient).map(({ id, name, kind, src, duration, width, height }) =>
({ id, name, kind, src, duration, width, height })),
clips: clips.map(({ id, mediaId, kind, track, start, in: inn, duration, name, props, keyframes, transitionIn, transitionOut, linkedId, linkGroup }) => {
const out = { id, mediaId, kind, track, start, in: inn, duration, name, props, keyframes, transitionIn, transitionOut };
if (linkGroup) out.linkGroup = linkGroup;
if (linkedId) out.linkedId = linkedId;
return out;
}),
markers: (markers || []).map(({ t, label }) => (label ? { t, label } : { t })),
inPoint: inPoint == null ? null : inPoint,
outPoint: outPoint == null ? null : outPoint,
disabledTracks: normalizeDisabledTracks(disabledTracks),
};
}
function listenSSE() {
const es = new EventSource("/api/events");
es.onmessage = () => syncFromServer();
}
/* Pull the server's project if it moved past our revision (an external tool —
e.g. Claude — wrote it). Our own saves land at our exact local revision, so
they compare equal and are skipped without any timing heuristics. Deferred
during gestures/exports and re-run when they end (runtime.pendingSync). */
async function syncFromServer(force) {
if (state.gesture || state.exporting) { runtime.pendingSync = true; return; }
runtime.pendingSync = false;
if (state.binTab !== "project") fetchLibrary(state.binTab).then(renderLibrary);
loadLibraryFonts();
try {
const res = await fetch("/api/project", { cache: "no-store" });
if (!res.ok) return;
const data = await res.json();
if (!data || !Array.isArray(data.clips)) return;
if (!force && (data.revision || 0) === (project.revision || 0)) return; // our own save
if (runtime.saveTimer) { // unsaved local edit vs. external write: external wins, tell the user
clearTimeout(runtime.saveTimer); runtime.saveTimer = null;
toast("Project was updated externally — your last change may need redoing.");
}
applyProject(data);
await probeMissingMeta();
} catch { }
}
/* Fill in duration/size for media entries added externally without metadata */
async function probeMissingMeta() {
let changed = false;
for (const m of project.media) {
if (m.kind === "svg") {
if (!runtime.mediaAux.get(m.id)?.svgText) { try { await loadSvgMedia(m); changed = true; } catch { } }
continue;
}
if (m.kind !== "image" && (m.duration == null || isNaN(m.duration))) {
try { Object.assign(m, await probeAV(m.src, m.kind)); changed = true; } catch { }
}
if (m.kind === "image" && !runtime.mediaAux.get(m.id)?.img) {
try {
const img = await loadImage(m.src);
runtime.mediaAux.set(m.id, { ...(runtime.mediaAux.get(m.id) || {}), img });
m.width = img.naturalWidth; m.height = img.naturalHeight; changed = true;
} catch { }
}
if (m.kind === "video" && !runtime.mediaAux.get(m.id)?.thumb) {
grabThumb(m).catch(() => { });
}
ensureWave(m);
}
if (changed) { renderBin(); scheduleSave(); }
state.dirtyTimeline = true;
}
function probeAV(src, kind) {
return new Promise((resolve, reject) => {
const el = document.createElement(kind === "audio" ? "audio" : "video");
el.preload = "metadata"; el.src = src;
el.onloadedmetadata = () => resolve({
duration: el.duration,
width: el.videoWidth || undefined, height: el.videoHeight || undefined,
});
el.onerror = reject;
});
}
function loadImage(src) {
return new Promise((res, rej) => { const i = new Image(); i.onload = () => res(i); i.onerror = rej; i.src = src; });
}
async function grabThumb(m) {
const v = document.createElement("video");
v.muted = true; v.preload = "auto"; v.src = m.src;
await new Promise((res, rej) => { v.onloadeddata = res; v.onerror = rej; });
v.currentTime = Math.min(0.5, (v.duration || 1) / 2);
await new Promise((res) => { v.onseeked = res; setTimeout(res, 1500); });
const c = document.createElement("canvas");
c.width = 160; c.height = 90;
c.getContext("2d").drawImage(v, 0, 0, 160, 90);
runtime.mediaAux.set(m.id, { ...(runtime.mediaAux.get(m.id) || {}), thumb: c.toDataURL("image/jpeg", 0.6) });
v.src = "";
renderBin(); state.dirtyTimeline = true;
}
/* ── Audio decoding (shared by clip waveforms and the fast-export mix) ── */
let decodeCtx = null;
function getDecodeCtx() {
return decodeCtx || (decodeCtx = new (window.AudioContext || window.webkitAudioContext)());
}
function getAudioBuffer(m) {
let p = runtime.audioBufs.get(m.id);
if (!p) {
p = fetch(m.src).then((r) => r.arrayBuffer())
.then((ab) => getDecodeCtx().decodeAudioData(ab));
runtime.audioBufs.set(m.id, p);
p.catch(() => runtime.audioBufs.delete(m.id));
}
return p;
}
function ensureWave(m) {
// Also decode peaks from video files when their audio is placed on an A track
if ((m.kind !== "audio" && m.kind !== "video") || runtime.wavePeaks.has(m.id)) return;
runtime.wavePeaks.set(m.id, null); // pending
getAudioBuffer(m).then((buf) => {
const n = Math.max(1, Math.ceil(buf.duration * WAVE_PEAKS_PER_SEC));
const step = buf.length / n;
const channels = [];
for (let ch = 0; ch < buf.numberOfChannels; ch++) {
const data = buf.getChannelData(ch);
const peaks = new Float32Array(n);
for (let i = 0; i < n; i++) {
let mx = 0;
const i0 = Math.floor(i * step), i1 = Math.min(data.length, Math.floor((i + 1) * step));
for (let j = i0; j < i1; j += 8) { const a = Math.abs(data[j]); if (a > mx) mx = a; }
peaks[i] = mx;
}
channels.push(peaks);
}
// Combined max envelope for clips that play full stereo
const max = new Float32Array(n);
for (let i = 0; i < n; i++) {
let mx = 0;
for (const p of channels) if (p[i] > mx) mx = p[i];
max[i] = mx;
}
runtime.wavePeaks.set(m.id, { channels, max });
if (m.channels == null) m.channels = buf.numberOfChannels;
state.dirtyTimeline = true;
}).catch(() => runtime.wavePeaks.delete(m.id));
}
function wavePeaksFor(c) {
const w = runtime.wavePeaks.get(c.mediaId);
if (!w) return null;
// Legacy: bare Float32Array
if (w instanceof Float32Array) return w;
if (!w.max) return null;
const ch = c.props?.audioChannel;
if ((ch === 0 || ch === 1) && w.channels?.[ch]) return w.channels[ch];
return w.max;
}
/* ═══════════════════════════ MEDIA IMPORT ═══════════════════════════ */
/* Windows often leaves File.type empty for video/audio — fall back to extension. */
function mediaKindFromFile(file) {
const t = file.type || "";
if (t === "image/svg+xml" || t === "image/svg") return "svg";
if (t.startsWith("video/")) return "video";
if (t.startsWith("audio/")) return "audio";
if (t.startsWith("image/")) return "image";
const ext = (file.name.split(".").pop() || "").toLowerCase();
if (ext === "svg") return "svg";
if (["mp4", "mov", "webm", "mkv", "m4v", "avi", "mpg", "mpeg"].includes(ext)) return "video";
if (["mp3", "wav", "m4a", "aac", "ogg", "flac", "wma"].includes(ext)) return "audio";
if (["png", "jpg", "jpeg", "gif", "webp", "bmp", "avif"].includes(ext)) return "image";
return null;
}
async function importFiles(fileList) {
const files = [...fileList];
if (!files.length) return;
let added = 0, skipped = 0;
for (const file of files) {
const kind = mediaKindFromFile(file);
if (!kind) { skipped++; continue; }
let src, transient = false;
if (state.connected) {
try {
const res = await fetch("/api/upload?name=" + encodeURIComponent(file.name), { method: "POST", body: file });
if (!res.ok) throw new Error("upload " + res.status);
src = (await res.json()).src;
} catch { src = URL.createObjectURL(file); transient = true; }
} else {
src = URL.createObjectURL(file); transient = true;
}
const m = { id: "m_" + uid(), name: file.name, kind, src, transient };
try {
if (kind === "svg") {
await loadSvgMedia(m);
} else if (kind === "image") {
const img = await loadImage(src);
runtime.mediaAux.set(m.id, { img });
m.width = img.naturalWidth; m.height = img.naturalHeight;
} else {
Object.assign(m, await probeAV(src, kind));
if (kind === "video") grabThumb(m).catch(() => { });
ensureWave(m);
}
} catch { skipped++; continue; }
project.media.push(m);
added++;
}
renderBin(); scheduleSave();
if (!added && skipped)
toast("Couldn't import — unsupported or unreadable file type");
else if (skipped)
toast(`Imported ${added}, skipped ${skipped}`);
}
function renderBin() {
els.binList.querySelectorAll(".bin-item").forEach((n) => n.remove());
els.binEmpty.style.display = project.media.length ? "none" : "";
for (const m of project.media) {
const item = document.createElement("div");
item.className = "bin-item"; item.draggable = true;
const aux = runtime.mediaAux.get(m.id) || {};
const icon = m.kind === "audio" ? "🎵" : m.kind === "image" ? "🖼" : m.kind === "svg" ? "✨" : "🎞";
const thumbSrc = aux.thumb || (m.kind === "image" || m.kind === "svg" ? m.src : null);
item.innerHTML = `
<div class="bin-thumb" ${thumbSrc ? `style="background-image:url('${thumbSrc}')"` : ""}>${thumbSrc ? "" : icon}</div>
<div class="bin-meta">
<div class="bin-name" title="${m.name}">${m.name}</div>
<div class="bin-sub">${m.kind}${m.duration ? " · " + fmt(m.duration) : ""}</div>
</div>
<span class="bin-del" title="Remove (and its clips)">✕</span>`;
item.addEventListener("dragstart", (e) => {
e.dataTransfer.setData("text/fablecut-media", m.id);
e.dataTransfer.effectAllowed = "copy";
});
item.addEventListener("dblclick", () => addClipFromMedia(m, null, state.time));
item.querySelector(".bin-del").addEventListener("click", () => {
pushUndo();
project.media = project.media.filter((x) => x.id !== m.id);
project.clips = project.clips.filter((c) => c.mediaId !== m.id);
renderBin(); scheduleSave(); renderInspector();
});
els.binList.appendChild(item);
}
}
/* Open the native file dialog. Windows anchors it to the <input>'s screen
position — park the input under the cursor and open after the mouse
gesture finishes so the dialog doesn't appear then jump. */
function openFileImport(clientX, clientY) {
const input = els.fileInput;
if (clientX != null && clientY != null) {
input.style.cssText =
`position:fixed;left:${clientX}px;top:${clientY}px;width:1px;height:1px;` +
`opacity:0;margin:0;padding:0;border:0;overflow:hidden;z-index:-1;`;
}
setTimeout(() => input.click(), 0);
}
/* Ctrl/Cmd+click in the Project bin opens the file importer. */
els.binList.addEventListener("click", (e) => {
if (!(e.ctrlKey || e.metaKey) || e.button !== 0) return;
if (e.target.closest(".bin-del")) return;
e.preventDefault();
openFileImport(e.clientX, e.clientY);
});
/* ═══════════════════ ASSET LIBRARY (./library on the server) ═══════════════
Read-only default assets in four tabs: Elements (overlay art), Sound FX,
SVG (Claude-authored vector animations), plus fonts consumed by the font
editor. Files are used in place (src under /library/…) — never copied. */
async function fetchLibrary(dir) {
try { runtime.library[dir] = await (await fetch("/api/library?dir=" + dir)).json(); }
catch { runtime.library[dir] = []; }
return runtime.library[dir];
}
function libKind(name) {
if (/\.svg$/i.test(name)) return "svg";
if (AUDIO_EXT.test(name)) return "audio";
if (VIDEO_EXT.test(name)) return "video";
if (IMAGE_EXT.test(name)) return "image";
return null;
}
/* Find-or-create the project media entry for a library file (dedup by src). */
function mediaForLibraryItem(f) {
let m = project.media.find((x) => x.src === f.src);
if (m) return m;
const kind = libKind(f.name);
if (!kind) return null;
m = { id: "m_" + uid(), name: f.name, kind, src: f.src };
project.media.push(m);
renderBin(); scheduleSave();
return m;
}
async function addLibraryItem(f, trackId, at) {
const m = mediaForLibraryItem(f);
if (!m) { toast("Unsupported file type: " + f.name); return; }
if ((m.kind === "audio" || m.kind === "video") && (m.duration == null || isNaN(m.duration))) {
try { Object.assign(m, await probeAV(m.src, m.kind)); } catch { }
ensureWave(m);
if (m.kind === "video") grabThumb(m).catch(() => { });
}
if (m.kind === "svg" && !runtime.mediaAux.get(m.id)?.svgText) {
try { await loadSvgMedia(m); } catch { }
}
if (m.kind === "image" && !runtime.mediaAux.get(m.id)?.img) {
try {
const img = await loadImage(m.src);
runtime.mediaAux.set(m.id, { ...(runtime.mediaAux.get(m.id) || {}), img });
m.width = img.naturalWidth; m.height = img.naturalHeight;
} catch { }
}
addClipFromMedia(m, trackId, at);
}
function toggleSfxPreview(f, btn) {
const cur = runtime.sfxPreview;
if (cur && cur.dataset.src === f.src && !cur.paused) {
cur.pause();
btn.textContent = "▶";
return;
}
if (cur) { cur.pause(); }
els.libList.querySelectorAll(".lib-play").forEach((b) => (b.textContent = "▶"));
const a = new Audio(f.src);
a.dataset.src = f.src;
a.onended = () => { btn.textContent = "▶"; };
a.play().catch(() => toast("Couldn't play " + f.name));
btn.textContent = "⏸";
runtime.sfxPreview = a;
}
function renderLibrary() {
const dir = state.binTab;
if (dir === "project") return;
const files = runtime.library[dir] || [];
els.libList.innerHTML = "";
if (!files.length) {
els.libList.innerHTML = `<div class="bin-empty">
<div class="bin-empty-icon">${dir === "sfx" ? "🔊" : dir === "svg" ? "✨" : "🧩"}</div>
<p>No assets yet.</p>
<p class="hint">Drop files into<br><b>library/${dir}/</b><br>— this list live-updates.</p></div>`;
return;
}
for (const f of files) {
const kind = libKind(f.name);
const item = document.createElement("div");
item.className = "bin-item lib-item";
item.draggable = true;
const visual = kind === "image" || kind === "svg";
const icon = kind === "audio" ? "🎵" : kind === "video" ? "🎞" : kind === "svg" ? "✨" : "🧩";
item.innerHTML = `
<div class="bin-thumb${kind === "svg" ? " svg" : ""}" ${visual ? `style="background-image:url('${f.src}')"` : ""}>${visual ? "" : icon}</div>
<div class="bin-meta">
<div class="bin-name" title="${f.rel}">${f.name}</div>
<div class="bin-sub">${(f.size / 1024).toFixed(0)} KB</div>
</div>
${dir === "sfx" ? `<button class="btn tiny lib-play" title="Preview">▶</button>` : ""}
<button class="btn tiny accent lib-add" title="Add at playhead">+</button>`;
item.addEventListener("dragstart", (e) => {
const m = mediaForLibraryItem(f);
if (!m) { e.preventDefault(); return; }
e.dataTransfer.setData("text/fablecut-media", m.id);
e.dataTransfer.effectAllowed = "copy";
});
item.addEventListener("dblclick", () => addLibraryItem(f, null, state.time));
item.querySelector(".lib-add").addEventListener("click", () => addLibraryItem(f, null, state.time));
const play = item.querySelector(".lib-play");
if (play) play.addEventListener("click", () => toggleSfxPreview(f, play));
els.libList.appendChild(item);
}
}
function setBinTab(tab) {
state.binTab = tab;
for (const b of els.binTabs.querySelectorAll("[data-tab]"))
b.classList.toggle("on", b.dataset.tab === tab);
const isProj = tab === "project";
els.binList.classList.toggle("hidden", !isProj);
els.libList.classList.toggle("hidden", isProj);
if (!isProj) fetchLibrary(tab).then(renderLibrary);
}
/* ═══════════════════════════ EDIT OPERATIONS ═══════════════════════════ */
function pushUndo() {
runtime.undo.push(JSON.stringify(project.clips));
if (runtime.undo.length > 100) runtime.undo.shift();
runtime.redo.length = 0;
}
function undo() {
if (!runtime.undo.length) return;
runtime.redo.push(JSON.stringify(project.clips));
project.clips = JSON.parse(runtime.undo.pop());
pruneSelection();
scheduleSave(); renderInspector();
}
function redo() {
if (!runtime.redo.length) return;
runtime.undo.push(JSON.stringify(project.clips));
project.clips = JSON.parse(runtime.redo.pop());
pruneSelection();
scheduleSave(); renderInspector();
}
function defaultTrackFor(kind) {
return kind === "audio" ? "A1" : kind === "svg" ? "V3" : "V1";
}
function linkedClip(c) {
return c?.linkedId ? getClip(c.linkedId) : null;
}
/* Expand a clip list so each AV-linked partner is included once.
Supports N-way `linkGroup` (video + L + R) and legacy pairwise `linkedId`. */
function withLinked(clips) {
const out = new Map();
const groups = new Set();
for (const c of clips) {
out.set(c.id, c);
if (c.linkGroup) groups.add(c.linkGroup);
else {
const L = linkedClip(c);
if (L) out.set(L.id, L);
}
}
if (groups.size) {
for (const x of project.clips) {
if (x.linkGroup && groups.has(x.linkGroup)) out.set(x.id, x);
}
}
return [...out.values()];
}
function syncLinkedTiming(c) {
for (const L of withLinked([c])) {
if (L.id === c.id) continue;
L.start = c.start;
L.in = c.in;
L.duration = c.duration;
if (c.props?.speed != null) {
L.props = L.props || {};
L.props.speed = c.props.speed;
}
}
}
/* Rebuild AV linkGroups after load. Unlinking isn't supported, so any video +
audio clips that share mediaId and the same start/in/duration belong together
(e.g. picture + L/R stems from one file). Legacy pairwise linkedId is cleared
in favor of linkGroup. */
function relinkClips() {
const near = (a, b) => Math.abs((+a || 0) - (+b || 0)) < 1e-3;
for (const c of project.clips) {
delete c.linkGroup;
delete c.linkedId;
}
const audios = project.clips.filter((c) => c.kind === "audio" && c.mediaId);
const used = new Set();
for (const v of project.clips) {
if (v.kind !== "video" || !v.mediaId) continue;
const partners = audios.filter((a) =>
!used.has(a.id) &&
a.mediaId === v.mediaId &&
near(a.start, v.start) &&
near(a.in, v.in) &&
near(a.duration, v.duration)
);
if (!partners.length) continue;
const lg = "lg_" + uid();
v.linkGroup = lg;
for (const a of partners) {
a.linkGroup = lg;
used.add(a.id);
}
}
}
function addClipFromMedia(m, trackId, at) {
pushUndo();
const kind = m.kind;
trackId = trackId || defaultTrackFor(kind);
const tr = TRACKS.find((t) => t.id === trackId);
if (!tr || (kind === "audio") !== (tr.kind === "audio")) trackId = defaultTrackFor(kind);
const start = Math.max(0, at ?? state.time);
const duration = m.duration || 5;
const name = m.name.replace(/\.[^.]+$/, "");
const c = {
id: "c_" + uid(), mediaId: m.id, kind, track: trackId,
start, in: 0, duration, name,
props: { ...DEFAULT_PROPS },
};
project.clips.push(c);
// Video+audio: picture on a V track; stereo L/R as separate linked clips on A1/A2.
// Mute the video clip so audio isn't doubled.
if (kind === "video") {
c.props.volume = 0;
const lg = "lg_" + uid();
c.linkGroup = lg;
const aL = {
id: "c_" + uid(), mediaId: m.id, kind: "audio", track: "A1",
start, in: 0, duration, name,
props: { ...DEFAULT_PROPS, audioChannel: 0 },
linkGroup: lg,
};
const aR = {
id: "c_" + uid(), mediaId: m.id, kind: "audio", track: "A2",
start, in: 0, duration, name,
props: { ...DEFAULT_PROPS, audioChannel: 1 },
linkGroup: lg,
};
project.clips.push(aL, aR);
ensureWave(m);
}
selectClip(c.id); scheduleSave();
return c;
}
/* Apply a named title style: reset the props a style owns, merge the style,
place it (canvas-aware), and make sure its fonts are loaded.
keepTransform: restyle the look only — x/y/scale/rotation/align stay as the
user set them. Used when switching styles on an existing clip; new titles
(keepTransform=false) still get the style's placement. */
function applyTitleStyle(clip, name, { keepTransform = false } = {}) {
const st = TITLE_STYLES[name] || TITLE_STYLES.plain;
const P = clip.props;
const kept = keepTransform
? { x: P.x, y: P.y, scale: P.scale, rotation: P.rotation, align: P.align }
: null;
Object.assign(P, STYLE_RESET, st.props);
if (kept) Object.assign(P, kept);
else {
const H = project.height || 720, W = project.width || 1280;
const place = st.place || "center";
P.x = 0;
P.y = place === "lower" ? Math.round(H * 0.30)
: place === "upper" ? -Math.round(H * 0.30)
: place === "lower-left" ? Math.round(H * 0.28) : 0;
if (place === "lower-left") { P.x = -Math.round(W * 0.18); P.align = "left"; }
}
ensureFont(P.font);
if (Array.isArray(P.fontCutSet)) P.fontCutSet.forEach(ensureFont);
clip.styleName = name;
}
/* Custom title-style dropdown: every entry renders in its own font, hovering
an entry live-previews the style on the canvas (transform kept — see
applyTitleStyle), moving away reverts, clicking commits. Nothing is saved
until a click. */
function openStylePicker(anchor, c) {
const snap = { props: JSON.parse(JSON.stringify(c.props)), styleName: c.styleName };
let committed = false;
const rewind = () => {
if (committed) return;
c.props = JSON.parse(JSON.stringify(snap.props));
c.styleName = snap.styleName;
};
const menu = document.createElement("div");
menu.className = "style-menu";
for (const [k, v] of Object.entries(TITLE_STYLES)) {
ensureFont(v.props.font); // so the entry itself renders in the style's face
const it = document.createElement("div");
it.className = "style-opt" + (c.styleName === k ? " on" : "");
it.textContent = v.label;
it.style.fontFamily = `"${v.props.font}", sans-serif`;
if (v.props.uppercase) it.style.textTransform = "uppercase";
it.addEventListener("mouseenter", () => {
rewind(); // preview from the clip's real state, not a previous preview
applyTitleStyle(c, k, { keepTransform: true });
});
it.addEventListener("click", () => {
rewind();
pushUndo();
applyTitleStyle(c, k, { keepTransform: true });
committed = true;
close();
scheduleSave(); renderInspector();
});
menu.appendChild(it);
}
menu.addEventListener("mouseleave", rewind);
const onDoc = (e) => { if (!menu.contains(e.target) && e.target !== anchor) close(); };
function close() {
rewind();
menu.remove();
document.removeEventListener("pointerdown", onDoc, true);
runtime.styleMenu = null;
}
document.addEventListener("pointerdown", onDoc, true);
const r = anchor.getBoundingClientRect();
menu.style.left = Math.round(Math.min(r.left, innerWidth - 220)) + "px";
menu.style.top = Math.round(Math.min(r.bottom + 4, innerHeight - 340)) + "px";
document.body.appendChild(menu);
runtime.styleMenu = { close };
}
function closeStylePicker() { if (runtime.styleMenu) runtime.styleMenu.close(); }
function addTitle() {
pushUndo();
const c = {
id: "c_" + uid(), mediaId: null, kind: "text", track: "V2",
start: state.time, in: 0, duration: 4, name: "Title",
props: { ...DEFAULT_PROPS },
};
// interesting by default: rotate through the styles so titles vary
runtime.titleStyleIdx = ((runtime.titleStyleIdx || 0) + 1) % STYLE_CYCLE.length;