Skip to content

Commit e8b494a

Browse files
feat(console): the ⌘K palette previews the selected record, creates a record from the query, and names what Enter does (#36387)
<!-- claude-projects-attribution: {"github_login":"zhuangjianguo"} --> _Requested by **Steedos** · [project thread](https://claude.ai/code/project/chan_018ETKaNwMZCNRYD7D8Q9Ubb?thread=cmsg_018ETKaNwMZCNRYD7D8Q9UbbUq2j5tRRVo3TVY3wcS1Fdg)_ Part of #36286 — this PR is step 1 (to-do items 1 to 4); item 5, the "current page" group on the empty palette, is left for a second PR on the same card. repo:objectstack#7 · zhuangjianguo · session_01QsR2jV3scu6UYPb42n5okQ Clause-②: yes (widening) — eight new published language-pack keys, in all eleven packs: console.commandPalette.create, createAs, previewEmpty, enterOpenRecord, enterCreate, enterSwitchApp, enterApplyTheme, enterOpen Metadata-protocol: none ## 维护者速读 - 在应用里打开搜索面板:搜到记录时右边显示选中记录的要点(标题和对象声明的关键字段),上下键跟着换;输入任意词,列表最后出现「新建『该词』为客户」等行,回车打开已填好名称的新建页;输入「新建」或对象名能找到「新建客户」这类入口;面板底部写明回车会做什么。 - 属于外壳体验对标 Attio 专题,落实维护者「立」的四条改进里的第 1 条(必做的前四项)。 - 出问题时用户最多看到预览或新建入口不对、点进一个空的新建页,不会改动任何数据,可以直接撤回。 - 请看下面的截图,确认右侧详情和新建行的样子是否符合预期。 ## What changes The ⌘K palette inside an app (`CommandPalette`, `ui/packages/app-shell/src/chrome/`) gains the card's items 1 to 4. Which records search finds and their order, the full search page, mobile and the AI entry are untouched. 1. **Record preview on the right** (`PalettePreviewPane.tsx`). While the query finds records, the palette widens (`sm:max-w-3xl`) and draws the selected hit read-only through the existing `RecordPreviewCard` (object label, title by the ADR-0079 ladder, the object's declared `highlightFields` through the record page's highlight strip, field-level security applied). The selection is cmdk's own, now controlled (`value` / `onValueChange`), so ArrowUp/ArrowDown move the preview. When a new set of hits lands, the selection moves to the first hit. The pane is a CSS container query on the palette frame: below a 45rem (720px) frame it is `display: none`, so a narrow window shows the results alone and nothing scrolls sideways. 2. **Create "words" as OBJECT** (`paletteCreate.ts`). Once something is typed, the last group, "Create", offers up to three of the app's navigation objects, the object of the page the palette was opened on first, then the navigation's order. Enter opens `/apps/APP/OBJECT/new?TITLEFIELD=words`, the create page that already reads its query string as the create prefill. An object is offered by the same verdict as the list's New: `resolveAffordance('listNew', …)` (bucket, `userActions.create`, effective API operations, create grant), then the create action's toolbar `visibleWhen` (fails closed) and `disabledWhen` bound with no record, as `objectViewToolbarAffordances` binds them. A "create as" row additionally needs the object's title field (`resolveNameField`) to be a `text`/`textarea` field, not `readonly`, that the member may write on create (`createFormFields`), so the words always land. 3. **New OBJECT** entries, in the same group: one per creatable object whose label ("New Customer", the list button's own `console.objectView.newObject` key), object label, machine name or the words "create new" match the query. An object whose New entry the query found gets no "create as" row (the query names the action, not a record). 4. **Enter hint** (`PaletteEnterHint.tsx`). A footer names what Enter does to the selected entry, read off the first word of its cmdk value: Open record (record, recent), Create, Switch app, Apply theme, or Open (every navigation entry). Eight new published `@object-ui/i18n` keys in all eleven packs, a widening of the language packs (Clause-② yes): `console.commandPalette.create`, `createAs`, `previewEmpty`, `enterOpenRecord`, `enterCreate`, `enterSwitchApp`, `enterApplyTheme`, `enterOpen` (zh-Hant regenerated by `gen:zh-hant`). No props or package exports change. README section of the palette updated. Changeset: `@object-ui/app-shell` + `@object-ui/i18n` patch. ### Screenshots (showcase app, 1440 wide, `zh-CN`; own `--fresh` backend + console dev server on this branch) Hit: "north" on the Accounts list, the first hit previewed, footer 「打开记录 ↵」 ![hit](https://github.com/objectstack-ai/objectstack/blob/00a0d416b65d2cf4c2fbb706adbe46270a083051/screens/36286/zh-1-hit.png?raw=true) Miss: 「张三丰」, the page's object first, footer 「新建 ↵」 ![miss](https://github.com/objectstack-ai/objectstack/blob/00a0d416b65d2cf4c2fbb706adbe46270a083051/screens/36286/zh-2-miss.png?raw=true) 「新建」: the New entries (below the navigation pages the word also finds) ![new](https://github.com/objectstack-ai/objectstack/blob/00a0d416b65d2cf4c2fbb706adbe46270a083051/screens/36286/zh-3-new.png?raw=true) Enter on the miss row: the create page with the name filled ![create](https://github.com/objectstack-ai/objectstack/blob/00a0d416b65d2cf4c2fbb706adbe46270a083051/screens/36286/zh-5-create.png?raw=true) A 700px window: results alone, no preview, no sideways scroll (measured `scrollWidth - clientWidth` = 0) ![narrow](https://github.com/objectstack-ai/objectstack/blob/00a0d416b65d2cf4c2fbb706adbe46270a083051/screens/36286/zh-4-narrow.png?raw=true) English: [hit](https://github.com/objectstack-ai/objectstack/blob/00a0d416b65d2cf4c2fbb706adbe46270a083051/screens/36286/1-hit.png?raw=true) · [miss](https://github.com/objectstack-ai/objectstack/blob/00a0d416b65d2cf4c2fbb706adbe46270a083051/screens/36286/2-miss.png?raw=true). The images live on the orphan ref `claude/issue-36286-screenshots` (no code), so this PR's diff carries no binary. ## Read first (by risk) 1. `ui/packages/app-shell/src/chrome/CommandPalette.tsx` — the hunk that computes `createTargets` / `newRecordRows` / `createAsRows`, and the render-time block that moves the selection to the first record hit when `hitSignature` changes (state adjusted during render, not in an effect). 2. `ui/packages/app-shell/src/chrome/paletteCreate.ts` — `paletteMayCreate` (the New verdict) and `palettePrefillField`. 3. `ui/packages/app-shell/src/chrome/PalettePreviewPane.tsx` — the 150 ms settle before the by-id read. ## Tests New file `CommandPalette.previewCreate-36286.test.tsx` (15 tests) against the real `CommandPaletteProvider` over the `find` fanout and `findOne`: the preview draws title + declared key fields and Enter opens the record; ArrowDown moves the preview and only the settled records are read (`findOne` called for C1 then C2, nothing else); the container-query classes; no pane and no wide palette without a hit; create-as order (route object first, else navigation order), the invoice the member may not create never offered, Enter lands on `/apps/crm/customer_36286/new?name=Zhang+San`; the empty palette and a cleared query offer no create row; "new" finds one New entry per creatable object and no create-as row; an object's name finds its New entry; the footer per entry kind; `visibleWhen` / `disabledWhen` / title-field gates as units. <details><summary>Local runs at 862d69b</summary> - `pnpm --filter @object-ui/app-shell type-check` (both `tsc --noEmit` and `tsconfig.test.json`), then `vitest run packages/app-shell/src/chrome/` under the lock: `VERDICT command-exit 0`, Test Files 29 passed (29), Tests 173 passed (173). - `vitest run packages/i18n/`: Test Files 106 passed (106), Tests 1978 passed, 13 skipped. (First run had 3 reds, fixed in this branch: zh-Hant not regenerated, and the de quote-pair count pin 121 to 122 for the new `createAs` pair.) - Earlier on this branch: every `CommandPalette.*.test.tsx`, `paletteMatch.test.ts` and `views/record-preview/*.test.tsx` green (part of the 126-file run whose only reds were the two i18n files above). - `ui`: `check:i18n-keys`, `check:i18n-drift` (0 en values changed, 8 keys added), `check:i18n-dead-keys`: exit 0. - eslint `--no-inline-config` on the changed files: 0 errors; `CommandPalette.tsx` carries the same 10 warnings as on `main`. - Derived families run locally (exit 0): `check-adr-0087-registration`, `check-changeset-no-major`, `check-empty-changeset`, `check-closing-keyword-parity`, `check-sdui-manifest`, `check-comment-mask-corpus`, `check:nul-bytes`, `check:published-files`, `check:cross-package-test-inputs`, `check:test-source-alias`, `check:undeclared-dep-imports`, `check:adr-anchors`, `check:role-word`, `check:watch-hint-literal`, `check:type-check-coverage`. NOT MEASURED: `check:type-check-debt` (killed at its 300 s local timeout; CI's). - `overlap-check`: VERDICT clean, merges with origin/main and 6 open PRs sharing the locale packs. </details> ## Acceptance notes - **Create opens the create page, not the list's modal.** The palette navigates to `/apps/APP/OBJECT/new` (the route the bare data surface's New and a related list's New open; it reads the query string as prefill). The list page's New opens a modal through `AppContent`'s `handleEdit`, which is outside this claim's file surface; reaching it from the palette would mean a new prop wired there. Worth a decision if the modal is wanted. - **Key fields are the declared `highlightFields` only.** An object that declares none previews its title alone: that is `RecordPreviewCard`'s rule, from the record page's 「没声明就不挑」 ruling, not a new choice. The card's acceptance line (industry, phone, email) holds for an object that declares them. - **At most three "create as" rows** (`CREATE_AS_MAX`), a judgment to keep the list short in apps with many objects; every other creatable object is still one "New OBJECT" entry away by name. - **The Create group comes last**, so Enter on a query that finds anything opens that thing; with the English word "new", records whose status is "new" come first and the New entries sit below them (the 「新建」 screenshot shows the Chinese case). - **Home's palette** reads the host app's navigation, so it offers the same rows there; the Studio palette offers none (no records, no app). - **One extra read per previewed record**: the hit payload carries the row, but `RecordPreviewCard` reads by id with `$expand` on the reference fields it shows, so lookups render as names; holding an arrow key reads nothing until the selection rests 150 ms. - The showcase's account object is labelled "Account (Success Overlay)" by that example; the screenshots show it as served. - The de pack's quote-pair count pin moves 121 to 122; a sibling PR adding another „“ pair will need the same one-line bump on merge. - Item 5 of the card (the "current page" group on the empty palette) is not in this PR. <details><summary>Readings at head a17d2c7 (after the first-push verification above)</summary> - 50b1abd merged origin/main: the PR conflicted on the de quote-pair count pin (main's #36011 added two pairs); the pin now reads 124. - 50b1abd went red in `Test UI (10/16)` on `dialogViewportGutterCensus-12603`: the palette's 768 px wide cap lacked the shared gutter. a17d2c7 reads `DIALOG_VIEWPORT_GUTTER` and lists the palette in `WIDE_SITES`. - Under the verify lock at a17d2c7: the gutter census plus `packages/app-shell/src/chrome/` gave `Test Files 30 passed (30)`, `Tests 180 passed (180)`; `pnpm --filter @object-ui/app-shell type-check` VERDICT command-exit 0 (after rebuilding `@object-ui/plugin-view`'s stale dist). - At 50b1abd: `packages/i18n/` plus the palette test gave `Test Files 107 passed (107)`, `Tests 1993 passed | 13 skipped`; `ui scripts/` gave `Test Files 172 passed | 2 skipped`, `Tests 5127 passed`. - CI on a17d2c7: 45 success, 13 skipped, 0 failed. - overlap-check at a17d2c7: exit 1 only against #36398 on `de-quote-pairing-3876.test.ts` (the same count pin; the second lander bumps it by one). - Dev report: comment 7077770300 on #36286. </details> ## Verification Two minutes: `cd examples/app-showcase && pnpm exec objectstack dev --seed-admin --fresh -p PORT`, then in `ui/apps/console` `DEV_PROXY_TARGET=http://localhost:PORT pnpm exec vite --port VPORT --strictPort`; sign in, open Accounts, press ⌘K, type `north`: Northwind is selected and the right pane shows Lifecycle / Industry / Annual Revenue; type `张三丰` and press Enter: the account create page opens with Account Name filled. --- _Generated by [Claude Code](https://claude.ai/code/session_01QsR2jV3scu6UYPb42n5okQ)_ <!-- signed: repo:objectstack#7 · zhuangjianguo · session_01QsR2jV3scu6UYPb42n5okQ --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent a10422d commit e8b494a

20 files changed

Lines changed: 959 additions & 11 deletions
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
---
2+
'@object-ui/app-shell': patch
3+
'@object-ui/i18n': patch
4+
---
5+
6+
feat(console): the ⌘K palette previews the record it is on, creates a record from what you typed, finds "New OBJECT", and says what Enter does
7+
8+
Clause-②: yes (widening) — eight new published language-pack keys, in all eleven packs: console.commandPalette.create, createAs, previewEmpty, enterOpenRecord, enterCreate, enterSwitchApp, enterApplyTheme, enterOpen
9+
Metadata-protocol: none
10+
11+
The command palette inside an app gains four things; which records it searches, and how it ranks them, are unchanged.
12+
13+
- **Record preview.** While the query finds records, the palette widens and shows the selected hit on the right, read-only: the object's label, the record's title and the object's declared key fields (`highlightFields`), drawn the way the record pointer card draws a record (field-level security applied; an object that declares no key fields shows its title alone). Arrow keys move the preview with the selection; the record is read once the selection rests for 150 ms. A palette narrower than 45rem (720px) shows the results alone.
14+
- **Create "words" as OBJECT.** Once something is typed, the end of the list offers to create a record of up to three of the app's objects, the object of the page the palette was opened on first, with the typed words in the object's title field: Enter opens that object's create page (`/apps/APP/OBJECT/new`) with the field filled. An object is offered only where its list offers New (the same verdict: CRUD bucket, `userActions.create`, effective API operations, the create grant, and the create action's `visibleWhen` / `disabledWhen`), and only when its title field is a text field the member may write on create.
15+
- **New OBJECT.** Typing "new", "create" or an object's name finds a "New OBJECT" entry for each such object, which opens its empty create page.
16+
- **Enter hint.** A footer names what Enter does to the selected entry: Open record, Create, Switch app, Apply theme or Open.
17+
18+
New locale keys, in every pack: `console.commandPalette.create`, `createAs`, `previewEmpty`, `enterOpenRecord`, `enterCreate`, `enterSwitchApp`, `enterApplyTheme`, `enterOpen`. No props or package exports change.

‎ui/packages/app-shell/README.md‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1426,6 +1426,16 @@ bar's middle zone, centered between the left group and the utility cluster. In
14261426
the `home`, `orgs` and `studio` frames, and below `lg` (as an icon button), it
14271427
sits at the utility cluster's left edge.
14281428

1429+
Inside an app, while the query finds records, the palette shows the selected
1430+
hit on the right, read-only: its title and the object's declared
1431+
`highlightFields`, as the record pointer card draws them (a palette narrower
1432+
than 45rem shows the results alone). Once something is typed, the end of the
1433+
list offers "New OBJECT" for the app's objects the query names and "Create
1434+
"words" as OBJECT" for up to three of them, the page's own object first; each
1435+
opens the object's create page (`/apps/APP/OBJECT/new`), the second with the
1436+
words in its title field. An object is offered exactly where its list offers
1437+
New. A footer names what Enter does to the selected entry.
1438+
14291439
```tsx
14301440
import { useCommandPalette } from '@object-ui/app-shell';
14311441

Lines changed: 333 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,333 @@
1+
/**
2+
* ObjectUI
3+
* Copyright (c) 2024-present ObjectStack Inc.
4+
*
5+
* This source code is licensed under the MIT license found in the
6+
* LICENSE file in the root directory of this source tree.
7+
*/
8+
9+
/**
10+
* The ⌘K palette previews the record hit it is on, offers to create a record
11+
* from what was typed, finds "New OBJECT" entries, and says what Enter does
12+
* (objectstack#36286).
13+
*
14+
* Pinned against the real `CommandPaletteProvider` (opened through its
15+
* `?palette=1` deep link) over the per-object `find` fanout, with the record
16+
* preview reading the record through the data source's `findOne`. Where Enter
17+
* went is read off the router.
18+
*/
19+
20+
import * as React from 'react';
21+
import { describe, it, expect, vi, afterEach } from 'vitest';
22+
import { render, fireEvent, waitFor, cleanup, screen, act } from '@testing-library/react';
23+
import { MemoryRouter, useLocation } from 'react-router-dom';
24+
import { MetadataCtx } from '@object-ui/react';
25+
26+
vi.mock('@object-ui/auth', async (importOriginal) => ({
27+
...(await importOriginal<Record<string, unknown>>()),
28+
useAuth: () => ({ user: { id: 'u1' }, activeOrganization: null }),
29+
}));
30+
31+
/** The member may read everything and create everything but an invoice. */
32+
const PERMS = {
33+
isLoaded: true,
34+
can: (object: string, action: string) => !(object === 'invoice_36286' && action === 'create'),
35+
cannot: (object: string, action: string) => object === 'invoice_36286' && action === 'create',
36+
check: () => ({ allowed: true }),
37+
checkField: () => true,
38+
getFieldPermissions: () => [],
39+
getRowFilter: () => undefined,
40+
getObjectApiOperations: () => undefined,
41+
roles: [],
42+
userId: 'u1',
43+
systemPermissions: undefined,
44+
hasCapabilities: () => true,
45+
hasAnyQueue: undefined,
46+
objectsUsingQueues: undefined,
47+
};
48+
vi.mock('@object-ui/permissions', async (importOriginal) => ({
49+
...(await importOriginal<Record<string, unknown>>()),
50+
usePermissions: () => PERMS,
51+
}));
52+
53+
// The preview's key fields draw through `lazy()`: load the detail entry at
54+
// module scope, so its cost is paid at import (ui/AGENTS.md, lazy boundaries).
55+
import '@object-ui/plugin-detail';
56+
57+
import { CommandPalette } from './CommandPalette';
58+
import { CommandPaletteProvider } from '../context/CommandPaletteProvider';
59+
import { paletteEnterAction } from './PaletteEnterHint';
60+
import { paletteCreateTargets, palettePrefillField, routeObjectName } from './paletteCreate';
61+
62+
const CUSTOMER = 'customer_36286';
63+
const CONTACT = 'contact_36286';
64+
const INVOICE = 'invoice_36286';
65+
66+
const OBJECTS = [
67+
{
68+
name: CUSTOMER,
69+
label: 'Customer',
70+
nameField: 'name',
71+
highlightFields: ['industry', 'phone'],
72+
fields: {
73+
name: { type: 'text', label: 'Customer Name' },
74+
industry: { type: 'text', label: 'Industry' },
75+
phone: { type: 'text', label: 'Phone' },
76+
},
77+
},
78+
{ name: CONTACT, label: 'Contact', nameField: 'full_name', fields: { full_name: { type: 'text', label: 'Full Name' } } },
79+
{ name: INVOICE, label: 'Invoice', nameField: 'subject', fields: { subject: { type: 'text', label: 'Subject' } } },
80+
];
81+
82+
const ROWS: Record<string, Array<Record<string, unknown>>> = {
83+
[CUSTOMER]: [
84+
{ id: 'C1', name: 'Qingdao Haichen Foods', industry: 'Food processing', phone: '0532-1000' },
85+
{ id: 'C2', name: 'Qingdao Harbour Logistics', industry: 'Logistics', phone: '0532-2000' },
86+
],
87+
[CONTACT]: [],
88+
[INVOICE]: [],
89+
};
90+
91+
const CRM = {
92+
name: 'crm',
93+
label: 'CRM',
94+
navigation: [
95+
{ id: 'n_contact', type: 'object', objectName: CONTACT, label: 'Contacts' },
96+
{ id: 'n_invoice', type: 'object', objectName: INVOICE, label: 'Invoices' },
97+
{ id: 'n_customer', type: 'object', objectName: CUSTOMER, label: 'Customers' },
98+
],
99+
};
100+
const SALES = { name: 'sales', label: 'Sales', navigation: [] };
101+
102+
function metadataValue() {
103+
return {
104+
apps: [],
105+
objects: [],
106+
dashboards: [],
107+
reports: [],
108+
pages: [],
109+
loading: false,
110+
error: null,
111+
refresh: async () => {},
112+
invalidate: () => {},
113+
ensureType: async () => [],
114+
getItem: async (type: string, name: string) => (type === 'object' ? OBJECTS.find((o) => o.name === name) ?? null : null),
115+
getItemsByType: () => [],
116+
getTypeStatus: () => 'ready' as const,
117+
};
118+
}
119+
120+
function Probe() {
121+
const location = useLocation();
122+
return <span data-testid="location" data-path={location.pathname} data-search={location.search} />;
123+
}
124+
125+
function mount(path = `/apps/crm/${CUSTOMER}`) {
126+
const ds = {
127+
find: vi.fn(async (name: string, params: { $search?: string }) => ({
128+
data: (ROWS[name] ?? []).filter((row) =>
129+
String(row.name ?? '').toLowerCase().includes(String(params?.$search ?? '').toLowerCase()),
130+
),
131+
})),
132+
findOne: vi.fn(async (name: string, id: string) => (ROWS[name] ?? []).find((row) => row.id === id) ?? null),
133+
};
134+
const metadata = metadataValue();
135+
render(
136+
<MetadataCtx.Provider value={metadata as never}>
137+
<MemoryRouter initialEntries={[`${path}?palette=1`]}>
138+
<CommandPaletteProvider>
139+
<Probe />
140+
<CommandPalette apps={[CRM, SALES]} activeApp={CRM} objects={OBJECTS} onAppChange={() => {}} dataSource={ds} />
141+
</CommandPaletteProvider>
142+
</MemoryRouter>
143+
</MetadataCtx.Provider>,
144+
);
145+
const input = document.querySelector('[cmdk-input]') as HTMLInputElement | null;
146+
if (!input) throw new Error('the palette did not open');
147+
return { ds, input };
148+
}
149+
150+
const type = (input: HTMLInputElement, value: string) => fireEvent.change(input, { target: { value } });
151+
const press = (input: HTMLInputElement, key: string) => fireEvent.keyDown(input, { key });
152+
const pane = () => screen.queryByTestId('palette-preview');
153+
const hint = () => screen.getByTestId('palette-enter-hint').getAttribute('data-enter-action');
154+
const selected = () => document.querySelector('[cmdk-item][data-selected="true"]')?.getAttribute('data-value');
155+
const values = (prefix: string) =>
156+
Array.from(document.querySelectorAll(`[cmdk-item][data-value^="${prefix}"]`)).map((el) => el.getAttribute('data-value'));
157+
const location = () => {
158+
const probe = screen.getByTestId('location');
159+
return `${probe.getAttribute('data-path')}${probe.getAttribute('data-search')}`;
160+
};
161+
162+
async function recordHitsShown(count: number) {
163+
await waitFor(() => expect(values('record ')).toHaveLength(count), { timeout: 4000 });
164+
}
165+
166+
afterEach(() => cleanup());
167+
168+
describe('objectstack#36286 — a record hit is previewed beside the results', () => {
169+
it('draws the selected hit read-only: its title and the object\'s declared key fields; Enter opens the record', async () => {
170+
const { ds, input } = mount();
171+
type(input, 'haichen');
172+
await recordHitsShown(1);
173+
174+
// The palette widens for two halves, and the pane follows the selection.
175+
expect(document.querySelector('[role="dialog"]')?.className).toContain('sm:max-w-3xl');
176+
await waitFor(() => expect(pane()?.querySelector('[data-record-preview="readable"]')).not.toBeNull(), { timeout: 4000 });
177+
expect(pane()).toHaveTextContent('Qingdao Haichen Foods');
178+
expect(await screen.findByText('Food processing')).toBeInTheDocument();
179+
expect(pane()).toHaveTextContent('Industry');
180+
expect(ds.findOne).toHaveBeenCalledWith(CUSTOMER, 'C1');
181+
expect(hint()).toBe('openRecord');
182+
183+
press(input, 'Enter');
184+
expect(location()).toBe(`/apps/crm/${CUSTOMER}/record/C1`);
185+
});
186+
187+
it('ArrowDown moves the preview to the second hit, reading only the record it settles on', async () => {
188+
const { ds, input } = mount();
189+
type(input, 'qingdao');
190+
await recordHitsShown(2);
191+
await waitFor(() => expect(pane()?.getAttribute('data-preview-record')).toBe('C1'), { timeout: 4000 });
192+
193+
press(input, 'ArrowDown');
194+
await waitFor(() => expect(pane()?.getAttribute('data-preview-record')).toBe('C2'), { timeout: 4000 });
195+
await waitFor(() => expect(pane()).toHaveTextContent('Qingdao Harbour Logistics'), { timeout: 4000 });
196+
expect(pane()).toHaveTextContent('Logistics');
197+
expect(ds.findOne.mock.calls.map((call) => call[1])).toEqual(['C1', 'C2']);
198+
});
199+
200+
it('the pane shows only from a 45rem palette: a container query on the palette frame', async () => {
201+
const { input } = mount();
202+
type(input, 'haichen');
203+
await recordHitsShown(1);
204+
expect(document.querySelector('[cmdk-root]')?.className).toContain('@container/palette');
205+
expect(pane()?.className).toMatch(/(^| )hidden( |$)/);
206+
expect(pane()?.className).toContain('@min-[45rem]/palette:block');
207+
});
208+
209+
it('CONTROL: no record hit, no pane and no wide palette', async () => {
210+
const { input } = mount();
211+
type(input, 'zhang san');
212+
await waitFor(() => expect(values('create as ')).not.toHaveLength(0));
213+
await act(async () => {
214+
await new Promise((resolve) => setTimeout(resolve, 400));
215+
});
216+
expect(pane()).toBeNull();
217+
expect(document.querySelector('[role="dialog"]')?.className).not.toContain('sm:max-w-3xl');
218+
});
219+
});
220+
221+
describe('objectstack#36286 — "Create \'words\' as OBJECT" below the results', () => {
222+
it('lists the creatable objects, the page\'s own object first; Enter opens its create form seeded with the words', async () => {
223+
const { input } = mount();
224+
type(input, 'Zhang San');
225+
await waitFor(() => expect(values('create as ')).toEqual([`create as ${CUSTOMER}`, `create as ${CONTACT}`]));
226+
expect(screen.getByText('Create "Zhang San" as Customer')).toBeInTheDocument();
227+
// No create grant on invoices: no row offers to create one.
228+
expect(values('create ').some((value) => value?.includes(INVOICE))).toBe(false);
229+
230+
expect(selected()).toBe(`create as ${CUSTOMER}`);
231+
expect(hint()).toBe('create');
232+
press(input, 'Enter');
233+
expect(location()).toBe(`/apps/crm/${CUSTOMER}/new?name=Zhang+San`);
234+
});
235+
236+
it('on a page of no object, the app\'s navigation order stands', async () => {
237+
const { input } = mount('/apps/crm');
238+
type(input, 'Zhang San');
239+
await waitFor(() => expect(values('create as ')).toEqual([`create as ${CONTACT}`, `create as ${CUSTOMER}`]));
240+
});
241+
242+
it('CONTROL: the empty palette offers no create row', async () => {
243+
mount();
244+
await act(async () => {});
245+
expect(values('create ')).toEqual([]);
246+
});
247+
248+
it('clearing the query takes the create rows away again', async () => {
249+
const { input } = mount();
250+
type(input, 'Zhang San');
251+
await waitFor(() => expect(values('create as ')).not.toHaveLength(0));
252+
type(input, '');
253+
await waitFor(() => expect(values('create ')).toEqual([]));
254+
});
255+
});
256+
257+
describe('objectstack#36286 — "New OBJECT" entries', () => {
258+
it('"new" finds one per object the member may create, never one it may not', async () => {
259+
const { input } = mount();
260+
type(input, 'new');
261+
await waitFor(() => expect(values('create new ')).toEqual([`create new ${CUSTOMER}`, `create new ${CONTACT}`]));
262+
expect(screen.getByText('New Customer')).toBeInTheDocument();
263+
expect(screen.getByText('New Contact')).toBeInTheDocument();
264+
expect(screen.queryByText('New Invoice')).toBeNull();
265+
// The query names the action, not a record called "new".
266+
expect(values('create as ')).toEqual([]);
267+
});
268+
269+
it('an object\'s own name finds its entry; Enter opens its empty create form', async () => {
270+
const { input } = mount('/apps/crm');
271+
type(input, 'contact');
272+
await waitFor(() => expect(values('create new ')).toEqual([`create new ${CONTACT}`]));
273+
// The other creatable object still takes the words as a record name.
274+
expect(values('create as ')).toEqual([`create as ${CUSTOMER}`]);
275+
act(() => {
276+
fireEvent.click(document.querySelector(`[cmdk-item][data-value="create new ${CONTACT}"]`)!);
277+
});
278+
expect(location()).toBe(`/apps/crm/${CONTACT}/new`);
279+
});
280+
});
281+
282+
describe('objectstack#36286 — the footer says what Enter does', () => {
283+
it('reads the action off the selected entry\'s kind', () => {
284+
expect(paletteEnterAction(`record Qingdao Customer ${CUSTOMER} C1`)).toBe('openRecord');
285+
expect(paletteEnterAction('recent Qingdao C1')).toBe('openRecord');
286+
expect(paletteEnterAction(`create as ${CUSTOMER}`)).toBe('create');
287+
expect(paletteEnterAction(`create new ${CUSTOMER}`)).toBe('create');
288+
expect(paletteEnterAction('app Sales sales')).toBe('switchApp');
289+
expect(paletteEnterAction('theme dark')).toBe('applyTheme');
290+
expect(paletteEnterAction(`object Customers ${CUSTOMER}`)).toBe('open');
291+
expect(paletteEnterAction('search all results full page')).toBe('open');
292+
expect(paletteEnterAction('')).toBeNull();
293+
});
294+
295+
it('an app entry says Switch app', async () => {
296+
const { input } = mount();
297+
type(input, 'sales');
298+
await waitFor(() => expect(selected()).toBe('app Sales sales'));
299+
expect(hint()).toBe('switchApp');
300+
expect(screen.getByTestId('palette-enter-hint')).toHaveTextContent('Switch app');
301+
});
302+
});
303+
304+
describe('objectstack#36286 — which objects a create row offers', () => {
305+
const byName = new Map(OBJECTS.map((o) => [o.name, o]));
306+
const names = OBJECTS.map((o) => o.name);
307+
308+
it('the create action\'s toolbar visibleWhen (fails closed) and disabledWhen hide an object', () => {
309+
const hidden = { ...OBJECTS[1], userActions: { create: { visibleWhen: 'false' } } };
310+
const greyed = { ...OBJECTS[0], userActions: { create: { disabledWhen: 'true' } } };
311+
const map = new Map<string, any>([[CUSTOMER, greyed], [CONTACT, hidden], [INVOICE, OBJECTS[2]]]);
312+
expect(paletteCreateTargets(names, map, PERMS as never, {}).map((t) => t.objectName)).toEqual([]);
313+
expect(paletteCreateTargets(names, byName as never, PERMS as never, {}).map((t) => t.objectName)).toEqual([
314+
CUSTOMER,
315+
CONTACT,
316+
]);
317+
});
318+
319+
it('only a writable text title field takes the typed words', () => {
320+
const base = OBJECTS[1];
321+
expect(palettePrefillField(base as never, PERMS as never)).toBe('full_name');
322+
expect(palettePrefillField({ ...base, fields: { full_name: { type: 'lookup' } } } as never, PERMS as never)).toBeUndefined();
323+
expect(palettePrefillField({ ...base, fields: { full_name: { type: 'text', readonly: true } } } as never, PERMS as never)).toBeUndefined();
324+
const noCreateField = { ...PERMS, checkField: () => false };
325+
expect(palettePrefillField(base as never, noCreateField as never)).toBeUndefined();
326+
});
327+
328+
it('the route\'s object is read off /apps/APP/OBJECT, only when the app lists it', () => {
329+
expect(routeObjectName(`/apps/crm/${CUSTOMER}/record/C1`, names)).toBe(CUSTOMER);
330+
expect(routeObjectName('/apps/crm/dashboard/sales', names)).toBeUndefined();
331+
expect(routeObjectName('/apps/crm', names)).toBeUndefined();
332+
});
333+
});

0 commit comments

Comments
 (0)