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
11 changes: 11 additions & 0 deletions .changeset/33061-palette-command-label-match.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
---
'@object-ui/app-shell': patch
'@object-ui/console': patch
---

fix(app-shell): a ⌘K built-in command is found by the words of its own label

Clause-②: no
Metadata-protocol: none

**The palette's built-in commands.** "Open Full Search Page" and the three theme commands were matched on hidden English values (`search all results full page`, `theme light`, …), so the full-search row was not found by `open` or `full search`, and under a non-English locale no command was found by any word of its label ("浅色主题" answered `light`, never `浅色`). Each command is now also matched by the label it shows, in the member's language. FROM: value words only. TO: the label's words or the value's words. The words that found a command before still find it.
Original file line number Diff line number Diff line change
@@ -0,0 +1,136 @@
/**
* 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.
*/

/**
* A ⌘K built-in command is found by the words of the label it shows, in the
* member's language (objectstack#33061).
*
* The full-search and theme commands were matched on their hidden values
* alone (`search all results full page`, `theme light`, …). The row labelled
* "Open Full Search Page" was not found by `open` or `full search`, and under
* a non-English locale no command was found by any word of its label: "浅色主题"
* answered `theme` and `light`, never `浅色`.
*
* Pinned through the real `CommandPaletteProvider` (opened by its `?palette=1`
* deep link) under a real `I18nProvider`, typing into the palette's input.
* Each label is read from the shipped locale pack, so the pin follows the
* pack's words:
*
* - `open` and `full search` find "Open Full Search Page" under `en`;
* - under `zh-Hans` the words of the pack's full-search and light-theme
* labels find those rows;
* - CONTROLS: `search` (a word of the value) still finds the full-search row,
* and an unrelated word, English or Chinese, finds no command.
*/

import * as React from 'react';
import { describe, it, expect, vi, afterEach } from 'vitest';
import { render, fireEvent, waitFor, cleanup } from '@testing-library/react';
import { MemoryRouter } from 'react-router-dom';
import { I18nProvider } from '@object-ui/i18n';
import { builtInLocales } from '@object-ui/i18n/locales';

vi.mock('@object-ui/auth', async (importOriginal) => ({
...(await importOriginal<Record<string, unknown>>()),
useAuth: () => ({ user: { id: 'u1' }, activeOrganization: null }),
}));

import { CommandPalette } from './CommandPalette';
import { CommandPaletteProvider } from '../context/CommandPaletteProvider';

/** A shipped pack's `console.commandPalette` rows. */
const paletteRows = (language: string): Record<string, string> =>
(builtInLocales as unknown as Record<string, { console: { commandPalette: Record<string, string> } }>)[language]
.console.commandPalette;

const APP = { name: 'showcase_app', label: 'Showcase', navigation: [] };

function mount(language: string, query: string) {
const dataSource = {
find: vi.fn(async () => ({ data: [] })),
searchAll: vi.fn(async () => ({ hits: [] })),
};
render(
<I18nProvider config={{ defaultLanguage: language, detectBrowserLanguage: false }} persistLanguage={false}>
<MemoryRouter initialEntries={['/apps/showcase_app?palette=1']}>
<CommandPaletteProvider>
<CommandPalette apps={[APP]} activeApp={APP} objects={[]} onAppChange={() => {}} dataSource={dataSource} />
</CommandPaletteProvider>
</MemoryRouter>
</I18nProvider>,
);
const input = document.querySelector('[cmdk-input]');
if (!input) throw new Error('the palette did not open');
fireEvent.change(input, { target: { value: query } });
}

/** The visible text of every command item cmdk rendered whose value starts with `kind `. */
function shown(kind: 'search' | 'theme'): string[] {
return Array.from(document.querySelectorAll(`[cmdk-item][data-value^="${kind} "]`)).map((el) =>
(el.textContent ?? '').trim(),
);
}

/** Types `query` into the open palette's input. */
function type(query: string) {
fireEvent.change(document.querySelector('[cmdk-input]')!, { target: { value: query } });
}

const commands = () => [...shown('search'), ...shown('theme')];

afterEach(() => cleanup());

describe('objectstack#33061 — a ⌘K built-in command is found by the words of its own label', () => {
const en = paletteRows('en');
const zh = paletteRows('zh-Hans');

it('`open` and `full search` find "Open Full Search Page" under en', () => {
expect(en.openFullSearch).toBe('Open Full Search Page');

mount('en', 'open');
expect(shown('search')).toEqual([en.openFullSearch]);
cleanup();

mount('en', 'full search');
expect(shown('search')).toEqual([en.openFullSearch]);
});

it('under zh-Hans the words of the pack labels find the full-search and light-theme rows', async () => {
const fullSearchWords = '完整搜索';
const lightWords = '浅色';
expect(zh.openFullSearch).toContain(fullSearchWords);
expect(zh.lightTheme).toContain(lightWords);
expect(zh.openFullSearch).not.toBe(en.openFullSearch);

mount('zh-Hans', fullSearchWords);
await waitFor(() => expect(shown('search')).toEqual([zh.openFullSearch]));
expect(shown('theme')).toEqual([]);
cleanup();

mount('zh-Hans', lightWords);
await waitFor(() => expect(shown('theme')).toEqual([zh.lightTheme]));
expect(shown('search')).toEqual([]);
});

it('CONTROL: `search`, a word of the value, still finds the full-search row', () => {
mount('en', 'search');
expect(shown('search')).toEqual([en.openFullSearch]);
});

it('CONTROL: an unrelated word finds no command, in en or zh-Hans', async () => {
mount('en', 'invoice');
expect(commands()).toEqual([]);
cleanup();

// The zh-Hans labels are drawn first, so the empty answer is read against them.
mount('zh-Hans', '');
await waitFor(() => expect(shown('search')).toEqual([zh.openFullSearch]));
type('发票');
expect(commands()).toEqual([]);
});
});
25 changes: 16 additions & 9 deletions ui/packages/app-shell/src/chrome/CommandPalette.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -294,10 +294,11 @@ function CommandPaletteBody(props: CommandPaletteProps & { gates: NavMemberGates
const navItems = gates ? flattenNavigation(navEntriesShownToMember(activeApp?.navigation || [], gates)) : [];

// The entries the palette shows for the query: a navigation entry or app by
// its label and its machine name, a built-in command by its value. They are
// matched here, on word prefixes and contiguous substrings, and only the
// matches are rendered, so cmdk's default subsequence scorer (it found
// "Field Zoo" for `zzzz`) no longer decides what shows (objectui#11812).
// its label and its machine name, a built-in command by its label and its
// value. They are matched here, on word prefixes and contiguous substrings,
// and only the matches are rendered, so cmdk's default subsequence scorer
// (it found "Field Zoo" for `zzzz`) no longer decides what shows
// (objectui#11812).
const matches = (...terms: Array<string | undefined>) => matchesPaletteQuery(inputValue, terms);
const navOfType = (type: string, nameKey: string) =>
navItems.filter((item) => item.type === type && matches(navLabel(item), item[nameKey]));
Expand Down Expand Up @@ -327,15 +328,21 @@ function CommandPaletteBody(props: CommandPaletteProps & { gates: NavMemberGates
switchableApps.length > 1
? switchableApps.filter((app) => matches(resolveKeyedI18nLabel(app.label, t), app.name))
: [];
const themeCommands = THEME_COMMANDS.filter((command) => matches(command.value));
// A built-in command is found by the words of the label it shows, in the
// member's language, and by its value (objectstack#33061): matched on the
// value alone, "Open Full Search Page" was not found by `open` or
// `full search`, and under a non-English locale no command was found by any
// word of its label.
const themeLabel = {
light: t('console.commandPalette.lightTheme'),
dark: t('console.commandPalette.darkTheme'),
system: t('console.commandPalette.systemTheme'),
};
const themeCommands = THEME_COMMANDS.filter((command) => matches(themeLabel[command.theme], command.value));
const fullSearchLabel = t('console.commandPalette.openFullSearch');
// The full-search page lives under an app (`/apps/APP/search`), so the
// `studio` scope, which has none, offers no such command (objectui#11863).
const showFullSearch = !inStudio && matches(FULL_SEARCH_VALUE);
const showFullSearch = !inStudio && matches(fullSearchLabel, FULL_SEARCH_VALUE);

// objectui#11863 — the Studio's packages, objects and flows, read only while
// the palette is open in the `studio` scope, matched like the entries above.
Expand Down Expand Up @@ -735,7 +742,7 @@ function CommandPaletteBody(props: CommandPaletteProps & { gates: NavMemberGates
onSelect={() => leaveTo(`${baseUrl}/search`)}
>
<Search className="mr-2 h-4 w-4" />
<span>{t('console.commandPalette.openFullSearch')}</span>
<span>{fullSearchLabel}</span>
</CommandItem>
</CommandGroup>
</>
Expand Down Expand Up @@ -788,14 +795,14 @@ function PaletteDialog({
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';

/** The theme commands, matched by their value (objectui#11812). */
/** The theme commands, matched by their label and their value (objectui#11812, objectstack#33061). */
const THEME_COMMANDS = [
{ value: 'theme light', theme: 'light', Icon: Sun },
{ value: 'theme dark', theme: 'dark', Icon: Moon },
{ value: 'theme system', theme: 'system', Icon: Monitor },
] as const;

/** The full-search command's value, which it is matched by (objectui#11812). */
/** The full-search command's value, matched beside its label (objectui#11812, objectstack#33061). */
const FULL_SEARCH_VALUE = 'search all results full page';

/** One Studio entry the `studio` scope lists (objectui#11863). */
Expand Down
Loading