File size: 10,430 Bytes
070c931
 
 
 
 
 
 
 
 
66de9c8
070c931
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bcfc897
070c931
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bcfc897
070c931
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { useEffect, useState, type ReactNode } from "react";
import { videoEditApi, type LayoutInfo, type LayoutSchema } from "../../api/endpoints";
import type {
  VideoCatalog,
  VideoJobState,
  VideoProjectData,
  VideoScene,
} from "../../api/types";
import { ChevronIcon, TrashIcon } from "../icons/Icons";
import { ErrorText, errorMessage } from "../ui";
import { DeleteAssetModal, RemoveMediaModal } from "./SceneMedia";
import { Voiceovers } from "./Voiceovers";

/** What every panel gets from the editor page. */
export type PanelProps = {
  id: string;
  project: VideoProjectData;
  /** The template's layout_prop_schema (default font sizes per layout); null until loaded or if it failed. */
  layoutSchema: LayoutSchema | null;
  /** The template's display names per layout id; null until loaded or if it failed. */
  layoutNames: Record<string, string> | null;
  /** Every layout of the template with its visual variants (Scene layout / Scene style in the scene editor). */
  layoutInfo: LayoutInfo | null;
  disabled: boolean;
  /** Run a quick change, then reload the project. Resolves true on success, false when it failed. */
  act: (fn: () => Promise<unknown>, done?: string) => Promise<boolean>;
  /** Start a background job and poll it until it finishes. */
  startJob: (label: string, start: () => Promise<unknown>, poll: () => Promise<VideoJobState | null>) => Promise<void>;
  locked: () => void;
};

const sorted = (scenes: VideoScene[]) => [...scenes].sort((a, b) => a.order - b.order);

// Audio: each scene's voiceover

/** Audio tab: each scene's voiceover, to play or record again. */
export function VoicePanel(p: PanelProps & { catalog: VideoCatalog | null }) {
  return <Voiceovers {...p} scenes={sorted(p.project.scenes)} />;
}

// Refresh the script: new titles and layouts, same narration

export function ScriptPanel(p: PanelProps) {
  const [instruction, setInstruction] = useState("");
  const [preview, setPreview] = useState<Record<string, unknown> | null>(null);
  const [error, setError] = useState<string | null>(null);

  async function loadPreview() {
    setError(null);
    try {
      setPreview(await videoEditApi.refreshPreview(p.id));
    } catch (e) {
      setError(errorMessage(e));
    }
  }

  return (
    <section className="card stack">
      <h3>Refresh the script</h3>
      <p className="muted small">Rewrites titles, on-screen text and layouts. The narration and voiceovers stay.</p>
      <textarea className="input" rows={2} value={instruction} maxLength={2000} placeholder="Anything to change (optional)"
                onChange={(e) => setInstruction(e.target.value)} />
      <div className="row wrap">
        <button className="btn btn-primary btn-small" disabled={p.disabled}
                onClick={() => p.startJob("Refreshing the script", () => videoEditApi.refreshScript(p.id, instruction || undefined),
                                          () => videoEditApi.refreshStatus(p.id))}>
          Refresh
        </button>
        <button className="btn btn-small" disabled={p.disabled} onClick={loadPreview}>See the last result</button>
        <button className="btn btn-small" disabled={p.disabled}
                onClick={() => p.act(() => videoEditApi.refreshVerify(p.id), "Checked.")}>Check it</button>
        <button className="btn btn-small" disabled={p.disabled}
                onClick={() => p.startJob("Refreshing the script", () => videoEditApi.refreshRetry(p.id, instruction || undefined),
                                          () => videoEditApi.refreshStatus(p.id))}>
          Try again
        </button>
      </div>
      {error && <ErrorText message={error} />}
      {preview && <pre className="vw-pre">{JSON.stringify(preview, null, 2)}</pre>}
    </section>
  );
}

// Frames: a still of any frame

export function FramesPanel(p: PanelProps) {
  const [frame, setFrame] = useState(0);
  const [src, setSrc] = useState<string | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [busy, setBusy] = useState(false);

  useEffect(() => () => { if (src) URL.revokeObjectURL(src); }, [src]);

  async function load() {
    setBusy(true);
    setError(null);
    try {
      setSrc(URL.createObjectURL(await videoEditApi.still(p.id, frame)));
    } catch (e) {
      setError(errorMessage(e));
    } finally {
      setBusy(false);
    }
  }

  return (
    <section className="card stack">
      <h3>Frame still</h3>
      <div className="row">
        <label className="row small">Frame <input className="input vw-num" type="number" min={0} value={frame}
                                                   onChange={(e) => setFrame(Math.max(0, Number(e.target.value)))} /></label>
        <button className="btn btn-small" disabled={busy} onClick={load}>{busy ? "Rendering..." : "Show frame"}</button>
        {src && <a className="btn btn-small" href={src} download={`frame-${frame}.png`}>Download</a>}
      </div>
      {error && <ErrorText message={error} />}
      {src && <img className="vw-still" src={src} alt={`Frame ${frame}`} />}
    </section>
  );
}

// Images/footage: what each scene shows, and what no scene uses yet

type Media = { key: string; filename: string; kind: string; url: string; assetId: number | null };

/** One image or clip, as a small 16:9 tile: clips get a CLIP badge and play on hover. */
function MediaTile({ m, children }: { m: Media; children?: ReactNode }) {
  const clip = m.kind === "video";
  return (
    <div className="vw-media-tile">
      {clip ? (
        <video src={m.url} muted loop playsInline preload="metadata"
               onMouseEnter={(e) => e.currentTarget.play().catch(() => undefined)} onMouseLeave={(e) => e.currentTarget.pause()} />
      ) : (
        <img src={m.url} alt="" loading="lazy" />
      )}
      {clip && <span className="vw-media-badge mono">Clip</span>}
      <span className="vw-media-name mono" title={m.filename}>{m.filename}</span>
      {children}
    </div>
  );
}

const MEDIA_GROUP = 5;

/** Images and stock footage, laid out like blog2video's editor: what each scene shows, grouped by five, and what no
 * scene uses yet. Put an unused one on a scene, or take one off a scene. */
export function ImagesPanel(p: PanelProps) {
  const scenes = sorted(p.project.scenes);
  const assets = (p.project.assets ?? []).filter((a) => (a.asset_type === "image" || a.asset_type === "video") && !a.excluded && a.r2_url);
  const used = new Set(scenes.flatMap((s) => (s.images ?? []).map((i) => i.filename)));
  const unassigned: Media[] = assets.filter((a) => !used.has(a.filename))
    .map((a) => ({ key: `a${a.id}`, filename: a.filename, kind: a.asset_type, url: a.r2_url!, assetId: a.id }));
  const images = assets.filter((a) => a.asset_type === "image").length;
  const clips = assets.length - images;
  const [openGroup, setOpenGroup] = useState<number | null>(0);
  const [removing, setRemoving] = useState<{ scene: VideoScene; filename: string; kind: string } | null>(null);
  const [deleting, setDeleting] = useState<Media | null>(null);

  const groups: VideoScene[][] = [];
  for (let i = 0; i < scenes.length; i += MEDIA_GROUP) groups.push(scenes.slice(i, i + MEDIA_GROUP));


  return (
    <div className="vw-media-cols">
      <section className="stack">
        <div className="vw-media-head">
          <h3>Images and stock footage</h3>
          <span className="muted small">{images} image{images === 1 ? "" : "s"} · {clips} stock clip{clips === 1 ? "" : "s"}</span>
        </div>
        {groups.map((group, g) => {
          const first = g * MEDIA_GROUP + 1;
          const open = openGroup === g;
          return (
            <section key={g} className="vw-group">
              <button type="button" className="vw-group-head" aria-expanded={open} onClick={() => setOpenGroup(open ? null : g)}>
                <span>Scenes {first}–{first + group.length - 1}</span>
                <ChevronIcon size={18} className={`chevron${open ? " open" : ""}`} />
              </button>
              {open && group.map((s) => (
                <div key={s.id} className="vw-media-scene">
                  <div className="vw-media-scene-title">
                    <span className="vw-num-badge">{s.order}</span>
                    <strong>{s.title || `Scene ${s.order}`}</strong>
                  </div>
                  <div className="vw-media-grid">
                    {(s.images ?? []).map((i) => (
                      <MediaTile key={i.filename} m={{ key: i.filename, filename: i.filename, kind: i.kind, url: i.url, assetId: i.asset_id }}>
                        <button type="button" className="vw-media-x" aria-label={`Remove from scene ${s.order}`} title="Remove from scene"
                                disabled={p.disabled} onClick={() => setRemoving({ scene: s, filename: i.filename, kind: i.kind })}>✕</button>
                      </MediaTile>
                    ))}
                    {(s.images ?? []).length === 0 && <span className="muted small">No media</span>}
                  </div>
                </div>
              ))}
            </section>
          );
        })}
      </section>

      <section className="stack">
        <div className="vw-media-head">
          <h3>Unassigned</h3>
          <span className="muted small">not used in any scene</span>
        </div>
        {unassigned.length === 0 ? (
          <p className="muted small">Every image and clip is on a scene.</p>
        ) : (
          <div className="vw-media-grid vw-unassigned">
            {unassigned.map((m) => (
              <MediaTile key={m.key} m={m}>
                {m.assetId !== null && (
                  <button type="button" className="vw-media-del" aria-label="Delete permanently" title="Delete permanently"
                          disabled={p.disabled} onClick={() => setDeleting(m)}>
                    <TrashIcon size={15} />
                  </button>
                )}
              </MediaTile>
            ))}
          </div>
        )}
      </section>

      {removing && <RemoveMediaModal {...p} scene={removing.scene} filename={removing.filename} kind={removing.kind}
                                     onClose={() => setRemoving(null)} />}
      {deleting && deleting.assetId !== null && (
        <DeleteAssetModal {...p} asset={{ id: deleting.assetId, kind: deleting.kind }} onClose={() => setDeleting(null)} />
      )}
    </div>
  );
}