Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions .changeset/36286-palette-add-view-edit.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
---
'@object-ui/app-shell': patch
---

feat(console): the ⌘K palette's "Current page" group offers the list's "Add view" and the record's "Edit"

Clause-②: no
Metadata-protocol: none

Opened with nothing typed, the command palette's "Current page" group now carries the page's own main entry beside its favorites row:

- **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.
- **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.

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.
8 changes: 8 additions & 0 deletions ui/packages/app-shell/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -1436,6 +1436,14 @@ 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.

With nothing typed, the palette leads with a "Current page" group: on an
object's list, the list's favorites entry and "Add view"; on a record page, the
record's star and "Edit". Each row runs the page's own control and is listed
only while the page draws that control. "Add view" and "Edit" are published by
the page beside the control (`usePublishPageCommand`, `chrome/paletteCommands.ts`)
with the control's own handler and verdict, so an Edit the header draws off is
listed off, with the header's reason.

```tsx
import { useCommandPalette } from '@object-ui/app-shell';

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,10 @@

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 { render, fireEvent, waitFor, cleanup, screen, act, within } from '@testing-library/react';
import { MemoryRouter, useLocation } from 'react-router-dom';
import { MetadataCtx } from '@object-ui/react';
import { InlineEditProvider, MetadataCtx, useInlineEdit } from '@object-ui/react';
import { MetadataClient } from '@object-ui/data-objectstack';

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

// The switcher's create card reads the dataset catalog (a chart view's
// source): answered empty here, with no network.
let metadataClient: MetadataClient | undefined;
vi.mock('../views/metadata-admin/useMetadata', async (importOriginal) => ({
...(await importOriginal<Record<string, unknown>>()),
useMetadataClient: () =>
(metadataClient ??= new MetadataClient({
baseUrl: 'http://localhost',
fetch: (async () => new Response('[]', { status: 200, headers: { 'content-type': 'application/json' } })) as unknown as typeof fetch,
})),
}));

// The view switcher's module reaches the draft-publish lint, which the source
// loads lazily: pay that load at import, not inside a test's window.
import '@objectstack/lint';
// 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';
Expand All @@ -64,6 +80,8 @@ import { RecentItemsProvider, useRecentItems } from '../context/RecentItemsProvi
import { useFavorites } from '../hooks/useFavorites';
import { scopedKey } from '../context/UserStateAdapters';
import { useObjectListFavorite } from '../layout/SidebarItemMenu';
import { ObjectViewTitleSwitcher } from '../views/objectViewTitleSwitcher';
import { PublishRecordEditCommand } from '../views/recordPaletteEdit';

const CUSTOMER = 'customer_36286';
const CONTACT = 'contact_36286';
Expand Down Expand Up @@ -481,3 +499,189 @@ describe('objectstack#36286 — the empty palette leads with the current page\'s
expect(paletteEnterAction(`favorite-remove current page record ${CUSTOMER}`)).toBe('removeFavorite');
});
});

describe('objectstack#36286 — the current page\'s Add view and Edit, run by the page\'s own control', () => {
const t = ((key: string, options?: { defaultValue?: string }) => options?.defaultValue ?? key) as never;
const SWITCHER_VIEWS = [{ id: 'all', label: 'All Customers', type: 'grid', authored: true }];

/** The list's own view switcher, as `ObjectView` mounts it. */
function ListSwitcher(props: { create?: boolean; onAddView?: () => void }) {
return (
<ObjectViewTitleSwitcher
views={SWITCHER_VIEWS}
activeViewId="all"
activeLabel="All Customers"
favorites={null}
onViewChange={() => {}}
onAddView={props.onAddView}
create={props.create
? { objectDef: OBJECTS[0] as never, canCreatePersonal: true, canCreateShared: false, hasUnsavedConditions: false, onCreate: vi.fn().mockResolvedValue(true) }
: undefined}
t={t}
/>
);
}

/** Starts an inline draft, as a field's double-click does on the record page. */
function StartInlineDraft() {
const session = useInlineEdit();
React.useEffect(() => {
session?.enter();
}, [session]);
return null;
}

function tree(path: string, page: React.ReactNode) {
const metadata = { ...metadataValue(), apps: [CRM] };
const ds = { find: vi.fn(async () => ({ data: [] })), findOne: vi.fn(async () => null) };
return (
<MetadataCtx.Provider value={metadata as never}>
<FavoritesProvider>
<RecentItemsProvider>
<MemoryRouter initialEntries={[`${path}?palette=1`]}>
<CommandPaletteProvider>
<Probe />
{page}
<CommandPalette apps={[CRM, SALES]} activeApp={CRM} objects={OBJECTS} onAppChange={() => {}} dataSource={ds} />
</CommandPaletteProvider>
</MemoryRouter>
</RecentItemsProvider>
</FavoritesProvider>
</MetadataCtx.Provider>
);
}
const LIST = `/apps/crm/${CUSTOMER}`;
const RECORD = `/apps/crm/${CUSTOMER}/record/C1`;
const input = () => document.querySelector('[cmdk-input]') as HTMLInputElement | null;
const addView = () => screen.queryByTestId('palette-current-page-add-view');
const edit = () => screen.queryByTestId('palette-current-page-edit');
const groupRows = () =>
Array.from(document.querySelectorAll('[cmdk-item][data-value*=" current page "]')).map((el) => el.getAttribute('data-value'));

afterEach(() => localStorage.clear());

it('on a list whose switcher offers the create card: listed after the favorites row; Enter opens the switcher on that card', async () => {
render(tree(LIST, <ListSwitcher create />));
await waitFor(() => expect(addView()).not.toBeNull());
expect(addView()).toHaveTextContent('Add view');
expect(groupRows()).toEqual([`favorite-add current page list ${CUSTOMER}`, `view-add current page ${CUSTOMER}`]);

press(input()!, 'ArrowDown');
await waitFor(() => expect(selected()).toBe(`view-add current page ${CUSTOMER}`));
expect(hint()).toBe('addView');
expect(screen.getByTestId('palette-enter-hint')).toHaveTextContent('Add view');

press(input()!, 'Enter');
await waitFor(() => expect(input()).toBeNull());
const menu = await screen.findByTestId('list-view-switcher-menu');
expect(await within(menu).findByTestId('create-view-card')).toBeInTheDocument();
expect(location()).toBe(LIST);
});

it('opened the switcher\'s own way afterwards, it shows the views again', async () => {
render(tree(LIST, <ListSwitcher create />));
await waitFor(() => expect(addView()).not.toBeNull());
fireEvent.click(addView()!);
const menu = await screen.findByTestId('list-view-switcher-menu');
fireEvent.click(await within(menu).findByTestId('create-view-card-back'));
expect(screen.getByTestId('list-view-switcher-body')).toBeInTheDocument();
});

it('a switcher that offers only the Create View dialog: Enter runs that dialog\'s door', async () => {
const onAddView = vi.fn();
render(tree(LIST, <ListSwitcher onAddView={onAddView} />));
await waitFor(() => expect(addView()).not.toBeNull());
fireEvent.click(addView()!);
expect(onAddView).toHaveBeenCalledTimes(1);
expect(screen.queryByTestId('list-view-switcher-menu')).toBeNull();
});

it('CONTROL: a switcher that offers no 「Add view」 (a reader who may create no view) lists none; the favorites row stays', async () => {
render(tree(LIST, <ListSwitcher />));
await waitFor(() => expect(screen.queryByTestId('palette-current-page-favorite')).not.toBeNull());
await act(async () => {});
expect(addView()).toBeNull();
});

it('on a record page: Edit runs the header entry\'s own handler', async () => {
const onClick = vi.fn();
render(tree(RECORD, (
<InlineEditProvider>
<PublishRecordEditCommand edit={{ onClick }} />
</InlineEditProvider>
)));
await waitFor(() => expect(edit()).not.toBeNull());
expect(edit()).toHaveTextContent('Edit');
expect(groupRows()).toEqual([`favorite-add current page record ${CUSTOMER}`, `record-edit current page ${CUSTOMER}`]);
press(input()!, 'ArrowDown');
await waitFor(() => expect(hint()).toBe('editRecord'));
press(input()!, 'Enter');
expect(onClick).toHaveBeenCalledTimes(1);
await waitFor(() => expect(input()).toBeNull());
});

it('an Edit the header draws off is listed off, with the header\'s reason, and does nothing', async () => {
const onClick = vi.fn();
render(tree(RECORD, (
<InlineEditProvider>
<PublishRecordEditCommand edit={{ onClick, disabled: true, disabledReason: 'Closed deals cannot be edited' }} />
</InlineEditProvider>
)));
await waitFor(() => expect(edit()).not.toBeNull());
expect(edit()?.getAttribute('aria-disabled')).toBe('true');
expect(screen.getByTestId('palette-current-page-edit-reason')).toHaveTextContent('Closed deals cannot be edited');
fireEvent.click(edit()!);
expect(onClick).not.toHaveBeenCalled();
expect(input()).not.toBeNull();
});

it('off while an inline draft is live, as the header greys its Edit (disableDuringInlineEdit)', async () => {
const onClick = vi.fn();
render(tree(RECORD, (
<InlineEditProvider>
<StartInlineDraft />
<PublishRecordEditCommand edit={{ onClick, disableDuringInlineEdit: true }} />
</InlineEditProvider>
)));
await waitFor(() => expect(edit()?.getAttribute('aria-disabled')).toBe('true'));
});

it('CONTROL: a live draft leaves Edit pressable where the header keeps it pressable (the edit state\'s page)', async () => {
render(tree(RECORD, (
<InlineEditProvider>
<StartInlineDraft />
<PublishRecordEditCommand edit={{ onClick: () => {}, disableDuringInlineEdit: false }} />
</InlineEditProvider>
)));
await waitFor(() => expect(edit()).not.toBeNull());
await act(async () => {});
expect(edit()?.getAttribute('aria-disabled')).not.toBe('true');
});

it('withdrawn when the page stops drawing it, and listed only on its own kind of page', async () => {
const view = render(tree(RECORD, (
<InlineEditProvider>
<PublishRecordEditCommand edit={{ onClick: () => {} }} />
</InlineEditProvider>
)));
await waitFor(() => expect(edit()).not.toBeNull());
view.rerender(tree(RECORD, <InlineEditProvider><PublishRecordEditCommand edit={undefined} /></InlineEditProvider>));
await waitFor(() => expect(edit()).toBeNull());
cleanup();

// A record drawer's Edit (were one published) is no row on the list behind it.
render(tree(LIST, (
<InlineEditProvider>
<PublishRecordEditCommand edit={{ onClick: () => {} }} />
</InlineEditProvider>
)));
await waitFor(() => expect(screen.queryByTestId('palette-current-page-favorite')).not.toBeNull());
await act(async () => {});
expect(edit()).toBeNull();
});

it('the footer reads the two rows\' kind', () => {
expect(paletteEnterAction(`view-add current page ${CUSTOMER}`)).toBe('addView');
expect(paletteEnterAction(`record-edit current page ${CUSTOMER}`)).toBe('editRecord');
});
});
78 changes: 62 additions & 16 deletions ui/packages/app-shell/src/chrome/PaletteCurrentPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,15 @@
* the `record` favorite `recordFavoriteItem` builds, named by the title the
* record was last visited under.
*
* - On an object's list, 「Add view」: what the view switcher's own 「Add
* view」 runs (its create card, or the admin's Create View dialog), listed
* while the switcher offers it.
* - On a record page, 「Edit」: the header's own Edit, listed while the header
* draws it, and off while the header's button is off.
*
* Those two are published by the page beside its own control
* (`paletteCommands.ts`), never recomputed here.
*
* The page is read off the address, matched against the route table the
* console's own route reads are matched against (`APP_ROUTE_METADATA_READS`),
* so a static route that shadows `:objectName` (`search`, `reports`) is not a
Expand All @@ -29,7 +38,7 @@

import { matchPath, matchRoutes } from 'react-router-dom';
import { CommandGroup, CommandItem } from '@object-ui/components';
import { Star, StarOff } from 'lucide-react';
import { Pencil, Plus, Star, StarOff } from 'lucide-react';
import { useObjectLabel, useObjectTranslation } from '@object-ui/i18n';
import { APP_ROUTE_METADATA_READS } from '../console/appRouteMetadataReads.js';
import { objectViewRouteObject } from '../console/appObjectScope.js';
Expand All @@ -39,7 +48,8 @@ import { useRecentItems } from '../context/RecentItemsProvider.js';
import { useRecentItemLabel } from '../hooks/useRecentItemLabel.js';
import { useObjectListFavorite } from '../layout/SidebarItemMenu.js';
import { servedObjectPluralLabel } from '../hooks/servedObjectLabel.js';
import { FAVORITE_ADD_KIND, FAVORITE_REMOVE_KIND } from './PaletteEnterHint.js';
import { ADD_VIEW_KIND, EDIT_RECORD_KIND, FAVORITE_ADD_KIND, FAVORITE_REMOVE_KIND } from './PaletteEnterHint.js';
import { usePageCommands, type PageCommandId } from './paletteCommands.js';

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

const { isFavorite: starred, toggle } = favorite;
return (
<CommandGroup heading={t('console.commandPalette.currentPage', { defaultValue: 'Current page' })}>
<CommandItem
data-testid="palette-current-page-favorite"
value={`${starred ? FAVORITE_REMOVE_KIND : FAVORITE_ADD_KIND} current page ${page.kind} ${page.objectName}`}
onSelect={() => run(toggle)}
>
{starred ? <StarOff className="mr-2 h-4 w-4" /> : <Star className="mr-2 h-4 w-4" />}
<span className="truncate">
{starred
? t('common.removeFromFavorites', { defaultValue: 'Remove from favorites' })
: t('common.addToFavorites', { defaultValue: 'Add to favorites' })}
</span>
</CommandItem>
{pageFavorite && (
<CommandItem
data-testid="palette-current-page-favorite"
value={`${pageFavorite.isFavorite ? FAVORITE_REMOVE_KIND : FAVORITE_ADD_KIND} current page ${page.kind} ${page.objectName}`}
onSelect={() => run(pageFavorite.toggle)}
>
{pageFavorite.isFavorite ? <StarOff className="mr-2 h-4 w-4" /> : <Star className="mr-2 h-4 w-4" />}
<span className="truncate">
{pageFavorite.isFavorite
? t('common.removeFromFavorites', { defaultValue: 'Remove from favorites' })
: t('common.addToFavorites', { defaultValue: 'Add to favorites' })}
</span>
</CommandItem>
)}
{command?.id === 'add-view' && (
<CommandItem
data-testid="palette-current-page-add-view"
value={`${ADD_VIEW_KIND} current page ${page.objectName}`}
disabled={command.disabled}
onSelect={() => run(command.run)}
>
<Plus className="mr-2 h-4 w-4" />
{/* The switcher's own words for it. */}
<span className="truncate">{t('view.switcher.addView', { defaultValue: 'Add view' })}</span>
</CommandItem>
)}
{command?.id === 'edit-record' && (
<CommandItem
data-testid="palette-current-page-edit"
value={`${EDIT_RECORD_KIND} current page ${page.objectName}`}
disabled={command.disabled}
onSelect={() => run(command.run)}
>
<Pencil className="mr-2 h-4 w-4" />
<span className="flex min-w-0 flex-col">
{/* The header button's own words for it. */}
<span className="truncate">{t('detail.edit', { defaultValue: 'Edit' })}</span>
{command.disabled && command.disabledReason && (
<span className="truncate text-xs text-muted-foreground" data-testid="palette-current-page-edit-reason">
{command.disabledReason}
</span>
)}
</span>
</CommandItem>
)}
</CommandGroup>
);
}
Loading
Loading