Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

refactor([extract-usependinglistrows-hook]): unify WardrobeSection + CharacterDetailEditor pending-row buffers

[._.]/ Adam Eivye608b52c994c
diff --git a/client/src/components/pipeline/CanonCard.jsx b/client/src/components/pipeline/CanonCard.jsx
index db147a4f6f..3b47a9e285 100644
--- a/client/src/components/pipeline/CanonCard.jsx
+++ b/client/src/components/pipeline/CanonCard.jsx
@@ -15,6 +15,7 @@ import { Loader2, ImagePlus, WandSparkles, Lock, Unlock, Shirt, Plus, Trash2, Ch
import useMediaJobProgress from '../../hooks/useMediaJobProgress';
import useRowDraft from '../../hooks/useRowDraft';
import useFieldDraft from '../../hooks/useFieldDraft';
+import usePendingListRows from '../../hooks/usePendingListRows';
import MediaJobThumb from './MediaJobThumb';
import EntryCard from '../universe/EntryCard';
import EntryThumbSlot from '../universe/EntryThumbSlot';
@@ -183,59 +184,28 @@ function WardrobeRow({ wardrobe, editable, onCommit, onRemove }) {
// universe-wide round-trip per character. The ride-along merge means a
// fast desc-blur after a name keystroke ships both columns together, so the
// row promotes correctly even if the user never explicitly blurs name first.
+//
+// Pending rows use `wd-<uuid>` ids (server `ensureId` preserves them, so
+// they round-trip verbatim across the pending → persisted promotion) —
+// `stripIdOnPromote` stays false to keep WardrobeRow mounted across the
+// swap and preserve sibling draft buffers.
function WardrobeSection({ wardrobes, editable, onChange }) {
const [open, setOpen] = useState(false);
- // Pending new rows live entirely client-side until the user types a name
- // — committing immediately would PATCH a nameless entry, the server-side
- // sanitizer would drop it, and the row would vanish mid-type.
- const [pendingNew, setPendingNew] = useState([]);
-
- const merged = pendingNew.length
- ? [...wardrobes, ...pendingNew]
- : wardrobes;
+ const { merged, addRow, updateRow, removeRow } = usePendingListRows({
+ persisted: wardrobes,
+ requiredColumn: 'name',
+ idPrefix: 'wd-',
+ blankRow: () => ({ name: '', description: '' }),
+ onChange,
+ });
if (!editable && merged.length === 0) return null;
const summary = merged.map((w) => w.name).filter(Boolean).join(', ');
- const isPending = (idx) => idx >= wardrobes.length;
-
- const commit = (idx, nextRow) => {
- if (isPending(idx)) {
- const pendingIdx = idx - wardrobes.length;
- // Stable React key across promotion — `w.id` was minted server-shaped
- // in `addOne` so it round-trips verbatim, which keeps `WardrobeRow`
- // mounted across the pending → persisted swap and preserves any
- // in-flight sibling draft in its `useRowDraft` buffer.
- if (nextRow.name?.trim()) {
- setPendingNew(pendingNew.filter((_, i) => i !== pendingIdx));
- onChange([...wardrobes, nextRow]);
- } else {
- setPendingNew(pendingNew.map((p, i) => i === pendingIdx ? nextRow : p));
- }
- return;
- }
- onChange(wardrobes.map((w, i) => (i === idx ? nextRow : w)));
- };
-
- const removeAt = (idx) => {
- if (isPending(idx)) {
- const pendingIdx = idx - wardrobes.length;
- setPendingNew(pendingNew.filter((_, i) => i !== pendingIdx));
- return;
- }
- onChange(wardrobes.filter((_, i) => i !== idx));
- };
const addOne = () => {
setOpen(true);
- // Mint a server-shaped `wd-<uuid>` client-side so the React key stays
- // stable across the pending → persisted promotion. Server `ensureId`
- // preserves any non-empty string, so this id round-trips unchanged.
- // `globalThis.crypto` — bare `crypto?.…` ReferenceErrors when the
- // identifier is undeclared (e.g. some non-secure contexts); going
- // through `globalThis` short-circuits cleanly to the Date+Math fallback.
- const id = `wd-${(globalThis.crypto?.randomUUID?.() ?? Date.now().toString(36) + Math.random().toString(36).slice(2))}`;
- setPendingNew((prev) => [...prev, { id, name: '', description: '' }]);
+ addRow();
};
return (
@@ -256,8 +226,8 @@ function WardrobeSection({ wardrobes, editable, onChange }) {
key={w.id || i}
wardrobe={w}
editable={editable}
- onCommit={(nextRow) => commit(i, nextRow)}
- onRemove={() => removeAt(i)}
+ onCommit={(nextRow) => updateRow(i, nextRow)}
+ onRemove={() => removeRow(i)}
/>
))}
{editable ? (
diff --git a/client/src/components/universe/CharacterDetailEditor.jsx b/client/src/components/universe/CharacterDetailEditor.jsx
index 4560bc67fb..6556e08d6c 100644
--- a/client/src/components/universe/CharacterDetailEditor.jsx
+++ b/client/src/components/universe/CharacterDetailEditor.jsx
@@ -18,6 +18,7 @@ import {
import { BIBLE_LIMITS as L } from '../../lib/bibleLimits';
import useFieldDraft from '../../hooks/useFieldDraft';
import useRowDraft from '../../hooks/useRowDraft';
+import usePendingListRows from '../../hooks/usePendingListRows';
import VoicePicker from '../voice/VoicePicker';
const SECTIONS = Object.freeze([
@@ -193,90 +194,77 @@ function CollapsibleSection({ icon: Icon, label, summary, defaultOpen = false, c
);
}
-export default function CharacterDetailEditor({ entry, onPatch, onExpand, expanding = false, disabled = false }) {
- // Per-section pending rows — kept local until the required column (first
- // column on each LIST_SECTION, always `name` or `label`) is non-empty.
- // Persisting a blank row immediately would round-trip a row the server
- // sanitizer drops, and the user's first keystroke would land in a row that
- // disappears on the next render. Mirrors WardrobeSection's pendingNew
- // pattern in CanonCard.jsx.
- const [pendingByList, setPendingByList] = useState({});
+// One LIST_SECTION's row buffer + UI. Extracted so each section gets its
+// own `usePendingListRows` instance (hooks can't be called inside the parent's
+// `LIST_SECTIONS.map`). Pending ids carry the `pending-<key>-<uuid>` prefix
+// and are stripped on promotion so the server's `ensureId` mints a fresh
+// `<kind>-<uuid>` under its own convention — see usePendingListRows.js for
+// the trade-off this strip implies for sibling drafts.
+function ListSectionEditor({ section, entry, onPatchList, disabled }) {
+ const persisted = Array.isArray(entry[section.field]) ? entry[section.field] : [];
+ const { merged, addRow, updateRow, removeRow } = usePendingListRows({
+ persisted,
+ requiredColumn: section.columns[0].name,
+ idPrefix: `pending-${section.key}-`,
+ stripIdOnPromote: true,
+ blankRow: () => Object.fromEntries(section.columns.map((c) => [c.name, ''])),
+ onChange: (next) => onPatchList(section.field, next),
+ });
+ const summary = merged.length === 0
+ ? 'empty'
+ : `${merged.length} ${merged.length === 1 ? section.singular : section.singular + 's'}`;
+ return (
+ <CollapsibleSection
+ icon={section.icon}
+ label={section.label}
+ summary={summary}
+ >
+ {merged.length === 0 ? (
+ <p className="text-[11px] text-gray-500 italic">No {section.label.toLowerCase()} yet.</p>
+ ) : (
+ <div className="space-y-1.5">
+ {merged.map((row, idx) => (
+ <ListRow
+ // Every persisted row carries a server-stamped id (see
+ // sanitizeStat / sanitizePaletteColor / etc.) and every
+ // pending row gets a client-only id from `addRow`. The
+ // index fallback would tie ListRow's local `drafts` state
+ // to a slot, so a delete on an earlier row would shift
+ // another row's drafts onto this one.
+ key={row.id || `${section.key}-${idx}`}
+ row={row}
+ idx={idx}
+ columns={section.columns}
+ swatchHex={section.swatchHex}
+ onChange={(next) => updateRow(idx, next)}
+ onDelete={() => removeRow(idx)}
+ disabled={disabled}
+ />
+ ))}
+ </div>
+ )}
+ <button
+ type="button"
+ onClick={addRow}
+ disabled={disabled}
+ className="inline-flex items-center gap-1 px-1.5 py-0.5 text-[10px] rounded border border-port-border text-gray-400 hover:text-white hover:border-gray-500 disabled:opacity-40"
+ >
+ <Plus size={10} /> {section.addLabel}
+ </button>
+ </CollapsibleSection>
+ );
+}
+export default function CharacterDetailEditor({ entry, onPatch, onExpand, expanding = false, disabled = false }) {
if (!entry) return null;
const patchField = (name, value) => onPatch?.({ [name]: value });
const patchList = (field, next) => onPatch?.({ [field]: next });
- const persistedFor = (section) =>
- (Array.isArray(entry[section.field]) ? entry[section.field] : []);
- const pendingFor = (section) => pendingByList[section.key] || [];
- const mergedFor = (section) => [...persistedFor(section), ...pendingFor(section)];
- const requiredColumn = (section) => section.columns[0].name;
-
const sectionSummary = (section) => {
const filled = section.fields.filter((f) => (entry[f.name] || '').trim()).length;
return filled ? `${filled}/${section.fields.length} filled` : 'empty';
};
- const listSummary = (section) => {
- const merged = mergedFor(section);
- if (merged.length === 0) return 'empty';
- return `${merged.length} ${merged.length === 1 ? section.singular : section.singular + 's'}`;
- };
-
- const addRow = (section) => {
- // Client-only id on pending rows so ListRow's local draft state stays
- // bound to THIS row across re-renders and after-deletes — without it,
- // the React key falls through to index and an earlier-row delete shifts
- // a different row's drafts buffer onto this one. The `pending-` prefix
- // is stripped at promotion (see updateRow) so the server's `ensureId`
- // mints a fresh `<kind>-<uuid>` id under its own convention; without
- // that strip the sanitizer would round-trip the client prefix back onto
- // the persisted row.
- const id = `pending-${section.key}-${(globalThis.crypto?.randomUUID?.() ?? Date.now().toString(36) + Math.random().toString(36).slice(2))}`;
- const blank = { id, ...Object.fromEntries(section.columns.map((c) => [c.name, ''])) };
- setPendingByList((prev) => ({
- ...prev,
- [section.key]: [...(prev[section.key] || []), blank],
- }));
- };
-
- const isPendingIdx = (section, idx) => idx >= persistedFor(section).length;
- const pendingIdxOf = (section, idx) => idx - persistedFor(section).length;
-
- const updateRow = (section, idx, nextRow) => {
- if (!isPendingIdx(section, idx)) {
- const persisted = persistedFor(section);
- patchList(section.field, persisted.map((r, i) => (i === idx ? nextRow : r)));
- return;
- }
- const pIdx = pendingIdxOf(section, idx);
- const pending = pendingFor(section);
- const requiredFilled = String(nextRow[requiredColumn(section)] || '').trim().length > 0;
- if (requiredFilled) {
- // Promote into persisted; drop from pending. Strip the client-only
- // `pending-*` id so the server's sanitizer mints a fresh `<kind>-<uuid>`
- // under its own convention (sanitizer's `ensureId` preserves any
- // non-empty string id verbatim, so an unstripped pending prefix would
- // round-trip onto the persisted row).
- const remaining = pending.filter((_, i) => i !== pIdx);
- setPendingByList((prev) => ({ ...prev, [section.key]: remaining }));
- const { id: _pendingId, ...promoted } = nextRow;
- patchList(section.field, [...persistedFor(section), promoted]);
- return;
- }
- const next = pending.map((r, i) => (i === pIdx ? nextRow : r));
- setPendingByList((prev) => ({ ...prev, [section.key]: next }));
- };
-
- const removeRow = (section, idx) => {
- if (isPendingIdx(section, idx)) {
- const pIdx = pendingIdxOf(section, idx);
- const next = pendingFor(section).filter((_, i) => i !== pIdx);
- setPendingByList((prev) => ({ ...prev, [section.key]: next }));
- return;
- }
- patchList(section.field, persistedFor(section).filter((_, i) => i !== idx));
- };
return (
<div className="mt-2 space-y-1.5">
@@ -323,50 +311,15 @@ export default function CharacterDetailEditor({ entry, onPatch, onExpand, expand
</CollapsibleSection>
))}
- {LIST_SECTIONS.map((section) => {
- const merged = mergedFor(section);
- return (
- <CollapsibleSection
- key={section.key}
- icon={section.icon}
- label={section.label}
- summary={listSummary(section)}
- >
- {merged.length === 0 ? (
- <p className="text-[11px] text-gray-500 italic">No {section.label.toLowerCase()} yet.</p>
- ) : (
- <div className="space-y-1.5">
- {merged.map((row, idx) => (
- <ListRow
- // Every persisted row carries a server-stamped id (see
- // sanitizeStat / sanitizePaletteColor / etc.) and every
- // pending row gets a client-only id from `addRow`. The
- // index fallback would tie ListRow's local `drafts` state
- // to a slot, so a delete on an earlier row would shift
- // another row's drafts onto this one.
- key={row.id || `${section.key}-${idx}`}
- row={row}
- idx={idx}
- columns={section.columns}
- swatchHex={section.swatchHex}
- onChange={(next) => updateRow(section, idx, next)}
- onDelete={() => removeRow(section, idx)}
- disabled={disabled}
- />
- ))}
- </div>
- )}
- <button
- type="button"
- onClick={() => addRow(section)}
- disabled={disabled}
- className="inline-flex items-center gap-1 px-1.5 py-0.5 text-[10px] rounded border border-port-border text-gray-400 hover:text-white hover:border-gray-500 disabled:opacity-40"
- >
- <Plus size={10} /> {section.addLabel}
- </button>
- </CollapsibleSection>
- );
- })}
+ {LIST_SECTIONS.map((section) => (
+ <ListSectionEditor
+ key={section.key}
+ section={section}
+ entry={entry}
+ onPatchList={patchList}
+ disabled={disabled}
+ />
+ ))}
</div>
);
}
diff --git a/client/src/hooks/README.md b/client/src/hooks/README.md
index 8fbe62e8ca..da5d67ef75 100644
--- a/client/src/hooks/README.md
+++ b/client/src/hooks/README.md
@@ -66,6 +66,7 @@ grep -i "what you want to do" client/src/hooks/README.md
| `useContainerWidth` | `[ref, width]` via ResizeObserver. | Layout responds to a specific container's width. |
| `useFieldDraft` | Local input draft that commits on blur. | Bible-editor-style single-field input that must dedupe sibling races. |
| `useRowDraft` | Multi-column row draft (analogue of `useFieldDraft`). | Multi-column row that commits as a unit. |
+| `usePendingListRows` | List-of-rows where a new row is held client-side until a required column fills, then promoted to `onChange`. | Editable list whose nameless rows would otherwise be dropped by the server sanitizer (WardrobeSection, CharacterDetailEditor list sections). |
| `useKeyboardControls` | Keyboard binding for CyberCity mode toggle. | CyberCity-specific. |
| `useKeyboardHelp` | Esc closes, even from inputs/textareas. | Help/cheatsheet modals. |
| `useLockToggle` | Optimistic-PATCH lock toggle. | New "lock this field/stage/arc" button — use this, do not re-implement. |
diff --git a/client/src/hooks/index.js b/client/src/hooks/index.js
index 9872113e41..a616399cbb 100644
--- a/client/src/hooks/index.js
+++ b/client/src/hooks/index.js
@@ -19,6 +19,7 @@ export { default as useMediaJobProgress } from './useMediaJobProgress.js';
export { default as useMoltworldWs } from './useMoltworldWs.js';
export { default as useMounted } from './useMounted.js';
export { default as useNextEvalCountdown } from './useNextEvalCountdown.js';
+export { default as usePendingListRows } from './usePendingListRows.js';
export { default as usePreviewRoute } from './usePreviewRoute.js';
export { default as useProviderModels } from './useProviderModels.js';
export { default as useRowDraft } from './useRowDraft.js';
diff --git a/client/src/hooks/usePendingListRows.js b/client/src/hooks/usePendingListRows.js
new file mode 100644
index 0000000000..bd1d9edf92
--- /dev/null
+++ b/client/src/hooks/usePendingListRows.js
@@ -0,0 +1,91 @@
+// Pending-row buffer for "list of records where a new row is held client-side
+// until a required column fills, then promoted to onChange." Mirrors the
+// pattern previously inlined in CanonCard's WardrobeSection and
+// CharacterDetailEditor's LIST_SECTIONS.
+//
+// Why pending-then-promote: persisting a blank row immediately would round-
+// trip a row the server sanitizer drops, and the user's first keystroke
+// would land in a row that disappears on the next render.
+//
+// Why client-only ids on pending rows: ListRow / WardrobeRow draft buffers
+// (useRowDraft / useFieldDraft) are keyed by stable React key. Falling
+// through to index would shift another row's drafts onto this one after a
+// delete or promotion.
+//
+// idPrefix + stripIdOnPromote handle the two id-shape conventions:
+// - server-shaped (e.g. 'wd-<uuid>') round-trip verbatim — set
+// stripIdOnPromote=false so the same id stays on the row across the
+// pending → persisted swap (keeps the row's React key + draft buffer
+// stable through promotion).
+// - client-only (e.g. 'pending-<key>-<uuid>') must be stripped at promotion
+// so the server's sanitizer mints a fresh `<kind>-<uuid>` under its own
+// convention. The trade-off: the row's React key changes from
+// `pending-foo-<uuid>` to the server-stamped id, which remounts the row
+// and resets its inner draft buffer. Acceptable because the only path
+// into promotion is the user blurring the required column (no live
+// drafts on sibling columns at that moment).
+//
+// `globalThis.crypto` rather than bare `crypto`: bare `crypto?.…` throws
+// ReferenceError in some non-secure-context envs; going through `globalThis`
+// short-circuits cleanly to the Date+Math fallback.
+import { useState } from 'react';
+
+function mintId(prefix) {
+ const uuid = globalThis.crypto?.randomUUID?.()
+ ?? `${Date.now().toString(36)}${Math.random().toString(36).slice(2)}`;
+ return `${prefix}${uuid}`;
+}
+
+export default function usePendingListRows({
+ persisted = [],
+ requiredColumn,
+ idPrefix = '',
+ stripIdOnPromote = false,
+ blankRow = () => ({}),
+ onChange,
+} = {}) {
+ const [pending, setPending] = useState([]);
+
+ const persistedLen = persisted.length;
+ // Preserve the persisted array reference when no pending rows are present
+ // so downstream `useMemo`/`React.memo` consumers don't see a new identity
+ // on every render.
+ const merged = pending.length ? [...persisted, ...pending] : persisted;
+ const isPending = (idx) => idx >= persistedLen;
+
+ const addRow = () => {
+ const row = { id: mintId(idPrefix), ...blankRow() };
+ setPending((prev) => [...prev, row]);
+ };
+
+ const updateRow = (idx, nextRow) => {
+ if (idx < persistedLen) {
+ onChange(persisted.map((r, i) => (i === idx ? nextRow : r)));
+ return;
+ }
+ const pIdx = idx - persistedLen;
+ const requiredFilled = String(nextRow[requiredColumn] || '').trim().length > 0;
+ if (requiredFilled) {
+ setPending((prev) => prev.filter((_, i) => i !== pIdx));
+ let promoted = nextRow;
+ if (stripIdOnPromote) {
+ const { id: _drop, ...rest } = nextRow;
+ promoted = rest;
+ }
+ onChange([...persisted, promoted]);
+ return;
+ }
+ setPending((prev) => prev.map((r, i) => (i === pIdx ? nextRow : r)));
+ };
+
+ const removeRow = (idx) => {
+ if (idx < persistedLen) {
+ onChange(persisted.filter((_, i) => i !== idx));
+ return;
+ }
+ const pIdx = idx - persistedLen;
+ setPending((prev) => prev.filter((_, i) => i !== pIdx));
+ };
+
+ return { merged, isPending, addRow, updateRow, removeRow };
+}
diff --git a/client/src/hooks/usePendingListRows.test.jsx b/client/src/hooks/usePendingListRows.test.jsx
new file mode 100644
index 0000000000..e50d306a5d
--- /dev/null
+++ b/client/src/hooks/usePendingListRows.test.jsx
@@ -0,0 +1,148 @@
+import { describe, it, expect, vi } from 'vitest';
+import { renderHook, act } from '@testing-library/react';
+import usePendingListRows from './usePendingListRows';
+
+const WARDROBE_BLANK = () => ({ name: '', description: '' });
+
+describe('usePendingListRows', () => {
+ it('merged equals persisted (same reference) when no pending rows exist', () => {
+ const persisted = [{ id: 'wd-1', name: 'Casual', description: 'jeans' }];
+ const { result } = renderHook(() => usePendingListRows({
+ persisted, requiredColumn: 'name', idPrefix: 'wd-', blankRow: WARDROBE_BLANK, onChange: vi.fn(),
+ }));
+ expect(result.current.merged).toBe(persisted);
+ });
+
+ it('addRow appends a pending row with idPrefix-prefixed id and blank shape', () => {
+ const onChange = vi.fn();
+ const { result } = renderHook(() => usePendingListRows({
+ persisted: [], requiredColumn: 'name', idPrefix: 'wd-', blankRow: WARDROBE_BLANK, onChange,
+ }));
+ act(() => result.current.addRow());
+ expect(result.current.merged).toHaveLength(1);
+ const [row] = result.current.merged;
+ expect(row.id.startsWith('wd-')).toBe(true);
+ expect(row.name).toBe('');
+ expect(row.description).toBe('');
+ expect(result.current.isPending(0)).toBe(true);
+ expect(onChange).not.toHaveBeenCalled();
+ });
+
+ it('updateRow on a pending row with blank required column keeps it pending', () => {
+ const onChange = vi.fn();
+ const { result } = renderHook(() => usePendingListRows({
+ persisted: [], requiredColumn: 'name', idPrefix: 'wd-', blankRow: WARDROBE_BLANK, onChange,
+ }));
+ act(() => result.current.addRow());
+ const pendingId = result.current.merged[0].id;
+ act(() => result.current.updateRow(0, { id: pendingId, name: '', description: 'jeans' }));
+ expect(onChange).not.toHaveBeenCalled();
+ expect(result.current.merged[0]).toEqual({ id: pendingId, name: '', description: 'jeans' });
+ });
+
+ it('updateRow on a pending row promotes when required column fills (stripIdOnPromote=false keeps id)', () => {
+ const persisted = [];
+ const onChange = vi.fn();
+ const { result, rerender } = renderHook(
+ ({ p }) => usePendingListRows({
+ persisted: p, requiredColumn: 'name', idPrefix: 'wd-', blankRow: WARDROBE_BLANK, onChange,
+ }),
+ { initialProps: { p: persisted } },
+ );
+ act(() => result.current.addRow());
+ const pendingId = result.current.merged[0].id;
+ act(() => result.current.updateRow(0, { id: pendingId, name: 'Casual', description: '' }));
+ expect(onChange).toHaveBeenCalledTimes(1);
+ expect(onChange).toHaveBeenCalledWith([{ id: pendingId, name: 'Casual', description: '' }]);
+ rerender({ p: [{ id: pendingId, name: 'Casual', description: '' }] });
+ expect(result.current.merged).toEqual([{ id: pendingId, name: 'Casual', description: '' }]);
+ expect(result.current.isPending(0)).toBe(false);
+ });
+
+ it('stripIdOnPromote=true drops the id field when promoting', () => {
+ const onChange = vi.fn();
+ const { result } = renderHook(() => usePendingListRows({
+ persisted: [],
+ requiredColumn: 'label',
+ idPrefix: 'pending-stats-',
+ stripIdOnPromote: true,
+ blankRow: () => ({ label: '', value: '' }),
+ onChange,
+ }));
+ act(() => result.current.addRow());
+ const pendingId = result.current.merged[0].id;
+ expect(pendingId.startsWith('pending-stats-')).toBe(true);
+ act(() => result.current.updateRow(0, { id: pendingId, label: 'Height', value: "5'7\"" }));
+ expect(onChange).toHaveBeenCalledWith([{ label: 'Height', value: "5'7\"" }]);
+ });
+
+ it('updateRow on a persisted row patches it without touching pending', () => {
+ const persisted = [{ id: 'wd-1', name: 'Casual', description: 'jeans' }];
+ const onChange = vi.fn();
+ const { result } = renderHook(() => usePendingListRows({
+ persisted, requiredColumn: 'name', idPrefix: 'wd-', blankRow: WARDROBE_BLANK, onChange,
+ }));
+ act(() => result.current.updateRow(0, { id: 'wd-1', name: 'Casual', description: 'denim' }));
+ expect(onChange).toHaveBeenCalledWith([{ id: 'wd-1', name: 'Casual', description: 'denim' }]);
+ });
+
+ it('removeRow drops a pending row without calling onChange', () => {
+ const onChange = vi.fn();
+ const { result } = renderHook(() => usePendingListRows({
+ persisted: [], requiredColumn: 'name', idPrefix: 'wd-', blankRow: WARDROBE_BLANK, onChange,
+ }));
+ act(() => result.current.addRow());
+ act(() => result.current.removeRow(0));
+ expect(onChange).not.toHaveBeenCalled();
+ expect(result.current.merged).toHaveLength(0);
+ });
+
+ it('removeRow drops a persisted row via onChange', () => {
+ const persisted = [
+ { id: 'wd-1', name: 'Casual', description: '' },
+ { id: 'wd-2', name: 'Formal', description: '' },
+ ];
+ const onChange = vi.fn();
+ const { result } = renderHook(() => usePendingListRows({
+ persisted, requiredColumn: 'name', idPrefix: 'wd-', blankRow: WARDROBE_BLANK, onChange,
+ }));
+ act(() => result.current.removeRow(0));
+ expect(onChange).toHaveBeenCalledWith([{ id: 'wd-2', name: 'Formal', description: '' }]);
+ });
+
+ it('whitespace-only required column does NOT promote', () => {
+ const onChange = vi.fn();
+ const { result } = renderHook(() => usePendingListRows({
+ persisted: [], requiredColumn: 'name', idPrefix: 'wd-', blankRow: WARDROBE_BLANK, onChange,
+ }));
+ act(() => result.current.addRow());
+ const pendingId = result.current.merged[0].id;
+ act(() => result.current.updateRow(0, { id: pendingId, name: ' ', description: 'foo' }));
+ expect(onChange).not.toHaveBeenCalled();
+ });
+
+ it('isPending partitions merged indices correctly with both persisted and pending rows', () => {
+ const persisted = [{ id: 'wd-1', name: 'Casual', description: '' }];
+ const { result } = renderHook(() => usePendingListRows({
+ persisted, requiredColumn: 'name', idPrefix: 'wd-', blankRow: WARDROBE_BLANK, onChange: vi.fn(),
+ }));
+ act(() => result.current.addRow());
+ expect(result.current.merged).toHaveLength(2);
+ expect(result.current.isPending(0)).toBe(false);
+ expect(result.current.isPending(1)).toBe(true);
+ });
+
+ it('addRow without crypto.randomUUID falls back to Date+Math (no crash)', () => {
+ // jsdom's `crypto` getter is non-writable, so swap randomUUID via spy
+ // instead of reassigning `globalThis.crypto`.
+ const spy = vi.spyOn(globalThis.crypto, 'randomUUID').mockReturnValue(undefined);
+ const { result } = renderHook(() => usePendingListRows({
+ persisted: [], requiredColumn: 'name', idPrefix: 'wd-', blankRow: WARDROBE_BLANK, onChange: vi.fn(),
+ }));
+ act(() => result.current.addRow());
+ expect(result.current.merged[0].id.startsWith('wd-')).toBe(true);
+ // Suffix is the Date+Math fallback string — non-empty.
+ expect(result.current.merged[0].id.length).toBeGreaterThan('wd-'.length);
+ spy.mockRestore();
+ });
+});