Skip to content

Commit f41950e

Browse files
committed
fix(studio): an uncommitted nav rename raises the held-edit guard
Claude-Session: https://claude.ai/code/session_01L6bhgXU26UBEjd1KKHgNEx Co-authored-by: Claude <noreply@anthropic.com>
1 parent 6892888 commit f41950e

5 files changed

Lines changed: 192 additions & 1 deletion

File tree

‎ui/packages/app-shell/src/views/metadata-admin/previews/AppNavCanvas.tsx‎

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -291,6 +291,14 @@ export interface AppNavCanvasProps {
291291
onPatch?: (patch: Record<string, unknown>) => void;
292292
selection: { kind: string; id: string } | null;
293293
onSelectionChange?: (sel: { kind: string; id: string; label?: string } | null) => void;
294+
/**
295+
* objectstack#27464 — the label of the entry whose rename is typed but not
296+
* yet committed (the input differs from the authored label), or `null`. A
297+
* rename commits on blur or Enter, so a reload or a tab close before either
298+
* drops it; a host reports it as an edit held unsent. Optional: a host with
299+
* no departure guard leaves it out.
300+
*/
301+
onRenamePendingChange?: (label: string | null) => void;
294302
}
295303

296304
export function AppNavCanvas({
@@ -299,6 +307,7 @@ export function AppNavCanvas({
299307
onPatch,
300308
selection,
301309
onSelectionChange,
310+
onRenamePendingChange,
302311
}: AppNavCanvasProps) {
303312
const locale = useMetadataLocale();
304313
const targetLabel = useNavTargetLabel();
@@ -477,6 +486,7 @@ export function AppNavCanvas({
477486
canEdit={!!onPatch}
478487
onClick={(p, lbl) => onSelectionChange?.({ kind: 'nav', id: p, label: lbl })}
479488
onRename={(lbl) => renameItem(i, lbl)}
489+
onRenamePendingChange={onRenamePendingChange}
480490
onRemove={() => removeItem(i)}
481491
onDragStart={() => setDragIndex(i)}
482492
onDragEnd={() => setDragIndex(null)}
@@ -504,6 +514,7 @@ function NavCardTree({
504514
canEdit,
505515
onClick,
506516
onRename,
517+
onRenamePendingChange,
507518
onRemove,
508519
onDragStart,
509520
onDragEnd,
@@ -519,6 +530,7 @@ function NavCardTree({
519530
canEdit: boolean;
520531
onClick: (path: string, label: string) => void;
521532
onRename: (label: string) => void;
533+
onRenamePendingChange?: (label: string | null) => void;
522534
onRemove: () => void;
523535
onDragStart: () => void;
524536
onDragEnd: () => void;
@@ -537,6 +549,7 @@ function NavCardTree({
537549
canEdit={canEdit && depth === 0}
538550
onClick={() => onClick(path, navLabel(item, index, locale, targetLabel))}
539551
onRename={onRename}
552+
onRenamePendingChange={onRenamePendingChange}
540553
onRemove={onRemove}
541554
onDragStart={onDragStart}
542555
onDragEnd={onDragEnd}
@@ -580,6 +593,7 @@ function NavCard({
580593
canEdit,
581594
onClick,
582595
onRename,
596+
onRenamePendingChange,
583597
onRemove,
584598
onDragStart,
585599
onDragEnd,
@@ -595,6 +609,7 @@ function NavCard({
595609
canEdit: boolean;
596610
onClick: () => void;
597611
onRename: (label: string) => void;
612+
onRenamePendingChange?: (label: string | null) => void;
598613
onRemove: () => void;
599614
onDragStart: () => void;
600615
onDragEnd: () => void;
@@ -615,6 +630,27 @@ function NavCard({
615630
if (!editing) setDraft(authored);
616631
}, [authored, editing]);
617632

633+
// objectstack#27464 — a typed rename that blur or Enter has not committed
634+
// yet is reported, keyed on the label string (AGENTS.md #10). Only a card
635+
// that has reported takes it back, so the other cards' mounts never clear it.
636+
const pendingRename = editing && draft.trim() !== '' && draft.trim() !== authored ? label : null;
637+
const reportRef = React.useRef(onRenamePendingChange);
638+
React.useLayoutEffect(() => {
639+
reportRef.current = onRenamePendingChange;
640+
});
641+
const reportedRef = React.useRef(false);
642+
React.useEffect(() => {
643+
if (pendingRename === null && !reportedRef.current) return;
644+
reportedRef.current = pendingRename !== null;
645+
reportRef.current?.(pendingRename);
646+
}, [pendingRename]);
647+
React.useEffect(
648+
() => () => {
649+
if (reportedRef.current) reportRef.current?.(null);
650+
},
651+
[],
652+
);
653+
618654
return (
619655
<div className={cn('relative', DEPTH_INDENT[Math.min(depth, DEPTH_INDENT.length - 1)])}>
620656
{dropPos === 'before' && (
Lines changed: 144 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,144 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* objectstack#27464 — a navigation rename typed into the Interfaces nav editor
5+
* but not committed yet (it commits on blur or Enter) is unsaved work: a reload
6+
* or a tab close asks first, as it does for every other held Studio edit.
7+
*
8+
* The canvas reports the pending rename and the pillar folds it into the one
9+
* held-edit report the surface already reads (`useHeldEditReport`), so the
10+
* surface's single `beforeunload` guard covers it. Rendered through the REAL
11+
* `StudioDesignSurface` on the real route shape. A bare `AppNavCanvas` (the
12+
* `AppPreview` caller passes no report) renames as before.
13+
*/
14+
15+
import '@testing-library/jest-dom/vitest';
16+
import * as React from 'react';
17+
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
18+
import { render, screen, fireEvent, cleanup, waitFor } from '@testing-library/react';
19+
import { MemoryRouter, Route, Routes } from 'react-router-dom';
20+
21+
const PKG = 'com.acme.app';
22+
const NAV = [{ id: 'nav_qa', type: 'page', label: 'QA Dash', pageName: 'home' }];
23+
const HOME = { name: 'home', label: 'Home', type: 'app', regions: [{ name: 'main', components: [] }] };
24+
25+
const mockClient = vi.hoisted(() => ({
26+
list: vi.fn(async (type: string) => (type === 'app' ? [{ name: 'acme_app', label: 'Acme' }] : [])),
27+
listDrafts: vi.fn(async () => []),
28+
listTypes: vi.fn(async () => ({ entries: [] })),
29+
get: vi.fn(async () => null),
30+
references: vi.fn(async () => []),
31+
layered: vi.fn(),
32+
getDraft: vi.fn(async () => {
33+
throw Object.assign(new Error('No pending draft'), { code: 'NO_DRAFT', status: 404 });
34+
}),
35+
save: vi.fn(async (type: string, name: string, item: unknown) => ({ type, name, item })),
36+
publish: vi.fn(async () => ({ success: true })),
37+
reset: vi.fn(async () => ({})),
38+
}));
39+
40+
vi.mock('../metadata-admin/useMetadata', async (importOriginal) => {
41+
const mod = await importOriginal<typeof import('../metadata-admin/useMetadata')>();
42+
return { ...mod, useMetadataClient: () => mockClient, useMetadataTypes: () => ({ loading: false, error: null, entries: [] }) };
43+
});
44+
vi.mock('./packages-io', async (importOriginal) => {
45+
const mod = await importOriginal<typeof import('./packages-io')>();
46+
return { ...mod, fetchPackages: vi.fn(async () => [{ id: PKG, name: 'Acme', writable: true, namespace: 'acme' }]) };
47+
});
48+
vi.mock('@object-ui/react', async (importOriginal) => {
49+
const mod = await importOriginal<typeof import('@object-ui/react')>();
50+
return { ...mod, useAdapter: () => ({}) };
51+
});
52+
vi.mock('./StudioAiCopilot', () => ({ StudioChatDock: () => null }));
53+
vi.mock('../../preview/DraftChangesPanel', () => ({ DraftChangesPanel: () => null }));
54+
55+
import { StudioDesignSurface } from './StudioDesignSurface';
56+
import { AppNavCanvas } from '../metadata-admin/previews/AppNavCanvas';
57+
58+
window.matchMedia = ((query: string) => ({
59+
matches: false, media: query, onchange: null,
60+
addEventListener: () => {}, removeEventListener: () => {}, addListener: () => {}, removeListener: () => {},
61+
dispatchEvent: () => false,
62+
})) as unknown as typeof window.matchMedia;
63+
(globalThis as { ResizeObserver?: unknown }).ResizeObserver =
64+
(globalThis as { ResizeObserver?: unknown }).ResizeObserver ?? class { observe() {} unobserve() {} disconnect() {} };
65+
66+
beforeEach(() => {
67+
for (const fn of Object.values(mockClient)) (fn as unknown as { mockClear: () => void }).mockClear();
68+
mockClient.layered.mockImplementation(async (type: string) => {
69+
const effective = type === 'app' ? { name: 'acme_app', label: 'Acme', navigation: NAV } : type === 'page' ? HOME : null;
70+
return { code: null, overlay: effective, overlayScope: effective ? 'env' : null, effective, editable: true };
71+
});
72+
vi.stubGlobal('fetch', vi.fn(async () => ({ ok: true, json: async () => [] })) as unknown as typeof fetch);
73+
});
74+
afterEach(() => {
75+
cleanup();
76+
vi.unstubAllGlobals();
77+
});
78+
79+
/** Whether a reload / tab close would be asked about. */
80+
function reloadAsks(): boolean {
81+
const e = new Event('beforeunload', { cancelable: true });
82+
window.dispatchEvent(e);
83+
return e.defaultPrevented;
84+
}
85+
86+
/** Opens nav editing and starts a rename of "QA Dash"; returns its input. */
87+
async function startRename(): Promise<HTMLInputElement> {
88+
render(
89+
<MemoryRouter initialEntries={[`/studio/${PKG}/interfaces`]}>
90+
<Routes>
91+
<Route path="/studio/:packageId/:tab" element={<StudioDesignSurface />} />
92+
</Routes>
93+
</MemoryRouter>,
94+
);
95+
await screen.findByRole('button', { name: /QA Dash/ }, { timeout: 8000 });
96+
fireEvent.click(screen.getByTitle(/^Edit navigation/));
97+
await screen.findByRole('button', { name: /Add nav item/ }, { timeout: 8000 });
98+
const card = screen.getAllByRole('button').find((b) => b.getAttribute('aria-pressed') !== null && b.textContent?.startsWith('QA Dash'))!;
99+
fireEvent.doubleClick(card.querySelector('span')!);
100+
return (await screen.findByDisplayValue('QA Dash')) as HTMLInputElement;
101+
}
102+
103+
describe('an uncommitted nav rename raises the held-edit guard (objectstack#27464)', () => {
104+
it('typing a rename asks on reload; Escape reverts it and the guard lets go', async () => {
105+
const input = await startRename();
106+
expect(reloadAsks()).toBe(false);
107+
fireEvent.change(input, { target: { value: 'QA Dash Lost' } });
108+
await waitFor(() => expect(reloadAsks()).toBe(true));
109+
fireEvent.keyDown(input, { key: 'Escape' });
110+
await waitFor(() => expect(reloadAsks()).toBe(false));
111+
expect(mockClient.save).not.toHaveBeenCalled();
112+
});
113+
114+
it('typing the authored label back is no rename, and the guard lets go', async () => {
115+
const input = await startRename();
116+
fireEvent.change(input, { target: { value: 'QA Dash Lost' } });
117+
await waitFor(() => expect(reloadAsks()).toBe(true));
118+
fireEvent.change(input, { target: { value: 'QA Dash' } });
119+
await waitFor(() => expect(reloadAsks()).toBe(false));
120+
});
121+
122+
it('committing hands the rename to the nav autosave; once it lands nothing is held', async () => {
123+
const input = await startRename();
124+
fireEvent.change(input, { target: { value: 'QA Dash Lost' } });
125+
await waitFor(() => expect(reloadAsks()).toBe(true));
126+
fireEvent.blur(input);
127+
await waitFor(() => expect(mockClient.save.mock.calls.some(([type]) => type === 'app')).toBe(true), { timeout: 8000 });
128+
const sent = mockClient.save.mock.calls.find(([type]) => type === 'app')![2] as { navigation: Array<{ label: unknown }> };
129+
expect(sent.navigation[0].label).toBe('QA Dash Lost');
130+
await waitFor(() => expect(reloadAsks()).toBe(false), { timeout: 8000 });
131+
});
132+
});
133+
134+
describe('a canvas with no report (the AppPreview caller) renames as before', () => {
135+
it('commits on blur and needs no report', () => {
136+
const onPatch = vi.fn();
137+
render(<AppNavCanvas draft={{ navigation: NAV }} rootKey="navigation" onPatch={onPatch} selection={null} />);
138+
fireEvent.doubleClick(screen.getByText('QA Dash'));
139+
const input = screen.getByDisplayValue('QA Dash');
140+
fireEvent.change(input, { target: { value: 'Renamed' } });
141+
fireEvent.blur(input);
142+
expect(onPatch).toHaveBeenCalledWith({ navigation: [expect.objectContaining({ label: 'Renamed' })] });
143+
});
144+
});

‎ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.tsx‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4834,7 +4834,13 @@ export function InterfacesPillar({
48344834
});
48354835
// Only the open leaf's own buffer is held (objectui#11272).
48364836
const leafHeld = draftLoaded ? leafIncomplete : null;
4837-
useHeldEditReport(onHeldEditChange, leafHeld?.clause ?? null);
4837+
// objectstack#27464 — a nav rename typed but not committed (blur / Enter)
4838+
// lives only in the canvas input, so it is held as the leaf's edit is: the
4839+
// same report, so the surface's one guard (beforeunload included) asks.
4840+
const [navRenamePending, setNavRenamePending] = React.useState<string | null>(null);
4841+
const navRenameClause =
4842+
navRenamePending === null ? null : tFormat('engine.studio.held.navRename', locale, { item: navRenamePending });
4843+
useHeldEditReport(onHeldEditChange, leafHeld?.clause ?? navRenameClause);
48384844
// objectui#12725 — the header's draft line reads the badge's ledger.
48394845
const leafDraftStatus = useStudioItemDraftStatus(
48404846
current ? { type: current.type, name: current.name } : null,
@@ -6103,6 +6109,7 @@ export function InterfacesPillar({
61036109
onPatch={onNavPatch}
61046110
selection={navSel}
61056111
onSelectionChange={(s) => setNavSel(s ? { kind: s.kind, id: s.id } : null)}
6112+
onRenamePendingChange={setNavRenamePending}
61066113
/>
61076114
) : navTree.length === 0 ? (
61086115
<p className="px-2 py-3 text-[11px] text-muted-foreground">

‎ui/packages/i18n/src/namespaces/studio/en.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2999,6 +2999,8 @@ const STUDIO_EN: Record<string, string> = {
29992999
// objectui#11910 — a dashboard widget held until it is bound; `input` is the
30003000
// widget inspector's own label for it (Dataset, Values (measures)).
30013001
'engine.studio.held.widgetNeedsInput': '{input} on the widget “{widget}” needs a value',
3002+
// objectstack#27464 — a navigation rename typed but not committed yet.
3003+
'engine.studio.held.navRename': 'the rename of the navigation item “{item}” is not finished',
30023004
'engine.studio.held.line': 'Not saved yet: {clause}. Your changes are kept here and saved once it is filled in.',
30033005
'engine.studio.held.publish': 'Not published: {clause}, so that change is not saved yet. Finish it, then publish.',
30043006
'engine.studio.held.inputHint': 'Required. Changes are saved once this has a value.',

‎ui/packages/i18n/src/namespaces/studio/zh.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2668,6 +2668,8 @@ const STUDIO_ZH: Record<string, string> = {
26682668
'engine.studio.held.needsRuleField': '规则「{rule}」需要选择一个字段',
26692669
'engine.studio.held.needsRuleMessage': '规则「{rule}」需要一条错误消息',
26702670
'engine.studio.held.widgetNeedsInput': '组件「{widget}」的「{input}」需要填写',
2671+
// objectstack#27464 — a navigation rename typed but not committed yet.
2672+
'engine.studio.held.navRename': '导航项「{item}」的重命名尚未完成',
26712673
'engine.studio.held.line': '尚未保存:{clause}。更改已保留在此处,补全后会自动保存。',
26722674
'engine.studio.held.publish': '未发布:{clause},该更改尚未保存。请先补全,再发布。',
26732675
'engine.studio.held.inputHint': '必填。填写后才会保存更改。',

0 commit comments

Comments
 (0)