|
| 1 | +import { |
| 2 | + useCallback, |
| 3 | + useEffect, |
| 4 | + useMemo, |
| 5 | + useRef, |
| 6 | + useState, |
| 7 | + useSyncExternalStore, |
| 8 | +} from "react"; |
| 9 | +import type { |
| 10 | + CanvasHistoryCursor, |
| 11 | + CanvasHistoryPage, |
| 12 | + ChannelCanvas, |
| 13 | +} from "../../features/channel-templates/capability"; |
| 14 | +import { CANVAS_BYTES } from "../../features/channel-templates/model"; |
| 15 | +import type { RelayEvent } from "../../features/relay/events"; |
| 16 | +import type { ProfileQueries } from "../../features/relay/profile-directory"; |
| 17 | +import { selectProfiles } from "../../features/relay/profile-selection"; |
| 18 | +import { publicKeyLabels } from "../../shared/identity/public-key"; |
| 19 | +import { Button } from "../../shared/design-system/ui/Button"; |
| 20 | +import { Dialog } from "../../shared/design-system/ui/Dialog"; |
| 21 | +import { Field } from "../../shared/design-system/ui/Field"; |
| 22 | +import { Radio, RadioGroup } from "../../shared/design-system/ui/RadioGroup"; |
| 23 | +import { Textarea } from "../../shared/design-system/ui/Textarea"; |
| 24 | +import styles from "./ChannelTemplates.module.css"; |
| 25 | + |
| 26 | +export function CanvasHistory({ |
| 27 | + canvas, |
| 28 | + channelId, |
| 29 | + profiles: queries, |
| 30 | + head, |
| 31 | + busy, |
| 32 | + loaded, |
| 33 | + dirty, |
| 34 | + refreshHead, |
| 35 | + restore, |
| 36 | +}: { |
| 37 | + canvas: ChannelCanvas; |
| 38 | + channelId: string; |
| 39 | + profiles: ProfileQueries; |
| 40 | + head: RelayEvent | undefined; |
| 41 | + busy: boolean; |
| 42 | + loaded: boolean; |
| 43 | + dirty: boolean; |
| 44 | + refreshHead(): Promise<void>; |
| 45 | + restore(revision: RelayEvent): Promise<void>; |
| 46 | +}) { |
| 47 | + const [page, setPage] = useState<CanvasHistoryPage>(); |
| 48 | + const [selected, setSelected] = useState<RelayEvent>(); |
| 49 | + const [loading, setLoading] = useState(false); |
| 50 | + const [error, setError] = useState(""); |
| 51 | + const [notice, setNotice] = useState(""); |
| 52 | + const [confirm, setConfirm] = useState(false); |
| 53 | + const cancel = useRef<HTMLButtonElement>(null); |
| 54 | + const restoreButton = useRef<HTMLButtonElement>(null); |
| 55 | + const generation = useRef(0); |
| 56 | + const refreshButton = useRef<HTMLButtonElement>(null); |
| 57 | + const attempted = useRef(false); |
| 58 | + const rows = useRef<HTMLDivElement>(null); |
| 59 | + const focusRevision = useRef<string | undefined>(undefined); |
| 60 | + useEffect(() => { |
| 61 | + if (focusRevision.current && page) { |
| 62 | + rows.current |
| 63 | + ?.querySelector<HTMLElement>( |
| 64 | + `[data-revision="${focusRevision.current}"]`, |
| 65 | + ) |
| 66 | + ?.focus(); |
| 67 | + focusRevision.current = undefined; |
| 68 | + } |
| 69 | + }, [page]); |
| 70 | + const keys = (page?.revisions ?? []) |
| 71 | + .map((event) => event.pubkey) |
| 72 | + .sort() |
| 73 | + .join(":"); |
| 74 | + const ids = useMemo(() => [...new Set(keys ? keys.split(":") : [])], [keys]); |
| 75 | + const selection = useMemo(() => selectProfiles(queries, ids), [queries, ids]); |
| 76 | + const profiles = useSyncExternalStore( |
| 77 | + selection.subscribe, |
| 78 | + selection.snapshot, |
| 79 | + selection.snapshot, |
| 80 | + ); |
| 81 | + const labels = publicKeyLabels(ids); |
| 82 | + useEffect(() => { |
| 83 | + void queries.ensure(ids, "background").catch(() => {}); |
| 84 | + }, [queries, ids]); |
| 85 | + const load = useCallback( |
| 86 | + async (cursor?: CanvasHistoryCursor) => { |
| 87 | + const current = ++generation.current; |
| 88 | + setLoading(true); |
| 89 | + setError(""); |
| 90 | + try { |
| 91 | + const result = await canvas.history(channelId, cursor); |
| 92 | + if (current !== generation.current) return; |
| 93 | + setPage((previous) => ({ |
| 94 | + ...result, |
| 95 | + revisions: cursor |
| 96 | + ? [...(previous?.revisions ?? []), ...result.revisions] |
| 97 | + : result.revisions, |
| 98 | + })); |
| 99 | + if (cursor) |
| 100 | + focusRevision.current = |
| 101 | + result.revisions[0]?.id ?? |
| 102 | + rows.current?.querySelector<HTMLElement>('[aria-checked="true"]') |
| 103 | + ?.dataset.revision; |
| 104 | + if (!cursor) |
| 105 | + setSelected( |
| 106 | + (previous) => |
| 107 | + result.revisions.find((row) => row.id === previous?.id) ?? |
| 108 | + result.revisions[0], |
| 109 | + ); |
| 110 | + setNotice( |
| 111 | + result.revisions.length |
| 112 | + ? `${result.revisions.length} revisions loaded.` |
| 113 | + : "No more revisions.", |
| 114 | + ); |
| 115 | + } catch (reason) { |
| 116 | + if (current === generation.current) setError(String(reason)); |
| 117 | + } finally { |
| 118 | + if (current === generation.current) setLoading(false); |
| 119 | + } |
| 120 | + }, |
| 121 | + [canvas, channelId], |
| 122 | + ); |
| 123 | + useEffect(() => { |
| 124 | + void load(); |
| 125 | + return () => { |
| 126 | + generation.current++; |
| 127 | + }; |
| 128 | + // This panel is keyed by the owning channel/session and mounted lazily. |
| 129 | + }, [load]); |
| 130 | + const tooLarge = |
| 131 | + selected && |
| 132 | + new TextEncoder().encode(selected.content).length > CANVAS_BYTES; |
| 133 | + const apply = async () => { |
| 134 | + if (!selected) return; |
| 135 | + const current = ++generation.current; |
| 136 | + attempted.current = true; |
| 137 | + try { |
| 138 | + await restore(selected); |
| 139 | + if (current !== generation.current) return; |
| 140 | + setNotice("Version restored as a new revision."); |
| 141 | + } catch (reason) { |
| 142 | + if (current !== generation.current) return; |
| 143 | + setError(reason instanceof Error ? reason.message : String(reason)); |
| 144 | + } |
| 145 | + setConfirm(false); |
| 146 | + setLoading(true); |
| 147 | + // Even an error can follow an accepted publication. Reconcile without |
| 148 | + // clearing its outcome or automatically retrying the write. |
| 149 | + try { |
| 150 | + const result = await canvas.history(channelId); |
| 151 | + if (current !== generation.current) return; |
| 152 | + setPage(result); |
| 153 | + setSelected( |
| 154 | + (previous) => |
| 155 | + result.revisions.find((row) => row.id === previous?.id) ?? |
| 156 | + result.revisions[0], |
| 157 | + ); |
| 158 | + } catch (reason) { |
| 159 | + if (current === generation.current) |
| 160 | + setError( |
| 161 | + (previous) => |
| 162 | + `${previous ? `${previous} ` : ""}History refresh failed: ${String(reason)}`, |
| 163 | + ); |
| 164 | + } finally { |
| 165 | + if (current === generation.current) setLoading(false); |
| 166 | + } |
| 167 | + }; |
| 168 | + return ( |
| 169 | + <div className={styles.stack}> |
| 170 | + <div className={styles.actions}> |
| 171 | + <Button |
| 172 | + ref={refreshButton} |
| 173 | + loading={loading || busy} |
| 174 | + onClick={() => { |
| 175 | + void refreshHead(); |
| 176 | + void load(); |
| 177 | + }} |
| 178 | + > |
| 179 | + Refresh history |
| 180 | + </Button> |
| 181 | + <span role="status">{loading ? "Loading history…" : notice}</span> |
| 182 | + </div> |
| 183 | + {page && !page.revisions.length && <p>No saved revisions.</p>} |
| 184 | + {page && page.revisions.length > 0 && ( |
| 185 | + <> |
| 186 | + <div ref={rows} className={styles.choices}> |
| 187 | + <Field label="Saved revisions"> |
| 188 | + <RadioGroup |
| 189 | + value={selected?.id ?? ""} |
| 190 | + disabled={busy} |
| 191 | + onValueChange={(id) => |
| 192 | + setSelected(page.revisions.find((row) => row.id === id)) |
| 193 | + } |
| 194 | + > |
| 195 | + {page.revisions.map((event) => ( |
| 196 | + <Radio |
| 197 | + key={event.id} |
| 198 | + value={event.id} |
| 199 | + data-revision={event.id} |
| 200 | + label={ |
| 201 | + <> |
| 202 | + <time |
| 203 | + dateTime={new Date( |
| 204 | + event.created_at * 1000, |
| 205 | + ).toISOString()} |
| 206 | + > |
| 207 | + {new Date(event.created_at * 1000).toLocaleString()} |
| 208 | + </time> |
| 209 | + {event.id === head?.id ? " · Current" : ""} |
| 210 | + </> |
| 211 | + } |
| 212 | + description={`${profiles.get(event.pubkey)?.name ?? labels.get(event.pubkey)} · ${event.id.slice(0, 8)}`} |
| 213 | + /> |
| 214 | + ))} |
| 215 | + </RadioGroup> |
| 216 | + </Field> |
| 217 | + </div> |
| 218 | + {page.next && ( |
| 219 | + <Button |
| 220 | + disabled={busy} |
| 221 | + loading={loading} |
| 222 | + onClick={() => void load(page.next)} |
| 223 | + > |
| 224 | + Load older |
| 225 | + </Button> |
| 226 | + )} |
| 227 | + </> |
| 228 | + )} |
| 229 | + {error && ( |
| 230 | + <p role="alert" className={styles.error}> |
| 231 | + {error} |
| 232 | + </p> |
| 233 | + )} |
| 234 | + {selected && ( |
| 235 | + <> |
| 236 | + <Textarea |
| 237 | + aria-label="Revision Markdown" |
| 238 | + variant="code" |
| 239 | + rows={10} |
| 240 | + readOnly |
| 241 | + value={selected.content} |
| 242 | + /> |
| 243 | + {!selected.content && <p>This version is empty.</p>} |
| 244 | + {tooLarge && ( |
| 245 | + <p> |
| 246 | + This version exceeds the 24 KiB Canvas limit and cannot be |
| 247 | + restored here. |
| 248 | + </p> |
| 249 | + )} |
| 250 | + <div className={styles.actions}> |
| 251 | + <Button |
| 252 | + ref={restoreButton} |
| 253 | + variant="prominent" |
| 254 | + disabled={ |
| 255 | + !loaded || |
| 256 | + busy || |
| 257 | + loading || |
| 258 | + !canvas.available || |
| 259 | + selected.id === head?.id || |
| 260 | + !!tooLarge |
| 261 | + } |
| 262 | + onClick={() => { |
| 263 | + setError(""); |
| 264 | + attempted.current = false; |
| 265 | + setConfirm(true); |
| 266 | + }} |
| 267 | + > |
| 268 | + Restore this version |
| 269 | + </Button> |
| 270 | + </div> |
| 271 | + </> |
| 272 | + )} |
| 273 | + <Dialog |
| 274 | + open={confirm} |
| 275 | + onOpenChange={setConfirm} |
| 276 | + title="Restore this version?" |
| 277 | + initialFocus={cancel} |
| 278 | + finalFocus={() => |
| 279 | + attempted.current ? refreshButton.current : restoreButton.current |
| 280 | + } |
| 281 | + preventClose={busy} |
| 282 | + dismissOnOutsideClick |
| 283 | + actions={ |
| 284 | + <> |
| 285 | + <Button |
| 286 | + ref={cancel} |
| 287 | + disabled={busy} |
| 288 | + onClick={() => setConfirm(false)} |
| 289 | + > |
| 290 | + Cancel |
| 291 | + </Button> |
| 292 | + <Button |
| 293 | + variant="prominent" |
| 294 | + loading={busy} |
| 295 | + onClick={() => void apply()} |
| 296 | + > |
| 297 | + Restore version |
| 298 | + </Button> |
| 299 | + </> |
| 300 | + } |
| 301 | + > |
| 302 | + <p> |
| 303 | + This publishes the selected version as a new Canvas revision. Existing |
| 304 | + history is kept. |
| 305 | + </p> |
| 306 | + {dirty && ( |
| 307 | + <p> |
| 308 | + Your unsaved draft will be kept separately. Copy any edits you want |
| 309 | + to keep before reloading the restored Canvas. |
| 310 | + </p> |
| 311 | + )} |
| 312 | + </Dialog> |
| 313 | + </div> |
| 314 | + ); |
| 315 | +} |
0 commit comments