From 27a7f0ab67dc5a35749201c66fe2a8b59c49bca9 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 07:46:20 +0000 Subject: [PATCH 1/7] feat(app-shell): palette record preview, create rows and Enter hint (wip) Claude-Session: https://claude.ai/code/session_01QsR2jV3scu6UYPb42n5okQ Co-authored-by: Claude --- .../app-shell/src/chrome/CommandPalette.tsx | 162 ++++++++++++++++- .../app-shell/src/chrome/PaletteEnterHint.tsx | 73 ++++++++ .../src/chrome/PalettePreviewPane.tsx | 94 ++++++++++ .../app-shell/src/chrome/paletteCreate.ts | 167 ++++++++++++++++++ ui/packages/i18n/src/locales/ar.ts | 8 + ui/packages/i18n/src/locales/de.ts | 8 + ui/packages/i18n/src/locales/en.ts | 8 + ui/packages/i18n/src/locales/es.ts | 8 + ui/packages/i18n/src/locales/fr.ts | 8 + ui/packages/i18n/src/locales/ja.ts | 8 + ui/packages/i18n/src/locales/ko.ts | 8 + ui/packages/i18n/src/locales/pt-BR.ts | 8 + ui/packages/i18n/src/locales/ru.ts | 8 + ui/packages/i18n/src/locales/zh-Hans.ts | 8 + ui/packages/i18n/src/locales/zh-Hant.ts | 8 + 15 files changed, 575 insertions(+), 9 deletions(-) create mode 100644 ui/packages/app-shell/src/chrome/PaletteEnterHint.tsx create mode 100644 ui/packages/app-shell/src/chrome/PalettePreviewPane.tsx create mode 100644 ui/packages/app-shell/src/chrome/paletteCreate.ts diff --git a/ui/packages/app-shell/src/chrome/CommandPalette.tsx b/ui/packages/app-shell/src/chrome/CommandPalette.tsx index 2eade76bf41..2577a269ddd 100644 --- a/ui/packages/app-shell/src/chrome/CommandPalette.tsx +++ b/ui/packages/app-shell/src/chrome/CommandPalette.tsx @@ -22,7 +22,7 @@ */ import { useEffect, useState, useMemo, type ReactNode } from 'react'; -import { useNavigate, useParams } from 'react-router-dom'; +import { useLocation, useNavigate, useParams } from 'react-router-dom'; import { Command, Dialog, @@ -36,6 +36,7 @@ import { CommandList, CommandSeparator, ObjectIconTile, + cn, } from '@object-ui/components'; import { LayoutDashboard, @@ -48,9 +49,10 @@ import { Boxes, Database, Workflow, + Plus, type LucideIcon, } from 'lucide-react'; -import { useRecordSearch } from '@object-ui/react'; +import { useObjectLabel, usePredicateScope, useRecordSearch, type RecordSearchHit } from '@object-ui/react'; import { usePermissions } from '@object-ui/permissions'; import { useTheme } from './ThemeProvider.js'; import { navEntriesShownToMember, useNavMemberGates, type NavMemberGates } from '../hooks/useNavMemberGates.js'; @@ -81,6 +83,17 @@ import { isPackageLessItem, studioOrgScopePath } from '../views/studio-design/st import { DESIGNER_SURFACE_PARAM, formatSurfaceParam } from '../views/metadata-admin/nav-selection.js'; import { flattenNavigation, useAppReportEntries } from '../views/appReportIndex.js'; import { useServedApps } from '../hooks/useLauncherApps.js'; +import { servedObjectLabel } from '../hooks/servedObjectLabel.js'; +import { + CREATE_AS_MAX, + paletteCreateHref, + paletteCreateTargets, + routeObjectName, + type PaletteCreateObjectDef, + type PaletteCreateTarget, +} from './paletteCreate.js'; +import { PalettePreviewPane, type PalettePreviewTarget } from './PalettePreviewPane.js'; +import { PaletteEnterHint } from './PaletteEnterHint.js'; /** A recent row names its object by name (objectstack#29121). */ const RECENT_ROW_LABELS: NavTargetLabelOptions = { byName: true }; @@ -229,7 +242,12 @@ function CommandPaletteBody(props: CommandPaletteProps & { gates: NavMemberGates const { apps, activeApp, objects, onAppChange, dataSource } = inStudio ? NO_APP : props; const { open, setOpen } = useCommandPalette(); const [inputValue, setInputValue] = useState(''); + // The entry the keyboard is on, by its cmdk value (objectstack#36286): the + // footer says what Enter does to it, and a record hit is previewed beside + // the results. + const [selectedValue, setSelectedValue] = useState(''); const navigate = useNavigate(); + const location = useLocation(); const { appName } = useParams(); const { setTheme } = useTheme(); const { t, language } = useObjectTranslation(); @@ -249,7 +267,10 @@ function CommandPaletteBody(props: CommandPaletteProps & { gates: NavMemberGates // Reset query when the palette closes so reopening doesn't show stale state. useEffect(() => { - if (!open) setInputValue(''); + if (!open) { + setInputValue(''); + setSelectedValue(''); + } }, [open]); // What was typed between the shortcut and this input's focus starts the // query (objectstack#32627). @@ -473,6 +494,51 @@ function CommandPaletteBody(props: CommandPaletteProps & { gates: NavMemberGates }); }, [recordHits, objectsByName, t]); + // objectstack#36286 — the record hit the keyboard is on, previewed beside + // the results while there are any. + const recordHitByValue = new Map(); + for (const hit of recordHits) recordHitByValue.set(recordHitValue(hit), hit); + const selectedHit = recordHitByValue.get(selectedValue); + const previewTarget: PalettePreviewTarget | null = selectedHit + ? { objectName: selectedHit.objectName, recordId: selectedHit.recordId } + : null; + const showPreview = recordGroups.length > 0; + + // objectstack#36286 — the app's objects the member may create a record of, + // the object of the page the palette was opened on first. Only once + // something is typed: the empty palette is the recent records' screen. + const predicateScope = usePredicateScope(); + const { objectLabel } = useObjectLabel(); + const query = inputValue.trim(); + const createTargets: PaletteCreateTarget[] = + open && query !== '' && !inStudio + ? paletteCreateTargets( + searchableObjectNames, + objectsByName as ReadonlyMap, + perms, + predicateScope, + routeObjectName(location.pathname, searchableObjectNames), + ) + : []; + const createLabel = (target: PaletteCreateTarget) => + servedObjectLabel(target.def as { name: string; label?: unknown }, language, objectLabel, target.objectName); + // A "New OBJECT" entry, found by its label's words and the object's own label and name. + const newRecordRows = createTargets + .map((target) => { + const objectText = createLabel(target); + const label = t('console.objectView.newObject', { object: objectText, defaultValue: 'New {{object}}' }); + return { target, label, objectText }; + }) + .filter((row) => matches(row.label, row.objectText, row.target.objectName, NEW_RECORD_TERM)); + // "Create 'words' as OBJECT": the typed words seed the object's title field. + // Not for an object the query already names as a "New" entry — the words + // ask for that action then, not for a record called that. + const newRecordObjects = new Set(newRecordRows.map((row) => row.target.objectName)); + const createAsRows = createTargets + .filter((target) => target.prefillField && !newRecordObjects.has(target.objectName)) + .slice(0, CREATE_AS_MAX) + .map((target) => ({ target, objectText: createLabel(target) })); + return ( - + {isSearching || studio.loading ? ( @@ -569,7 +638,7 @@ function CommandPaletteBody(props: CommandPaletteProps & { gates: NavMemberGates key={`${hit.objectName}:${hit.recordId}`} // Stable across queries: cmdk filters nothing here // (`shouldFilter` false), it only selects by the value. - value={`record ${hit.display} ${hit.objectLabel} ${hit.objectName} ${hit.recordId}`} + value={recordHitValue(hit)} onSelect={() => leaveTo(`${recordHitBaseUrl(hit.objectName)}/${hit.objectName}/record/${hit.recordId}`)} > @@ -584,6 +653,46 @@ function CommandPaletteBody(props: CommandPaletteProps & { gates: NavMemberGates ); })} + + {/* objectstack#36286 — create a record: "Create 'words' as OBJECT" + below the results, then the "New OBJECT" entries the query finds. */} + {(createAsRows.length > 0 || newRecordRows.length > 0) && ( + + {createAsRows.map(({ target, objectText }) => ( + + leaveTo(paletteCreateHref(baseUrl, target.objectName, { field: target.prefillField!, value: query })) + } + > + + + {t('console.commandPalette.createAs', { + query, + object: objectText, + defaultValue: 'Create "{{query}}" as {{object}}', + })} + + + ))} + {newRecordRows.map(({ target, label }) => ( + leaveTo(paletteCreateHref(baseUrl, target.objectName))} + > + + {label} + + ))} + + )} + {/* Object Navigation */} {objectItems.length > 0 && ( @@ -765,6 +874,8 @@ function CommandPaletteBody(props: CommandPaletteProps & { gates: NavMemberGates )} + {showPreview && } + ); } @@ -786,6 +897,9 @@ function PaletteDialog({ title, description, contentProps, + value, + onValueChange, + wide, children, }: { open: boolean; @@ -793,14 +907,19 @@ function PaletteDialog({ title: ReactNode; description: ReactNode; contentProps: Record<`data-${string}`, string>; + /** The selected entry's cmdk value (objectstack#36286). */ + value: string; + onValueChange: (value: string) => void; + /** Room for the record preview beside the results (objectstack#36286). */ + wide: boolean; children: ReactNode; }) { return ( - + {title} {description} - + {children} @@ -808,9 +927,22 @@ function PaletteDialog({ ); } -/** The cmdk root's classes, as `CommandDialog` draws them. */ +/** + * The palette's width while a record preview is drawn beside the results + * (objectstack#36286): room for two halves. The preview pane itself shows only + * from a 45rem frame on (`PREVIEW_PANE_CLASS`), so a narrower window keeps the + * results alone. + */ +const PALETTE_WIDE_CLASS = 'sm:max-w-3xl'; + +/** + * The cmdk root's classes, as `CommandDialog` draws them, laid out as a grid + * (objectstack#36286): the input and the footer span the frame, the results + * and the record preview pane share the row between them. The root is also the + * container the pane's width query reads (`@container/palette`). + */ const PALETTE_COMMAND_CLASS = - '[&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground [&_[cmdk-group]:not([hidden])_~[cmdk-group]]:pt-0 [&_[cmdk-group]]:px-2 [&_[cmdk-input-wrapper]_svg]:h-5 [&_[cmdk-input-wrapper]_svg]:w-5 [&_[cmdk-input]]:h-12 [&_[cmdk-item]]:px-2 [&_[cmdk-item]]:py-3 [&_[cmdk-item]_svg]:h-5 [&_[cmdk-item]_svg]:w-5'; + '@container/palette grid grid-cols-[minmax(0,1fr)_auto] [&>[cmdk-input-wrapper]]:col-span-2 [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground [&_[cmdk-group]:not([hidden])_~[cmdk-group]]:pt-0 [&_[cmdk-group]]:px-2 [&_[cmdk-input-wrapper]_svg]:h-5 [&_[cmdk-input-wrapper]_svg]:w-5 [&_[cmdk-input]]:h-12 [&_[cmdk-item]]:px-2 [&_[cmdk-item]]:py-3 [&_[cmdk-item]_svg]:h-5 [&_[cmdk-item]_svg]:w-5'; /** The theme commands, matched by their label and their value (objectui#11812, objectstack#33061). */ const THEME_COMMANDS = [ @@ -819,6 +951,18 @@ const THEME_COMMANDS = [ { value: 'theme system', theme: 'system', Icon: Monitor }, ] as const; +/** + * A record hit's cmdk value (objectstack#36286 reads the selection back by it): + * stable across queries, since cmdk filters nothing here (`shouldFilter` + * false) and only selects by the value. + */ +function recordHitValue(hit: RecordSearchHit): string { + return `record ${hit.display} ${hit.objectLabel} ${hit.objectName} ${hit.recordId}`; +} + +/** A "New OBJECT" entry is also found by this word, in every language (objectstack#36286). */ +const NEW_RECORD_TERM = 'create new'; + /** The full-search command's value, matched beside its label (objectui#11812, objectstack#33061). */ const FULL_SEARCH_VALUE = 'search all results full page'; diff --git a/ui/packages/app-shell/src/chrome/PaletteEnterHint.tsx b/ui/packages/app-shell/src/chrome/PaletteEnterHint.tsx new file mode 100644 index 00000000000..5597cd4321c --- /dev/null +++ b/ui/packages/app-shell/src/chrome/PaletteEnterHint.tsx @@ -0,0 +1,73 @@ +/** + * ObjectUI + * Copyright (c) 2024-present ObjectStack Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +/** + * The ⌘K palette's footer (objectstack#36286): what Enter does to the entry + * the keyboard is on — open the record, create one, switch app, apply a + * theme, or open the page the entry names. + * + * The entry is named by its cmdk `value`, and every palette entry's value + * starts with the word for its kind (`record …`, `create …`, `app …`); the + * hint is read off that word, so an entry kind added without a word here + * reads "Open", the answer for every navigation entry. + */ + +import { Kbd } from '@object-ui/components'; +import { useObjectTranslation } from '@object-ui/i18n'; + +/** What Enter does, by the leading word of the selected entry's value. */ +export type PaletteEnterAction = 'openRecord' | 'create' | 'switchApp' | 'applyTheme' | 'open'; + +const ACTION_BY_KIND: Record = { + record: 'openRecord', + recent: 'openRecord', + create: 'create', + app: 'switchApp', + theme: 'applyTheme', +}; + +/** The action Enter runs on the entry whose cmdk value is `value`; `null` when nothing is selected. */ +export function paletteEnterAction(value: string | null | undefined): PaletteEnterAction | null { + const kind = (value ?? '').trim().split(/\s+/, 1)[0]?.toLowerCase() ?? ''; + if (kind === '') return null; + return ACTION_BY_KIND[kind] ?? 'open'; +} + +export function PaletteEnterHint({ value }: { value: string | null | undefined }) { + const { t } = useObjectTranslation(); + const action = paletteEnterAction(value); + // One literal key per action, so every key this asks for is greppable. + const label = (): string => { + switch (action) { + case 'openRecord': + return t('console.commandPalette.enterOpenRecord', { defaultValue: 'Open record' }); + case 'create': + return t('console.commandPalette.enterCreate', { defaultValue: 'Create' }); + case 'switchApp': + return t('console.commandPalette.enterSwitchApp', { defaultValue: 'Switch app' }); + case 'applyTheme': + return t('console.commandPalette.enterApplyTheme', { defaultValue: 'Apply theme' }); + default: + return t('console.commandPalette.enterOpen', { defaultValue: 'Open' }); + } + }; + return ( +
+ {action && ( + <> + {label()} + + + )} +
+ ); +} diff --git a/ui/packages/app-shell/src/chrome/PalettePreviewPane.tsx b/ui/packages/app-shell/src/chrome/PalettePreviewPane.tsx new file mode 100644 index 00000000000..bc189c574a0 --- /dev/null +++ b/ui/packages/app-shell/src/chrome/PalettePreviewPane.tsx @@ -0,0 +1,94 @@ +/** + * ObjectUI + * Copyright (c) 2024-present ObjectStack Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +/** + * The ⌘K palette's right-hand pane (objectstack#36286): the record hit the + * keyboard is on, drawn read-only, beside the results. + * + * It draws the record as `RecordPreviewCard` draws any record reference: the + * object's label, the record's title (the ADR-0079 ladder) and the object's + * declared key fields (`highlightFields`, ADR-0085) through the record page's + * own highlight strip, with field-level security applied to the row. An + * object that declares no key fields shows its title alone, as the record + * page's strip does: nothing is guessed. + * + * The card reads the record by id, one read per record shown. The pane hands + * it the selection only once the selection has rested for + * {@link PREVIEW_SETTLE_MS} (the record shown until then stays), so holding an + * arrow key through the results reads nothing on the way, and the card drops + * the answer of a read whose record is no longer the one shown. + * + * The pane is drawn only while the palette is at least 45rem (720px) wide, a + * container query on the palette's frame: a narrower palette shows the + * results alone, and never scrolls sideways. + */ + +import { useEffect, useState } from 'react'; +import { useObjectTranslation } from '@object-ui/i18n'; +import { RecordPreviewCard, type RecordPreviewSource } from '../views/record-preview/RecordPreviewCard.js'; + +/** How long a selection rests before the pane reads its record. */ +export const PREVIEW_SETTLE_MS = 150; + +/** The record a pane shows: the selected record hit's pair. */ +export interface PalettePreviewTarget { + objectName: string; + recordId: string; +} + +/** The pane's frame classes: hidden below a 45rem palette (see the module doc). */ +export const PREVIEW_PANE_CLASS = + 'hidden @min-[45rem]/palette:block w-[50cqw] max-h-[300px] min-w-0 overflow-y-auto border-l p-3'; + +/** + * `target` once it has stayed the same for `ms`. While a new target settles the + * previous one is still answered, so the pane does not blink between two + * records; with no target, nothing is. + */ +function useSettledTarget(target: PalettePreviewTarget | null, ms: number): PalettePreviewTarget | null { + // Keyed on the pair's text, never on the object handed in (ui/AGENTS.md #10). + const objectName = target?.objectName ?? null; + const recordId = target?.recordId ?? null; + const [settled, setSettled] = useState(null); + useEffect(() => { + if (objectName === null || recordId === null) { + setSettled(null); + return; + } + const timer = setTimeout(() => setSettled({ objectName, recordId }), ms); + return () => clearTimeout(timer); + }, [objectName, recordId, ms]); + return objectName !== null && recordId !== null ? settled : null; +} + +export function PalettePreviewPane({ + target, + dataSource, +}: { + /** The selected record hit, or `null` when the selection is not a record hit. */ + target: PalettePreviewTarget | null; + dataSource?: RecordPreviewSource | null; +}) { + const { t } = useObjectTranslation(); + const settled = useSettledTarget(target, PREVIEW_SETTLE_MS); + return ( + + ); +} diff --git a/ui/packages/app-shell/src/chrome/paletteCreate.ts b/ui/packages/app-shell/src/chrome/paletteCreate.ts new file mode 100644 index 00000000000..9e3c3ae4743 --- /dev/null +++ b/ui/packages/app-shell/src/chrome/paletteCreate.ts @@ -0,0 +1,167 @@ +/** + * ObjectUI + * Copyright (c) 2024-present ObjectStack Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +/** + * The ⌘K palette's create rows (objectstack#36286): which of the app's objects + * the member may create a record of, and the address each create opens. + * + * An object is offered exactly where the object list offers its New: the + * `listNew` verdict of `resolveAffordance` (the spec's CRUD bucket and + * `userActions`, intersected with the server's effective API operations and + * the caller's create grant), then the create action's toolbar-scope + * predicates, bound with no record as the list's toolbar binds them: + * `visibleWhen` fails closed, `disabledWhen` fails soft. A greyed New is not + * offered here: the palette draws no disabled row. + * + * A create opens the object's create page, `/apps/APP/OBJECT/new`, the route + * the bare data surface's New and a related list's New open. A "create as" + * row carries the typed words as that page's query-string prefill of the + * object's title field (`resolveNameField`, the ADR-0079 ladder), and is + * offered only where that field is a plain text field the member may write + * on create (`createFormFields`), so the words always land in the form. + */ + +import { + evalRowPredicate, + resolveAffordance, + resolveFieldAffordance, + resolveNameField, + type AffordanceGrantPrincipal, + type AffordanceSource, + type FieldAffordancePrincipal, + type RowCrudPredicates, +} from '@object-ui/core'; + +/** The object definition keys the create rows read. */ +export interface PaletteCreateObjectDef { + name: string; + label?: unknown; + icon?: unknown; + color?: unknown; + fields?: Record | unknown; + [key: string]: unknown; +} + +/** What the create rows ask of the permission provider: `usePermissions()`. */ +export type PaletteCreatePerms = AffordanceGrantPrincipal & FieldAffordancePrincipal; + +/** One object the member may create a record of. */ +export interface PaletteCreateTarget { + objectName: string; + def: PaletteCreateObjectDef; + /** The field a "create as" row fills with the typed words; absent ⇒ no such row. */ + prefillField?: string; +} + +/** At most this many "create as" rows are drawn, the route's own object first. */ +export const CREATE_AS_MAX = 3; + +/** Field types that hold the typed words as they are. */ +const PREFILLABLE_TYPES = new Set(['text', 'textarea']); + +/** + * The create action's toolbar-scope predicate, bound with no record, the way + * `useRowPredicate(pred, null, …)` binds it for the list's New. + */ +function toolbarPredicate(pred: unknown, fallback: boolean, scope: Record, label: string): boolean { + if (typeof pred === 'boolean') return pred; + if (pred == null || pred === '') return fallback; + return evalRowPredicate(pred as Parameters[0], null, { + fallback, + scope, + warnOnError: true, + label, + }); +} + +/** May the member create a record of `def` from a toolbar with no record in scope? */ +export function paletteMayCreate( + def: PaletteCreateObjectDef, + perms: PaletteCreatePerms | undefined, + scope: Record, +): boolean { + const verdict = resolveAffordance('listNew', { + objectSchema: def as AffordanceSource['objectSchema'], + objectName: def.name, + perms, + }); + if (!verdict.allowed) return false; + const predicates: RowCrudPredicates | undefined = verdict.predicates; + if (!toolbarPredicate(predicates?.visibleWhen ?? true, false, scope, 'builtin:create:visibleWhen')) return false; + const disabled = + predicates?.disabledWhen != null && + toolbarPredicate(predicates.disabledWhen, false, scope, 'builtin:create:disabledWhen'); + return !disabled; +} + +/** The title field a create may be seeded with, or `undefined`. */ +export function palettePrefillField(def: PaletteCreateObjectDef, perms: PaletteCreatePerms | undefined): string | undefined { + const name = resolveNameField(def); + if (!name) return undefined; + const fields = def.fields && typeof def.fields === 'object' && !Array.isArray(def.fields) + ? (def.fields as Record) + : undefined; + const field = fields?.[name]; + if (!field || typeof field.type !== 'string' || !PREFILLABLE_TYPES.has(field.type)) return undefined; + if (field.readonly === true) return undefined; + if (!resolveFieldAffordance('createFormFields', perms, def.name, name)) return undefined; + return name; +} + +/** + * The objects of `objectNames` (the app's navigation objects, in its order) + * the member may create a record of, `currentObjectName` first when it is one + * of them. + */ +export function paletteCreateTargets( + objectNames: readonly string[], + objectsByName: ReadonlyMap, + perms: PaletteCreatePerms | undefined, + scope: Record, + currentObjectName?: string, +): PaletteCreateTarget[] { + const seen = new Set(); + const targets: PaletteCreateTarget[] = []; + for (const name of objectNames) { + if (seen.has(name)) continue; + seen.add(name); + const def = objectsByName.get(name); + if (!def || !paletteMayCreate(def, perms, scope)) continue; + targets.push({ objectName: name, def, prefillField: palettePrefillField(def, perms) }); + } + const current = targets.findIndex((target) => target.objectName === currentObjectName); + if (current > 0) targets.unshift(...targets.splice(current, 1)); + return targets; +} + +/** The address a create opens: the object's create page, seeded when `prefill` names a field. */ +export function paletteCreateHref( + baseUrl: string, + objectName: string, + prefill?: { field: string; value: string }, +): string { + const page = `${baseUrl}/${encodeURIComponent(objectName)}/new`; + if (!prefill) return page; + return `${page}?${new URLSearchParams([[prefill.field, prefill.value]]).toString()}`; +} + +/** + * The object of the page the palette was opened on, read off its address + * (`/apps/APP/OBJECT…`), when it is one of `objectNames`. + */ +export function routeObjectName(pathname: string, objectNames: readonly string[]): string | undefined { + const segment = /^\/apps\/[^/]+\/([^/?#]+)/.exec(pathname)?.[1]; + if (!segment) return undefined; + let name: string; + try { + name = decodeURIComponent(segment); + } catch { + return undefined; + } + return objectNames.includes(name) ? name : undefined; +} diff --git a/ui/packages/i18n/src/locales/ar.ts b/ui/packages/i18n/src/locales/ar.ts index 1fa0256b476..781b238aa2f 100644 --- a/ui/packages/i18n/src/locales/ar.ts +++ b/ui/packages/i18n/src/locales/ar.ts @@ -2899,6 +2899,14 @@ const ar = { systemTheme: "مظهر النظام", actions: "الإجراءات", openFullSearch: "فتح صفحة البحث الكاملة", + create: "إنشاء", + createAs: "إنشاء «{{query}}» كـ {{object}}", + previewEmpty: "اختر سجلاً لعرض تفاصيله.", + enterOpenRecord: "فتح السجل", + enterCreate: "إنشاء", + enterSwitchApp: "تبديل التطبيق", + enterApplyTheme: "تطبيق المظهر", + enterOpen: "فتح", searching: "جارٍ البحث…", records: "السجلات", recentRecords: "شوهد مؤخراً", diff --git a/ui/packages/i18n/src/locales/de.ts b/ui/packages/i18n/src/locales/de.ts index 7791b59d402..cc0200dc593 100644 --- a/ui/packages/i18n/src/locales/de.ts +++ b/ui/packages/i18n/src/locales/de.ts @@ -2611,6 +2611,14 @@ const de = { systemTheme: "Systemdesign", actions: "Aktionen", openFullSearch: "Vollständige Suchseite öffnen", + create: "Erstellen", + createAs: "„{{query}}“ als {{object}} erstellen", + previewEmpty: "Wählen Sie einen Datensatz, um seine Details zu sehen.", + enterOpenRecord: "Datensatz öffnen", + enterCreate: "Erstellen", + enterSwitchApp: "App wechseln", + enterApplyTheme: "Design anwenden", + enterOpen: "Öffnen", searching: "Suche…", records: "Datensätze", recentRecords: "Zuletzt angesehen", diff --git a/ui/packages/i18n/src/locales/en.ts b/ui/packages/i18n/src/locales/en.ts index 06a2ea41f63..c27373fb642 100644 --- a/ui/packages/i18n/src/locales/en.ts +++ b/ui/packages/i18n/src/locales/en.ts @@ -2796,6 +2796,14 @@ const en = { systemTheme: 'System Theme', actions: 'Actions', openFullSearch: 'Open Full Search Page', + create: 'Create', + createAs: 'Create "{{query}}" as {{object}}', + previewEmpty: 'Select a record to see its details.', + enterOpenRecord: 'Open record', + enterCreate: 'Create', + enterSwitchApp: 'Switch app', + enterApplyTheme: 'Apply theme', + enterOpen: 'Open', }, ai: { pendingDrafts: { diff --git a/ui/packages/i18n/src/locales/es.ts b/ui/packages/i18n/src/locales/es.ts index 84b4753fdef..fcb9c8a008a 100644 --- a/ui/packages/i18n/src/locales/es.ts +++ b/ui/packages/i18n/src/locales/es.ts @@ -2685,6 +2685,14 @@ const es = { systemTheme: "Tema del sistema", actions: "Acciones", openFullSearch: "Abrir página de búsqueda completa", + create: "Crear", + createAs: "Crear «{{query}}» como {{object}}", + previewEmpty: "Selecciona un registro para ver sus detalles.", + enterOpenRecord: "Abrir registro", + enterCreate: "Crear", + enterSwitchApp: "Cambiar aplicación", + enterApplyTheme: "Aplicar tema", + enterOpen: "Abrir", searching: "Buscando…", records: "Registros", recentRecords: "Visto recientemente", diff --git a/ui/packages/i18n/src/locales/fr.ts b/ui/packages/i18n/src/locales/fr.ts index e5f07ac6881..70f7a8c4b65 100644 --- a/ui/packages/i18n/src/locales/fr.ts +++ b/ui/packages/i18n/src/locales/fr.ts @@ -2681,6 +2681,14 @@ const fr = { systemTheme: "Thème système", actions: "Actions", openFullSearch: "Ouvrir la page de recherche complète", + create: "Créer", + createAs: "Créer « {{query}} » comme {{object}}", + previewEmpty: "Sélectionnez un enregistrement pour voir ses détails.", + enterOpenRecord: "Ouvrir l'enregistrement", + enterCreate: "Créer", + enterSwitchApp: "Changer d'application", + enterApplyTheme: "Appliquer le thème", + enterOpen: "Ouvrir", searching: "Recherche…", records: "Enregistrements", recentRecords: "Récemment consultés", diff --git a/ui/packages/i18n/src/locales/ja.ts b/ui/packages/i18n/src/locales/ja.ts index 056bf21a38b..d6e2b9f06cb 100644 --- a/ui/packages/i18n/src/locales/ja.ts +++ b/ui/packages/i18n/src/locales/ja.ts @@ -2613,6 +2613,14 @@ const ja = { systemTheme: "システムテーマ", actions: "アクション", openFullSearch: "完全な検索ページを開く", + create: "新規作成", + createAs: "「{{query}}」を{{object}}として作成", + previewEmpty: "レコードを選択すると詳細が表示されます。", + enterOpenRecord: "レコードを開く", + enterCreate: "作成", + enterSwitchApp: "アプリを切り替え", + enterApplyTheme: "テーマを適用", + enterOpen: "開く", searching: "検索中…", records: "レコード", recentRecords: "最近閲覧", diff --git a/ui/packages/i18n/src/locales/ko.ts b/ui/packages/i18n/src/locales/ko.ts index 92f7645689c..d6c2cdbaa4a 100644 --- a/ui/packages/i18n/src/locales/ko.ts +++ b/ui/packages/i18n/src/locales/ko.ts @@ -2611,6 +2611,14 @@ const ko = { systemTheme: "시스템 테마", actions: "작업", openFullSearch: "전체 검색 페이지 열기", + create: "만들기", + createAs: "'{{query}}'을(를) {{object}}(으)로 만들기", + previewEmpty: "레코드를 선택하면 세부 정보가 표시됩니다.", + enterOpenRecord: "레코드 열기", + enterCreate: "만들기", + enterSwitchApp: "앱 전환", + enterApplyTheme: "테마 적용", + enterOpen: "열기", searching: "검색 중…", records: "레코드", recentRecords: "최근 본 항목", diff --git a/ui/packages/i18n/src/locales/pt-BR.ts b/ui/packages/i18n/src/locales/pt-BR.ts index 0f89efbb6fc..a425c644dd4 100644 --- a/ui/packages/i18n/src/locales/pt-BR.ts +++ b/ui/packages/i18n/src/locales/pt-BR.ts @@ -2680,6 +2680,14 @@ const pt = { systemTheme: "Tema do sistema", actions: "Ações", openFullSearch: "Abrir página de pesquisa completa", + create: "Criar", + createAs: "Criar “{{query}}” como {{object}}", + previewEmpty: "Selecione um registro para ver os detalhes.", + enterOpenRecord: "Abrir registro", + enterCreate: "Criar", + enterSwitchApp: "Trocar aplicativo", + enterApplyTheme: "Aplicar tema", + enterOpen: "Abrir", searching: "Pesquisando…", records: "Registros", recentRecords: "Vistos recentemente", diff --git a/ui/packages/i18n/src/locales/ru.ts b/ui/packages/i18n/src/locales/ru.ts index aea162b0410..0fe0d41e7c9 100644 --- a/ui/packages/i18n/src/locales/ru.ts +++ b/ui/packages/i18n/src/locales/ru.ts @@ -2761,6 +2761,14 @@ const ru = { systemTheme: "Системная тема", actions: "Действия", openFullSearch: "Открыть полную страницу поиска", + create: "Создать", + createAs: "Создать «{{query}}» как {{object}}", + previewEmpty: "Выберите запись, чтобы увидеть подробности.", + enterOpenRecord: "Открыть запись", + enterCreate: "Создать", + enterSwitchApp: "Переключить приложение", + enterApplyTheme: "Применить тему", + enterOpen: "Открыть", searching: "Поиск…", records: "Записи", recentRecords: "Недавно просмотренные", diff --git a/ui/packages/i18n/src/locales/zh-Hans.ts b/ui/packages/i18n/src/locales/zh-Hans.ts index cc782f9a597..a3acb8a421c 100644 --- a/ui/packages/i18n/src/locales/zh-Hans.ts +++ b/ui/packages/i18n/src/locales/zh-Hans.ts @@ -2354,6 +2354,14 @@ const zh = { systemTheme: '系统主题', actions: '操作', openFullSearch: '打开完整搜索页面', + create: '新建', + createAs: '新建「{{query}}」为{{object}}', + previewEmpty: '选中一条记录即可查看详情。', + enterOpenRecord: '打开记录', + enterCreate: '新建', + enterSwitchApp: '切换应用', + enterApplyTheme: '应用主题', + enterOpen: '打开', }, ai: { pendingDrafts: { diff --git a/ui/packages/i18n/src/locales/zh-Hant.ts b/ui/packages/i18n/src/locales/zh-Hant.ts index 4c10186e75a..8683ae0fdb6 100644 --- a/ui/packages/i18n/src/locales/zh-Hant.ts +++ b/ui/packages/i18n/src/locales/zh-Hant.ts @@ -2354,6 +2354,14 @@ const zhHant = { systemTheme: '系統主題', actions: '操作', openFullSearch: '開啟完整搜尋頁面', + create: '新建', + createAs: '新建「{{query}}」為{{object}}', + previewEmpty: '選取一筆記錄即可查看詳細資料。', + enterOpenRecord: '開啟記錄', + enterCreate: '新建', + enterSwitchApp: '切換應用', + enterApplyTheme: '套用主題', + enterOpen: '開啟', }, ai: { pendingDrafts: { From f08a76c92e1f64eff33b6cbf6d8651d978130d26 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 07:49:35 +0000 Subject: [PATCH 2/7] feat(app-shell): palette create rows at the end of the list; tests, changeset, README Claude-Session: https://claude.ai/code/session_01QsR2jV3scu6UYPb42n5okQ Co-authored-by: Claude --- .changeset/36286-palette-preview-create.md | 18 + ui/packages/app-shell/README.md | 10 + ...ommandPalette.previewCreate-36286.test.tsx | 333 ++++++++++++++++++ .../app-shell/src/chrome/CommandPalette.tsx | 82 +++-- 4 files changed, 404 insertions(+), 39 deletions(-) create mode 100644 .changeset/36286-palette-preview-create.md create mode 100644 ui/packages/app-shell/src/chrome/CommandPalette.previewCreate-36286.test.tsx diff --git a/.changeset/36286-palette-preview-create.md b/.changeset/36286-palette-preview-create.md new file mode 100644 index 00000000000..fe0bf0369a2 --- /dev/null +++ b/.changeset/36286-palette-preview-create.md @@ -0,0 +1,18 @@ +--- +'@object-ui/app-shell': patch +'@object-ui/i18n': patch +--- + +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 + +Clause-②: no +Metadata-protocol: none + +The command palette inside an app gains four things; which records it searches, and how it ranks them, are unchanged. + +- **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. +- **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. +- **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. +- **Enter hint.** A footer names what Enter does to the selected entry: Open record, Create, Switch app, Apply theme or Open. + +New locale keys, in every pack: `console.commandPalette.create`, `createAs`, `previewEmpty`, `enterOpenRecord`, `enterCreate`, `enterSwitchApp`, `enterApplyTheme`, `enterOpen`. No props or package exports change. diff --git a/ui/packages/app-shell/README.md b/ui/packages/app-shell/README.md index 512b5271025..9e2bc8f6172 100644 --- a/ui/packages/app-shell/README.md +++ b/ui/packages/app-shell/README.md @@ -1426,6 +1426,16 @@ bar's middle zone, centered between the left group and the utility cluster. In the `home`, `orgs` and `studio` frames, and below `lg` (as an icon button), it sits at the utility cluster's left edge. +Inside an app, while the query finds records, the palette shows the selected +hit on the right, read-only: its title and the object's declared +`highlightFields`, as the record pointer card draws them (a palette narrower +than 45rem shows the results alone). Once something is typed, the end of the +list offers "New OBJECT" for the app's objects the query names and "Create +"words" as OBJECT" for up to three of them, the page's own object first; each +opens the object's create page (`/apps/APP/OBJECT/new`), the second with the +words in its title field. An object is offered exactly where its list offers +New. A footer names what Enter does to the selected entry. + ```tsx import { useCommandPalette } from '@object-ui/app-shell'; diff --git a/ui/packages/app-shell/src/chrome/CommandPalette.previewCreate-36286.test.tsx b/ui/packages/app-shell/src/chrome/CommandPalette.previewCreate-36286.test.tsx new file mode 100644 index 00000000000..8ae429c0b36 --- /dev/null +++ b/ui/packages/app-shell/src/chrome/CommandPalette.previewCreate-36286.test.tsx @@ -0,0 +1,333 @@ +/** + * ObjectUI + * Copyright (c) 2024-present ObjectStack Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +/** + * The ⌘K palette previews the record hit it is on, offers to create a record + * from what was typed, finds "New OBJECT" entries, and says what Enter does + * (objectstack#36286). + * + * Pinned against the real `CommandPaletteProvider` (opened through its + * `?palette=1` deep link) over the per-object `find` fanout, with the record + * preview reading the record through the data source's `findOne`. Where Enter + * went is read off the router. + */ + +import * as React from 'react'; +import { describe, it, expect, vi, afterEach } from 'vitest'; +import { render, fireEvent, waitFor, cleanup, screen, act } from '@testing-library/react'; +import { MemoryRouter, useLocation } from 'react-router-dom'; +import { MetadataCtx } from '@object-ui/react'; + +vi.mock('@object-ui/auth', async (importOriginal) => ({ + ...(await importOriginal>()), + useAuth: () => ({ user: { id: 'u1' }, activeOrganization: null }), +})); + +/** The member may read everything and create everything but an invoice. */ +const PERMS = { + isLoaded: true, + can: (object: string, action: string) => !(object === 'invoice_36286' && action === 'create'), + cannot: (object: string, action: string) => object === 'invoice_36286' && action === 'create', + check: () => ({ allowed: true }), + checkField: () => true, + getFieldPermissions: () => [], + getRowFilter: () => undefined, + getObjectApiOperations: () => undefined, + roles: [], + userId: 'u1', + systemPermissions: undefined, + hasCapabilities: () => true, + hasAnyQueue: undefined, + objectsUsingQueues: undefined, +}; +vi.mock('@object-ui/permissions', async (importOriginal) => ({ + ...(await importOriginal>()), + usePermissions: () => PERMS, +})); + +// The preview's key fields draw through `lazy()`: load the detail entry at +// module scope, so its cost is paid at import (ui/AGENTS.md, lazy boundaries). +import '@object-ui/plugin-detail'; + +import { CommandPalette } from './CommandPalette'; +import { CommandPaletteProvider } from '../context/CommandPaletteProvider'; +import { paletteEnterAction } from './PaletteEnterHint'; +import { paletteCreateTargets, palettePrefillField, routeObjectName } from './paletteCreate'; + +const CUSTOMER = 'customer_36286'; +const CONTACT = 'contact_36286'; +const INVOICE = 'invoice_36286'; + +const OBJECTS = [ + { + name: CUSTOMER, + label: 'Customer', + nameField: 'name', + highlightFields: ['industry', 'phone'], + fields: { + name: { type: 'text', label: 'Customer Name' }, + industry: { type: 'text', label: 'Industry' }, + phone: { type: 'text', label: 'Phone' }, + }, + }, + { name: CONTACT, label: 'Contact', nameField: 'full_name', fields: { full_name: { type: 'text', label: 'Full Name' } } }, + { name: INVOICE, label: 'Invoice', nameField: 'subject', fields: { subject: { type: 'text', label: 'Subject' } } }, +]; + +const ROWS: Record>> = { + [CUSTOMER]: [ + { id: 'C1', name: 'Qingdao Haichen Foods', industry: 'Food processing', phone: '0532-1000' }, + { id: 'C2', name: 'Qingdao Harbour Logistics', industry: 'Logistics', phone: '0532-2000' }, + ], + [CONTACT]: [], + [INVOICE]: [], +}; + +const CRM = { + name: 'crm', + label: 'CRM', + navigation: [ + { id: 'n_contact', type: 'object', objectName: CONTACT, label: 'Contacts' }, + { id: 'n_invoice', type: 'object', objectName: INVOICE, label: 'Invoices' }, + { id: 'n_customer', type: 'object', objectName: CUSTOMER, label: 'Customers' }, + ], +}; +const SALES = { name: 'sales', label: 'Sales', navigation: [] }; + +function metadataValue() { + return { + apps: [], + objects: [], + dashboards: [], + reports: [], + pages: [], + loading: false, + error: null, + refresh: async () => {}, + invalidate: () => {}, + ensureType: async () => [], + getItem: async (type: string, name: string) => (type === 'object' ? OBJECTS.find((o) => o.name === name) ?? null : null), + getItemsByType: () => [], + getTypeStatus: () => 'ready' as const, + }; +} + +function Probe() { + const location = useLocation(); + return ; +} + +function mount(path = `/apps/crm/${CUSTOMER}`) { + const ds = { + find: vi.fn(async (name: string, params: { $search?: string }) => ({ + data: (ROWS[name] ?? []).filter((row) => + String(row.name ?? '').toLowerCase().includes(String(params?.$search ?? '').toLowerCase()), + ), + })), + findOne: vi.fn(async (name: string, id: string) => (ROWS[name] ?? []).find((row) => row.id === id) ?? null), + }; + const metadata = metadataValue(); + render( + + + + + {}} dataSource={ds} /> + + + , + ); + const input = document.querySelector('[cmdk-input]') as HTMLInputElement | null; + if (!input) throw new Error('the palette did not open'); + return { ds, input }; +} + +const type = (input: HTMLInputElement, value: string) => fireEvent.change(input, { target: { value } }); +const press = (input: HTMLInputElement, key: string) => fireEvent.keyDown(input, { key }); +const pane = () => screen.queryByTestId('palette-preview'); +const hint = () => screen.getByTestId('palette-enter-hint').getAttribute('data-enter-action'); +const selected = () => document.querySelector('[cmdk-item][data-selected="true"]')?.getAttribute('data-value'); +const values = (prefix: string) => + Array.from(document.querySelectorAll(`[cmdk-item][data-value^="${prefix}"]`)).map((el) => el.getAttribute('data-value')); +const location = () => { + const probe = screen.getByTestId('location'); + return `${probe.getAttribute('data-path')}${probe.getAttribute('data-search')}`; +}; + +async function recordHitsShown(count: number) { + await waitFor(() => expect(values('record ')).toHaveLength(count), { timeout: 4000 }); +} + +afterEach(() => cleanup()); + +describe('objectstack#36286 — a record hit is previewed beside the results', () => { + it('draws the selected hit read-only: its title and the object\'s declared key fields; Enter opens the record', async () => { + const { ds, input } = mount(); + type(input, 'haichen'); + await recordHitsShown(1); + + // The palette widens for two halves, and the pane follows the selection. + expect(document.querySelector('[role="dialog"]')?.className).toContain('sm:max-w-3xl'); + await waitFor(() => expect(pane()?.querySelector('[data-record-preview="readable"]')).not.toBeNull(), { timeout: 4000 }); + expect(pane()).toHaveTextContent('Qingdao Haichen Foods'); + expect(await screen.findByText('Food processing')).toBeInTheDocument(); + expect(pane()).toHaveTextContent('Industry'); + expect(ds.findOne).toHaveBeenCalledWith(CUSTOMER, 'C1'); + expect(hint()).toBe('openRecord'); + + press(input, 'Enter'); + expect(location()).toBe(`/apps/crm/${CUSTOMER}/record/C1`); + }); + + it('ArrowDown moves the preview to the second hit, reading only the record it settles on', async () => { + const { ds, input } = mount(); + type(input, 'qingdao'); + await recordHitsShown(2); + await waitFor(() => expect(pane()?.getAttribute('data-preview-record')).toBe('C1'), { timeout: 4000 }); + + press(input, 'ArrowDown'); + await waitFor(() => expect(pane()?.getAttribute('data-preview-record')).toBe('C2'), { timeout: 4000 }); + await waitFor(() => expect(pane()).toHaveTextContent('Qingdao Harbour Logistics'), { timeout: 4000 }); + expect(pane()).toHaveTextContent('Logistics'); + expect(ds.findOne.mock.calls.map((call) => call[1])).toEqual(['C1', 'C2']); + }); + + it('the pane shows only from a 45rem palette: a container query on the palette frame', async () => { + const { input } = mount(); + type(input, 'haichen'); + await recordHitsShown(1); + expect(document.querySelector('[cmdk-root]')?.className).toContain('@container/palette'); + expect(pane()?.className).toMatch(/(^| )hidden( |$)/); + expect(pane()?.className).toContain('@min-[45rem]/palette:block'); + }); + + it('CONTROL: no record hit, no pane and no wide palette', async () => { + const { input } = mount(); + type(input, 'zhang san'); + await waitFor(() => expect(values('create as ')).not.toHaveLength(0)); + await act(async () => { + await new Promise((resolve) => setTimeout(resolve, 400)); + }); + expect(pane()).toBeNull(); + expect(document.querySelector('[role="dialog"]')?.className).not.toContain('sm:max-w-3xl'); + }); +}); + +describe('objectstack#36286 — "Create \'words\' as OBJECT" below the results', () => { + it('lists the creatable objects, the page\'s own object first; Enter opens its create form seeded with the words', async () => { + const { input } = mount(); + type(input, 'Zhang San'); + await waitFor(() => expect(values('create as ')).toEqual([`create as ${CUSTOMER}`, `create as ${CONTACT}`])); + expect(screen.getByText('Create "Zhang San" as Customer')).toBeInTheDocument(); + // No create grant on invoices: no row offers to create one. + expect(values('create ').some((value) => value?.includes(INVOICE))).toBe(false); + + expect(selected()).toBe(`create as ${CUSTOMER}`); + expect(hint()).toBe('create'); + press(input, 'Enter'); + expect(location()).toBe(`/apps/crm/${CUSTOMER}/new?name=Zhang+San`); + }); + + it('on a page of no object, the app\'s navigation order stands', async () => { + const { input } = mount('/apps/crm'); + type(input, 'Zhang San'); + await waitFor(() => expect(values('create as ')).toEqual([`create as ${CONTACT}`, `create as ${CUSTOMER}`])); + }); + + it('CONTROL: the empty palette offers no create row', async () => { + mount(); + await act(async () => {}); + expect(values('create ')).toEqual([]); + }); + + it('clearing the query takes the create rows away again', async () => { + const { input } = mount(); + type(input, 'Zhang San'); + await waitFor(() => expect(values('create as ')).not.toHaveLength(0)); + type(input, ''); + await waitFor(() => expect(values('create ')).toEqual([])); + }); +}); + +describe('objectstack#36286 — "New OBJECT" entries', () => { + it('"new" finds one per object the member may create, never one it may not', async () => { + const { input } = mount(); + type(input, 'new'); + await waitFor(() => expect(values('create new ')).toEqual([`create new ${CUSTOMER}`, `create new ${CONTACT}`])); + expect(screen.getByText('New Customer')).toBeInTheDocument(); + expect(screen.getByText('New Contact')).toBeInTheDocument(); + expect(screen.queryByText('New Invoice')).toBeNull(); + // The query names the action, not a record called "new". + expect(values('create as ')).toEqual([]); + }); + + it('an object\'s own name finds its entry; Enter opens its empty create form', async () => { + const { input } = mount('/apps/crm'); + type(input, 'contact'); + await waitFor(() => expect(values('create new ')).toEqual([`create new ${CONTACT}`])); + // The other creatable object still takes the words as a record name. + expect(values('create as ')).toEqual([`create as ${CUSTOMER}`]); + act(() => { + fireEvent.click(document.querySelector(`[cmdk-item][data-value="create new ${CONTACT}"]`)!); + }); + expect(location()).toBe(`/apps/crm/${CONTACT}/new`); + }); +}); + +describe('objectstack#36286 — the footer says what Enter does', () => { + it('reads the action off the selected entry\'s kind', () => { + expect(paletteEnterAction(`record Qingdao Customer ${CUSTOMER} C1`)).toBe('openRecord'); + expect(paletteEnterAction('recent Qingdao C1')).toBe('openRecord'); + expect(paletteEnterAction(`create as ${CUSTOMER}`)).toBe('create'); + expect(paletteEnterAction(`create new ${CUSTOMER}`)).toBe('create'); + expect(paletteEnterAction('app Sales sales')).toBe('switchApp'); + expect(paletteEnterAction('theme dark')).toBe('applyTheme'); + expect(paletteEnterAction(`object Customers ${CUSTOMER}`)).toBe('open'); + expect(paletteEnterAction('search all results full page')).toBe('open'); + expect(paletteEnterAction('')).toBeNull(); + }); + + it('an app entry says Switch app', async () => { + const { input } = mount(); + type(input, 'sales'); + await waitFor(() => expect(selected()).toBe('app Sales sales')); + expect(hint()).toBe('switchApp'); + expect(screen.getByTestId('palette-enter-hint')).toHaveTextContent('Switch app'); + }); +}); + +describe('objectstack#36286 — which objects a create row offers', () => { + const byName = new Map(OBJECTS.map((o) => [o.name, o])); + const names = OBJECTS.map((o) => o.name); + + it('the create action\'s toolbar visibleWhen (fails closed) and disabledWhen hide an object', () => { + const hidden = { ...OBJECTS[1], userActions: { create: { visibleWhen: 'false' } } }; + const greyed = { ...OBJECTS[0], userActions: { create: { disabledWhen: 'true' } } }; + const map = new Map([[CUSTOMER, greyed], [CONTACT, hidden], [INVOICE, OBJECTS[2]]]); + expect(paletteCreateTargets(names, map, PERMS as never, {}).map((t) => t.objectName)).toEqual([]); + expect(paletteCreateTargets(names, byName as never, PERMS as never, {}).map((t) => t.objectName)).toEqual([ + CUSTOMER, + CONTACT, + ]); + }); + + it('only a writable text title field takes the typed words', () => { + const base = OBJECTS[1]; + expect(palettePrefillField(base as never, PERMS as never)).toBe('full_name'); + expect(palettePrefillField({ ...base, fields: { full_name: { type: 'lookup' } } } as never, PERMS as never)).toBeUndefined(); + expect(palettePrefillField({ ...base, fields: { full_name: { type: 'text', readonly: true } } } as never, PERMS as never)).toBeUndefined(); + const noCreateField = { ...PERMS, checkField: () => false }; + expect(palettePrefillField(base as never, noCreateField as never)).toBeUndefined(); + }); + + it('the route\'s object is read off /apps/APP/OBJECT, only when the app lists it', () => { + expect(routeObjectName(`/apps/crm/${CUSTOMER}/record/C1`, names)).toBe(CUSTOMER); + expect(routeObjectName('/apps/crm/dashboard/sales', names)).toBeUndefined(); + expect(routeObjectName('/apps/crm', names)).toBeUndefined(); + }); +}); diff --git a/ui/packages/app-shell/src/chrome/CommandPalette.tsx b/ui/packages/app-shell/src/chrome/CommandPalette.tsx index 2577a269ddd..2776106cbbc 100644 --- a/ui/packages/app-shell/src/chrome/CommandPalette.tsx +++ b/ui/packages/app-shell/src/chrome/CommandPalette.tsx @@ -654,45 +654,6 @@ function CommandPaletteBody(props: CommandPaletteProps & { gates: NavMemberGates ); })} - {/* objectstack#36286 — create a record: "Create 'words' as OBJECT" - below the results, then the "New OBJECT" entries the query finds. */} - {(createAsRows.length > 0 || newRecordRows.length > 0) && ( - - {createAsRows.map(({ target, objectText }) => ( - - leaveTo(paletteCreateHref(baseUrl, target.objectName, { field: target.prefillField!, value: query })) - } - > - - - {t('console.commandPalette.createAs', { - query, - object: objectText, - defaultValue: 'Create "{{query}}" as {{object}}', - })} - - - ))} - {newRecordRows.map(({ target, label }) => ( - leaveTo(paletteCreateHref(baseUrl, target.objectName))} - > - - {label} - - ))} - - )} - {/* Object Navigation */} {objectItems.length > 0 && ( @@ -857,6 +818,49 @@ function CommandPaletteBody(props: CommandPaletteProps & { gates: NavMemberGates )} + {/* objectstack#36286 — create a record, below every result: the + "New OBJECT" entries the query finds, then "Create 'words' as + OBJECT". Last, so Enter on a query that finds something opens it. */} + {(newRecordRows.length > 0 || createAsRows.length > 0) && ( + <> + + + {newRecordRows.map(({ target, label }) => ( + leaveTo(paletteCreateHref(baseUrl, target.objectName))} + > + + {label} + + ))} + {createAsRows.map(({ target, objectText }) => ( + + leaveTo(paletteCreateHref(baseUrl, target.objectName, { field: target.prefillField!, value: query })) + } + > + + + {t('console.commandPalette.createAs', { + query, + object: objectText, + defaultValue: 'Create "{{query}}" as {{object}}', + })} + + + ))} + + + )} + {/* Full Search Page */} {showFullSearch && ( <> From df3f42501601a30521c5f0cc5fbe926c15f7a3cb Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 08:00:17 +0000 Subject: [PATCH 3/7] fix(app-shell): a new set of record hits takes the palette selection Claude-Session: https://claude.ai/code/session_01QsR2jV3scu6UYPb42n5okQ Co-authored-by: Claude --- ui/packages/app-shell/src/chrome/CommandPalette.tsx | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/ui/packages/app-shell/src/chrome/CommandPalette.tsx b/ui/packages/app-shell/src/chrome/CommandPalette.tsx index 2776106cbbc..19937945c8a 100644 --- a/ui/packages/app-shell/src/chrome/CommandPalette.tsx +++ b/ui/packages/app-shell/src/chrome/CommandPalette.tsx @@ -503,6 +503,16 @@ function CommandPaletteBody(props: CommandPaletteProps & { gates: NavMemberGates ? { objectName: selectedHit.objectName, recordId: selectedHit.recordId } : null; const showPreview = recordGroups.length > 0; + // A query's record hits answer after its other entries are drawn, above + // them: when a new set of hits lands, the selection moves to the first one, + // so the top entry is the one Enter opens and the pane previews. + const firstHitValue = recordGroups[0]?.hits[0] ? recordHitValue(recordGroups[0].hits[0]) : ''; + const hitSignature = recordHits.map(recordHitValue).join('\n'); + useEffect(() => { + if (firstHitValue !== '') setSelectedValue(firstHitValue); + // Keyed on the hits' text alone: only a new set of hits moves the + // selection, and the arrow keys own it after (ui/AGENTS.md #10). + }, [hitSignature, firstHitValue]); // objectstack#36286 — the app's objects the member may create a record of, // the object of the page the palette was opened on first. Only once From 95490eb27680506e21e047c4a735a5f4a85f4204 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 08:03:49 +0000 Subject: [PATCH 4/7] test(i18n): regenerate zh-Hant and count the new de quote pair Claude-Session: https://claude.ai/code/session_01QsR2jV3scu6UYPb42n5okQ Co-authored-by: Claude --- .../i18n/src/__tests__/de-quote-pairing-3876.test.ts | 9 +++++++-- ui/packages/i18n/src/locales/zh-Hant.ts | 4 ++-- 2 files changed, 9 insertions(+), 4 deletions(-) diff --git a/ui/packages/i18n/src/__tests__/de-quote-pairing-3876.test.ts b/ui/packages/i18n/src/__tests__/de-quote-pairing-3876.test.ts index 5160e9a4e74..69ebf57894d 100644 --- a/ui/packages/i18n/src/__tests__/de-quote-pairing-3876.test.ts +++ b/ui/packages/i18n/src/__tests__/de-quote-pairing-3876.test.ts @@ -455,7 +455,10 @@ describe('objectui#3876 — de pack closes „ with “ and not with a straight // 121 once objectstack-ai/objectstack#35955 added // `console.objectView.draft.saveToViewConfirm`, the shared-view save's // question naming the view („{{name}}“) — one interpolated span, view data. - expect(okSpans, 'correctly paired spans').toBe(121); + // 122 once objectstack-ai/objectstack#36286 added + // `console.commandPalette.createAs`, the palette's row creating a record + // from the typed words („{{query}}“) — one interpolated span, user input. + expect(okSpans, 'correctly paired spans').toBe(122); }); it('keeps the count identity that replaces the card’s count(„) === count(“)', () => { @@ -574,7 +577,9 @@ describe('objectui#3876 — de pack closes „ with “ and not with a straight // after objectstack-ai/objectstack#35688 added `fields.tags.add`, one more // matched pair. 121 / 121 / 0 after objectstack-ai/objectstack#35955 added // `console.objectView.draft.saveToViewConfirm`, one more matched pair. - expect({ open, close, rdq }).toEqual({ open: 121, close: 121, rdq: 0 }); + // 122 / 122 / 0 after objectstack-ai/objectstack#36286 added + // `console.commandPalette.createAs`, one more matched pair. + expect({ open, close, rdq }).toEqual({ open: 122, close: 122, rdq: 0 }); // The durable shape: every „ closed by a “, every surplus “ an English // opener answered by a ”. Survived translating the two English values. expect(close).toBe(open + rdq); diff --git a/ui/packages/i18n/src/locales/zh-Hant.ts b/ui/packages/i18n/src/locales/zh-Hant.ts index 8683ae0fdb6..355212063ba 100644 --- a/ui/packages/i18n/src/locales/zh-Hant.ts +++ b/ui/packages/i18n/src/locales/zh-Hant.ts @@ -2356,11 +2356,11 @@ const zhHant = { openFullSearch: '開啟完整搜尋頁面', create: '新建', createAs: '新建「{{query}}」為{{object}}', - previewEmpty: '選取一筆記錄即可查看詳細資料。', + previewEmpty: '選中一條記錄即可檢視詳情。', enterOpenRecord: '開啟記錄', enterCreate: '新建', enterSwitchApp: '切換應用', - enterApplyTheme: '套用主題', + enterApplyTheme: '應用主題', enterOpen: '開啟', }, ai: { From 862d69b3826bc1bc1a0d667b946740ea042b570d Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 08:23:59 +0000 Subject: [PATCH 5/7] refactor(app-shell): palette selection follows new hits without an effect Claude-Session: https://claude.ai/code/session_01QsR2jV3scu6UYPb42n5okQ Co-authored-by: Claude --- ui/packages/app-shell/src/chrome/CommandPalette.tsx | 10 ++++++---- .../app-shell/src/chrome/PalettePreviewPane.tsx | 7 ++----- 2 files changed, 8 insertions(+), 9 deletions(-) diff --git a/ui/packages/app-shell/src/chrome/CommandPalette.tsx b/ui/packages/app-shell/src/chrome/CommandPalette.tsx index 19937945c8a..9bcc08d8554 100644 --- a/ui/packages/app-shell/src/chrome/CommandPalette.tsx +++ b/ui/packages/app-shell/src/chrome/CommandPalette.tsx @@ -507,12 +507,14 @@ function CommandPaletteBody(props: CommandPaletteProps & { gates: NavMemberGates // them: when a new set of hits lands, the selection moves to the first one, // so the top entry is the one Enter opens and the pane previews. const firstHitValue = recordGroups[0]?.hits[0] ? recordHitValue(recordGroups[0].hits[0]) : ''; + // Compared by the hits' text alone (ui/AGENTS.md #10): only a new set of + // hits moves the selection, and the arrow keys own it after. const hitSignature = recordHits.map(recordHitValue).join('\n'); - useEffect(() => { + const [seenHitSignature, setSeenHitSignature] = useState(''); + if (hitSignature !== seenHitSignature) { + setSeenHitSignature(hitSignature); if (firstHitValue !== '') setSelectedValue(firstHitValue); - // Keyed on the hits' text alone: only a new set of hits moves the - // selection, and the arrow keys own it after (ui/AGENTS.md #10). - }, [hitSignature, firstHitValue]); + } // objectstack#36286 — the app's objects the member may create a record of, // the object of the page the palette was opened on first. Only once diff --git a/ui/packages/app-shell/src/chrome/PalettePreviewPane.tsx b/ui/packages/app-shell/src/chrome/PalettePreviewPane.tsx index bc189c574a0..068de7e8996 100644 --- a/ui/packages/app-shell/src/chrome/PalettePreviewPane.tsx +++ b/ui/packages/app-shell/src/chrome/PalettePreviewPane.tsx @@ -48,7 +48,7 @@ export const PREVIEW_PANE_CLASS = /** * `target` once it has stayed the same for `ms`. While a new target settles the * previous one is still answered, so the pane does not blink between two - * records; with no target, nothing is. + * records; with no target, nothing is answered. */ function useSettledTarget(target: PalettePreviewTarget | null, ms: number): PalettePreviewTarget | null { // Keyed on the pair's text, never on the object handed in (ui/AGENTS.md #10). @@ -56,10 +56,7 @@ function useSettledTarget(target: PalettePreviewTarget | null, ms: number): Pale const recordId = target?.recordId ?? null; const [settled, setSettled] = useState(null); useEffect(() => { - if (objectName === null || recordId === null) { - setSettled(null); - return; - } + if (objectName === null || recordId === null) return; const timer = setTimeout(() => setSettled({ objectName, recordId }), ms); return () => clearTimeout(timer); }, [objectName, recordId, ms]); From a17d2c75bfddbbd6e5128f11aa30107b28251027 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 09:56:37 +0000 Subject: [PATCH 6/7] fix(app-shell): the wide palette reads the shared dialog viewport gutter The 768px cap the palette takes beside a record preview is wider than a 640px window holds with a margin; read DIALOG_VIEWPORT_GUTTER as every other wide dialog does, and list the palette in the gutter census. Claude-Session: https://claude.ai/code/session_01QsR2jV3scu6UYPb42n5okQ Co-authored-by: Claude --- ui/packages/app-shell/src/chrome/CommandPalette.tsx | 6 ++++-- .../src/__tests__/dialogViewportGutterCensus-12603.test.ts | 1 + 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/ui/packages/app-shell/src/chrome/CommandPalette.tsx b/ui/packages/app-shell/src/chrome/CommandPalette.tsx index 9bcc08d8554..b2c51c49b6b 100644 --- a/ui/packages/app-shell/src/chrome/CommandPalette.tsx +++ b/ui/packages/app-shell/src/chrome/CommandPalette.tsx @@ -35,6 +35,7 @@ import { CommandItem, CommandList, CommandSeparator, + DIALOG_VIEWPORT_GUTTER, ObjectIconTile, cn, } from '@object-ui/components'; @@ -947,9 +948,10 @@ function PaletteDialog({ * The palette's width while a record preview is drawn beside the results * (objectstack#36286): room for two halves. The preview pane itself shows only * from a 45rem frame on (`PREVIEW_PANE_CLASS`), so a narrower window keeps the - * results alone. + * results alone. The cap (768px) is wider than the narrowest `sm` window can + * hold with a margin, so it reads the shared viewport gutter (objectui#12603). */ -const PALETTE_WIDE_CLASS = 'sm:max-w-3xl'; +const PALETTE_WIDE_CLASS = `sm:max-w-3xl ${DIALOG_VIEWPORT_GUTTER}`; /** * The cmdk root's classes, as `CommandDialog` draws them, laid out as a grid diff --git a/ui/packages/components/src/__tests__/dialogViewportGutterCensus-12603.test.ts b/ui/packages/components/src/__tests__/dialogViewportGutterCensus-12603.test.ts index 0e2412a243e..c455a60a2f6 100644 --- a/ui/packages/components/src/__tests__/dialogViewportGutterCensus-12603.test.ts +++ b/ui/packages/components/src/__tests__/dialogViewportGutterCensus-12603.test.ts @@ -342,6 +342,7 @@ const sites: Site[] = scans.flatMap((s) => s.sites); * and is added here; a dialog that narrows leaves in the same commit. */ const WIDE_SITES: Array<[file: string, tags: string[]]> = [ + ['packages/app-shell/src/chrome/CommandPalette.tsx', ['DialogContent']], ['packages/app-shell/src/hooks/useActionModal.tsx', ['DialogContent']], ['packages/app-shell/src/views/ActionParamDialog.tsx', ['DialogContent']], ['packages/app-shell/src/views/FlowRunner.tsx', ['DialogContent']], From dcb510f0a1686a61a0b35fdfb71698c281f97a5f Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 10:33:17 +0000 Subject: [PATCH 7/7] docs(changeset): declare the palette's eight new locale keys as a widening MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The eight console.commandPalette keys are new published language-pack keys, so Clause-② is yes (widening), not no. Claude-Session: https://claude.ai/code/session_01QsR2jV3scu6UYPb42n5okQ Co-authored-by: Claude --- .changeset/36286-palette-preview-create.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.changeset/36286-palette-preview-create.md b/.changeset/36286-palette-preview-create.md index fe0bf0369a2..93ae6209bfe 100644 --- a/.changeset/36286-palette-preview-create.md +++ b/.changeset/36286-palette-preview-create.md @@ -5,7 +5,7 @@ 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 -Clause-②: no +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 The command palette inside an app gains four things; which records it searches, and how it ranks them, are unchanged.