CE-WP-0007 T10-T12: field add/edit dialog, pencil edit, integration tests

- FieldDefinitionForm shared component (label + text/textarea/date)
- Add field opens inline form; per-field pencil edit with stable ids
- forms-field-edit.dom.test.tsx covers add, edit, and link-to-new-field
- Workplan T10-T12 and README marked done
This commit is contained in:
2026-06-08 00:46:06 +02:00
parent 2fd085b65e
commit 48a53df9fc
6 changed files with 540 additions and 54 deletions

View File

@@ -34,7 +34,7 @@ import {
useScrollToAnnotation,
} from "@work/index";
import { FormRenderer } from "@binder/FormRenderer";
import { FormRenderer, type FieldDefinitionPatch } from "@binder/FormRenderer";
import { DEMO_SCHEMA } from "./demo-schema";
import { HighlightRectBridge } from "./HighlightRectBridge";
@@ -64,24 +64,76 @@ export function FormsApp() {
[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] };
});
const [showAddFieldForm, setShowAddFieldForm] = useState(false);
const [editingFieldId, setEditingFieldId] = useState<string | null>(null);
const nextFieldId = useCallback((fields: readonly FormFieldSchema[]): string => {
let max = 0;
for (const f of fields) {
const m = /^field_(\d+)$/.exec(f.id);
if (m) max = Math.max(max, Number(m[1]));
}
return `field_${max + 1}`;
}, []);
const handleConfirmAddField = useCallback(
(patch: FieldDefinitionPatch) => {
setSchema((prev) => {
const id = nextFieldId(prev.fields);
const n = prev.fields.length + 1;
const field: FormFieldSchema = {
id,
type: patch.type,
label: patch.label.length > 0 ? patch.label : `New field ${n}`,
};
return { ...prev, fields: [...prev.fields, field] };
});
setShowAddFieldForm(false);
},
[nextFieldId],
);
const handleSaveFieldEdit = useCallback(
(fieldId: string, patch: FieldDefinitionPatch) => {
setSchema((prev) => ({
...prev,
fields: prev.fields.map((f) =>
f.id === fieldId
? {
...f,
type: patch.type,
label: patch.label.length > 0 ? patch.label : f.label,
}
: f,
),
}));
setEditingFieldId(null);
},
[],
);
return (
<div style={{ display: "flex", flexDirection: "column", height: "100%" }}>
<div style={{ display: "flex", flex: 1, minHeight: 0 }}>
<CollectionList />
<ViewerShell />
<FormPane schema={schema} onAddField={addField} />
<FormPane
schema={schema}
showAddFieldForm={showAddFieldForm}
editingFieldId={editingFieldId}
onRequestAddField={() => {
setEditingFieldId(null);
setShowAddFieldForm(true);
}}
onConfirmAddField={handleConfirmAddField}
onCancelAddField={() => setShowAddFieldForm(false)}
onBeginEditField={(fieldId) => {
setShowAddFieldForm(false);
setEditingFieldId(fieldId);
}}
onSaveFieldEdit={handleSaveFieldEdit}
onCancelFieldEdit={() => setEditingFieldId(null)}
/>
</div>
<EvidenceStrip fieldLabels={fieldLabels} />
<ScrollBridge />
@@ -104,10 +156,24 @@ function ScrollBridge() {
function FormPane({
schema,
onAddField,
showAddFieldForm,
editingFieldId,
onRequestAddField,
onConfirmAddField,
onCancelAddField,
onBeginEditField,
onSaveFieldEdit,
onCancelFieldEdit,
}: {
schema: FormSchema;
onAddField: () => void;
showAddFieldForm: boolean;
editingFieldId: string | null;
onRequestAddField: () => void;
onConfirmAddField: (patch: FieldDefinitionPatch) => void;
onCancelAddField: () => void;
onBeginEditField: (fieldId: string) => void;
onSaveFieldEdit: (fieldId: string, patch: FieldDefinitionPatch) => void;
onCancelFieldEdit: () => void;
}) {
const { document } = useActiveDocument();
const { bindings } = useBinder();
@@ -189,23 +255,14 @@ function FormPane({
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>
}
showAddFieldForm={showAddFieldForm}
onRequestAddField={onRequestAddField}
onConfirmAddField={onConfirmAddField}
onCancelAddField={onCancelAddField}
editingFieldId={editingFieldId}
onBeginEditField={onBeginEditField}
onSaveFieldEdit={onSaveFieldEdit}
onCancelFieldEdit={onCancelFieldEdit}
/>
) : (
<EmptyHint />

View File

@@ -0,0 +1,117 @@
/**
* Shared label + type editor for add-field and edit-field flows (CE-WP-0007-T10/T11).
* Styled to match EvidenceFormBody / InlineCaptureForm.
*/
import type { CSSProperties, ReactNode } from "react";
import type { FormFieldSchema } from "./FormRenderer";
export type FieldType = FormFieldSchema["type"];
const FIELD_TYPES: readonly { value: FieldType; label: string }[] = [
{ value: "text", label: "Text" },
{ value: "textarea", label: "Text area" },
{ value: "date", label: "Date" },
];
export interface FieldDefinitionFormProps {
readonly label: string;
readonly type: FieldType;
onChangeLabel(next: string): void;
onChangeType(next: FieldType): void;
onSave(): void;
onCancel(): void;
readonly saveLabel?: string;
readonly cancelLabel?: string;
readonly badge?: ReactNode;
readonly testidPrefix: string;
}
export function FieldDefinitionForm(p: FieldDefinitionFormProps) {
const saveLabel = p.saveLabel ?? "Save";
const cancelLabel = p.cancelLabel ?? "Cancel";
return (
<div
data-testid={`${p.testidPrefix}-form`}
style={{
border: "1px dashed #b78b1c",
background: "#fff8d6",
marginBottom: 8,
borderRadius: 2,
padding: 8,
fontSize: 12,
}}
>
{p.badge && (
<div style={{ marginBottom: 6, fontWeight: 600 }}>{p.badge}</div>
)}
<label style={labelStyle} htmlFor={`${p.testidPrefix}-label`}>
Field label
</label>
<input
id={`${p.testidPrefix}-label`}
type="text"
value={p.label}
onChange={(e) => p.onChangeLabel(e.target.value)}
data-testid={`${p.testidPrefix}-label-input`}
style={inputStyle}
/>
<label style={labelStyle} htmlFor={`${p.testidPrefix}-type`}>
Field type
</label>
<select
id={`${p.testidPrefix}-type`}
value={p.type}
onChange={(e) => p.onChangeType(e.target.value as FieldType)}
data-testid={`${p.testidPrefix}-type-select`}
style={inputStyle}
>
{FIELD_TYPES.map((opt) => (
<option key={opt.value} value={opt.value}>
{opt.label}
</option>
))}
</select>
<div style={{ display: "flex", gap: 6, marginTop: 4 }}>
<button
type="button"
onClick={p.onSave}
data-testid={`${p.testidPrefix}-save`}
style={buttonStyle}
>
{saveLabel}
</button>
<button
type="button"
onClick={p.onCancel}
data-testid={`${p.testidPrefix}-cancel`}
style={buttonStyle}
>
{cancelLabel}
</button>
</div>
</div>
);
}
const labelStyle: CSSProperties = {
display: "block",
color: "#666",
fontSize: 11,
marginBottom: 2,
};
const inputStyle: CSSProperties = {
width: "100%",
boxSizing: "border-box",
fontSize: 12,
padding: 4,
marginBottom: 6,
};
const buttonStyle: CSSProperties = {
fontSize: 12,
padding: "4px 10px",
};

View File

@@ -6,18 +6,14 @@
* draw curves from the active field to its linked evidence card and on
* to the source highlight.
*
* Lives in `src/binder/` (not `src/work/`) because it depends on the
* rect-registry hooks in `binder/visual-guide`. See `wiki/DependencyMap.md`
* §2/§5 for the `work ⊄ binder` rule that motivates this placement.
*
* No styling beyond minimum legibility (workplan T06 note). Tailwind /
* design system can land later without changing the registry contract.
* CE-WP-0007-T10/T11: add-field and edit-field flows use FieldDefinitionForm.
*/
import { useRef, type ChangeEvent, type ReactNode } from "react";
import { useRef, useState, type ChangeEvent, type CSSProperties, type ReactNode } from "react";
import type { EvidenceTarget } from "@shared/evidence-link";
import { FieldDefinitionForm, type FieldType } from "./FieldDefinitionForm";
import { useActiveState, type ActiveState } from "./state/active";
import { useRegisterRect } from "./visual-guide/react-hooks";
@@ -40,40 +36,91 @@ export interface FormSchema {
readonly fields: readonly FormFieldSchema[];
}
export interface FieldDefinitionPatch {
readonly label: string;
readonly type: FieldType;
}
export interface FormRendererProps {
readonly schema: FormSchema;
readonly values?: Readonly<Record<string, string>>;
readonly onValueChange?: (fieldId: string, value: string) => void;
/**
* Per-field annotation count. Rendered as a small chip beside the
* label so the user can tell which fields already have evidence.
*/
readonly linkCounts?: Readonly<Record<string, number>>;
/** Hover preview for the evidence-count chip (first linked quote). */
readonly linkHints?: Readonly<Record<string, string>>;
readonly headerAction?: ReactNode;
readonly showAddFieldForm?: boolean;
readonly onRequestAddField?: () => void;
readonly onConfirmAddField?: (patch: FieldDefinitionPatch) => void;
readonly onCancelAddField?: () => void;
readonly editingFieldId?: string | null;
readonly onBeginEditField?: (fieldId: string) => void;
readonly onSaveFieldEdit?: (fieldId: string, patch: FieldDefinitionPatch) => void;
readonly onCancelFieldEdit?: () => void;
}
const iconButtonStyle: CSSProperties = {
fontSize: 11,
padding: "2px 6px",
background: "white",
border: "1px solid #888",
borderRadius: 3,
cursor: "pointer",
lineHeight: 1,
};
function FieldRow({
field,
value,
linkCount,
linkHint,
isActive,
isEditing,
editLabel,
editType,
onChange,
onFocus,
onBeginEdit,
onChangeEditLabel,
onChangeEditType,
onSaveEdit,
onCancelEdit,
}: {
field: FormFieldSchema;
value: string;
linkCount: number;
linkHint?: string;
isActive: boolean;
isEditing: boolean;
editLabel: string;
editType: FieldType;
onChange: (next: string) => void;
onFocus: () => void;
onBeginEdit: () => void;
onChangeEditLabel: (next: string) => void;
onChangeEditType: (next: FieldType) => void;
onSaveEdit: () => void;
onCancelEdit: () => void;
}) {
const ref = useRef<HTMLDivElement>(null);
useRegisterRect("field", field.id, ref);
if (isEditing) {
return (
<div ref={ref} data-field-id={field.id} style={{ marginBottom: 12 }}>
<FieldDefinitionForm
label={editLabel}
type={editType}
onChangeLabel={onChangeEditLabel}
onChangeType={onChangeEditType}
onSave={onSaveEdit}
onCancel={onCancelEdit}
saveLabel="Save field"
badge="Editing field"
testidPrefix={`field-edit-${field.id}`}
/>
</div>
);
}
const sharedProps = {
id: `field-${field.id}`,
value,
@@ -90,6 +137,7 @@ function FieldRow({
data-link-count={String(linkCount)}
aria-current={isActive ? "true" : undefined}
style={{
position: "relative",
marginBottom: 12,
fontFamily: "system-ui, sans-serif",
padding: 4,
@@ -97,9 +145,34 @@ function FieldRow({
background: isActive ? "#e8f0ff" : "transparent",
}}
>
<button
type="button"
aria-label={`Edit field ${field.label}`}
data-testid={`field-edit-toggle-${field.id}`}
title="Edit field label and type"
onClick={(e) => {
e.stopPropagation();
onBeginEdit();
}}
style={{
...iconButtonStyle,
position: "absolute",
top: 4,
right: 4,
zIndex: 1,
}}
>
</button>
<label
htmlFor={sharedProps.id}
style={{ display: "block", fontSize: 12, fontWeight: 600, marginBottom: 4 }}
style={{
display: "block",
fontSize: 12,
fontWeight: 600,
marginBottom: 4,
paddingRight: 28,
}}
>
{field.label}
{linkCount > 0 ? (
@@ -135,15 +208,32 @@ export function FormRenderer({
onValueChange,
linkCounts,
linkHints,
headerAction,
showAddFieldForm,
onRequestAddField,
onConfirmAddField,
onCancelAddField,
editingFieldId,
onBeginEditField,
onSaveFieldEdit,
onCancelFieldEdit,
}: FormRendererProps) {
const { state, focusTarget } = useActiveState();
const [addLabel, setAddLabel] = useState("New field");
const [addType, setAddType] = useState<FieldType>("text");
const [editLabel, setEditLabel] = useState("");
const [editType, setEditType] = useState<FieldType>("text");
const handleFocus = (fieldId: string) => {
const target: EvidenceTarget = { targetType: "form-field", targetId: fieldId };
focusTarget(target);
};
const beginEdit = (field: FormFieldSchema) => {
setEditLabel(field.label);
setEditType(field.type);
onBeginEditField?.(field.id);
};
return (
<form
data-form-id={schema.id}
@@ -162,8 +252,46 @@ export function FormRenderer({
<h2 style={{ fontSize: 14, margin: 0, fontFamily: "system-ui, sans-serif" }}>
{schema.title}
</h2>
{headerAction}
<button
type="button"
data-testid="add-field-button"
onClick={() => {
setAddLabel(`New field ${schema.fields.length + 1}`);
setAddType("text");
onRequestAddField?.();
}}
style={{
fontSize: 11,
padding: "4px 10px",
border: "1px solid #888",
borderRadius: 4,
background: "white",
cursor: "pointer",
}}
>
Add field
</button>
</div>
{showAddFieldForm && (
<FieldDefinitionForm
label={addLabel}
type={addType}
onChangeLabel={setAddLabel}
onChangeType={setAddType}
onSave={() =>
onConfirmAddField?.({
label: addLabel.trim(),
type: addType,
})
}
onCancel={() => onCancelAddField?.()}
saveLabel="Add field"
badge="New form field"
testidPrefix="field-add"
/>
)}
{schema.fields.map((field) => (
<FieldRow
key={field.id}
@@ -172,10 +300,23 @@ export function FormRenderer({
linkCount={linkCounts?.[field.id] ?? 0}
linkHint={linkHints?.[field.id]}
isActive={isFieldActive(state, field.id)}
isEditing={editingFieldId === field.id}
editLabel={editLabel}
editType={editType}
onChange={(next) => onValueChange?.(field.id, next)}
onFocus={() => handleFocus(field.id)}
onBeginEdit={() => beginEdit(field)}
onChangeEditLabel={setEditLabel}
onChangeEditType={setEditType}
onSaveEdit={() =>
onSaveFieldEdit?.(field.id, {
label: editLabel.trim(),
type: editType,
})
}
onCancelEdit={() => onCancelFieldEdit?.()}
/>
))}
</form>
);
}
}

View File

@@ -0,0 +1,171 @@
/**
* CE-WP-0007-T10/T11/T12 — add-field type+label dialog and field edit icon.
*/
// @vitest-environment happy-dom
import { act, cleanup, render, screen, waitFor } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import type { Selector } from "@shared/selector";
import type { PdfSelectionCapture } from "@anchor/index";
import manifest from "../../fixtures/pdfs/manifest.json" with { type: "json" };
interface ViewerProps {
pdfUrl: string;
storedAnnotations: readonly { id: string; text: string; selectors: readonly Selector[] }[];
scrollToAnnotationId?: string;
onSelectionCaptured(capture: PdfSelectionCapture, selectors: Selector[]): void;
}
const viewerSnapshot: { onSelectionCaptured: ViewerProps["onSelectionCaptured"] | null } = {
onSelectionCaptured: null,
};
vi.mock("@anchor/index", async (importOriginal) => {
const original = await importOriginal<typeof import("@anchor/index")>();
const MockPdfSpikeViewer = (props: ViewerProps) => {
viewerSnapshot.onSelectionCaptured = props.onSelectionCaptured;
return <div data-testid="mock-pdf-viewer" />;
};
return { ...original, PdfSpikeViewer: MockPdfSpikeViewer };
});
const FIXTURE = manifest.fixtures.find((f) => f.id === "fristsetzung-bezifferung")!;
const SYNTHETIC_CANONICAL = ["Pre.", FIXTURE.known_good_quote, "Post."].join(" ");
import { seedSessionWithDoc } from "./helpers/seed-session";
function syntheticCaptureFor(text: string, page: number): PdfSelectionCapture {
return {
kind: "pdf",
text,
page,
rects: [{ x: 0.1, y: 0.2, width: 0.4, height: 0.04 }],
boundingRect: { x: 0.1, y: 0.2, width: 0.4, height: 0.04 },
};
}
async function loadApp() {
const { App } = await import("@app/App");
return render(<App />);
}
async function saveEvidenceInReview(
user: ReturnType<typeof userEvent.setup>,
commentary: string,
) {
await waitFor(() => expect(viewerSnapshot.onSelectionCaptured).not.toBeNull());
await act(async () => {
viewerSnapshot.onSelectionCaptured!(
syntheticCaptureFor(FIXTURE.known_good_quote, FIXTURE.known_good_quote_page),
[{ type: "TextQuoteSelector", exact: FIXTURE.known_good_quote }],
);
});
await user.type(screen.getByTestId("inline-capture-commentary"), commentary);
await user.click(screen.getByTestId("inline-capture-save"));
await screen.findByText(new RegExp(commentary));
}
describe("Capture — field add/edit UX (CE-WP-0007-T10/T11)", () => {
beforeEach(() => {
viewerSnapshot.onSelectionCaptured = null;
globalThis.localStorage?.clear();
if (typeof window !== "undefined") {
history.replaceState(null, "", window.location.pathname);
}
seedSessionWithDoc({
sessionName: "T10-field-edit",
documentTitle: FIXTURE.filename,
canonicalText: SYNTHETIC_CANONICAL,
mode: "forms",
});
});
afterEach(() => {
vi.restoreAllMocks();
cleanup();
});
it(
"adds a date field with a custom label via the add-field form",
{ timeout: 15000 },
async () => {
const user = userEvent.setup();
await loadApp();
await user.click(screen.getByTestId("add-field-button"));
await screen.findByTestId("field-add-form");
await user.clear(screen.getByTestId("field-add-label-input"));
await user.type(screen.getByTestId("field-add-label-input"), "Hearing date");
await user.selectOptions(screen.getByTestId("field-add-type-select"), "date");
await user.click(screen.getByTestId("field-add-save"));
const hearingInput = await screen.findByLabelText("Hearing date");
expect(hearingInput.getAttribute("type")).toBe("date");
},
);
it(
"edits an existing field label and type via the pencil icon",
{ timeout: 15000 },
async () => {
const user = userEvent.setup();
await loadApp();
await user.click(screen.getByTestId("field-edit-toggle-summary"));
await screen.findByTestId("field-edit-summary-form");
await user.clear(screen.getByTestId("field-edit-summary-label-input"));
await user.type(
screen.getByTestId("field-edit-summary-label-input"),
"Matter summary",
);
await user.selectOptions(
screen.getByTestId("field-edit-summary-type-select"),
"text",
);
await user.click(screen.getByTestId("field-edit-summary-save"));
await screen.findByLabelText("Matter summary");
expect(screen.queryByLabelText("Summary of the matter")).toBeNull();
},
);
it(
"links evidence to a newly added field",
{ timeout: 20000 },
async () => {
const user = userEvent.setup();
seedSessionWithDoc({
sessionName: "T12-field-link",
documentTitle: FIXTURE.filename,
canonicalText: SYNTHETIC_CANONICAL,
});
await loadApp();
await saveEvidenceInReview(user, "Link to custom field");
await user.click(screen.getByRole("button", { name: "Capture" }));
await user.click(screen.getByTestId("add-field-button"));
const addLabel = screen.getByTestId("field-add-label-input");
await user.clear(addLabel);
await user.type(addLabel, "Custom slot");
await user.click(screen.getByTestId("field-add-save"));
const customField = await screen.findByLabelText("Custom slot");
await user.click(customField);
const stripCard = screen.getByRole("button", { name: /Link to custom field/ });
await user.click(stripCard);
await waitFor(() => {
const chips = screen.getAllByText(/1 evidence/);
expect(chips.length).toBeGreaterThanOrEqual(1);
});
},
);
});

View File

@@ -7,7 +7,7 @@ repo: citation-evidence
repo_id: a677c189-b4e2-4f2a-9e48-faa482c277e6
topic_slug: citation_evidence_mvp
topic_id: 96fa8e80-9f74-40f2-84cd-644e9747b9ec
status: active
status: done
owner: Bernd
created: 2026-06-07
updated: 2026-06-08
@@ -246,7 +246,7 @@ state_hub_task_id: "823d4986-892d-467e-819e-54f0f2a363e8"
```task
id: CE-WP-0007-T10
priority: medium
status: todo
status: done
depends_on: [T08]
state_hub_task_id: "dab723e6-66a6-4587-8ab7-e0c5e4cb5d0a"
```
@@ -274,7 +274,7 @@ correct input type and label.
```task
id: CE-WP-0007-T11
priority: medium
status: todo
status: done
depends_on: [T10]
state_hub_task_id: "c55541c7-57e2-4f5d-a4ef-ed54c470cbd9"
```
@@ -300,7 +300,7 @@ links and visual guide still resolve by field id.
```task
id: CE-WP-0007-T12
priority: high
status: todo
status: done
depends_on: [T10, T11]
state_hub_task_id: "585b054e-eb5e-410e-90ee-84e698b13f7f"
```

View File

@@ -2,7 +2,7 @@
MVP workplans for the citation-evidence umbrella repo. CE-WP-0001..0006
delivered the PRD §20 reference scenario and Forms/Review UX polish.
CE-WP-0007 Capture-view polish is active (field add/edit UX in progress).
CE-WP-0007 delivered Capture-view polish including field add/edit UX.
| Workplan | Title | Status |
|----------|----------------------------------------|--------|
@@ -12,7 +12,7 @@ CE-WP-0007 Capture-view polish is active (field add/edit UX in progress).
| `CE-WP-0004` | Citation card export — Markdown + HTML renderers, sidebar export | done |
| `CE-WP-0005` | Demo sessions — uploads, named sessions, ZIP export/import | done |
| `CE-WP-0006` | Forms & review UX refinements — blob fix, scroll centre, linking | done |
| `CE-WP-0007` | Capture view polish — scroll, linking, layout, rename, field UX | active |
| `CE-WP-0007` | Capture view polish — scroll, linking, layout, rename, field UX | done |
## Order