-
Notifications
You must be signed in to change notification settings - Fork 1.9k
Expand file tree
/
Copy pathExportPage.tsx
More file actions
1832 lines (1715 loc) · 53.7 KB
/
Copy pathExportPage.tsx
File metadata and controls
1832 lines (1715 loc) · 53.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
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
import { Button } from "@cap/ui-solid";
import { debounce } from "@solid-primitives/scheduled";
import { makePersisted } from "@solid-primitives/storage";
import { createMutation } from "@tanstack/solid-query";
import { Channel } from "@tauri-apps/api/core";
import { CheckMenuItem, Menu } from "@tauri-apps/api/menu";
import { ask } from "@tauri-apps/plugin-dialog";
import { remove } from "@tauri-apps/plugin-fs";
import { type as ostype } from "@tauri-apps/plugin-os";
import { cx } from "cva";
import {
createEffect,
createSignal,
For,
Match,
mergeProps,
on,
onCleanup,
Show,
Suspense,
Switch,
} from "solid-js";
import { createStore, produce, reconcile } from "solid-js/store";
import toast from "solid-toast";
import { SignInButton } from "~/components/SignInButton";
import Tooltip from "~/components/Tooltip";
import CaptionControlsWindows11 from "~/components/titlebar/controls/CaptionControlsWindows11";
import { authStore } from "~/store";
import { trackEvent } from "~/utils/analytics";
import { createSignInMutation } from "~/utils/auth";
import {
beginExportSessionGuard,
createExportTask,
createExportToFileTask,
} from "~/utils/export";
import { createSelectedOrganization } from "~/utils/organization-branding";
import {
commands,
type ExportCompression,
type ExportSettings,
type FramesRendered,
type UploadProgress,
} from "~/utils/tauri";
import { type RenderState, useEditorContext } from "./context";
import { RESOLUTION_OPTIONS } from "./Header";
import { Dialog, Field } from "./ui";
class SilentError extends Error {}
export const COMPRESSION_OPTIONS: Array<{
label: string;
value: ExportCompression;
bpp: number;
}> = [
{ label: "Maximum", value: "Maximum", bpp: 0.3 },
{ label: "Social Media", value: "Social", bpp: 0.15 },
{ label: "Web", value: "Web", bpp: 0.08 },
{ label: "Potato", value: "Potato", bpp: 0.04 },
];
const COMPRESSION_TO_BPP: Record<ExportCompression, number> = {
Maximum: 0.3,
Social: 0.15,
Web: 0.08,
Potato: 0.04,
};
export const FPS_OPTIONS = [
{ label: "15 FPS", value: 15 },
{ label: "30 FPS", value: 30 },
{ label: "60 FPS", value: 60 },
] satisfies Array<{ label: string; value: number }>;
export const GIF_FPS_OPTIONS = [
{ label: "10 FPS", value: 10 },
{ label: "15 FPS", value: 15 },
{ label: "20 FPS", value: 20 },
{ label: "25 FPS", value: 25 },
{ label: "30 FPS", value: 30 },
] satisfies Array<{ label: string; value: number }>;
export const EXPORT_TO_OPTIONS = [
{
label: "File",
value: "file",
icon: IconCapFile,
description: "Save to your computer",
},
{
label: "Clipboard",
value: "clipboard",
icon: IconCapCopy,
description: "Copy to paste anywhere",
},
{
label: "Shareable Link",
value: "link",
icon: IconCapLink,
description: "Share via Cap cloud",
},
] as const;
type ExportFormat = ExportSettings["format"];
const FORMAT_OPTIONS = [
{ label: "MP4", value: "Mp4" },
{ label: "GIF", value: "Gif" },
] as { label: string; value: ExportFormat; disabled?: boolean }[];
type ExportToOption = (typeof EXPORT_TO_OPTIONS)[number]["value"];
interface Settings {
format: ExportFormat;
fps: number;
exportTo: ExportToOption;
resolution: { label: string; value: string; width: number; height: number };
compression: ExportCompression;
optimizeFilesize: boolean;
organizationId?: string | null;
}
function buildExportSettings(
settings: Settings,
cursorOnly: boolean,
compressionBpp: number | null,
forceFfmpegDecoder: boolean,
): ExportSettings {
const resolutionBase = {
x: settings.resolution.width,
y: settings.resolution.height,
};
if (cursorOnly) {
return {
format: "Mov",
fps: settings.fps,
resolution_base: resolutionBase,
cursor_only: true,
};
}
if (settings.format === "Mp4") {
return {
format: "Mp4",
fps: settings.fps,
resolution_base: resolutionBase,
compression: settings.compression,
custom_bpp: compressionBpp,
force_ffmpeg_decoder: forceFfmpegDecoder,
optimize_filesize: settings.optimizeFilesize,
};
}
return {
format: "Gif",
fps: settings.fps,
resolution_base: resolutionBase,
quality: null,
};
}
export function ExportPage() {
const {
setDialog,
editorInstance,
editorState,
setExportState,
exportState,
meta,
refetchMeta,
} = useEditorContext();
const projectPath = editorInstance.path;
const auth = authStore.createQuery();
const organizationSelection = createSelectedOrganization();
const organisations = organizationSelection.organizations;
const hasTransparentBackground = () => {
const backgroundSource =
editorInstance.savedProjectConfig.background.source;
return (
backgroundSource.type === "color" &&
backgroundSource.alpha !== undefined &&
backgroundSource.alpha < 255
);
};
const isCancellationError = (error: unknown) =>
error instanceof SilentError ||
error === "Export cancelled" ||
error === "Save dialog cancelled" ||
(error instanceof Error &&
(error.message === "Export cancelled" ||
error.message === "Save dialog cancelled"));
const [_settings, setSettings] = makePersisted(
createStore<Settings>({
format: "Mp4",
fps: 30,
exportTo: "file",
resolution: { label: "720p", value: "720p", width: 1280, height: 720 },
compression: "Maximum",
optimizeFilesize: false,
}),
{ name: "export_settings" },
);
const VALID_COMPRESSIONS: ExportCompression[] = [
"Maximum",
"Social",
"Web",
"Potato",
];
const [cursorOnly, setCursorOnly] = createSignal(false);
const requiresTransparentExport = () => hasTransparentBackground();
const disablesLinkExport = () => hasTransparentBackground() || cursorOnly();
const shouldUseGifMode = () =>
!cursorOnly() &&
(hasTransparentBackground() ||
(_settings.format === "Gif" && _settings.exportTo !== "link"));
const isMovCursorOnlyExport = () => cursorOnly();
const resetTransientExportOptions = () => {
setCursorOnly(false);
};
const handleBack = () => {
resetTransientExportOptions();
setDialog((d) => ({ ...d, open: false }));
};
const settings = mergeProps(_settings, () => {
const ret: Partial<Settings> = {};
if (!["Mp4", "Gif"].includes(_settings.format)) ret.format = "Mp4";
else if (!cursorOnly()) {
if (requiresTransparentExport() && _settings.format === "Mp4")
ret.format = "Gif";
else if (
!requiresTransparentExport() &&
_settings.format === "Gif" &&
_settings.exportTo === "link"
)
ret.format = "Mp4";
}
if (disablesLinkExport() && _settings.exportTo === "link")
ret.exportTo = "file";
if (shouldUseGifMode()) {
if (!["720p", "1080p"].includes(_settings.resolution.value)) {
ret.resolution = { ...RESOLUTION_OPTIONS._720p };
}
if (GIF_FPS_OPTIONS.every((option) => option.value !== _settings.fps)) {
ret.fps = 15;
}
} else if (FPS_OPTIONS.every((option) => option.value !== _settings.fps)) {
ret.fps = 30;
}
if (!VALID_COMPRESSIONS.includes(_settings.compression))
ret.compression = "Maximum";
Object.defineProperty(ret, "organizationId", {
get() {
const selectedOrganizationId =
organizationSelection.selectedOrganizationId();
if (!_settings.organizationId) return selectedOrganizationId;
if (
organisations().some(
(organization) => organization.id === _settings.organizationId,
)
) {
return _settings.organizationId;
}
return selectedOrganizationId;
},
});
return ret;
});
const [previewUrl, setPreviewUrl] = createSignal<string | null>(null);
const [previewLoading, setPreviewLoading] = createSignal(false);
const [previewUnavailable, setPreviewUnavailable] = createSignal(false);
const [renderEstimate, setRenderEstimate] = createSignal<{
frameRenderTimeMs: number;
totalFrames: number;
estimatedSizeMb: number;
} | null>(null);
type EstimateCacheKey = string;
const estimateCache = new Map<
EstimateCacheKey,
{ frameRenderTimeMs: number; totalFrames: number; estimatedSizeMb: number }
>();
const getEstimateCacheKey = (
fps: number,
width: number,
height: number,
bpp: number,
mode: "video" | "gif" | "cursor",
): EstimateCacheKey => `${fps}-${width}-${height}-${bpp}-${mode}`;
const updateSettings: typeof setSettings = ((
...args: Parameters<typeof setSettings>
) => {
setPreviewLoading(true);
return (setSettings as (...args: Parameters<typeof setSettings>) => void)(
...args,
);
}) as typeof setSettings;
const [previewDialogOpen, setPreviewDialogOpen] = createSignal(false);
const [compressionBpp, setCompressionBpp] = createSignal(
COMPRESSION_TO_BPP[_settings.compression] ?? 0.15,
);
const [advancedMode, setAdvancedMode] = createSignal(false);
const [forceFfmpegDecoder, setForceFfmpegDecoder] = createSignal(false);
const isCustomBpp = () => {
const currentBpp = compressionBpp();
return !COMPRESSION_OPTIONS.some(
(opt) => Math.abs(opt.bpp - currentBpp) < 0.001,
);
};
const _matchingPreset = () => {
const currentBpp = compressionBpp();
return COMPRESSION_OPTIONS.find(
(opt) => Math.abs(opt.bpp - currentBpp) < 0.001,
);
};
createEffect(
on(
() => _settings.compression,
(compression) => {
const bpp = COMPRESSION_TO_BPP[compression];
if (bpp !== undefined && !advancedMode()) setCompressionBpp(bpp);
},
),
);
type PreviewRequest = {
frameTime: number;
fps: number;
resWidth: number;
resHeight: number;
bpp: number;
};
let previewInFlight = false;
let pendingPreviewRequest: PreviewRequest | null = null;
const runPreviewRequest = async (request: PreviewRequest, retryCount = 0) => {
const { frameTime, fps, resWidth, resHeight, bpp } = request;
const cacheKey = getEstimateCacheKey(
fps,
resWidth,
resHeight,
bpp,
isMovCursorOnlyExport() ? "cursor" : shouldUseGifMode() ? "gif" : "video",
);
const cachedEstimate = estimateCache.get(cacheKey);
if (cachedEstimate) {
setRenderEstimate(cachedEstimate);
}
const maxRetries = 2;
try {
const result = await commands.generateExportPreviewFast(frameTime, {
fps,
resolution_base: { x: resWidth, y: resHeight },
compression_bpp: bpp,
cursor_only: cursorOnly(),
});
const oldUrl = previewUrl();
if (oldUrl) URL.revokeObjectURL(oldUrl);
const byteArray = Uint8Array.from(atob(result.jpeg_base64), (c) =>
c.charCodeAt(0),
);
const blob = new Blob([byteArray], { type: "image/jpeg" });
setPreviewUrl(URL.createObjectURL(blob));
const newEstimate = {
frameRenderTimeMs: result.frame_render_time_ms,
totalFrames: result.total_frames,
estimatedSizeMb: result.estimated_size_mb,
};
if (!cachedEstimate) {
estimateCache.set(cacheKey, newEstimate);
}
setPreviewUnavailable(false);
setRenderEstimate(newEstimate);
} catch (e) {
console.error("Failed to generate preview:", e);
if (retryCount < maxRetries) {
await new Promise((resolve) =>
setTimeout(resolve, 200 * (retryCount + 1)),
);
return runPreviewRequest(request, retryCount + 1);
}
setPreviewUnavailable(true);
}
};
const fetchPreview = async (
frameTime: number,
fps: number,
resWidth: number,
resHeight: number,
bpp: number,
) => {
setPreviewUnavailable(false);
pendingPreviewRequest = { frameTime, fps, resWidth, resHeight, bpp };
if (previewInFlight) return;
previewInFlight = true;
try {
while (pendingPreviewRequest) {
const request = pendingPreviewRequest;
pendingPreviewRequest = null;
await runPreviewRequest(request);
}
} finally {
previewInFlight = false;
setPreviewLoading(false);
}
};
const debouncedFetchPreview = debounce(fetchPreview, 300);
setPreviewLoading(true);
fetchPreview(
editorState.playbackTime ?? 0,
settings.fps,
settings.resolution.width,
settings.resolution.height,
compressionBpp(),
);
createEffect(
on(
[
() => settings.format,
() => settings.fps,
() => settings.resolution.width,
() => settings.resolution.height,
cursorOnly,
compressionBpp,
],
() => {
const frameTime = editorState.playbackTime ?? 0;
setPreviewLoading(true);
debouncedFetchPreview(
frameTime,
settings.fps,
settings.resolution.width,
settings.resolution.height,
compressionBpp(),
);
},
{ defer: true },
),
);
onCleanup(() => {
const url = previewUrl();
if (url) URL.revokeObjectURL(url);
});
let cancelCurrentExport: (() => void) | null = null;
onCleanup(() => {
cancelCurrentExport?.();
cancelCurrentExport = null;
});
const exportWithSettings = (
onProgress: (progress: FramesRendered) => void,
) => {
const customBpp = advancedMode() && isCustomBpp() ? compressionBpp() : null;
const exportSettings = buildExportSettings(
settings,
isMovCursorOnlyExport(),
customBpp,
forceFfmpegDecoder(),
);
const { promise, cancel } = createExportTask(
projectPath,
exportSettings,
onProgress,
);
cancelCurrentExport = cancel;
return promise.finally(() => {
if (cancelCurrentExport === cancel) cancelCurrentExport = null;
});
};
const [outputPath, setOutputPath] = createSignal<string | null>(null);
const [isCancelled, setIsCancelled] = createSignal(false);
const exportFileExtension = () =>
isMovCursorOnlyExport() ? "mov" : settings.format === "Gif" ? "gif" : "mp4";
const exportedAssetLabel = () =>
isMovCursorOnlyExport()
? "Cursor track"
: settings.format === "Gif"
? "GIF"
: "Recording";
const exportMediumLabel = () =>
isMovCursorOnlyExport()
? "cursor track"
: settings.format === "Gif"
? "GIF"
: "video";
const handleCancel = async () => {
if (
await ask("Are you sure you want to cancel the export?", {
title: "Cancel Export",
kind: "warning",
})
) {
setIsCancelled(true);
cancelCurrentExport?.();
cancelCurrentExport = null;
setExportState({ type: "idle" });
const path = outputPath();
if (path) {
try {
await remove(path);
} catch (e) {
console.error("Failed to delete cancelled file", e);
}
}
}
};
const copy = createMutation(() => ({
mutationFn: async () => {
setIsCancelled(false);
if (exportState.type !== "idle") return;
const releaseExportSession = await beginExportSessionGuard();
try {
setExportState(reconcile({ action: "copy", type: "starting" }));
const outputPath = await exportWithSettings((progress) => {
if (isCancelled()) throw new SilentError("Cancelled");
setExportState({ type: "rendering", progress });
});
if (isCancelled()) throw new SilentError("Cancelled");
setExportState({ type: "copying" });
await commands.copyVideoToClipboard(outputPath);
} finally {
await releaseExportSession();
}
},
onError: (error) => {
if (isCancelled() || isCancellationError(error)) {
setExportState(reconcile({ type: "idle" }));
return;
}
commands.globalMessageDialog(
error instanceof Error ? error.message : "Failed to copy recording",
);
setExportState(reconcile({ type: "idle" }));
},
onSuccess() {
setExportState({ type: "done" });
toast.success(`${exportedAssetLabel()} exported to clipboard`);
},
}));
const save = createMutation(() => ({
mutationFn: async () => {
setIsCancelled(false);
if (exportState.type !== "idle") return;
const extension = exportFileExtension();
const customBpp =
advancedMode() && isCustomBpp() ? compressionBpp() : null;
const exportSettings = buildExportSettings(
settings,
isMovCursorOnlyExport(),
customBpp,
forceFfmpegDecoder(),
);
const task = createExportToFileTask(
projectPath,
exportSettings,
`${meta().prettyName}.${extension}`,
extension,
(progress) => {
if (isCancelled()) throw new SilentError("Cancelled");
setExportState({ type: "rendering", progress });
},
() => {
setExportState(reconcile({ action: "save", type: "starting" }));
},
() => {
setExportState({ action: "save", type: "copying" });
},
);
cancelCurrentExport = task.cancel;
const savePath = await task.promise.finally(() => {
if (cancelCurrentExport === task.cancel) cancelCurrentExport = null;
});
if (isCancelled()) throw new SilentError("Cancelled");
setOutputPath(savePath);
setExportState({ type: "done" });
},
onError: (error) => {
if (isCancelled() || isCancellationError(error)) {
setExportState({ type: "idle" });
return;
}
commands.globalMessageDialog(
error instanceof Error
? error.message
: `Failed to export recording: ${error}`,
);
setExportState({ type: "idle" });
},
onSuccess() {
toast.success(`${exportedAssetLabel()} exported to file`);
},
}));
const upload = createMutation(() => ({
mutationFn: async () => {
setIsCancelled(false);
if (exportState.type !== "idle") return;
const releaseExportSession = await beginExportSessionGuard();
try {
setExportState(reconcile({ action: "upload", type: "starting" }));
const existingAuth = await authStore.get();
if (!existingAuth) createSignInMutation();
trackEvent("create_shareable_link_clicked", {
resolution: settings.resolution,
fps: settings.fps,
has_existing_auth: !!existingAuth,
});
const metadata = await commands.getVideoMetadata(projectPath);
const plan = await commands.checkUpgradedAndUpdate();
const canShare = {
allowed: plan || metadata.duration < 300,
reason: !plan && metadata.duration >= 300 ? "upgrade_required" : null,
};
if (!canShare.allowed) {
if (canShare.reason === "upgrade_required") {
await commands.showWindow("Upgrade");
await new Promise((resolve) => setTimeout(resolve, 1000));
throw new SilentError();
}
}
const uploadChannel = new Channel<UploadProgress>((progress) => {
console.log("Upload progress:", progress);
setExportState(
produce((state) => {
if (state.type !== "uploading") return;
state.progress = Math.round(progress.progress * 100);
}),
);
});
await exportWithSettings((progress) => {
if (isCancelled()) throw new SilentError("Cancelled");
setExportState({ type: "rendering", progress });
});
if (isCancelled()) throw new SilentError("Cancelled");
setExportState({ type: "uploading", progress: 0 });
console.log({ organizationId: settings.organizationId });
const result = meta().sharing
? await commands.uploadExportedVideo(
projectPath,
"Reupload",
uploadChannel,
settings.organizationId ?? null,
)
: await commands.uploadExportedVideo(
projectPath,
{ Initial: { pre_created_video: null } },
uploadChannel,
settings.organizationId ?? null,
);
if (result === "NotAuthenticated")
throw new Error("You need to sign in to share recordings");
else if (result === "PlanCheckFailed")
throw new Error("Failed to verify your subscription status");
else if (result === "UpgradeRequired")
throw new Error("This feature requires an upgraded plan");
} finally {
await releaseExportSession();
}
},
onSuccess: async () => {
await refetchMeta();
setExportState({ type: "done" });
},
onError: (error) => {
if (isCancelled() || isCancellationError(error)) {
setExportState(reconcile({ type: "idle" }));
return;
}
console.error(error);
if (!(error instanceof SilentError)) {
commands.globalMessageDialog(
error instanceof Error ? error.message : "Failed to upload recording",
);
}
setExportState(reconcile({ type: "idle" }));
},
}));
const formatDuration = (seconds: number) => {
const hours = Math.floor(seconds / 3600);
const minutes = Math.floor((seconds % 3600) / 60);
const secs = seconds % 60;
if (hours > 0) {
return `${hours}:${minutes.toString().padStart(2, "0")}:${secs.toString().padStart(2, "0")}`;
}
return `${minutes}:${secs.toString().padStart(2, "0")}`;
};
return (
<div class="flex flex-col h-full bg-gray-1 overflow-hidden">
<div
data-tauri-drag-region
class="flex relative flex-row items-center w-full h-14 border-b border-gray-3 shrink-0"
>
<h1 class="absolute inset-0 flex items-center justify-center text-sm font-medium text-gray-12 pointer-events-none">
Export
</h1>
<div
data-tauri-drag-region
class={cx(
"flex flex-row flex-1 gap-2 items-center px-4 h-full",
ostype() !== "windows" && "pr-2",
)}
>
{ostype() === "macos" && <div class="h-full w-16" />}
<div data-tauri-drag-region class="flex-1 h-full" />
{ostype() === "windows" && <CaptionControlsWindows11 />}
</div>
</div>
<div class="flex-1 min-h-0 flex relative">
<div class="flex-1 min-h-0 p-5 flex flex-col">
<div class="flex items-center gap-1.5 mb-2">
<span class="text-sm font-medium text-gray-11">Preview</span>
<Tooltip content="This is a rendered frame from your video. Adjust the settings below to see the quality of the final exported video.">
<IconLucideInfo class="size-3.5 text-gray-9 hover:text-gray-11 cursor-help transition-colors" />
</Tooltip>
</div>
<div class="relative flex-1 min-h-0 rounded-xl overflow-hidden bg-gray-2 border border-gray-3 flex items-center justify-center group">
<Show
when={previewUrl()}
fallback={
<div class="absolute inset-0 flex items-center justify-center">
<Show
when={previewLoading()}
fallback={
<div class="flex flex-col items-center gap-3 text-gray-10">
<IconLucideImage class="size-12 text-gray-8" />
<span class="text-sm">
{previewUnavailable()
? "Preview unavailable"
: "Generating preview..."}
</span>
</div>
}
>
<div class="absolute inset-4 rounded-lg bg-gray-4 overflow-hidden">
<div class="absolute inset-y-0 w-full animate-shimmer bg-linear-to-r from-transparent from-30% via-gray-6 via-50% to-transparent to-70%" />
</div>
</Show>
</div>
}
>
{(url) => (
<>
<img
src={url()}
alt="Export preview"
class="relative z-0 w-full h-full object-contain"
/>
<Show when={previewLoading()}>
<div class="absolute inset-0 z-50 overflow-hidden pointer-events-none">
<div class="absolute inset-y-0 w-full animate-shimmer bg-linear-to-r from-transparent from-30% via-white/60 via-50% to-transparent to-70%" />
</div>
</Show>
<button
type="button"
onClick={() => setPreviewDialogOpen(true)}
class="absolute bottom-3 right-3 p-2 rounded-lg bg-gray-12/80 hover:bg-gray-12 text-gray-1 opacity-0 group-hover:opacity-100 transition-opacity"
>
<IconLucideMaximize2 class="size-4" />
</button>
</>
)}
</Show>
</div>
<Show
when={
!previewUnavailable() && !previewLoading() && renderEstimate()
}
fallback={
<div class="flex items-center justify-center gap-4 mt-4 h-4 text-xs text-gray-11">
<span class="flex items-center gap-1.5">
<IconLucideClock class="size-3.5" />
<span class="h-3.5 w-10 bg-gray-4 rounded-sm animate-pulse" />
</span>
<span class="flex items-center gap-1.5">
<IconLucideMonitor class="size-3.5" />
<span class="h-3.5 w-20 bg-gray-4 rounded-sm animate-pulse" />
</span>
<span class="flex items-center gap-1.5">
<IconLucideHardDrive class="size-3.5" />
<span class="h-3.5 w-16 bg-gray-4 rounded-sm animate-pulse" />
</span>
<span class="flex items-center gap-1.5">
<IconLucideZap class="size-3.5" />
<span class="h-3.5 w-12 bg-gray-4 rounded-sm animate-pulse" />
</span>
</div>
}
>
{(est) => {
const data = est();
const durationSeconds = data.totalFrames / settings.fps;
const exportSpeedMultiplier = shouldUseGifMode() ? 4 : 10;
const totalTimeMs =
(data.frameRenderTimeMs * data.totalFrames) /
exportSpeedMultiplier;
const estimatedTimeSeconds = Math.max(1, totalTimeMs / 1000);
const estimatedSizeMb = data.estimatedSizeMb;
return (
<div class="flex items-center justify-center gap-4 mt-4 h-4 text-xs text-gray-11">
<span class="flex items-center gap-1.5">
<IconLucideClock class="size-3.5" />
<span class="min-w-10">
{formatDuration(Math.round(durationSeconds))}
</span>
</span>
<span class="flex items-center gap-1.5">
<IconLucideMonitor class="size-3.5" />
<span class="min-w-20">
{settings.resolution.width}×{settings.resolution.height}
</span>
</span>
<span class="flex items-center gap-1.5">
<IconLucideHardDrive class="size-3.5" />
<span class="min-w-16">
~{estimatedSizeMb.toFixed(1)} MB
</span>
</span>
<span class="flex items-center gap-1.5">
<IconLucideZap class="size-3.5" />
<span class="min-w-12">
~{formatDuration(Math.round(estimatedTimeSeconds))}
</span>
</span>
</div>
);
}}
</Show>
</div>
<div class="w-[400px] border-l border-gray-3 flex flex-col bg-gray-1 dark:bg-gray-2">
<button
type="button"
onClick={handleBack}
class="flex flex-none gap-2 items-center px-4 w-full h-16 text-sm font-medium border-b transition-colors text-gray-12 border-gray-3 hover:bg-gray-3"
>
<IconCapMoveLeft class="size-4 text-gray-11" />
Back to editor
</button>
<div class="flex-1 overflow-y-auto p-4 space-y-5">
<Field name="Destination" icon={<IconCapUpload class="size-4" />}>
<div class="flex gap-1.5">
<For each={EXPORT_TO_OPTIONS}>
{(option) => {
const Icon = option.icon;
const isSelected = () => settings.exportTo === option.value;
const isDisabled = () =>
option.value === "link" && disablesLinkExport();
const disabledReason = () =>
isDisabled()
? cursorOnly()
? "Cursor-only exports can only be saved to a file or clipboard"
: "Transparent exports can only be saved to a file or clipboard"
: undefined;
const button = (
<button
type="button"
class={cx(
"flex-1 flex flex-col items-center gap-1.5 px-3 py-2.5 rounded-lg border transition-colors",
isSelected()
? "bg-gray-3 border-gray-5 text-gray-12"
: "bg-transparent border-transparent text-gray-11 hover:bg-gray-3 hover:border-gray-4",
isDisabled() && "opacity-50 cursor-not-allowed",
)}
disabled={isDisabled()}
onClick={() => {
setSettings(
produce((newSettings) => {
newSettings.exportTo =
option.value as ExportToOption;
if (
option.value === "link" &&
settings.format === "Gif"
) {
newSettings.format = "Mp4";
}
}),
);
}}
>
<Icon
class={cx(
"size-5",
isSelected() ? "text-gray-12" : "text-gray-10",
)}
/>
<span class="text-xs font-medium">{option.label}</span>
</button>
);
return disabledReason() ? (
<Tooltip content={disabledReason()}>{button}</Tooltip>
) : (
button
);
}}
</For>
</div>
<Suspense>
<Show
when={
settings.exportTo === "link" && organisations().length > 1
}
>
<button
type="button"
class="w-full flex items-center justify-between px-3 py-2 mt-3 rounded-lg bg-gray-3 hover:bg-gray-4 transition-colors text-sm"
onClick={async () => {
const menu = await Menu.new({
items: await Promise.all(
organisations().map((org) =>
CheckMenuItem.new({
text: org.name,
action: () => {
setSettings("organizationId", org.id);
void organizationSelection
.setSelectedOrganizationId(org.id)
.catch(console.error);
},
checked: settings.organizationId === org.id,
}),
),
),
});
menu.popup();
}}
>
<span class="text-gray-11">Organization</span>
<span class="flex items-center gap-1 text-gray-12">
{
(
organisations().find(
(o) => o.id === settings.organizationId,
) ?? organisations()[0]
)?.name
}