Skip to content
17 changes: 17 additions & 0 deletions .changeset/39147-nav-editor-keywords.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
---
'@object-ui/app-shell': patch
'@object-ui/types': patch
'@object-ui/i18n': patch
---

feat(console): Setup's and the Studio's navigation editor edit an entry's search keywords

Clause-②: yes (widening)
Metadata-protocol: none

A navigation entry's `keywords` (the other words a person may type in the console's search to find it, such as its old name after a rename) can now be set in the navigation editor that Setup's app editor and the Studio's nav inspector share, instead of only in source.

- The new **Search keywords** field adds, edits and removes words on every entry type except a separator. Removing the last word removes the key; nothing writes an empty list.
- Each edit is checked against the spec's own `keywords` rule before it is written: a keyword over the length limit, or one keyword too many, is not written, and the spec's message is shown beside the field.
- `NavigationEntryItem` (`@object-ui/types`) declares the optional `keywords` member, typed from the spec's nav-item base, so the editor and the served entry shape agree.
- New strings `engine.inspector.appNav.keywords`, `keywordsHint`, `keywordsAdd`, `keywordsItem`, `keywordsRemove` and `keywordsEmpty` in the Studio namespace (`en`, `zh`).
Original file line number Diff line number Diff line change
@@ -0,0 +1,246 @@
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.

/**
* objectstack#39147 — Setup's app editor and the Studio's nav inspector (both
* `AppNavInspector`) edit an entry's search keywords.
*
* A navigation entry declares `keywords` (objectstack#39052) and the command
* palette finds the entry by them (objectstack#39055), but no editor offered a
* field for them: an admin could set them only in source.
*
* - an admin adds, edits and removes keywords; the saved entry carries them,
* parses, and the palette's matcher finds it by the new word;
* - emptying the list removes the key, never writes `[]`;
* - a 61-character keyword and a 21st keyword are refused with the spec's own
* message, and nothing is written (CONTROL: 60 characters and a 20th pass);
* - a separator is offered no keywords field, and a retype to a separator
* drops them while a retype to another entry type keeps them.
*/

import * as React from 'react';
import { describe, it, expect, vi, afterEach } from 'vitest';
import { render, screen, cleanup, fireEvent } from '@testing-library/react';
import { MetadataCtx } from '@object-ui/react';
import { NavigationItemSchema } from '@objectstack/spec/ui';

// ONE client for the whole file, as the real hook hands out (see
// `AppNavInspector.labelInherits-11196.test.tsx`).
const client = vi.hoisted(() => ({ list: async () => [] }));

vi.mock('../useMetadata', async (importOriginal) => ({
...(await importOriginal<Record<string, unknown>>()),
useMetadataClient: () => client,
}));

import { AppNavInspector } from './AppNavInspector';
import { navEntryOffersField, retypedNavEntry } from './nav-target';
import { navEntryKeywords, paletteNavEntryHit } from '../../../chrome/paletteNavKeywords';
import { t } from '../i18n';
// Paid at collection, not inside a clocked case (check:test-source-alias).
import '@objectstack/lint';

afterEach(cleanup);

const METADATA = {
apps: [],
objects: [{ name: 'lead', label: 'Leads' }],
dashboards: [],
reports: [],
pages: [],
loading: false,
error: null,
refresh: async () => {},
invalidate: () => {},
ensureType: async () => [],
getItem: async () => null,
getItemsByType: () => [],
getTypeStatus: () => 'ready' as const,
};

type Entry = Record<string, unknown>;
type NavPatch = { navigation: Entry[] };

const L = 'en-US';
const PAGE_ENTRY: Entry = { id: 'nav_home', type: 'page', pageName: 'home', label: 'Home' };
const SEPARATOR: Entry = { id: 'nav_sep', type: 'separator' };

function inspect(navigation: Entry[], index = 0) {
const onPatch = vi.fn<(patch: NavPatch) => void>();
render(
<MetadataCtx.Provider value={METADATA as never}>
<AppNavInspector
type="app"
name="crm"
selection={{ kind: 'nav', id: `navigation[${index}]` }}
draft={{ name: 'crm', navigation }}
onPatch={onPatch as never}
onClearSelection={() => {}}
locale={L}
readOnly={false}
/>
</MetadataCtx.Provider>,
);
return onPatch;
}

/** What the save meets: `undefined`-valued keys erased, as JSON does. */
const wire = (entry: Entry) => JSON.parse(JSON.stringify(entry)) as Entry;

function issuesOf(entry: Entry) {
const r = NavigationItemSchema.safeParse(wire(entry));
return r.success ? [] : r.error.issues;
}

/** The keyword row inputs, in order. */
const rows = () => screen.queryAllByPlaceholderText(t('engine.inspector.appNav.keywordsItem', L)) as HTMLInputElement[];

function typeInto(input: HTMLInputElement, value: string) {
fireEvent.change(input, { target: { value } });
fireEvent.blur(input);
}

function addKeyword(value: string) {
fireEvent.click(screen.getByRole('button', { name: t('engine.inspector.appNav.keywordsAdd', L) }));
const all = rows();
typeInto(all[all.length - 1], value);
}

/** The palette's own matcher, against the saved entry: its label is its term. */
const paletteHit = (query: string, entry: Entry) =>
paletteNavEntryHit(query, [String(entry.label ?? '')], navEntryKeywords(entry), []);

describe('objectstack#39147 — the nav editor edits an entry\'s search keywords', () => {
it('an admin adds a keyword: the saved entry carries it, parses, and the palette finds the entry by it', () => {
const onPatch = inspect([PAGE_ENTRY]);
expect(rows()).toEqual([]);
expect(screen.getByText(t('engine.inspector.appNav.keywordsEmpty', L))).toBeInTheDocument();
addKeyword('pipeline');
expect(onPatch).toHaveBeenCalledTimes(1);
const saved = onPatch.mock.calls[0][0].navigation[0];
expect(saved).toEqual({ ...PAGE_ENTRY, keywords: ['pipeline'] });
expect(issuesOf(saved)).toEqual([]);
// NON-VACUITY: before the edit the palette does not find it by that word.
expect(paletteHit('pipel', PAGE_ENTRY)).toEqual({ found: false });
expect(paletteHit('pipel', saved)).toEqual({ found: true, keyword: 'pipeline' });
});

it('an admin edits a keyword: the saved entry carries the new word', () => {
const entry = { ...PAGE_ENTRY, keywords: ['old name', 'deals'] };
const onPatch = inspect([entry]);
expect(rows().map((r) => r.value)).toEqual(['old name', 'deals']);
typeInto(rows()[0], 'opportunities');
expect(onPatch).toHaveBeenCalledTimes(1);
const saved = onPatch.mock.calls[0][0].navigation[0];
expect(saved).toEqual({ ...entry, keywords: ['opportunities', 'deals'] });
expect(issuesOf(saved)).toEqual([]);
});

it('an admin removes a keyword; removing the last one removes the key, never writes []', () => {
const entry = { ...PAGE_ENTRY, keywords: ['deals'] };
const onPatch = inspect([entry]);
fireEvent.click(screen.getByRole('button', { name: t('engine.inspector.appNav.keywordsRemove', L) }));
expect(onPatch).toHaveBeenCalledTimes(1);
const saved = onPatch.mock.calls[0][0].navigation[0];
expect('keywords' in saved).toBe(false);
expect(saved).toEqual(PAGE_ENTRY);
});

it('leaving a keyword unchanged writes nothing', () => {
const onPatch = inspect([{ ...PAGE_ENTRY, keywords: ['deals'] }]);
typeInto(rows()[0], 'deals');
expect(onPatch).not.toHaveBeenCalled();
});

it('refuses a 61-character keyword with the spec\'s message and writes nothing (CONTROL: 60 pass)', () => {
const tooLong = 'k'.repeat(61);
const specIssues = issuesOf({ ...PAGE_ENTRY, keywords: [tooLong] });
expect(specIssues.length).toBeGreaterThan(0);
const onPatch = inspect([PAGE_ENTRY]);
addKeyword(tooLong);
expect(onPatch).not.toHaveBeenCalled();
expect(screen.getByRole('alert')).toHaveTextContent(specIssues[0].message);

cleanup();
const control = inspect([PAGE_ENTRY]);
addKeyword('k'.repeat(60));
expect(control).toHaveBeenCalledTimes(1);
expect(issuesOf(control.mock.calls[0][0].navigation[0])).toEqual([]);
expect(screen.queryByRole('alert')).toBeNull();
});

it('refuses a 21st keyword with the spec\'s message and writes nothing (CONTROL: a 20th passes)', () => {
const twenty = Array.from({ length: 20 }, (_, i) => `word${i}`);
const specIssues = issuesOf({ ...PAGE_ENTRY, keywords: [...twenty, 'one more'] });
expect(specIssues.length).toBeGreaterThan(0);
const onPatch = inspect([{ ...PAGE_ENTRY, keywords: twenty }]);
addKeyword('one more');
expect(onPatch).not.toHaveBeenCalled();
expect(screen.getByRole('alert')).toHaveTextContent(specIssues[0].message);

cleanup();
const nineteen = twenty.slice(0, 19);
const control = inspect([{ ...PAGE_ENTRY, keywords: nineteen }]);
addKeyword('word19');
expect(control).toHaveBeenCalledTimes(1);
const saved = control.mock.calls[0][0].navigation[0];
expect(saved.keywords).toEqual(twenty);
expect(issuesOf(saved)).toEqual([]);
});

it('a separator is offered no keywords field', () => {
expect(navEntryOffersField('separator', 'keywords')).toBe(false);
inspect([PAGE_ENTRY, SEPARATOR], 1);
expect(screen.queryByText(t('engine.inspector.appNav.keywords', L))).toBeNull();
expect(screen.queryByRole('button', { name: t('engine.inspector.appNav.keywordsAdd', L) })).toBeNull();
});

it('a retype to a separator drops the keywords; a retype to another entry type keeps them', () => {
const entry = { ...PAGE_ENTRY, keywords: ['deals'] };
const separator = retypedNavEntry(entry, 'separator');
expect('keywords' in separator).toBe(false);
expect(issuesOf(separator)).toEqual([]);
expect(retypedNavEntry(entry, 'dashboard').keywords).toEqual(['deals']);
});
});

describe('objectstack#39147 — a refused keywords draft stays with its own entry', () => {
it('switching from an entry with a refused draft to another keyword-less entry shows an empty field and writes nothing to it', () => {
// Both entries declare no `keywords`, so the field's `value` is
// `undefined` for each: only a fresh field per entry resets its rows.
const second: Entry = { id: 'nav_leads', type: 'page', pageName: 'leads', label: 'Leads' };
const navigation = [PAGE_ENTRY, second];
const onPatch = vi.fn<(patch: NavPatch) => void>();
const view = (index: number) => (
<MetadataCtx.Provider value={METADATA as never}>
<AppNavInspector
type="app"
name="crm"
selection={{ kind: 'nav', id: `navigation[${index}]` }}
draft={{ name: 'crm', navigation }}
onPatch={onPatch as never}
onClearSelection={() => {}}
locale={L}
readOnly={false}
/>
</MetadataCtx.Provider>
);
const { rerender } = render(view(0));
addKeyword('pipeline');
addKeyword('k'.repeat(61));
expect(screen.getByRole('alert')).toBeInTheDocument();
const writesOnA = onPatch.mock.calls.length;

rerender(view(1));
expect(rows()).toEqual([]);
expect(screen.getByText(t('engine.inspector.appNav.keywordsEmpty', L))).toBeInTheDocument();
expect(screen.queryByRole('alert')).toBeNull();
expect(onPatch).toHaveBeenCalledTimes(writesOnA);

// The next edit on B writes B's own word, and nothing carried from A.
addKeyword('leads');
expect(onPatch).toHaveBeenCalledTimes(writesOnA + 1);
const saved = onPatch.mock.calls[writesOnA][0].navigation[1];
expect(saved).toEqual({ ...second, keywords: ['leads'] });
expect(issuesOf(saved)).toEqual([]);
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -35,12 +35,19 @@
* Studio's nav inspector reads too. A separator declares neither a `label` nor
* an `icon`, so it is offered neither field: a value typed there used to write
* a key the save refused (`unrecognized_keys`).
*
* The entry's search keywords (objectstack#39147): the words a person may type
* in the console's search to find the entry (`keywords`, objectstack#39052),
* offered wherever `navEntryOffersField` offers them, so never on a separator.
* Each edit is judged by the spec's own `keywords` declaration before it is
* written: a list the schema refuses is not written, and the schema's message
* says why. An empty list removes the key, never writes `[]`.
*/

import * as React from 'react';
import { resolveHref } from '@object-ui/layout';
import type { NavigationItem } from '@object-ui/types';
import type { I18nLabel } from '@objectstack/spec/ui';
import { ObjectNavItemSchema, type I18nLabel } from '@objectstack/spec/ui';
import { Label } from '@object-ui/components';
import type { MetadataInspectorProps } from '../inspector-registry.js';
import { t } from '../i18n.js';
Expand All @@ -65,6 +72,7 @@ import {
} from './_shared.js';
import { InspectorComboField } from './InspectorComboField.js';
import { FiltersEditor } from './NavFiltersEditor.js';
import { FlowStringListField } from './FlowStringListField.js';
import { IconPickerWidget } from '../widgets.js';
import {
NAV_ITEM_TYPES,
Expand Down Expand Up @@ -214,6 +222,18 @@ function useMetadataOptions(
return state;
}

/**
* Why the spec refuses `keywords` as an entry's search keywords, or `null` when
* it takes them (objectstack#39147). Judged by the spec's own declaration, the
* shared nav-item base member every entry but a separator spreads, so the
* editor's limits and messages are the save's, never a restated copy. Read at
* call time: the member is a lazy schema.
*/
export function navKeywordsRefusal(keywords: readonly string[]): string | null {
const parsed = ObjectNavItemSchema.shape.keywords.safeParse(keywords);
return parsed.success ? null : (parsed.error.issues[0]?.message ?? parsed.error.message);
}

/** Preview template context that keeps template vars VISIBLE in the href. */
const PREVIEW_CTX = {
currentUserId: '{current_user_id}',
Expand All @@ -237,6 +257,9 @@ export function AppNavInspector({ selection, draft, name, onPatch, onClearSelect
// The console's own resolver for what a label-less item inherits.
const targetLabel = useNavTargetLabel();
const iconFieldId = React.useId();
// The keywords the spec refused, kept per entry so another entry's field
// never shows this one's message (objectstack#39147).
const [keywordsRefusal, setKeywordsRefusal] = React.useState<{ id: string; message: string } | null>(null);
// Views are named `<object>.<key>` (MetadataProvider) — scope the picker
// to the bound object instead of offering the whole workspace's views.
const viewOptions = React.useMemo(
Expand Down Expand Up @@ -301,6 +324,26 @@ export function AppNavInspector({ selection, draft, name, onPatch, onClearSelect
else patch({ label: next });
};

/**
* The Keywords field's edit (objectstack#39147). An empty list removes the
* key, never writes `[]`; a list the spec refuses is not written, and its
* message stays beside the field until an edit the spec takes. A list equal
* to the stored one writes nothing. The list field trims each row and drops
* blank ones before this runs, so the spec's untrimmed-word refusal never
* shows in this editor.
*/
const commitKeywords = (list: string[] | undefined) => {
const refusal = list ? navKeywordsRefusal(list) : null;
if (refusal) {
setKeywordsRefusal({ id: selection.id, message: refusal });
return;
}
setKeywordsRefusal(null);
if (JSON.stringify(list ?? []) === JSON.stringify(Array.isArray(node.keywords) ? node.keywords : [])) return;
if (list) patch({ keywords: list });
else patch({}, ['keywords']);
};

const switchType = (nextType: NavItemType) => {
const targetKey = NAV_TYPE_TARGETS[nextType].targetKey;
const keep = nextType === 'object' ? OBJECT_MODE_FIELDS.default : targetKey ? [targetKey] : [];
Expand Down Expand Up @@ -380,6 +423,30 @@ export function AppNavInspector({ selection, draft, name, onPatch, onClearSelect
/>
</div>
)}
{navEntryOffersField(entryType, 'keywords') && (
<div className="space-y-1" data-testid="nav-keywords">
<FlowStringListField
// A fresh field per entry: its rows are that entry's, so a refused
// draft never carries over to the next entry selected.
key={selection.id}
label={t('engine.inspector.appNav.keywords', locale)}
value={node.keywords}
onCommit={commitKeywords}
disabled={readOnly}
addLabel={t('engine.inspector.appNav.keywordsAdd', locale)}
itemLabel={t('engine.inspector.appNav.keywordsItem', locale)}
removeLabel={t('engine.inspector.appNav.keywordsRemove', locale)}
emptyLabel={t('engine.inspector.appNav.keywordsEmpty', locale)}
/>
{keywordsRefusal?.id === selection.id ? (
<p role="alert" className="text-[11px] text-destructive" data-testid="nav-keywords-refusal">
{keywordsRefusal.message}
</p>
) : (
<p className="text-[11px] text-muted-foreground">{t('engine.inspector.appNav.keywordsHint', locale)}</p>
)}
</div>
)}

<InspectorSelectField
label={t('engine.inspector.appNav.typeField', locale)}
Expand Down
8 changes: 8 additions & 0 deletions ui/packages/i18n/src/namespaces/studio/en.ts
Original file line number Diff line number Diff line change
Expand Up @@ -834,6 +834,14 @@ const STUDIO_EN: Record<string, string> = {
'engine.inspector.appNav.orderHint': 'Entries with a lower number come first in the menu; an entry without one counts as 0.',
'engine.inspector.appNav.visibleHint': 'Shows this entry only to people for whom the condition is true. Leave it empty to show it to everyone.',
'engine.inspector.appNav.visibleNotSaved': 'Not saved yet: the entry keeps its previous condition until this one has no errors.',
// objectstack#39147 — the nav editor's search keywords field (the entry's
// `keywords`); the spec's own message explains a refused list.
'engine.inspector.appNav.keywords': 'Search keywords',
'engine.inspector.appNav.keywordsHint': 'Other words people may type in search to find this entry, such as its old name after a rename.',
'engine.inspector.appNav.keywordsAdd': 'Add keyword',
'engine.inspector.appNav.keywordsItem': 'Word or phrase',
'engine.inspector.appNav.keywordsRemove': 'Remove keyword',
'engine.inspector.appNav.keywordsEmpty': 'No keywords',
// Page block inspector
'engine.inspector.pageBlock.kind': 'Block',
'engine.inspector.pageBlock.close': 'Close block',
Expand Down
Loading
Loading