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
18 changes: 18 additions & 0 deletions .changeset/36286-palette-current-page.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
---
'@object-ui/app-shell': patch
'@object-ui/i18n': patch
---

feat(console): the empty ⌘K palette leads with a "Current page" group: the page's favorites entry

Clause-②: yes (widening) — one new published language-pack key, in all eleven packs: console.commandPalette.currentPage
Metadata-protocol: none

Opened with nothing typed, the command palette inside an app now starts with a "Current page" group, above the recently viewed records, when the page behind it is an object's list or a record page:

- **On an object's list** (`/apps/APP/OBJECT`, or one of its views): "Add to favorites" (or "Remove from favorites"), the list's own favorites entry from its ⋮ More menu. It pins the app's navigation entry for the list where the app has one, and keeps an object favorite otherwise, exactly as that menu does.
- **On a record page**: the record's star — the same `record` favorite the star beside the record's name toggles, named by the title the record was last visited under.

The row is first, so Enter on the empty palette now runs it; the footer says so ("Add to favorites ↵" / "Remove from favorites ↵", the menu's own words). Typing takes the group away. On every other page (an app's landing, a dashboard, the search page, a create form) the palette is unchanged. Which records the palette searches and how it ranks them, the full search page, and the phone's search are unchanged.

New locale key, in every pack: `console.commandPalette.currentPage`. No props or package exports change.
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,12 @@ import { CommandPalette } from './CommandPalette';
import { CommandPaletteProvider } from '../context/CommandPaletteProvider';
import { paletteEnterAction } from './PaletteEnterHint';
import { paletteCreateTargets, palettePrefillField, routeObjectName } from './paletteCreate';
import { paletteCurrentPage } from './PaletteCurrentPage';
import { FavoritesProvider, recordFavoriteItem, type FavoriteItem } from '../context/FavoritesProvider';
import { RecentItemsProvider, useRecentItems } from '../context/RecentItemsProvider';
import { useFavorites } from '../hooks/useFavorites';
import { scopedKey } from '../context/UserStateAdapters';
import { useObjectListFavorite } from '../layout/SidebarItemMenu';

const CUSTOMER = 'customer_36286';
const CONTACT = 'contact_36286';
Expand Down Expand Up @@ -331,3 +337,147 @@ describe('objectstack#36286 — which objects a create row offers', () => {
expect(routeObjectName('/apps/crm', names)).toBeUndefined();
});
});

describe('objectstack#36286 — the empty palette leads with the current page\'s entries', () => {
/** The list's own favorites entry, as `ObjectView`'s ⋮ More reads it. */
let listFavorite: { isFavorite: boolean } | null = null;
let favorites: FavoriteItem[] = [];
function PageProbe({ objectName }: { objectName?: string }) {
const list = useObjectListFavorite({ appSegment: 'crm', objectName, label: 'Customers' });
const stored = useFavorites().favorites;
React.useEffect(() => {
listFavorite = list;
favorites = stored;
});
return null;
}
/** The visit the record page records once its title is known. */
function SeedVisit({ recordId, title }: { recordId: string; title: string }) {
const { addRecentItem } = useRecentItems();
React.useEffect(() => {
addRecentItem({ id: `record:${CUSTOMER}:${recordId}`, label: title, href: `/apps/crm/${CUSTOMER}/record/${recordId}`, type: 'record' });
}, [addRecentItem, recordId, title]);
return null;
}

function mountPage(path: string, { visit, listObject }: { visit?: { recordId: string; title: string }; listObject?: string } = {}) {
const metadata = { ...metadataValue(), apps: [CRM] };
const ds = { find: vi.fn(async () => ({ data: [] })), findOne: vi.fn(async () => null) };
const view = render(
<MetadataCtx.Provider value={metadata as never}>
<FavoritesProvider>
<RecentItemsProvider>
<MemoryRouter initialEntries={[`${path}?palette=1`]}>
<CommandPaletteProvider>
<Probe />
<PageProbe objectName={listObject} />
{visit && <SeedVisit {...visit} />}
<CommandPalette apps={[CRM, SALES]} activeApp={CRM} objects={OBJECTS} onAppChange={() => {}} dataSource={ds} />
</CommandPaletteProvider>
</MemoryRouter>
</RecentItemsProvider>
</FavoritesProvider>
</MetadataCtx.Provider>,
);
return view;
}
const input = () => document.querySelector('[cmdk-input]') as HTMLInputElement | null;
const heading = () => document.querySelector('[cmdk-group-heading]')?.textContent;
const row = () => screen.queryByTestId('palette-current-page-favorite');

afterEach(() => {
localStorage.clear();
listFavorite = null;
favorites = [];
});

it('on an object\'s list: first, selected, and Enter runs the list\'s own favorites entry', async () => {
mountPage(`/apps/crm/${CUSTOMER}`, { listObject: CUSTOMER });
await waitFor(() => expect(row()).not.toBeNull());
expect(heading()).toBe('Current page');
expect(row()).toHaveTextContent('Add to favorites');
await waitFor(() => expect(selected()).toBe(`favorite-add current page list ${CUSTOMER}`));
expect(hint()).toBe('addFavorite');
expect(screen.getByTestId('palette-enter-hint')).toHaveTextContent('Add to favorites');
expect(listFavorite?.isFavorite).toBe(false);

press(input()!, 'Enter');
// The page's own entry turned on: the app lists the object, so its navigation entry is pinned.
await waitFor(() => expect(listFavorite?.isFavorite).toBe(true));
expect(favorites.map((f) => f.id)).toEqual(['nav:n_customer']);
expect(location()).toBe(`/apps/crm/${CUSTOMER}`);
expect(input()).toBeNull();
});

it('a named view of the list is the list too', async () => {
mountPage(`/apps/crm/${CUSTOMER}/view/all`);
await waitFor(() => expect(row()).not.toBeNull());
expect(row()?.getAttribute('data-value')).toBe(`favorite-add current page list ${CUSTOMER}`);
});

it('on a record page: Enter stars the record, named by the title it was visited under', async () => {
mountPage(`/apps/crm/${CUSTOMER}/record/C1`, { visit: { recordId: 'C1', title: 'Qingdao Haichen Foods' } });
await waitFor(() => expect(row()).not.toBeNull());
expect(heading()).toBe('Current page');
await waitFor(() => expect(selected()).toBe(`favorite-add current page record ${CUSTOMER}`));

press(input()!, 'Enter');
await waitFor(() => expect(favorites).toHaveLength(1));
// The very entry the record page's star toggles.
expect(favorites[0]).toMatchObject(recordFavoriteItem('crm', CUSTOMER, 'C1', 'Qingdao Haichen Foods'));
});

it('a record already starred offers to take the star off', async () => {
const starred = { ...recordFavoriteItem('crm', CUSTOMER, 'C1', 'Qingdao Haichen Foods'), favoritedAt: '2026-11-22T00:00:00.000Z' };
localStorage.setItem(scopedKey('objectui-favorites', 'u1'), JSON.stringify([starred]));
mountPage(`/apps/crm/${CUSTOMER}/record/C1`);
await waitFor(() => expect(row()).toHaveTextContent('Remove from favorites'));
await waitFor(() => expect(hint()).toBe('removeFavorite'));
press(input()!, 'Enter');
await waitFor(() => expect(favorites).toEqual([]));
});

it('typing takes the group away; clearing brings it back', async () => {
mountPage(`/apps/crm/${CUSTOMER}`);
await waitFor(() => expect(row()).not.toBeNull());
type(input()!, 'zhang');
await waitFor(() => expect(row()).toBeNull());
type(input()!, '');
await waitFor(() => expect(row()).not.toBeNull());
});

it.each([
['the app\'s landing', '/apps/crm'],
['a dashboard', '/apps/crm/dashboard/sales'],
['the full search page', '/apps/crm/search'],
['a create form', `/apps/crm/${CUSTOMER}/new`],
['an object the console does not serve', '/apps/crm/no_such_object'],
])('CONTROL: no group on %s', async (_name, path) => {
mountPage(path);
await waitFor(() => expect(input()).not.toBeNull());
await act(async () => {});
expect(row()).toBeNull();
expect(screen.queryByText('Current page')).toBeNull();
});

it('reads the page off the address, by the console\'s own route table', () => {
const served = (name: string) => name === CUSTOMER;
expect(paletteCurrentPage(`/apps/crm/${CUSTOMER}`, served)).toEqual({ kind: 'list', appSegment: 'crm', objectName: CUSTOMER });
expect(paletteCurrentPage(`/apps/crm/${CUSTOMER}/view/all`, served)?.kind).toBe('list');
expect(paletteCurrentPage(`/apps/crm/${CUSTOMER}/record/C1/page/print`, served)).toEqual({
kind: 'record',
appSegment: 'crm',
objectName: CUSTOMER,
recordId: 'C1',
});
expect(paletteCurrentPage(`/apps/crm/${CUSTOMER}/record/C1/edit`, served)).toBeNull();
expect(paletteCurrentPage(`/apps/crm/${CUSTOMER}/data`, served)).toBeNull();
expect(paletteCurrentPage('/apps/crm/reports', served)).toBeNull();
expect(paletteCurrentPage('/home', served)).toBeNull();
});

it('the footer reads the favorites rows\' kind', () => {
expect(paletteEnterAction(`favorite-add current page list ${CUSTOMER}`)).toBe('addFavorite');
expect(paletteEnterAction(`favorite-remove current page record ${CUSTOMER}`)).toBe('removeFavorite');
});
});
17 changes: 17 additions & 0 deletions ui/packages/app-shell/src/chrome/CommandPalette.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,7 @@ import {
} from './paletteCreate.js';
import { PalettePreviewPane, type PalettePreviewTarget } from './PalettePreviewPane.js';
import { PaletteEnterHint } from './PaletteEnterHint.js';
import { PaletteCurrentPageGroup, paletteCurrentPage } from './PaletteCurrentPage.js';

/** A recent row names its object by name (objectstack#29121). */
const RECENT_ROW_LABELS: NavTargetLabelOptions = { byName: true };
Expand Down Expand Up @@ -517,6 +518,14 @@ function CommandPaletteBody(props: CommandPaletteProps & { gates: NavMemberGates
if (firstHitValue !== '') setSelectedValue(firstHitValue);
}

// objectstack#36286 — what the page behind the palette offers (its list's
// or its record's favorites entry), above everything else on the empty
// palette; nothing once something is typed.
const currentPage =
open && !inStudio && inputValue.trim() === ''
? paletteCurrentPage(location.pathname, (name) => objectsByName.has(name))
: null;

// 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.
Expand Down Expand Up @@ -589,6 +598,14 @@ function CommandPaletteBody(props: CommandPaletteProps & { gates: NavMemberGates
)}
</CommandEmpty>

{currentPage && (
<PaletteCurrentPageGroup
page={currentPage}
objectDef={objectsByName.get(currentPage.objectName)}
run={runCommand}
/>
)}

{/* Recently visited records (cloud-synced via sys_user_preference).
Only renders when the input is empty so search results don't
compete with this fallback list. */}
Expand Down
142 changes: 142 additions & 0 deletions ui/packages/app-shell/src/chrome/PaletteCurrentPage.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,142 @@
/**
* 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 "Current page" group (objectstack#36286): drawn at the top
* of the empty palette, it offers what the page behind the palette offers.
*
* Each row runs the page's own entry, behind the page's own condition, and is
* drawn only where the page draws that entry:
*
* - On an object's list (`ObjectView`), the list's favorites entry of its ⋮
* More menu: `useObjectListFavorite`, with the plural label the list is
* titled by.
* - On a record page (`RecordDetailView`), the star beside the record's name:
* the `record` favorite `recordFavoriteItem` builds, named by the title the
* record was last visited under.
*
* 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
* list. An object the console does not serve opens the not-found state, which
* offers neither entry, so it has no group either.
*/

import { matchPath, matchRoutes } from 'react-router-dom';
import { CommandGroup, CommandItem } from '@object-ui/components';
import { 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';
import { recordFavoriteItem } from '../context/FavoritesProvider.js';
import { useFavorites } from '../hooks/useFavorites.js';
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';

/** The page behind the palette, when it is one the group offers entries for. */
export type PaletteCurrentPage =
| { kind: 'list'; appSegment: string; objectName: string }
| { kind: 'record'; appSegment: string; objectName: string; recordId: string };

/** The route paths (below `/apps/:appName`) whose element is `RecordDetailView`. */
const RECORD_PAGE_ROUTES: readonly string[] = [
':objectName/record/:recordId',
':objectName/record/:recordId/page/:pageName',
];

/**
* The page at `pathname`: an object's list or a record page, of an object
* `isServedObject` knows; `null` on every other page.
*/
export function paletteCurrentPage(
pathname: string,
isServedObject: (objectName: string) => boolean,
): PaletteCurrentPage | null {
const app = matchPath('/apps/:appSegment/*', pathname);
const appSegment = app?.params.appSegment;
if (!appSegment) return null;
const subPath = app.params['*'] ?? '';

const listObject = objectViewRouteObject(subPath);
if (listObject) return isServedObject(listObject) ? { kind: 'list', appSegment, objectName: listObject } : null;

const matches = matchRoutes(
APP_ROUTE_METADATA_READS.map(({ path }) => ({ path })),
`/${subPath.replace(/^\/+/, '')}`,
);
const match = matches?.[matches.length - 1];
if (!match || !RECORD_PAGE_ROUTES.includes(match.route.path ?? '')) return null;
const { objectName, recordId } = match.params;
if (!objectName || !recordId || !isServedObject(objectName)) return null;
return { kind: 'record', appSegment, objectName, recordId };
}

/** The object definition keys the group reads. */
interface CurrentPageObjectDef {
name: string;
label?: unknown;
pluralLabel?: unknown;
}

/**
* The group's rows for `page`. `run` closes the palette and runs the entry,
* as every palette command does.
*/
export function PaletteCurrentPageGroup({
page,
objectDef,
run,
}: {
page: PaletteCurrentPage;
objectDef: CurrentPageObjectDef;
run: (command: () => void) => void;
}) {
const { t, language } = useObjectTranslation();
const { objectPluralLabel } = useObjectLabel();
const onList = page.kind === 'list';
// The list's ⋮ More entry, with the title the list is drawn under.
const listFavorite = useObjectListFavorite({
appSegment: onList ? page.appSegment : undefined,
objectName: onList ? page.objectName : undefined,
label: servedObjectPluralLabel(objectDef, language, objectPluralLabel),
});
const { isFavorite, toggleFavorite } = useFavorites();
const { recentItems } = useRecentItems();
const recentLabel = useRecentItemLabel();

let favorite: { isFavorite: boolean; toggle: () => void } | null = listFavorite;
if (page.kind === 'record') {
const id = recordFavoriteItem(page.appSegment, page.objectName, page.recordId, undefined).id;
// The record page records its visit under the favorite's id, with its title.
const visit = recentItems.find((item) => item.type === 'record' && item.id === id);
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 { 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>
</CommandGroup>
);
}
Loading
Loading