Skip to content

Commit 512a9c2

Browse files
wesbillmanCarl
andauthored
Add Canvas history and confirmed restore UI (#552)
Signed-off-by: Carl <32a2e2c9d428ee08902cab75d956da2c1d235a22d4766b0dd4138bf6e2e5db1d@buzz.block.builderlab.xyz> Co-authored-by: Carl <32a2e2c9d428ee08902cab75d956da2c1d235a22d4766b0dd4138bf6e2e5db1d@buzz.block.builderlab.xyz>
1 parent 85c7f39 commit 512a9c2

9 files changed

Lines changed: 1149 additions & 43 deletions

File tree

‎docs/plugin-architecture.md‎

Lines changed: 24 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -284,13 +284,35 @@ post-write different-head check remains conservative and also retains the draft.
284284
**Compatibility gate:** deploy with a relay supporting Canvas revision preconditions
285285
([block/buzz#6780](https://github.com/block/buzz/pull/6780)) for atomic protection.
286286
An older relay may ignore the tag; strong reads and client head comparison alone
287-
cannot prevent concurrent overwrite. This client change does not upgrade the relay
288-
or add Canvas history/restore. Detected conflicts require reviewing the saved Canvas. Refresh confirms before discarding
287+
cannot prevent concurrent overwrite. The client does not upgrade the relay.
288+
Detected conflicts require reviewing the saved Canvas. Refresh confirms before discarding
289289
edits. Local recovery drafts are partitioned by community/viewer/channel; if browser
290290
storage is unavailable they survive only while the editor stays open. Save never
291291
promotes local recovery storage to shared state. Already accepted outbox operations
292292
remain session-owned if the drawer closes or plugin is disabled.
293293

294+
**Canvas history:** Channel actions → View canvas → History lazily reads retained
295+
kind-40100 revisions in pages of 25, ordered by `created_at DESC, id ASC` with
296+
`until`/`before_id` keyset cursors. The first page is writer-backed so a just-restored
297+
revision is visible; older pages remain replica-eligible. The current marker uses
298+
the editor's strong-read head, not list position. Refresh history rechecks the
299+
head without replacing the editor draft. Author labels use the shared profile
300+
directory, with public-key fallbacks; previews are read-only Markdown source.
301+
302+
Restore requires explicit confirmation and publishes the selected content as a
303+
new signed revision through the existing Canvas save/outbox owner. Its precondition
304+
is the displayed head, never the historical revision or a silently substituted
305+
newer head. Clean editors adopt the confirmed result. Edited or stale recovered
306+
drafts keep their content and original base until explicit reload; browsing and
307+
cancelling never replace drafts. Restore inherits Save's delivery confirmation,
308+
which may automatically replay the exact signed event with its original
309+
`expected-revision`. It never creates a fresh event or substitutes a newer
310+
precondition to retry. If confirmation ultimately fails or remains uncertain,
311+
the dialog retains drafts and shows the error without starting another restore.
312+
Empty revisions can be restored; revisions exceeding the existing 24 KiB save
313+
limit remain previewable but cannot be restored here. No diff viewer or new
314+
delivery owner is introduced.
315+
294316
### Top-bar launchers and the companion slot
295317

296318
A panel may supply `launcher: { icon, target }`. The host renders the decorative
Lines changed: 315 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,315 @@
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

Comments
 (0)