CE-WP-0006/0007: Capture view polish, workplans, and UX refinements

- Blob URL stability, scroll centre, strip-only visual guide
- Focus-gated linking, unlink clears overlay, field badge tooltips
- Capture layout (viewer centre), grey guide lines, Add field button
- Workplans CE-WP-0006 (done) and CE-WP-0007 (T01-T09 done, T10-T12 todo)
- Integration tests and viewer-url helpers
This commit is contained in:
2026-06-08 00:37:34 +02:00
parent d25b01f6d5
commit 2fd085b65e
26 changed files with 1767 additions and 356 deletions

View File

@@ -1,33 +1,30 @@
/**
* FormsApp — the evidence-backed form mode for CE-WP-0003.
* FormsApp (Capture mode) — evidence-backed form layout (CE-WP-0003/0006/0007).
*
* Layout:
* Layout (CE-WP-0007):
*
* ┌────────────┬─────────────────┬─────────────┐
* │ Collection │ FormRenderer │ ViewerShell
* │ │ (left) │ (right) │
* │ Collection │ ViewerShell │ FormPane
* ├────────────┴─────────────────┴─────────────┤
* │ EvidenceStrip (bottom) │
* │ EvidenceStrip (bottom)
* └────────────────────────────────────────────┘
*
* Linking interaction (T05):
* 1. User clicks an evidence card in the strip → it becomes "selected
* for linking" (highlighted; banner appears in the form pane).
* 2. User then clicks a form field. The field's `FormFieldActivated`
* event triggers `bindings.linkEvidenceToTarget(selected, field)`.
* 3. The selected-for-linking state clears; the field's link count
* chip increments.
*
* Active-evidence cycling (T06) and the visual guide overlay (T07) build
* on this composition without changing the link interaction.
* Linking: field must have focus; clicking evidence links directly.
*/
import { useEffect, useMemo, useState } from "react";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import type { EvidenceItem } from "@shared/evidence";
import type { AnnotationId, EvidenceItemId } from "@shared/ids";
import type { EvidenceLink } from "@shared/evidence-link";
import type { EvidenceItemId } from "@shared/ids";
import { Overlay, useActiveState, useBinder } from "@binder/index";
import {
Overlay,
useActiveState,
useBinder,
useRegisterRect,
} from "@binder/index";
import type { FormFieldSchema, FormSchema } from "@binder/FormRenderer";
import {
CollectionList,
ViewerShell,
@@ -39,19 +36,54 @@ import {
import { FormRenderer } from "@binder/FormRenderer";
import { ActiveEvidenceChips, type ActiveEvidenceChipsItem } from "./ActiveEvidenceChips";
import { DEMO_SCHEMA } from "./demo-schema";
import { HighlightRectBridge } from "./HighlightRectBridge";
export type EvidenceStripFilter = "all" | "attached";
const STRIP_FILTER_EVENT = "citation-evidence:strip-filter";
function publishStripFilter(mode: EvidenceStripFilter) {
if (typeof window === "undefined") return;
window.dispatchEvent(new CustomEvent(STRIP_FILTER_EVENT, { detail: mode }));
}
function quotePreview(text: string, max = 80): string {
const t = text.trim();
return t.length > max ? `${t.slice(0, max)}` : t;
}
export function FormsApp() {
const [schema, setSchema] = useState<FormSchema>(() => ({
...DEMO_SCHEMA,
fields: [...DEMO_SCHEMA.fields],
}));
const fieldLabels = useMemo(
() => new Map(schema.fields.map((f) => [f.id, f.label] as const)),
[schema],
);
const addField = useCallback(() => {
setSchema((prev) => {
const n = prev.fields.length + 1;
const field: FormFieldSchema = {
type: "text",
id: `field_${n}`,
label: `New field ${n}`,
};
return { ...prev, fields: [...prev.fields, field] };
});
}, []);
return (
<div style={{ display: "flex", flexDirection: "column", height: "100%" }}>
<div style={{ display: "flex", flex: 1, minHeight: 0 }}>
<CollectionList />
<FormPane />
<ViewerShell />
<FormPane schema={schema} onAddField={addField} />
</div>
<EvidenceStrip />
<EvidenceStrip fieldLabels={fieldLabels} />
<ScrollBridge />
<HighlightRectBridge />
<Overlay />
@@ -59,12 +91,6 @@ export function FormsApp() {
);
}
/**
* Bridge: the binder's active-state machine doesn't know how to scroll
* the viewer; the work-level `useScrollToAnnotation` does. This subscriber
* reads `activeAnnotationId` from the binder and calls `scrollTo` whenever
* it changes. Lives in app/ because that's where both subsystems meet.
*/
function ScrollBridge() {
const { state } = useActiveState();
const { scrollTo } = useScrollToAnnotation();
@@ -76,88 +102,114 @@ function ScrollBridge() {
return null;
}
function FormPane() {
function FormPane({
schema,
onAddField,
}: {
schema: FormSchema;
onAddField: () => void;
}) {
const { document } = useActiveDocument();
const { bindings } = useBinder();
const engine = useEngine();
const linkTick = useEngineEventTick("EvidenceLinkCreated");
const { state: activeState } = useActiveState();
const unlinkTick = useEngineEventTick("EvidenceLinkRemoved");
const { state: activeState, setActiveEvidence } = useActiveState();
const [selectedForLinking, setSelectedForLinking] = useState<EvidenceItemId | null>(
null,
);
useEffect(() => {
return engine.bus.on("FormFieldActivated", () => {
publishStripFilter("attached");
});
}, [engine]);
useEffect(() => {
const target = activeState.activeTarget;
if (!target || activeState.activeEvidenceItemId) return;
const links = bindings.listEvidenceForTarget(target);
if (links.length === 0) return;
const item = engine.evidence.get(links[0]!.evidenceItemId);
if (!item) return;
setActiveEvidence(item.id, item.annotationIds[0] ?? null);
}, [
activeState.activeTarget,
activeState.activeEvidenceItemId,
bindings,
engine,
linkTick,
unlinkTick,
setActiveEvidence,
]);
// Compute per-field link counts. Re-derives on link create.
const linkCounts = useMemo<Record<string, number>>(() => {
const out: Record<string, number> = {};
for (const field of DEMO_SCHEMA.fields) {
for (const field of schema.fields) {
out[field.id] = bindings.listEvidenceForTarget({
targetType: "form-field",
targetId: field.id,
}).length;
}
void linkTick;
void unlinkTick;
return out;
}, [bindings, linkTick]);
}, [schema.fields, bindings, linkTick, unlinkTick]);
// Compute chip items for the currently-active target.
const activeChipItems = useMemo<readonly ActiveEvidenceChipsItem[]>(() => {
if (!activeState.activeTarget) return [];
const links = bindings.listEvidenceForTarget(activeState.activeTarget);
return links
.map((link): ActiveEvidenceChipsItem | null => {
const item = engine.evidence.get(link.evidenceItemId);
if (!item) return null;
const annotationId: AnnotationId | null = item.annotationIds[0] ?? null;
const annotation = annotationId ? engine.annotations.get(annotationId) : null;
return {
evidenceItemId: link.evidenceItemId,
annotationId,
quote: annotation?.quote ?? "(no quote)",
...(item.commentary ? { commentary: item.commentary } : {}),
};
})
.filter((c): c is ActiveEvidenceChipsItem => c !== null);
// linkTick is included so newly created links populate the chips
// without an explicit refresh.
}, [activeState.activeTarget, bindings, engine, linkTick]);
// Listen for FormFieldActivated and, if an evidence is staged, create
// the link. The state machine reduction (focus-target) happens in
// parallel via ActiveStateProvider's own handler.
useEffect(() => {
return engine.bus.on("FormFieldActivated", (event) => {
if (!selectedForLinking) return;
bindings.linkEvidenceToTarget({
evidenceItemId: selectedForLinking,
target: event.target,
const linkHints = useMemo<Record<string, string>>(() => {
const out: Record<string, string> = {};
for (const field of schema.fields) {
const links = bindings.listEvidenceForTarget({
targetType: "form-field",
targetId: field.id,
});
setSelectedForLinking(null);
});
}, [engine, bindings, selectedForLinking]);
if (links.length === 0) continue;
const item = engine.evidence.get(links[0]!.evidenceItemId);
const ann = item?.annotationIds[0]
? engine.annotations.get(item.annotationIds[0])
: null;
const quote = ann?.quote ?? item?.commentary ?? "";
if (quote) out[field.id] = quotePreview(quote);
}
void linkTick;
void unlinkTick;
return out;
}, [schema.fields, bindings, engine, linkTick, unlinkTick]);
return (
<main
style={{
flex: "1 1 0",
flex: "0 0 320px",
minWidth: 320,
borderRight: "1px solid #ddd",
borderLeft: "1px solid #ddd",
overflow: "auto",
display: "flex",
flexDirection: "column",
}}
>
<SelectedBanner
selectedForLinking={selectedForLinking}
onClear={() => setSelectedForLinking(null)}
/>
{document ? (
<>
<FormRenderer schema={DEMO_SCHEMA} linkCounts={linkCounts} />
<ActiveEvidenceChips items={activeChipItems} />
</>
<FormRenderer
schema={schema}
linkCounts={linkCounts}
linkHints={linkHints}
headerAction={
<button
type="button"
data-testid="add-field-button"
onClick={onAddField}
style={{
fontSize: 11,
padding: "4px 10px",
border: "1px solid #888",
borderRadius: 4,
background: "white",
cursor: "pointer",
}}
>
Add field
</button>
}
/>
) : (
<EmptyHint />
)}
<SelectionContext setSelected={setSelectedForLinking} />
</main>
);
}
@@ -165,97 +217,114 @@ function FormPane() {
function EmptyHint() {
return (
<p style={{ padding: 12, color: "#666", fontSize: 13, fontFamily: "system-ui, sans-serif" }}>
Pick a fixture from the collection list to start binding evidence.
Pick a document from the collection to start capturing evidence links.
</p>
);
}
function SelectedBanner({
selectedForLinking,
onClear,
function EvidenceStrip({
fieldLabels,
}: {
selectedForLinking: EvidenceItemId | null;
onClear: () => void;
fieldLabels: ReadonlyMap<string, string>;
}) {
if (!selectedForLinking) return null;
return (
<div
role="status"
aria-live="polite"
style={{
padding: 8,
background: "#fff4d6",
borderBottom: "1px solid #f0c040",
fontFamily: "system-ui, sans-serif",
fontSize: 12,
display: "flex",
alignItems: "center",
gap: 8,
}}
>
<span>
Evidence staged for linking. Click a form field to link it, or{" "}
</span>
<button onClick={onClear} style={{ fontSize: 12, padding: "2px 8px" }}>
cancel
</button>
</div>
);
}
/**
* Bridges the strip's "stage this evidence" callback to the FormPane's
* local state. The strip lives in a sibling DOM subtree; rather than
* lifting `selectedForLinking` all the way up to FormsApp, we publish a
* setter into a module-scoped event target.
*
* Simpler than another context for one local handshake.
*/
const STAGED_EVENT = "citation-evidence:staged-for-linking";
function SelectionContext({
setSelected,
}: {
setSelected: (id: EvidenceItemId | null) => void;
}) {
useEffect(() => {
const handler = (e: Event) => {
const detail = (e as CustomEvent<EvidenceItemId | null>).detail;
setSelected(detail);
};
window.addEventListener(STAGED_EVENT, handler);
return () => window.removeEventListener(STAGED_EVENT, handler);
}, [setSelected]);
return null;
}
export function publishStagedForLinking(id: EvidenceItemId | null) {
if (typeof window === "undefined") return;
window.dispatchEvent(new CustomEvent(STAGED_EVENT, { detail: id }));
}
function EvidenceStrip() {
const engine = useEngine();
const { bindings } = useBinder();
const { document } = useActiveDocument();
const createTick = useEngineEventTick("EvidenceItemCreated");
const updateTick = useEngineEventTick("EvidenceItemUpdated");
const linkTick = useEngineEventTick("EvidenceLinkCreated");
const { state: activeState } = useActiveState();
const [stagedId, setStagedId] = useState<EvidenceItemId | null>(null);
const unlinkTick = useEngineEventTick("EvidenceLinkRemoved");
const { state: activeState, setActiveEvidence, clearActiveEvidence } =
useActiveState();
const items = useMemo<readonly EvidenceItem[]>(() => {
const [userFilter, setUserFilter] = useState<EvidenceStripFilter>("all");
const [sessionFilter, setSessionFilter] = useState<EvidenceStripFilter | null>(
null,
);
const effectiveFilter = sessionFilter ?? userFilter;
useEffect(() => {
const handler = (e: Event) => {
setSessionFilter((e as CustomEvent<EvidenceStripFilter>).detail);
};
window.addEventListener(STRIP_FILTER_EVENT, handler);
return () => window.removeEventListener(STRIP_FILTER_EVENT, handler);
}, []);
useEffect(() => {
if (!activeState.activeTarget) {
setSessionFilter(null);
}
}, [activeState.activeTarget]);
const allItems = useMemo<readonly EvidenceItem[]>(() => {
if (!document) return [];
void createTick;
void updateTick;
void linkTick;
void unlinkTick;
return engine.evidence.listByDocument(document.id);
}, [document, engine, createTick, updateTick, linkTick]);
}, [document, engine, createTick, updateTick, linkTick, unlinkTick]);
const handleStage = (id: EvidenceItemId) => {
const next = stagedId === id ? null : id;
setStagedId(next);
publishStagedForLinking(next);
};
const items = useMemo(() => {
if (effectiveFilter !== "attached" || !activeState.activeTarget) {
return allItems;
}
const links = bindings.listEvidenceForTarget(activeState.activeTarget);
const ids = new Set(links.map((l) => l.evidenceItemId));
const attached = allItems.filter((item) => ids.has(item.id));
return attached.length > 0 ? attached : allItems;
}, [
allItems,
effectiveFilter,
activeState.activeTarget,
bindings,
linkTick,
unlinkTick,
]);
const tryLink = useCallback(
(evidenceItemId: EvidenceItemId, fieldId: string): boolean => {
const existing = bindings
.listEvidenceForTarget({ targetType: "form-field", targetId: fieldId })
.some((l) => l.evidenceItemId === evidenceItemId);
if (existing) return false;
bindings.linkEvidenceToTarget({
evidenceItemId,
target: { targetType: "form-field", targetId: fieldId },
});
return true;
},
[bindings],
);
const handleCardClick = useCallback(
(item: EvidenceItem) => {
const annId = item.annotationIds[0] ?? null;
setActiveEvidence(item.id, annId);
const target = activeState.activeTarget;
if (target?.targetType === "form-field") {
tryLink(item.id, target.targetId);
}
},
[activeState.activeTarget, setActiveEvidence, tryLink],
);
const handleUnlink = useCallback(
(link: EvidenceLink) => {
bindings.unlinkEvidence(link.id);
if (
activeState.activeEvidenceItemId === link.evidenceItemId &&
activeState.activeTarget?.targetType === link.targetType &&
activeState.activeTarget?.targetId === link.targetId
) {
clearActiveEvidence();
}
},
[bindings, activeState, clearActiveEvidence],
);
if (!document) return null;
@@ -267,56 +336,185 @@ function EvidenceStrip() {
background: "#fafafa",
padding: 8,
display: "flex",
gap: 8,
overflowX: "auto",
flexDirection: "column",
gap: 6,
flex: "0 0 auto",
minHeight: 100,
fontFamily: "system-ui, sans-serif",
}}
>
{items.length === 0 && (
<p style={{ fontSize: 12, color: "#888", margin: 0, alignSelf: "center" }}>
No evidence yet. Switch to Review mode to capture a passage.
</p>
)}
{items.map((item) => {
const firstAnn = item.annotationIds[0]
? engine.annotations.get(item.annotationIds[0])
: null;
const quote = firstAnn?.quote ?? "(no quote)";
const isStaged = stagedId === item.id;
const isActive = activeState.activeEvidenceItemId === item.id;
return (
<button
<div style={{ display: "flex", alignItems: "center", gap: 8, fontSize: 11 }}>
<span style={{ color: "#666" }}>Show:</span>
<FilterToggle
label="All"
active={effectiveFilter === "all"}
onClick={() => {
setUserFilter("all");
setSessionFilter(null);
}}
/>
<FilterToggle
label="Linked to field"
active={effectiveFilter === "attached"}
onClick={() => {
setUserFilter("attached");
setSessionFilter(null);
}}
/>
</div>
<div style={{ display: "flex", gap: 8, overflowX: "auto" }}>
{items.length === 0 && (
<p style={{ fontSize: 12, color: "#888", margin: 0, alignSelf: "center" }}>
{effectiveFilter === "attached"
? "No evidence linked to the active field."
: "No evidence yet. Switch to Review mode to capture a passage."}
</p>
)}
{items.map((item) => (
<EvidenceStripCard
key={item.id}
onClick={() => handleStage(item.id)}
data-staged={isStaged ? "true" : "false"}
aria-current={isActive ? "true" : undefined}
style={{
minWidth: 220,
maxWidth: 280,
textAlign: "left",
fontSize: 12,
padding: 8,
border: isActive
? "2px solid #0050b3"
: isStaged
? "2px solid #f0a000"
: "1px solid #ccc",
background: isActive ? "#e8f0ff" : isStaged ? "#fff4d6" : "white",
cursor: "pointer",
}}
>
<div style={{ fontStyle: "italic", marginBottom: 4 }}>
&ldquo;{quote.slice(0, 100)}
{quote.length > 100 ? "…" : ""}&rdquo;
</div>
{item.commentary && (
<div style={{ color: "#333" }}>{item.commentary}</div>
)}
</button>
);
})}
item={item}
isActive={activeState.activeEvidenceItemId === item.id}
links={bindings.listTargetsForEvidence(item.id)}
fieldLabels={fieldLabels}
onClick={() => handleCardClick(item)}
onUnlink={handleUnlink}
/>
))}
</div>
</section>
);
}
function FilterToggle({
label,
active,
onClick,
}: {
label: string;
active: boolean;
onClick: () => void;
}) {
return (
<button
type="button"
onClick={onClick}
aria-pressed={active}
style={{
fontSize: 11,
padding: "2px 8px",
borderRadius: 4,
border: active ? "1px solid #0050b3" : "1px solid #ccc",
background: active ? "#e8f0ff" : "white",
cursor: "pointer",
}}
>
{label}
</button>
);
}
function EvidenceStripCard({
item,
isActive,
links,
fieldLabels,
onClick,
onUnlink,
}: {
item: EvidenceItem;
isActive: boolean;
links: readonly EvidenceLink[];
fieldLabels: ReadonlyMap<string, string>;
onClick: () => void;
onUnlink: (link: EvidenceLink) => void;
}) {
const engine = useEngine();
const ref = useRef<HTMLDivElement>(null);
useRegisterRect("evidence-card", item.id, ref);
const firstAnn = item.annotationIds[0]
? engine.annotations.get(item.annotationIds[0])
: null;
const quote = firstAnn?.quote ?? "(no quote)";
const formLinks = links.filter((l) => l.targetType === "form-field");
return (
<div
ref={ref}
style={{
position: "relative",
minWidth: 220,
maxWidth: 280,
flexShrink: 0,
}}
>
{formLinks.length > 0 && (
<div
style={{
position: "absolute",
top: 4,
right: 4,
display: "flex",
gap: 2,
zIndex: 1,
}}
>
{formLinks.map((link) => {
const label = fieldLabels.get(link.targetId) ?? link.targetId;
return (
<button
key={link.id}
type="button"
title={`Linked to: ${label}. Click to remove link.`}
aria-label={`Remove link to ${label}`}
onClick={(e) => {
e.stopPropagation();
onUnlink(link);
}}
style={{
fontSize: 10,
lineHeight: 1,
padding: "2px 4px",
border: "1px solid #88a",
borderRadius: 3,
background: "#eef",
cursor: "pointer",
}}
>
</button>
);
})}
</div>
)}
<button
type="button"
onClick={onClick}
aria-current={isActive ? "true" : undefined}
style={{
width: "100%",
textAlign: "left",
fontSize: 12,
padding: 8,
border: isActive ? "2px solid #0050b3" : "1px solid #ccc",
background: isActive ? "#e8f0ff" : "white",
cursor: "pointer",
}}
>
<div
style={{
fontStyle: "italic",
marginBottom: 4,
paddingRight: formLinks.length ? 24 : 0,
}}
>
&ldquo;{quote.slice(0, 100)}
{quote.length > 100 ? "…" : ""}&rdquo;
</div>
{item.commentary && <div style={{ color: "#333" }}>{item.commentary}</div>}
</button>
</div>
);
}