-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPieceDetail.tsx
More file actions
812 lines (775 loc) · 27.6 KB
/
Copy pathPieceDetail.tsx
File metadata and controls
812 lines (775 loc) · 27.6 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
import {
type ComponentProps,
useCallback,
useEffect,
useMemo,
useRef,
useState,
} from "react";
import {
usePieceHistoryRouting,
usePieceTagsRouting,
} from "../routing/pieceRouting";
import RoutedGlobalEntryField from "./RoutedGlobalEntryField";
import {
Alert,
alpha,
Box,
Collapse,
Divider,
Button,
CircularProgress,
IconButton,
LinearProgress,
Stack,
Typography,
} from "@mui/material";
import ExpandMoreIcon from "@mui/icons-material/ExpandMore";
import CheckCircleIcon from "@mui/icons-material/CheckCircle";
import { useBlocker, useLocation, useNavigate, Link as RouterLink } from "react-router-dom";
import type { PieceDetail as PieceDetailType, PieceState } from "../util/types";
import { DEFAULT_TRACK_ID } from "../util/music";
import { formatState, isTerminalState, getCustomFieldDefinitions } from "../util/workflow";
import { useIsMutating, useMutation, useMutationState, useQuery, useQueryClient } from "@tanstack/react-query";
import {
fetchPieceShowcaseVideo,
requestPieceShowcaseVideo,
updatePiece,
updatePastState,
updateCurrentState,
moveImage,
extractErrorMessage,
addPieceState,
} from "../util/api";
import AppImage from "./AppImage";
import NavigationBlocker from "./NavigationBlocker";
import WorkflowState from "./WorkflowState";
import TagManager from "./TagManager";
import StateCarousel from "./StateCarousel";
import ProcessSummary from "./ProcessSummary";
import PiecePhotoGallery, {
PiecePhotoGalleryButton,
type PiecePhotoGalleryImage,
} from "./PiecePhotoGallery";
import ShowcaseVideoInputPicker, {
type ShowcaseVideoInputSelection,
} from "./ShowcaseVideoInputPicker";
import { PieceDetailSaveStatusProvider } from "./PieceDetailSaveStatusContext";
import { usePieceDetailSaveStatus } from "./usePieceDetailSaveStatus";
import ShareControls from "./PieceShareControls";
import SectionCard from "./SectionCard";
import EditableToggle from "./EditableToggle";
import PieceNameEditor from "./PieceNameEditor";
type PieceDetailProps = {
piece: PieceDetailType;
history?: PieceState[];
historyLoading?: boolean;
historyError?: unknown;
refetchHistory?: () => void;
onPieceUpdated: (updated: PieceDetailType) => void;
};
export default function PieceDetail({
piece,
history,
historyLoading = false,
historyError = null,
refetchHistory,
onPieceUpdated,
}: PieceDetailProps) {
return (
<PieceDetailSaveStatusProvider>
<PieceDetailContent
piece={piece}
history={history}
historyLoading={historyLoading}
historyError={historyError}
refetchHistory={refetchHistory}
onPieceUpdated={onPieceUpdated}
/>
</PieceDetailSaveStatusProvider>
);
}
function PieceDetailContent({
piece,
history,
historyLoading = false,
historyError,
refetchHistory,
onPieceUpdated,
}: PieceDetailProps) {
const pieceDetailSaveStatus = usePieceDetailSaveStatus();
const isSaving = useIsMutating({ mutationKey: ["autosave"] }) > 0;
const hasSaveError =
useMutationState({
filters: { mutationKey: ["autosave"], status: "error" },
}).length > 0;
const pendingTransitionRef = useRef<string | null>(null);
const currentState = piece.current_state;
const isTerminal = isTerminalState(currentState.state);
const canEdit = piece.can_edit;
const hasWorkflowContent =
canEdit || getCustomFieldDefinitions(currentState.state).length > 0;
const statesHistory: PieceState[] = useMemo(() => {
if (!history) {
return piece.history && piece.history.length > 0 ? piece.history : [currentState];
}
// Replace the current state in history with the fresh currentState from piece
return history.map((state) =>
state.id === currentState.id ? currentState : state
);
}, [history, piece.history, currentState]);
const pastHistory = statesHistory.slice(0, -1);
const historyRouting = usePieceHistoryRouting(piece.id);
const tagsRouting = usePieceTagsRouting(piece.id);
const { rewindedStateId } = historyRouting;
const rewindedState = rewindedStateId
? pastHistory.find((ps) => ps.id === rewindedStateId) ?? null
: null;
function formatDate(d: Date): string {
const y = d.getFullYear();
const m = String(d.getMonth() + 1).padStart(2, "0");
const day = String(d.getDate()).padStart(2, "0");
return `${y}/${m}/${day}`;
}
const createdLabel = formatDate(piece.created);
const modifiedLabel = formatDate(piece.last_modified);
const galleryImages: PiecePhotoGalleryImage[] = statesHistory.flatMap(
(state) => {
const isCurrentState =
state.created &&
currentState.created &&
state.created.getTime() === currentState.created.getTime() &&
state.state === currentState.state;
return state.images.map((image, imageIndex) => ({
...image,
stateLabel: formatState(state.state),
stateId: state.id,
editableCurrentStateIndex:
canEdit && isCurrentState ? imageIndex : null,
}));
},
);
// Block navigation away from the dirty form, but allow routing-hook sub-routes
// that are pure in-page UI and do not mutate piece state.
// /photos is intentionally excluded: the gallery can write back to the current
// state using the last-saved prop values, which would silently drop dirty edits.
const blocker = useBlocker(
useCallback(
({ nextLocation }: { nextLocation: { pathname: string } }) => {
if (!canEdit || !hasSaveError) return false;
const next = nextLocation.pathname;
const base = `/pieces/${piece.id}`;
if (next === base) return false;
if (next.startsWith(`${base}/history/`)) return false;
if (next === `${base}/video`) return false;
if (next === `${base}/tags/new`) return false;
if (next.startsWith(`${base}/state/fields/`)) return false;
return true;
},
[canEdit, hasSaveError, piece.id],
),
);
const { mutate: transitionMutate, isPending: transitioning, error: rawTransitionError } = useMutation({
mutationFn: (nextState: string) =>
addPieceState(piece.id, { state: nextState as PieceDetailType["current_state"]["state"] }),
onSuccess: (updated) => onPieceUpdated(updated),
});
// If a save is in progress when the user clicks a transition button, defer
// the transition until the save completes rather than prompting the user.
useEffect(() => {
if (!isSaving && pendingTransitionRef.current) {
transitionMutate(pendingTransitionRef.current);
pendingTransitionRef.current = null;
}
}, [isSaving, transitionMutate]);
const handleTransition = useCallback(
(nextState: string) => {
if (isSaving) {
pendingTransitionRef.current = nextState;
} else {
transitionMutate(nextState);
}
},
[isSaving, transitionMutate],
);
const transitionError = rawTransitionError
? extractErrorMessage(rawTransitionError, "Failed to transition state. Please try again.")
: null;
const { mutate: handleLocationSelect, isPending: locationSaving, error: rawLocationError } = useMutation({
mutationFn: (entry: { id: string; name: string } | null) => {
const saveLocationRequest = () => updatePiece(piece.id, { current_location: entry?.name ?? "" });
return pieceDetailSaveStatus
? pieceDetailSaveStatus.runManualSave(saveLocationRequest)
: saveLocationRequest();
},
onSuccess: (updated) => onPieceUpdated(updated),
});
const locationError = rawLocationError
? extractErrorMessage(rawLocationError, "Failed to save location. Please try again.")
: null;
const navigate = useNavigate();
const location = useLocation();
const hasGalleryImages = galleryImages.length > 0;
const thumbnailIndex = piece.thumbnail
? galleryImages.findIndex((img) =>
piece.thumbnail?.image_id && img.image_id
? img.image_id === piece.thumbnail.image_id
: img.url === piece.thumbnail?.url,
)
: -1;
const heroLightboxIndex = thumbnailIndex >= 0 ? thumbnailIndex : 0;
const galleryProps = {
images: galleryImages,
pieceId: piece.id,
currentStateNotes: currentState.notes,
currentStateCustomFields: currentState.custom_fields ?? {},
currentThumbnailUrl: piece.thumbnail?.url,
onPieceUpdated,
updatePieceFn: canEdit ? updatePiece : undefined,
updateCurrentStateFn: canEdit ? updateCurrentState : undefined,
updatePastStateFn: piece.is_editable ? updatePastState : undefined,
pieceStates: statesHistory.length > 0
? statesHistory.map((s) => ({ id: s.id, label: formatState(s.state) }))
: [{ id: currentState.id, label: formatState(currentState.state) }],
moveImageFn: piece.is_editable ? moveImage : undefined,
historyLoading,
historyError,
refetchHistory,
} satisfies ComponentProps<typeof PiecePhotoGallery>;
return (
<Box
sx={{
textAlign: "left",
px: { xs: 1.5, sm: 2.5 },
pb: 4,
}}
>
<Box sx={{ mx: "auto", maxWidth: 980, background: "transparent" }}>
{/* Desktop: two-column hero+info; Mobile: stacked */}
<Box
sx={{
display: { xs: "grid", md: "grid" },
gridTemplateColumns: { xs: "1fr", md: "1fr 1fr" },
gridTemplateAreas: {
xs: '"hero" "info"',
md: '"info hero"',
},
gap: { md: 3 },
alignItems: "start",
mb: { xs: 0, md: 2 },
}}
>
{/* Left column (desktop) / bottom (mobile): title + tags + states */}
<Box sx={{ pt: { xs: 1.75, md: 0 }, pb: 0.5, gridArea: "info", minWidth: 0 }}>
<Typography
variant="caption"
sx={{
display: "block",
mb: 0.5,
color: "text.secondary",
letterSpacing: "0.12em",
textTransform: "uppercase",
}}
>
Created {createdLabel} · Modified {modifiedLabel}
</Typography>
<PieceNameEditor
piece={piece}
onPieceUpdated={onPieceUpdated}
/>
{canEdit ? (
<TagManager
pieceId={piece.id}
initialTags={piece.tags ?? []}
onSaved={onPieceUpdated}
tagDialogOpen={tagsRouting.tagDialogOpen}
onOpenTagDialog={tagsRouting.onOpenTagDialog}
onCloseTagDialog={tagsRouting.onCloseTagDialog}
/>
) : null}
<Box sx={{ mt: 2, mb: 1.5 }}>
<StateCarousel
statesHistory={statesHistory}
piece={piece}
onPieceUpdated={onPieceUpdated}
rewindedStateId={rewindedStateId}
onRewind={(id) =>
id ? historyRouting.onRewind(id) : historyRouting.onClearRewind()
}
historyLoading={historyLoading}
historyError={historyError}
refetchHistory={refetchHistory}
onTransition={handleTransition}
transitioning={transitioning}
transitionError={transitionError}
hasSaveError={hasSaveError}
/>
</Box>
{canEdit && isTerminal && (
<Box sx={{ mb: 1.5 }}>
<ShareControls piece={piece} onPieceUpdated={onPieceUpdated} />
</Box>
)}
{piece.can_edit && (
<Box sx={{ mb: 1.5 }}>
<Button
component={RouterLink}
to={`/pieces/${piece.id}/showcase`}
variant="outlined"
size="small"
>
Preview showcase
</Button>
</Box>
)}
{canEdit && (
<Box sx={{ mb: 1.5 }}>
<EditableToggle piece={piece} onPieceUpdated={onPieceUpdated} />
</Box>
)}
<Box sx={{ mb: 1.5 }}>
<RoutedGlobalEntryField
pieceId={piece.id}
fieldName="current_location"
globalName="location"
label="Current location"
value={piece.current_location ?? ""}
onSelect={(entry) => void handleLocationSelect(entry)}
disabled={!canEdit}
hideActionWhenDisabled
sx={{ opacity: locationSaving ? 0.7 : 1 }}
canCreate
/>
{locationError && (
<Typography variant="body2" color="error" sx={{ mt: 0.75 }}>
{locationError}
</Typography>
)}
</Box>
</Box>
{/* Right column (desktop) / top (mobile): hero image */}
<Box sx={{ gridArea: "hero" }}>
<Box
onClick={
hasGalleryImages
? () => navigate(`/pieces/${piece.id}/photos/${heroLightboxIndex}`, { state: location.state })
: undefined
}
sx={(theme) => ({
position: "relative",
overflow: "hidden",
borderRadius: { xs: "8px", md: "10px" },
minHeight: { xs: 200, sm: 260 },
aspectRatio: { md: "4 / 3" },
backgroundColor: alpha(theme.palette.background.paper, 0.46),
boxShadow: `0 24px 60px ${alpha(theme.palette.common.black, 0.22)}`,
cursor: hasGalleryImages ? "pointer" : "default",
})}
>
{piece.thumbnail ? (
<Box sx={{ position: "absolute", inset: 0 }}>
<AppImage
url={piece.thumbnail.url}
croppedUrl={piece.thumbnail.cropped_url}
crop={piece.thumbnail.crop}
r2Key={piece.thumbnail.r2_key}
cropTaskFailed={piece.thumbnail.crop_task_failed}
alt={piece.name}
context="detail"
style={{
width: "100%",
height: "100%",
objectFit: piece.thumbnail.crop ? "contain" : "cover",
display: "block",
}}
/>
</Box>
) : null}
<Box
sx={(theme) => ({
position: "absolute",
inset: 0,
background: piece.thumbnail
? `linear-gradient(180deg, ${alpha(theme.palette.common.black, 0.24)} 0%, transparent 40%)`
: alpha(theme.palette.background.default, 0.9),
})}
/>
{/* Photo gallery button — inside hero on mobile only */}
<Box
sx={{
display: { xs: "flex", md: "none" },
position: "relative",
zIndex: 1,
justifyContent: "flex-end",
p: { xs: 1.5, sm: 2 },
}}
>
<PiecePhotoGalleryButton
images={galleryImages}
pieceId={piece.id}
/>
</Box>
</Box>
{/* Photo gallery + upload trigger — below hero on desktop only */}
<Box
sx={{
display: { xs: "none", md: "flex" },
alignItems: "center",
gap: 1,
mt: 1,
}}
>
<Box id="piece-upload-trigger" />
<PiecePhotoGallery {...galleryProps} />
</Box>
</Box>
</Box>
{rewindedState ? (
<SectionCard>
<WorkflowState
key={rewindedState.id}
initialPieceState={rewindedState}
pieceId={piece.id}
onSaved={onPieceUpdated}
readOnly={!piece.is_editable}
hideNotes={!canEdit}
saveStateFn={(payload) =>
updatePastState(piece.id, rewindedState.id, payload)
}
/>
</SectionCard>
) : hasWorkflowContent ? (
<SectionCard>
<WorkflowState
key={
currentState.state +
(currentState.created?.toISOString() ?? "")
}
initialPieceState={currentState}
pieceId={piece.id}
onSaved={onPieceUpdated}
readOnly={!canEdit}
hideNotes={!canEdit}
/>
</SectionCard>
) : null}
<Divider sx={{ my: 2, opacity: 0.4 }} />
{isTerminal && canEdit && (
<Alert severity="info" sx={{ mb: 2.5, borderRadius: 3 }}>
This piece is in a terminal state (
<strong>{formatState(currentState.state)}</strong>). No further
transitions are possible.
</Alert>
)}
{canEdit && isTerminal && (
<Box sx={{ mb: 2.5 }}>
<ShowcaseVideoPanel
piece={piece}
history={statesHistory}
historyLoading={historyLoading}
historyError={historyError}
refetchHistory={refetchHistory}
/>
</Box>
)}
<Box sx={{ mb: 2.5 }}>
<SectionCard
title="Process Summary"
titleId="process-summary-title"
>
{historyError ? (
<Box sx={{ py: 1, textAlign: "center" }}>
<Typography variant="body2" color="error" sx={{ mb: 1 }}>
Failed to load process summary.
</Typography>
<Button size="small" variant="outlined" onClick={refetchHistory}>
Retry
</Button>
</Box>
) : historyLoading ? (
<Box sx={{ display: "flex", justifyContent: "center", py: 2 }}>
<CircularProgress size={24} />
</Box>
) : (
<ProcessSummary piece={piece} history={statesHistory} />
)}
</SectionCard>
</Box>
</Box>
{canEdit && (
<NavigationBlocker
open={blocker.state === "blocked"}
onStay={() => blocker.reset?.()}
onLeave={() => blocker.proceed?.()}
/>
)}
</Box>
);
}
type ArtifactActionsProps = {
artifact: { url: string };
};
function ArtifactActions({ artifact }: ArtifactActionsProps) {
return (
<Box
component="video"
src={artifact.url}
controls
playsInline
sx={{
width: "100%",
borderRadius: 1,
display: "block",
backgroundColor: "black",
}}
/>
);
}
function ShowcaseVideoPanel({
piece,
history,
historyLoading,
historyError,
refetchHistory,
}: {
piece: PieceDetailType;
history?: PieceState[];
historyLoading: boolean;
historyError?: unknown;
refetchHistory?: () => void;
}) {
const queryClient = useQueryClient();
const [expanded, setExpanded] = useState(false);
const [selection, setSelection] = useState<ShowcaseVideoInputSelection>({
excludedImageKeys: [],
excludedNoteKeys: [],
musicTrackId: DEFAULT_TRACK_ID,
});
// Piece edits change the render hash server-side; invalidate so the fresh
// current_input_hash is fetched and the stale-needs-regeneration status
// (or re-enabled button) reflects the updated piece content.
const prevPieceRef = useRef(piece);
useEffect(() => {
if (prevPieceRef.current !== piece) {
prevPieceRef.current = piece;
queryClient.invalidateQueries({ queryKey: ["showcase-video", piece.id] });
}
}, [piece, queryClient]);
const {
data: showcaseVideo,
error: rawStatusError,
isLoading,
} = useQuery({
queryKey: ["showcase-video", piece.id],
queryFn: () => fetchPieceShowcaseVideo(piece.id),
refetchInterval: (query) =>
query.state.data?.status === "pending" ||
query.state.data?.status === "running"
? 2500
: false,
});
const {
mutate: generateVideo,
isPending: generating,
error: rawGenerateError,
} = useMutation({
mutationFn: () => requestPieceShowcaseVideo(piece.id, selection),
onSuccess: (updated) => {
queryClient.setQueryData(["showcase-video", piece.id], updated);
},
});
const currentStatus = showcaseVideo?.status ?? "idle";
const storedImageKeys = showcaseVideo?.excluded_image_keys ?? [];
const storedNoteKeys = showcaseVideo?.excluded_note_keys ?? [];
const selectionMatchesStoredTask =
selection.musicTrackId === (showcaseVideo?.music_track_id ?? DEFAULT_TRACK_ID) &&
selection.excludedImageKeys.length === storedImageKeys.length &&
selection.excludedImageKeys.every((k) => storedImageKeys.includes(k)) &&
selection.excludedNoteKeys.length === storedNoteKeys.length &&
selection.excludedNoteKeys.every((k) => storedNoteKeys.includes(k));
const hashUnchanged =
selectionMatchesStoredTask &&
currentStatus === "succeeded" &&
showcaseVideo?.current_input_hash != null &&
showcaseVideo.current_input_hash === showcaseVideo?.stored_input_hash;
const canGenerate =
!generating &&
!hashUnchanged &&
(showcaseVideo?.enabled ?? true) &&
currentStatus !== "pending" &&
currentStatus !== "running" &&
(showcaseVideo?.eligible ?? true) &&
!historyLoading &&
!historyError;
const statusLabel =
currentStatus === "idle"
? "No render has been requested yet."
: currentStatus === "disabled"
? "Showcase video generation is unavailable."
: currentStatus === "failed"
? "The latest render failed."
: currentStatus === "stale-needs-regeneration"
? "The latest render is stale."
: "The latest render is ready.";
const isActive =
currentStatus === "pending" || currentStatus === "running";
const activeProgress =
currentStatus === "running" ? (showcaseVideo?.progress ?? 0) : null;
const artifact = showcaseVideo?.artifact ?? null;
const errorMessage = rawGenerateError
? extractErrorMessage(
rawGenerateError,
"Failed to request a video render. Please try again.",
)
: rawStatusError
? extractErrorMessage(
rawStatusError,
"Failed to load showcase video status.",
)
: null;
return (
<SectionCard
title="Showcase Video"
subtitle="Render a deterministic Keepsake slideshow from the piece history."
titleAdornment={
<Box sx={{ display: "flex", alignItems: "center", gap: 0.5 }}>
{artifact && !expanded && (
<CheckCircleIcon fontSize="small" sx={{ color: "success.main" }} />
)}
<IconButton
size="small"
onClick={() => setExpanded((prev) => !prev)}
aria-label={expanded ? "Collapse showcase video" : "Expand showcase video"}
sx={{ transform: expanded ? "rotate(180deg)" : "rotate(0deg)", transition: "transform 0.2s" }}
>
<ExpandMoreIcon fontSize="small" />
</IconButton>
</Box>
}
>
<Collapse in={expanded} unmountOnExit>
<Stack spacing={2}>
{historyError ? (
<Box sx={{ py: 2, textAlign: "center" }}>
<Typography variant="body2" color="error" sx={{ mb: 1 }}>
Failed to load past photos and notes for the video.
</Typography>
{refetchHistory && (
<Button size="small" variant="outlined" onClick={refetchHistory}>
Retry
</Button>
)}
</Box>
) : historyLoading ? (
<Box sx={{ display: "flex", justifyContent: "center", py: 3 }}>
<CircularProgress size={24} />
</Box>
) : (
<ShowcaseVideoInputPicker
piece={piece}
history={history}
selection={selection}
onSelectionChange={setSelection}
disabled={generating || currentStatus === "pending" || currentStatus === "running"}
/>
)}
<Box
sx={(theme) => ({
borderRadius: 2,
border: "1px solid",
borderColor: "divider",
backgroundColor: theme.palette.background.paper,
p: 1.5,
})}
>
<Stack spacing={1.25}>
{isActive ? (
currentStatus === "pending" ? (
<Box sx={{ display: "flex", alignItems: "center", gap: 1 }}>
<CircularProgress size={16} />
<Typography variant="body2" color="text.secondary">
Queued — you can safely navigate away.
</Typography>
</Box>
) : (
<Box>
<Typography variant="body2" color="text.secondary" sx={{ mb: 0.75 }}>
Rendering in the background…
</Typography>
<LinearProgress
variant={activeProgress !== null ? "determinate" : "indeterminate"}
value={activeProgress ?? undefined}
/>
</Box>
)
) : (
<Typography variant="body2" sx={{ fontWeight: 600 }}>
{statusLabel}
</Typography>
)}
{isLoading && !showcaseVideo ? (
<Box sx={{ display: "flex", alignItems: "center", gap: 1 }}>
<CircularProgress size={16} />
<Typography variant="body2" color="text.secondary">
Checking for the latest render...
</Typography>
</Box>
) : null}
{showcaseVideo?.stale_reason ? (
<Alert severity="warning" variant="outlined">
{showcaseVideo.stale_reason}
</Alert>
) : null}
{showcaseVideo?.disabled_reason ? (
<Alert severity="info" variant="outlined">
{showcaseVideo.disabled_reason}
</Alert>
) : null}
{showcaseVideo?.error ? (
<Alert severity="error" variant="outlined">
{showcaseVideo.error}
</Alert>
) : null}
{errorMessage ? (
<Typography variant="body2" color="error">
{errorMessage}
</Typography>
) : null}
{artifact ? (
<ArtifactActions artifact={artifact} />
) : null}
<Stack
direction={{ xs: "column", sm: "row" }}
spacing={1}
alignItems={{ xs: "stretch", sm: "center" }}
>
<Button
variant="contained"
onClick={() => generateVideo()}
disabled={!canGenerate}
startIcon={generating ? <CircularProgress size={16} /> : undefined}
>
{currentStatus === "succeeded" ||
currentStatus === "stale-needs-regeneration"
? "Render again"
: currentStatus === "disabled"
? "Unavailable"
: "Generate video"}
</Button>
{!isActive && (
<Typography variant="caption" color="text.secondary">
{showcaseVideo?.enabled === false
? "Configure R2 storage to enable showcase videos."
: showcaseVideo?.eligible === false
? "This piece is not eligible for video generation yet."
: "Renders asynchronously — you can navigate away."}
</Typography>
)}
</Stack>
</Stack>
</Box>
</Stack>
</Collapse>
</SectionCard>
);
}