Skip to content

Commit e5213e7

Browse files
feat(console): the ⌘K palette's Current page group offers Add view and Edit (#36711)
<!-- claude-projects-attribution: {"github_login":"os-warren"} --> _Requested by **Warren** · [project thread](https://claude.ai/code/project/chan_01U5RdnAAmkSQmZbqh6FtqZ8?thread=cmsg_01U5RdnAAmkSQmZbqh6FtqZ88koXu8fkc7uTmy43dVUPer)_ Fixes #36286 Clause-②: no Metadata-protocol: none ## 维护者速读 - 用户在列表页按 ⌘K,「当前页面」组里多了「新建视图」,回车直接打开视图切换器的新建卡片;在记录页按 ⌘K 多了「编辑」,回车等同点页面右上角的编辑按钮。 - 属于外壳专题(去掉顶栏那一层)里搜索面板这张卡的最后一项,做完这张卡就关闭。 - 面板里的这两行完全跟着页面上的按钮走:按钮不出现它就不出现,按钮变灰它也变灰并写明原因;出问题只影响这两行,撤回本 PR 即恢复原样。 - 无。 ## What changes The empty ⌘K palette's "Current page" group (its favorites row landed earlier) now carries the page's own main entry: - **On an object's list: "Add view".** Listed exactly where the view switcher offers "Add view". Enter opens the switcher on its in-place create card; for a host whose switcher offers only the Create View dialog, it opens that dialog. Opened the switcher's own way afterwards, the dropdown shows the views again. - **On a record page: "Edit".** The header's own `sys_edit` entry: Enter runs its `onClick` (the record form, or the page's edit state where the page draws body tables). It is listed off exactly when the header's button is off (`userActions.edit.disabledWhen`, the state lock, a live inline draft the header greys Edit for), with the header's reason under it. An approval-locked record, a record already in its edit state and a record in a drawer or pane over a list list no Edit row, because the page draws no Edit there (or the page behind the palette is the list). - The footer names what Enter does ("Add view ↵", "Edit ↵"), in the controls' own words. No new locale keys: both rows reuse the controls' labels (`view.switcher.addView`, `detail.edit`). How: nothing is recomputed in the palette. The page publishes the command beside the control that runs it, for as long as it draws that control (`usePublishPageCommand`, new `chrome/paletteCommands.ts`, a module store like `advertisedShortcuts`), and the palette lists what is published. `ObjectViewTitleSwitcher` publishes "Add view" under the same condition its footer button is drawn (`create || onAddView`); `RecordDetailView` publishes the header's `sys_edit` entry through `PublishRecordEditCommand` (new `views/recordPaletteEdit.tsx`), mounted inside the page's `InlineEditProvider` so the inline-draft greying is read where the header reads it. `ObjectViewSwitcherMenu` gains an optional `startOnCreate` prop (package-internal, not exported). This is the route the card's release comment recorded (seat 2: pages advertise their own command and verdict; the palette lists them). ## Tests - Palette harness (`CommandPalette.previewCreate-36286.test.tsx`), new top-level describe, 10 tests, over the real `CommandPaletteProvider` with the real `ObjectViewTitleSwitcher` and the real `PublishRecordEditCommand` in an `InlineEditProvider`: row order and selection, Enter opens the switcher on the create card; dialog-only host runs `onAddView`; CONTROL no row when the switcher offers no Add view; Edit runs the entry's handler; an off Edit is listed off with its reason and does nothing; a live inline draft turns it off; CONTROL a draft leaves it on where the header does; withdrawn when the page stops drawing it, and never listed on the wrong kind of page; footer kinds. - `RecordDetailView.harness.test.tsx`, new block `RecordDetailView.paletteEdit-36286` (4 tests) over the real record page: the page publishes Edit and running it calls the same `onEdit` the header button calls; off exactly when the header button is off (`edit.disabledWhen` holds); CONTROL a predicate that does not hold leaves both on; CONTROL an embedded record publishes nothing. <details><summary>Runs at d8c8135</summary> - `vitest run` of `packages/app-shell/src/chrome/` + the RecordDetailView harness + `objectViewTitleSwitcher` (2 files), `inPlaceViewCreate-35553`, `ObjectView.titleViewSwitcher-27594`, `RecordDetailView.phoneFace-27058`, `.favoritesEntry-12427`, `.headerActionGates`, `.drawerLevelEdit-33111` under the verify lock: Test Files 38 passed (38), Tests 398 passed (398), VERDICT command-exit 0 (at 27f5347; the last commit touched only the palette harness's imports, re-run there: 37 passed). - `pnpm --filter @object-ui/app-shell type-check` (tsc --noEmit + tsconfig.test.json): VERDICT command-exit 0. - Ablation 1, `scripts/ablation-replace.mjs` on `recordPaletteEdit.tsx`, the `disabled:` verdict replaced with `disabled: false`: 3 failed (the disabledWhen, off-with-reason and inline-draft tests), restored blob 282bf9e equals HEAD. - Ablation 2, `setStartOnCreate(true)` deleted from `objectViewTitleSwitcher.tsx`: 2 failed (the two create-card tests), restored blob c9b9cf6 equals HEAD. Source-resolved relative imports, no dist leg. </details> ## Acceptance notes - The card's acceptance lines for step 2 read "列表页上是收藏这个视图、新建视图;记录页上是收藏这条记录、编辑". The favorites rows landed earlier; this PR adds the other two, so it closes the card. - Row words are the controls' own ("Add view", "Edit"), as the favorites rows reuse the menu's words; Attio's "New view" wording would need two new keys, not added. - An authored record page that draws no `page:header` still publishes Edit, as the header entry is built for every face; I found no such page in the examples. - The phone's palette is out of the card's scope and unchanged; the switcher's phone sheet takes the same `startOnCreate`, adjusted during render so a kept-mounted body is asked again. ## Verification Two-minute check: run the showcase, open Accounts, press ⌘K, ArrowDown to "Add view", Enter: the view switcher opens on its create card. Open any account, ⌘K, ArrowDown to "Edit", Enter: the page enters its edit state (Cancel / Save in the header), as the header's Edit does. Browser run (showcase on its own `--fresh` backend + console vite, Playwright Chromium 1440x900, signed in through `/login`): list page group rows `favorite-add`, `view-add`; footer "Add view ↵"; after Enter the palette is closed, the switcher menu and `create-view-card` are present. Record page group rows `favorite-add`, `record-edit`; footer "Edit ↵"; after Enter the header shows Cancel and Save. Four screenshots are attached to the project thread (GitHub's image store takes browser uploads only), not committed. Gates at d8c8135: `dispatch-gates --commands` derived 38 families; all 38 run, each exit 0 (`pnpm --dir ui exec vitest run scripts/` was OOM-killed on the first pass beside the dev servers and re-run under the lock: Test Files 172 passed, 2 skipped; `check:test-source-alias` went red on the first pass and is fixed in d8c8135); `--ran` reconciliation 38 derived, 38 run, 0 NOT-MEASURED. ESLint on the changed source files: 0 errors. `check:new-line-citations`: 0 new. overlap-check: VERDICT clean (origin/main and #36629, which shares `RecordDetailView.tsx`, merge cleanly). ## Human Minimum - [x] 1. Schemas start as Zod; `packages/spec` holds no runtime logic. - [x] 2. Every name I added uses the casing for its kind. - [x] 3. No formatter ran; `pnpm lint` passes. - [x] 4. One issue, one branch off an up-to-date `main`, one pull request. - [x] 5. A change that publishes carries a changeset, and both declaration lines are filled in here and in the changeset. - [x] 6. `packages/spec` touched: its generated artifacts are regenerated and committed. (not touched) - [x] 7. No hand edits to `content/docs/references/`, `packages/*/CHANGELOG.md` or `content/docs/releases/`. - [x] 8. Title, body and comments are in English. - [x] The *Before Submitting* list in CONTRIBUTING.md is done. --- _Generated by [Claude Code](https://claude.ai/code/session_01JQwxbXBGc8PQRp6Q7TM7EU)_ --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 9e0c0c2 commit e5213e7

11 files changed

Lines changed: 648 additions & 22 deletions
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
---
2+
'@object-ui/app-shell': patch
3+
---
4+
5+
feat(console): the ⌘K palette's "Current page" group offers the list's "Add view" and the record's "Edit"
6+
7+
Clause-②: no
8+
Metadata-protocol: none
9+
10+
Opened with nothing typed, the command palette's "Current page" group now carries the page's own main entry beside its favorites row:
11+
12+
- **On an object's list**: "Add view", listed exactly where the view switcher offers "Add view". Enter opens the switcher on its in-place create card, or, for a host that offers only the Create View dialog, opens that dialog.
13+
- **On a record page**: "Edit", the header's own Edit. It runs what the header button runs (the record form, or the page's edit state), and it is off exactly when the button is off: a `userActions.edit.disabledWhen` that holds, the state lock, or a live inline draft the header greys Edit for, with the header's reason under it. A record an approval locks, a record already in its edit state and a record shown in a drawer or pane over a list offer no Edit row.
14+
15+
The footer names what Enter does ("Add view ↵", "Edit ↵"), in the controls' own words. Nothing is recomputed in the palette: the list and the record page publish the command beside the control while they draw it. No locale keys, props or package exports change.

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

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1436,6 +1436,14 @@ opens the object's create page (`/apps/APP/OBJECT/new`), the second with the
14361436
words in its title field. An object is offered exactly where its list offers
14371437
New. A footer names what Enter does to the selected entry.
14381438

1439+
With nothing typed, the palette leads with a "Current page" group: on an
1440+
object's list, the list's favorites entry and "Add view"; on a record page, the
1441+
record's star and "Edit". Each row runs the page's own control and is listed
1442+
only while the page draws that control. "Add view" and "Edit" are published by
1443+
the page beside the control (`usePublishPageCommand`, `chrome/paletteCommands.ts`)
1444+
with the control's own handler and verdict, so an Edit the header draws off is
1445+
listed off, with the header's reason.
1446+
14391447
```tsx
14401448
import { useCommandPalette } from '@object-ui/app-shell';
14411449

‎ui/packages/app-shell/src/chrome/CommandPalette.previewCreate-36286.test.tsx‎

Lines changed: 206 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -19,9 +19,10 @@
1919

2020
import * as React from 'react';
2121
import { describe, it, expect, vi, afterEach } from 'vitest';
22-
import { render, fireEvent, waitFor, cleanup, screen, act } from '@testing-library/react';
22+
import { render, fireEvent, waitFor, cleanup, screen, act, within } from '@testing-library/react';
2323
import { MemoryRouter, useLocation } from 'react-router-dom';
24-
import { MetadataCtx } from '@object-ui/react';
24+
import { InlineEditProvider, MetadataCtx, useInlineEdit } from '@object-ui/react';
25+
import { MetadataClient } from '@object-ui/data-objectstack';
2526

2627
vi.mock('@object-ui/auth', async (importOriginal) => ({
2728
...(await importOriginal<Record<string, unknown>>()),
@@ -50,6 +51,21 @@ vi.mock('@object-ui/permissions', async (importOriginal) => ({
5051
usePermissions: () => PERMS,
5152
}));
5253

54+
// The switcher's create card reads the dataset catalog (a chart view's
55+
// source): answered empty here, with no network.
56+
let metadataClient: MetadataClient | undefined;
57+
vi.mock('../views/metadata-admin/useMetadata', async (importOriginal) => ({
58+
...(await importOriginal<Record<string, unknown>>()),
59+
useMetadataClient: () =>
60+
(metadataClient ??= new MetadataClient({
61+
baseUrl: 'http://localhost',
62+
fetch: (async () => new Response('[]', { status: 200, headers: { 'content-type': 'application/json' } })) as unknown as typeof fetch,
63+
})),
64+
}));
65+
66+
// The view switcher's module reaches the draft-publish lint, which the source
67+
// loads lazily: pay that load at import, not inside a test's window.
68+
import '@objectstack/lint';
5369
// The preview's key fields draw through `lazy()`: load the detail entry at
5470
// module scope, so its cost is paid at import (ui/AGENTS.md, lazy boundaries).
5571
import '@object-ui/plugin-detail';
@@ -64,6 +80,8 @@ import { RecentItemsProvider, useRecentItems } from '../context/RecentItemsProvi
6480
import { useFavorites } from '../hooks/useFavorites';
6581
import { scopedKey } from '../context/UserStateAdapters';
6682
import { useObjectListFavorite } from '../layout/SidebarItemMenu';
83+
import { ObjectViewTitleSwitcher } from '../views/objectViewTitleSwitcher';
84+
import { PublishRecordEditCommand } from '../views/recordPaletteEdit';
6785

6886
const CUSTOMER = 'customer_36286';
6987
const CONTACT = 'contact_36286';
@@ -481,3 +499,189 @@ describe('objectstack#36286 — the empty palette leads with the current page\'s
481499
expect(paletteEnterAction(`favorite-remove current page record ${CUSTOMER}`)).toBe('removeFavorite');
482500
});
483501
});
502+
503+
describe('objectstack#36286 — the current page\'s Add view and Edit, run by the page\'s own control', () => {
504+
const t = ((key: string, options?: { defaultValue?: string }) => options?.defaultValue ?? key) as never;
505+
const SWITCHER_VIEWS = [{ id: 'all', label: 'All Customers', type: 'grid', authored: true }];
506+
507+
/** The list's own view switcher, as `ObjectView` mounts it. */
508+
function ListSwitcher(props: { create?: boolean; onAddView?: () => void }) {
509+
return (
510+
<ObjectViewTitleSwitcher
511+
views={SWITCHER_VIEWS}
512+
activeViewId="all"
513+
activeLabel="All Customers"
514+
favorites={null}
515+
onViewChange={() => {}}
516+
onAddView={props.onAddView}
517+
create={props.create
518+
? { objectDef: OBJECTS[0] as never, canCreatePersonal: true, canCreateShared: false, hasUnsavedConditions: false, onCreate: vi.fn().mockResolvedValue(true) }
519+
: undefined}
520+
t={t}
521+
/>
522+
);
523+
}
524+
525+
/** Starts an inline draft, as a field's double-click does on the record page. */
526+
function StartInlineDraft() {
527+
const session = useInlineEdit();
528+
React.useEffect(() => {
529+
session?.enter();
530+
}, [session]);
531+
return null;
532+
}
533+
534+
function tree(path: string, page: React.ReactNode) {
535+
const metadata = { ...metadataValue(), apps: [CRM] };
536+
const ds = { find: vi.fn(async () => ({ data: [] })), findOne: vi.fn(async () => null) };
537+
return (
538+
<MetadataCtx.Provider value={metadata as never}>
539+
<FavoritesProvider>
540+
<RecentItemsProvider>
541+
<MemoryRouter initialEntries={[`${path}?palette=1`]}>
542+
<CommandPaletteProvider>
543+
<Probe />
544+
{page}
545+
<CommandPalette apps={[CRM, SALES]} activeApp={CRM} objects={OBJECTS} onAppChange={() => {}} dataSource={ds} />
546+
</CommandPaletteProvider>
547+
</MemoryRouter>
548+
</RecentItemsProvider>
549+
</FavoritesProvider>
550+
</MetadataCtx.Provider>
551+
);
552+
}
553+
const LIST = `/apps/crm/${CUSTOMER}`;
554+
const RECORD = `/apps/crm/${CUSTOMER}/record/C1`;
555+
const input = () => document.querySelector('[cmdk-input]') as HTMLInputElement | null;
556+
const addView = () => screen.queryByTestId('palette-current-page-add-view');
557+
const edit = () => screen.queryByTestId('palette-current-page-edit');
558+
const groupRows = () =>
559+
Array.from(document.querySelectorAll('[cmdk-item][data-value*=" current page "]')).map((el) => el.getAttribute('data-value'));
560+
561+
afterEach(() => localStorage.clear());
562+
563+
it('on a list whose switcher offers the create card: listed after the favorites row; Enter opens the switcher on that card', async () => {
564+
render(tree(LIST, <ListSwitcher create />));
565+
await waitFor(() => expect(addView()).not.toBeNull());
566+
expect(addView()).toHaveTextContent('Add view');
567+
expect(groupRows()).toEqual([`favorite-add current page list ${CUSTOMER}`, `view-add current page ${CUSTOMER}`]);
568+
569+
press(input()!, 'ArrowDown');
570+
await waitFor(() => expect(selected()).toBe(`view-add current page ${CUSTOMER}`));
571+
expect(hint()).toBe('addView');
572+
expect(screen.getByTestId('palette-enter-hint')).toHaveTextContent('Add view');
573+
574+
press(input()!, 'Enter');
575+
await waitFor(() => expect(input()).toBeNull());
576+
const menu = await screen.findByTestId('list-view-switcher-menu');
577+
expect(await within(menu).findByTestId('create-view-card')).toBeInTheDocument();
578+
expect(location()).toBe(LIST);
579+
});
580+
581+
it('opened the switcher\'s own way afterwards, it shows the views again', async () => {
582+
render(tree(LIST, <ListSwitcher create />));
583+
await waitFor(() => expect(addView()).not.toBeNull());
584+
fireEvent.click(addView()!);
585+
const menu = await screen.findByTestId('list-view-switcher-menu');
586+
fireEvent.click(await within(menu).findByTestId('create-view-card-back'));
587+
expect(screen.getByTestId('list-view-switcher-body')).toBeInTheDocument();
588+
});
589+
590+
it('a switcher that offers only the Create View dialog: Enter runs that dialog\'s door', async () => {
591+
const onAddView = vi.fn();
592+
render(tree(LIST, <ListSwitcher onAddView={onAddView} />));
593+
await waitFor(() => expect(addView()).not.toBeNull());
594+
fireEvent.click(addView()!);
595+
expect(onAddView).toHaveBeenCalledTimes(1);
596+
expect(screen.queryByTestId('list-view-switcher-menu')).toBeNull();
597+
});
598+
599+
it('CONTROL: a switcher that offers no 「Add view」 (a reader who may create no view) lists none; the favorites row stays', async () => {
600+
render(tree(LIST, <ListSwitcher />));
601+
await waitFor(() => expect(screen.queryByTestId('palette-current-page-favorite')).not.toBeNull());
602+
await act(async () => {});
603+
expect(addView()).toBeNull();
604+
});
605+
606+
it('on a record page: Edit runs the header entry\'s own handler', async () => {
607+
const onClick = vi.fn();
608+
render(tree(RECORD, (
609+
<InlineEditProvider>
610+
<PublishRecordEditCommand edit={{ onClick }} />
611+
</InlineEditProvider>
612+
)));
613+
await waitFor(() => expect(edit()).not.toBeNull());
614+
expect(edit()).toHaveTextContent('Edit');
615+
expect(groupRows()).toEqual([`favorite-add current page record ${CUSTOMER}`, `record-edit current page ${CUSTOMER}`]);
616+
press(input()!, 'ArrowDown');
617+
await waitFor(() => expect(hint()).toBe('editRecord'));
618+
press(input()!, 'Enter');
619+
expect(onClick).toHaveBeenCalledTimes(1);
620+
await waitFor(() => expect(input()).toBeNull());
621+
});
622+
623+
it('an Edit the header draws off is listed off, with the header\'s reason, and does nothing', async () => {
624+
const onClick = vi.fn();
625+
render(tree(RECORD, (
626+
<InlineEditProvider>
627+
<PublishRecordEditCommand edit={{ onClick, disabled: true, disabledReason: 'Closed deals cannot be edited' }} />
628+
</InlineEditProvider>
629+
)));
630+
await waitFor(() => expect(edit()).not.toBeNull());
631+
expect(edit()?.getAttribute('aria-disabled')).toBe('true');
632+
expect(screen.getByTestId('palette-current-page-edit-reason')).toHaveTextContent('Closed deals cannot be edited');
633+
fireEvent.click(edit()!);
634+
expect(onClick).not.toHaveBeenCalled();
635+
expect(input()).not.toBeNull();
636+
});
637+
638+
it('off while an inline draft is live, as the header greys its Edit (disableDuringInlineEdit)', async () => {
639+
const onClick = vi.fn();
640+
render(tree(RECORD, (
641+
<InlineEditProvider>
642+
<StartInlineDraft />
643+
<PublishRecordEditCommand edit={{ onClick, disableDuringInlineEdit: true }} />
644+
</InlineEditProvider>
645+
)));
646+
await waitFor(() => expect(edit()?.getAttribute('aria-disabled')).toBe('true'));
647+
});
648+
649+
it('CONTROL: a live draft leaves Edit pressable where the header keeps it pressable (the edit state\'s page)', async () => {
650+
render(tree(RECORD, (
651+
<InlineEditProvider>
652+
<StartInlineDraft />
653+
<PublishRecordEditCommand edit={{ onClick: () => {}, disableDuringInlineEdit: false }} />
654+
</InlineEditProvider>
655+
)));
656+
await waitFor(() => expect(edit()).not.toBeNull());
657+
await act(async () => {});
658+
expect(edit()?.getAttribute('aria-disabled')).not.toBe('true');
659+
});
660+
661+
it('withdrawn when the page stops drawing it, and listed only on its own kind of page', async () => {
662+
const view = render(tree(RECORD, (
663+
<InlineEditProvider>
664+
<PublishRecordEditCommand edit={{ onClick: () => {} }} />
665+
</InlineEditProvider>
666+
)));
667+
await waitFor(() => expect(edit()).not.toBeNull());
668+
view.rerender(tree(RECORD, <InlineEditProvider><PublishRecordEditCommand edit={undefined} /></InlineEditProvider>));
669+
await waitFor(() => expect(edit()).toBeNull());
670+
cleanup();
671+
672+
// A record drawer's Edit (were one published) is no row on the list behind it.
673+
render(tree(LIST, (
674+
<InlineEditProvider>
675+
<PublishRecordEditCommand edit={{ onClick: () => {} }} />
676+
</InlineEditProvider>
677+
)));
678+
await waitFor(() => expect(screen.queryByTestId('palette-current-page-favorite')).not.toBeNull());
679+
await act(async () => {});
680+
expect(edit()).toBeNull();
681+
});
682+
683+
it('the footer reads the two rows\' kind', () => {
684+
expect(paletteEnterAction(`view-add current page ${CUSTOMER}`)).toBe('addView');
685+
expect(paletteEnterAction(`record-edit current page ${CUSTOMER}`)).toBe('editRecord');
686+
});
687+
});

‎ui/packages/app-shell/src/chrome/PaletteCurrentPage.tsx‎

Lines changed: 62 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,15 @@
2020
* the `record` favorite `recordFavoriteItem` builds, named by the title the
2121
* record was last visited under.
2222
*
23+
* - On an object's list, 「Add view」: what the view switcher's own 「Add
24+
* view」 runs (its create card, or the admin's Create View dialog), listed
25+
* while the switcher offers it.
26+
* - On a record page, 「Edit」: the header's own Edit, listed while the header
27+
* draws it, and off while the header's button is off.
28+
*
29+
* Those two are published by the page beside its own control
30+
* (`paletteCommands.ts`), never recomputed here.
31+
*
2332
* The page is read off the address, matched against the route table the
2433
* console's own route reads are matched against (`APP_ROUTE_METADATA_READS`),
2534
* so a static route that shadows `:objectName` (`search`, `reports`) is not a
@@ -29,7 +38,7 @@
2938

3039
import { matchPath, matchRoutes } from 'react-router-dom';
3140
import { CommandGroup, CommandItem } from '@object-ui/components';
32-
import { Star, StarOff } from 'lucide-react';
41+
import { Pencil, Plus, Star, StarOff } from 'lucide-react';
3342
import { useObjectLabel, useObjectTranslation } from '@object-ui/i18n';
3443
import { APP_ROUTE_METADATA_READS } from '../console/appRouteMetadataReads.js';
3544
import { objectViewRouteObject } from '../console/appObjectScope.js';
@@ -39,7 +48,8 @@ import { useRecentItems } from '../context/RecentItemsProvider.js';
3948
import { useRecentItemLabel } from '../hooks/useRecentItemLabel.js';
4049
import { useObjectListFavorite } from '../layout/SidebarItemMenu.js';
4150
import { servedObjectPluralLabel } from '../hooks/servedObjectLabel.js';
42-
import { FAVORITE_ADD_KIND, FAVORITE_REMOVE_KIND } from './PaletteEnterHint.js';
51+
import { ADD_VIEW_KIND, EDIT_RECORD_KIND, FAVORITE_ADD_KIND, FAVORITE_REMOVE_KIND } from './PaletteEnterHint.js';
52+
import { usePageCommands, type PageCommandId } from './paletteCommands.js';
4353

4454
/** The page behind the palette, when it is one the group offers entries for. */
4555
export type PaletteCurrentPage =
@@ -120,23 +130,59 @@ export function PaletteCurrentPageGroup({
120130
const item = recordFavoriteItem(page.appSegment, page.objectName, page.recordId, visit ? recentLabel(visit) : undefined);
121131
favorite = { isFavorite: isFavorite(item.id), toggle: () => toggleFavorite(item) };
122132
}
123-
if (!favorite) return null;
133+
const pageFavorite = favorite;
134+
// The page's own command for this kind of page, as the page publishes it.
135+
const commandId: PageCommandId = page.kind === 'list' ? 'add-view' : 'edit-record';
136+
const command = usePageCommands().find((published) => published.id === commandId);
137+
if (!pageFavorite && !command) return null;
124138

125-
const { isFavorite: starred, toggle } = favorite;
126139
return (
127140
<CommandGroup heading={t('console.commandPalette.currentPage', { defaultValue: 'Current page' })}>
128-
<CommandItem
129-
data-testid="palette-current-page-favorite"
130-
value={`${starred ? FAVORITE_REMOVE_KIND : FAVORITE_ADD_KIND} current page ${page.kind} ${page.objectName}`}
131-
onSelect={() => run(toggle)}
132-
>
133-
{starred ? <StarOff className="mr-2 h-4 w-4" /> : <Star className="mr-2 h-4 w-4" />}
134-
<span className="truncate">
135-
{starred
136-
? t('common.removeFromFavorites', { defaultValue: 'Remove from favorites' })
137-
: t('common.addToFavorites', { defaultValue: 'Add to favorites' })}
138-
</span>
139-
</CommandItem>
141+
{pageFavorite && (
142+
<CommandItem
143+
data-testid="palette-current-page-favorite"
144+
value={`${pageFavorite.isFavorite ? FAVORITE_REMOVE_KIND : FAVORITE_ADD_KIND} current page ${page.kind} ${page.objectName}`}
145+
onSelect={() => run(pageFavorite.toggle)}
146+
>
147+
{pageFavorite.isFavorite ? <StarOff className="mr-2 h-4 w-4" /> : <Star className="mr-2 h-4 w-4" />}
148+
<span className="truncate">
149+
{pageFavorite.isFavorite
150+
? t('common.removeFromFavorites', { defaultValue: 'Remove from favorites' })
151+
: t('common.addToFavorites', { defaultValue: 'Add to favorites' })}
152+
</span>
153+
</CommandItem>
154+
)}
155+
{command?.id === 'add-view' && (
156+
<CommandItem
157+
data-testid="palette-current-page-add-view"
158+
value={`${ADD_VIEW_KIND} current page ${page.objectName}`}
159+
disabled={command.disabled}
160+
onSelect={() => run(command.run)}
161+
>
162+
<Plus className="mr-2 h-4 w-4" />
163+
{/* The switcher's own words for it. */}
164+
<span className="truncate">{t('view.switcher.addView', { defaultValue: 'Add view' })}</span>
165+
</CommandItem>
166+
)}
167+
{command?.id === 'edit-record' && (
168+
<CommandItem
169+
data-testid="palette-current-page-edit"
170+
value={`${EDIT_RECORD_KIND} current page ${page.objectName}`}
171+
disabled={command.disabled}
172+
onSelect={() => run(command.run)}
173+
>
174+
<Pencil className="mr-2 h-4 w-4" />
175+
<span className="flex min-w-0 flex-col">
176+
{/* The header button's own words for it. */}
177+
<span className="truncate">{t('detail.edit', { defaultValue: 'Edit' })}</span>
178+
{command.disabled && command.disabledReason && (
179+
<span className="truncate text-xs text-muted-foreground" data-testid="palette-current-page-edit-reason">
180+
{command.disabledReason}
181+
</span>
182+
)}
183+
</span>
184+
</CommandItem>
185+
)}
140186
</CommandGroup>
141187
);
142188
}

0 commit comments

Comments
 (0)