File size: 10,386 Bytes
689359a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"use client";
import { useCallback, useEffect, useRef, useState } from "react";
import { ApiRequestError, parseApiError } from "@/lib/api-error";
import { remapCaptionTransforms, type EditDocument, type EditorState } from "@/lib/editor/document";

export async function editorRequest<T>(
  url: string,
  method = "GET",
  body?: unknown,
  signal?: AbortSignal,
): Promise<T> {
  const response = await fetch(url, {
    method,
    cache: "no-store",
    ...(signal ? { signal } : {}),
    ...(body === undefined
      ? {}
      : {
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify(body),
        }),
  });
  if (!response.ok)
    throw new ApiRequestError(await parseApiError(response, "Could not update the editor."));
  return response.json();
}
interface History {
  past: EditDocument[];
  present: EditDocument;
  future: EditDocument[];
}

function upgradeCachedHistory(history: History, server: EditDocument): History {
  const upgrade = (document: EditDocument): EditDocument => ({
    ...server,
    ...document,
    // Missing means this cache predates editable B-roll; [] is an intentional removal.
    broll: structuredClone(document.broll ?? server.broll ?? []),
    ...(document.hookTiming !== undefined || server.hookTiming !== undefined
      ? { hookTiming: structuredClone(document.hookTiming ?? null) } : {}),
    // Missing placement fields mean the original layout, including in old undo
    // snapshots. Inheriting today's server placement would corrupt undo.
    ...(document.textTransforms !== undefined || server.textTransforms !== undefined
      ? { textTransforms: structuredClone(document.textTransforms ?? {}) } : {}),
    ...(document.captionTransforms !== undefined || server.captionTransforms !== undefined
      ? { captionTransforms: Object.fromEntries(Object.entries(document.captionTransforms ?? {}).map(([key, value]) => [key, { ...value, size: value.size ?? null }])) } : {}),
  });
  return {
    past: history.past.map(upgrade),
    present: upgrade(history.present),
    future: history.future.map(upgrade),
  };
}
export function useEditor(endpoint: string) {
  const [asset, setAsset] = useState<EditorState | null>(null);
  const [history, setHistory] = useState<History | null>(null);
  const [status, setStatus] = useState("Preparing preview…");
  const [error, setError] = useState<string | null>(null);
  const [storageError, setStorageError] = useState(false);
  const historyRef = useRef<History | null>(null);
  const assetRef = useRef<EditorState | null>(null);
  const revision = useRef(0),
    saved = useRef("");
  const inFlight = useRef<Promise<void> | null>(null);
  const mounted = useRef(true);
  const cacheKey = `supoclip-editor:${endpoint}`;
  const lastEdit = useRef({ group: "", at: 0 });
  const cache = useCallback(
    (value: History) => {
      try {
        localStorage.setItem(
          cacheKey,
          JSON.stringify({
            basis: assetRef.current?.basis,
            revision: revision.current,
            saved: saved.current,
            history: value,
          }),
        );
        setStorageError(false);
      } catch {
        setStorageError(true);
      }
    },
    [cacheKey],
  );
  const publish = useCallback(
    (next: History) => {
      historyRef.current = next;
      setHistory(next);
      cache(next);
      const isSaved = JSON.stringify(next.present) === saved.current;
      setStatus(isSaved ? "All changes saved" : "Unsaved changes");
      if (isSaved) setError(null);
    },
    [cache],
  );
  const update = useCallback(
    (change: (doc: EditDocument) => EditDocument, group = "") => {
      const current = historyRef.current;
      if (!current) return;
      const changed = change(current.present);
      const next = changed.words !== current.present.words || changed.captions.wordsPerLine !== current.present.captions.wordsPerLine
        ? remapCaptionTransforms(current.present, changed) : changed;
      if (JSON.stringify(next) === JSON.stringify(current.present)) return;
      const coalesce =
        group &&
        lastEdit.current.group === group &&
        (group.startsWith("gesture:") || Date.now() - lastEdit.current.at < 700);
      publish({
        past: coalesce
          ? current.past
          : [...current.past, current.present].slice(-50),
        present: next,
        future: [],
      });
      lastEdit.current = { group, at: Date.now() };
    },
    [publish],
  );
  const undo = useCallback(() => {
    const h = historyRef.current;
    if (h?.past.length)
      publish({
        past: h.past.slice(0, -1),
        present: h.past[h.past.length - 1],
        future: [h.present, ...h.future],
      });
    lastEdit.current.group = "";
  }, [publish]);
  const redo = useCallback(() => {
    const h = historyRef.current;
    if (h?.future.length)
      publish({
        past: [...h.past, h.present],
        present: h.future[0],
        future: h.future.slice(1),
      });
    lastEdit.current.group = "";
  }, [publish]);
  const save = useCallback(async () => {
    // All callers drain the same serialized queue, including edits made during a save.
    for (;;) {
      while (inFlight.current) await inFlight.current;
      const h = historyRef.current,
        a = assetRef.current;
      if (!h || !a || JSON.stringify(h.present) === saved.current) return;
      const document = h.present;
      setStatus("Saving…");
      const operation = (async () => {
        try {
          const result = await editorRequest<{ revision: number }>(
            endpoint,
            "PATCH",
            { basis: a.basis, revision: revision.current, document },
          );
          revision.current = result.revision;
          saved.current = JSON.stringify(document);
          if (mounted.current) {
            setError(null);
            setStatus(
              JSON.stringify(historyRef.current?.present) === saved.current
                ? "All changes saved"
                : "Unsaved changes",
            );
            if (historyRef.current) cache(historyRef.current);
          }
        } catch (e) {
          if (mounted.current) {
            setError(e instanceof Error ? e.message : "Could not save draft");
            setStatus("Save failed · draft kept locally");
          }
          throw e;
        }
      })();
      inFlight.current = operation;
      try {
        await operation;
      } finally {
        if (inFlight.current === operation) inFlight.current = null;
      }
    }
  }, [cache, endpoint]);
  useEffect(() => {
    mounted.current = true;
    let stopped = false;
    let timer: ReturnType<typeof setTimeout>;
    async function load() {
      try {
        const state = await editorRequest<EditorState>(endpoint);
        if (stopped) return;
        setAsset(state);
        if (state.status === "unprepared") {
          await editorRequest(`${endpoint}/prepare`, "POST");
          if (!stopped) timer = setTimeout(load, 1500);
          return;
        }
        if (state.status === "preparing") {
          timer = setTimeout(load, 1500);
          return;
        }
        if (state.status === "failed") {
          setError(state.error || "Preview preparation failed");
          return;
        }
        assetRef.current = state;
        revision.current = state.draft.revision;
        saved.current = JSON.stringify(state.draft.document);
        let h: History = {
          past: [],
          present: state.draft.document,
          future: [],
        };
        try {
          const local = JSON.parse(localStorage.getItem(cacheKey) || "null");
          if (
            local?.basis === state.basis &&
            local.history?.present?.version === 1
          ) {
            const restored = upgradeCachedHistory(local.history, state.draft.document);
            if (
              local.revision === state.draft.revision ||
              JSON.stringify(restored.present) === saved.current
            )
              h = restored;
            else if (JSON.stringify(local.history.present) !== local.saved) {
              h = restored;
              revision.current = local.revision;
              setError(
                "A newer draft exists on the server. Your local changes are retained. Download a draft backup, then reload the saved version to resolve the conflict.",
              );
            }
          }
        } catch {
          /* An unreadable local cache never prevents server recovery. */
        }
        historyRef.current = h;
        setHistory(h);
        setStatus(
          JSON.stringify(h.present) === saved.current
            ? "All changes saved"
            : "Recovered local draft",
        );
      } catch (e) {
        if (!stopped)
          setError(e instanceof Error ? e.message : "Could not load editor");
      }
    }
    void load();
    return () => {
      stopped = true;
      mounted.current = false;
      clearTimeout(timer);
    };
  }, [cacheKey, endpoint]);
  useEffect(() => {
    if (!history || error) return;
    const timer = setTimeout(() => void save().catch(() => {}), 700);
    return () => clearTimeout(timer);
  }, [history, save, error]);
  useEffect(() => {
    const warn = (event: BeforeUnloadEvent) => {
      if (
        historyRef.current &&
        JSON.stringify(historyRef.current.present) !== saved.current
      )
        event.preventDefault();
    };
    window.addEventListener("beforeunload", warn);
    return () => window.removeEventListener("beforeunload", warn);
  }, []);
  const reload = async () => {
    if (inFlight.current) await inFlight.current.catch(() => {});
    const state = await editorRequest<EditorState>(endpoint);
    if (state.status !== "ready") throw new Error("Preview is not ready");
    revision.current = state.draft.revision;
    saved.current = JSON.stringify(state.draft.document);
    assetRef.current = state;
    setAsset(state);
    const h = { past: [], present: state.draft.document, future: [] };
    historyRef.current = h;
    setHistory(h);
    cache(h);
    setError(null);
    setStatus("All changes saved");
  };
  return {
    asset,
    document: history?.present ?? null,
    update,
    undo,
    redo,
    canUndo: !!history?.past.length,
    canRedo: !!history?.future.length,
    save,
    reload,
    status,
    error,
    storageError,
  };
}