Skip to content
Draft
Show file tree
Hide file tree
Changes from 3 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
7 changes: 7 additions & 0 deletions .changeset/powersearch-value-only-opt-in.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
'@astryxdesign/core': patch
---

[perf] PowerSearch: value-only matches (operators with `isValueOnlyMatchAllowed: true`) now come from an opt-in import. Pass `valueOnlyMatches: powerSearchValueOnlyMatches` in the config, imported from `@astryxdesign/core`. A page whose configs do not pass it ships none of the matcher's code, and PowerSearch no longer loads it on first focus. An opt-in in a config without the matcher lists no value-only match and warns once in development.
Comment thread
astracat-bot[bot] marked this conversation as resolved.
Resolved

@cixzhang
6 changes: 5 additions & 1 deletion apps/storybook/stories/PowerSearch.stories.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,10 @@

import React, {useState} from 'react';
import type {Meta, StoryObj} from '@storybook/react';
import {PowerSearch} from '@astryxdesign/core/PowerSearch';
import {
PowerSearch,
powerSearchValueOnlyMatches,
} from '@astryxdesign/core/PowerSearch';
import type {
PowerSearchConfig,
PowerSearchFilter,
Expand Down Expand Up @@ -1688,6 +1691,7 @@ const valueOnlySlowUserSource: SearchSource = {

const valueOnlyConfig: PowerSearchConfig = {
name: 'ValueOnlyMatches',
valueOnlyMatches: powerSearchValueOnlyMatches,
contentSearchFieldKey: 'title',
fields: [
{
Expand Down
60 changes: 37 additions & 23 deletions docs/specs/components/PowerSearch/PowerSearch.spec.md

Large diffs are not rendered by default.

3 changes: 3 additions & 0 deletions packages/core/src/PowerSearch/PowerSearch.doc.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -217,8 +217,11 @@ export const docs = {
// "Owner is any of Jane Doe". A field shows at most three such rows. A field
// with more ends with "More Genre matching 'fiction'", which opens Genre's
// editor. An editor that searches, such as the owner's, opens on the text.
// The config passes the matcher, so pages without it ship none of its code.
import {powerSearchValueOnlyMatches} from '@astryxdesign/core';
const config = {
name: 'Books',
valueOnlyMatches: powerSearchValueOnlyMatches,
fields: [
{
key: 'genre',
Expand Down
27 changes: 22 additions & 5 deletions packages/core/src/PowerSearch/PowerSearch.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ import {__resetLiveRegionsForTest} from '../hooks/useAnnounce';
import type {PowerSearchConfig, PowerSearchFilter} from './types';
import type {SearchSource, SearchableItem} from '../Typeahead/types';
import {InternationalizationProvider} from '../i18n/InternationalizationProvider';
import {loadValueOnlyMatches} from './valueOnlyMatchLoader';
import {powerSearchValueOnlyMatches} from './valueOnlyMatches';
import {TestIcon} from '../__tests__/TestIcon';
import {getTooltip} from '../__tests__/tooltipDescription';

Expand Down Expand Up @@ -1263,10 +1263,6 @@ describe('field menu after the search source changes', () => {
// =============================================================================

describe('value-only matches', () => {
// The module loads on first intent; these cases start after that.
beforeAll(async () => {
await loadValueOnlyMatches();
});
const genres = ['Fiction', 'Fictional Worlds', 'Science Fiction', 'Fichte'];
/** A people source whose answers the test releases. */
function deferredPeople() {
Expand All @@ -1285,6 +1281,7 @@ describe('value-only matches', () => {
extra: Partial<PowerSearchConfig> = {},
): PowerSearchConfig {
return {
valueOnlyMatches: powerSearchValueOnlyMatches,
name: 'Books',
fields: [
{
Expand Down Expand Up @@ -1504,6 +1501,7 @@ describe('value-only matches', () => {
it('opens an enum_list field More row on its Tokenizer, searching the text', async () => {
const user = userEvent.setup();
const listConfig: PowerSearchConfig = {
valueOnlyMatches: powerSearchValueOnlyMatches,
name: 'Tags',
fields: [
{
Expand Down Expand Up @@ -1576,6 +1574,7 @@ describe('value-only matches', () => {
try {
const people = deferredPeople();
const offConfig: PowerSearchConfig = {
valueOnlyMatches: powerSearchValueOnlyMatches,
name: 'off',
fields: [
{
Expand Down Expand Up @@ -1608,6 +1607,24 @@ describe('value-only matches', () => {
}
});

it('warns once in development for an opt-in while the config has no matcher', () => {
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
try {
const config: PowerSearchConfig = {
...makeConfig(deferredPeople().source),
valueOnlyMatches: undefined,
};
const {rerender} = render(<Harness config={config} />);
rerender(<Harness config={config} />);
const messages = warn.mock.calls
.map(call => String(call[0]))
.filter(message => message.includes('no `valueOnlyMatches`'));
expect(messages).toHaveLength(1);
} finally {
warn.mockRestore();
}
});

it('asks a source once for a word typed within 150 ms, while the other rows show at once', async () => {
vi.useFakeTimers();
try {
Expand Down
18 changes: 10 additions & 8 deletions packages/core/src/PowerSearch/PowerSearch.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -80,8 +80,8 @@ import {usePowerSearchSource} from './usePowerSearchSource';
import {
findDisallowedOptIns,
hasValueOnlyOptIn,
startValueOnlyMatchesLoad,
} from './valueOnlyMatchLoader';
valueOnlyMatcherOf,
} from './valueOnlyOptIn';
import {formatDateRange, formatFilterValueForRender} from './formatFilterValue';
import {NestedEditor, PowerSearchEditPopover} from './PowerSearchEditPopover';
import {PowerSearchValueEditor} from './PowerSearchValueEditor';
Expand Down Expand Up @@ -654,6 +654,13 @@ export function PowerSearch({
)}: \`isValueOnlyMatchAllowed\` adds no value-only match while the field sets \`isValueMatchAllowed: false\`, which turns off every value suggestion of the field. Remove one of the two.`,
disallowedOptIns.length > 0,
);
useDevWarningPerMessage(
'PowerSearch',
'`isValueOnlyMatchAllowed` adds no value-only match while the config has no `valueOnlyMatches`. Pass `valueOnlyMatches: powerSearchValueOnlyMatches` in the config.',
process.env.NODE_ENV !== 'production' &&
valueOnlyMatcherOf(config.config.valueOnlyMatches) == null &&
hasValueOnlyOptIn(config),
);
const t = useComponentTranslator();
const locale = useLocale();
const calendar = useCalendarSystem(undefined, 'PowerSearch');
Expand All @@ -678,7 +685,6 @@ export function PowerSearch({
// matches under incremental search results.
const searchSource = usePowerSearchSource(config, maxSearchResults, {
maxSourceItems: maxOperatorMenuItems ?? DEFAULT_MAX_OPERATOR_MENU_ITEMS,
presentation: isSheetPresentation ? 'sheet' : 'popover',
});
const triggerRef = useRef<HTMLButtonElement>(null);
// `hasAutoFocus` applies only to the control the field first mounts. A
Expand Down Expand Up @@ -1548,13 +1554,9 @@ export function PowerSearch({
// The flow restores focus to the element that was active when it opened;
// make sure that is the trigger even for a tap on a token.
triggerRef.current?.focus({preventScroll: true});
// Opening the flow is the first intent for Add filter's value-only rows.
if (hasValueOnlyOptIn(config)) {
startValueOnlyMatchesLoad();
}
setIsSheetPresented(true);
setIsSheetOpen(true);
}, [config, isDisabled]);
}, [isDisabled]);

// The field's end lane — the result count and `endContent` — sits outside
// the trigger button: a caller's action button there keeps its own tab stop
Expand Down
38 changes: 7 additions & 31 deletions packages/core/src/PowerSearch/PowerSearchBottomSheet.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ import {InternationalizationProvider} from '../i18n/InternationalizationProvider
import type {Overrides} from '../i18n/types';
import {useInternalConfig} from './useInternalConfig';
import {usePowerSearchSource} from './usePowerSearchSource';
import {loadValueOnlyMatches} from './valueOnlyMatchLoader';
import {powerSearchValueOnlyMatches} from './valueOnlyMatches';
import {
createSheetSuggestionSource,
filterSignature,
Expand Down Expand Up @@ -4733,6 +4733,7 @@ describe('PowerSearch value-only matches in the sheet (FR18, FR30)', () => {
operators: [{key: 'contains', label: 'contains', value: {type: 'string'}}],
};
const valueOnlyConfig: PowerSearchConfig = {
valueOnlyMatches: powerSearchValueOnlyMatches,
name: 'ValueOnly',
contentSearchFieldKey: 'title',
fields: [
Expand Down Expand Up @@ -4837,10 +4838,6 @@ describe('PowerSearch value-only matches in the sheet (FR18, FR30)', () => {
});
return {texts, stop: () => observer.disconnect()};
}
// Most cases start after the module has loaded.
beforeAll(async () => {
await loadValueOnlyMatches();
});
beforeEach(() => {
ownerSearch.mockClear();
reviewerSearch.mockClear();
Expand Down Expand Up @@ -4912,6 +4909,7 @@ describe('PowerSearch value-only matches in the sheet (FR18, FR30)', () => {
setup({
config: {
name: 'Deferred',
valueOnlyMatches: powerSearchValueOnlyMatches,
contentSearchFieldKey: 'title',
fields: [titleField, ownerField(deferred.source)],
},
Expand Down Expand Up @@ -4955,6 +4953,7 @@ describe('PowerSearch value-only matches in the sheet (FR18, FR30)', () => {
setup({
config: {
name: 'Deferred',
valueOnlyMatches: powerSearchValueOnlyMatches,
contentSearchFieldKey: 'title',
fields: [titleField, ownerField(deferred.source)],
},
Expand Down Expand Up @@ -4999,6 +4998,7 @@ describe('PowerSearch value-only matches in the sheet (FR18, FR30)', () => {
const source: SearchSource = {...deferred.source, cancel};
const config: PowerSearchConfig = {
name: 'Deferred',
valueOnlyMatches: powerSearchValueOnlyMatches,
contentSearchFieldKey: 'title',
fields: [titleField, ownerField(source)],
};
Expand Down Expand Up @@ -5026,6 +5026,7 @@ describe('PowerSearch value-only matches in the sheet (FR18, FR30)', () => {
const firstCancel = vi.fn();
const configWith = (source: SearchSource): PowerSearchConfig => ({
name: 'Deferred',
valueOnlyMatches: powerSearchValueOnlyMatches,
contentSearchFieldKey: 'title',
fields: [titleField, ownerField(source)],
});
Expand Down Expand Up @@ -5090,6 +5091,7 @@ describe('PowerSearch value-only matches in the sheet (FR18, FR30)', () => {
<PowerSearch
config={{
name: 'Deferred',
valueOnlyMatches: powerSearchValueOnlyMatches,
contentSearchFieldKey: 'title',
fields: [
titleField,
Expand Down Expand Up @@ -5128,32 +5130,6 @@ describe('PowerSearch value-only matches in the sheet (FR18, FR30)', () => {
expect(sourceSearch).toHaveBeenCalledTimes(1);
});

it('loads the value-only rows as the flow opens and lists them once they land', async () => {
// A fresh module registry gives a PowerSearch whose value-only module
// has not loaded yet.
vi.resetModules();
const fresh = await import('./PowerSearch');
const loader = await import('./valueOnlyMatchLoader');
render(
<fresh.PowerSearch
config={valueOnlyConfig}
filters={[]}
onChange={() => {}}
presentation="bottom-sheet"
/>,
);
expect(loader.getLoadedValueOnlyMatches()).toBeNull();
// The fresh PowerSearch loads its sheet on the first press.
openSheet();
await waitFor(() => search());
fireEvent.change(search(), {target: {value: 'fic'}});
await waitFor(() =>
expect(resultNames()).toContain("More Genre matching 'fic'"),
);
expect(resultNames()[0]).toBe('"fic"');
expect(loader.getLoadedValueOnlyMatches()).not.toBeNull();
});

it('adds a value row to the draft and closes Add filter with its text', () => {
const {onChange} = setup({config: valueOnlyConfig});
typeQuery('fic');
Expand Down
3 changes: 3 additions & 0 deletions packages/core/src/PowerSearch/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@ export {PowerSearchFilterEditor} from './PowerSearchFilterEditor';

export {resolveOperatorLabel} from './resolveOperatorLabel';

export {powerSearchValueOnlyMatches} from './valueOnlyMatches';

export {
createPowerSearchConfig,
usePowerSearchConfig,
Expand All @@ -30,6 +32,7 @@ export type {FieldDefinition, InferData} from './usePowerSearchConfig';
export type {
// Config types
PowerSearchConfig,
PowerSearchValueOnlyMatches,
PowerSearchField,
PowerSearchOperator,
PowerSearchOperatorBase,
Expand Down
24 changes: 22 additions & 2 deletions packages/core/src/PowerSearch/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -293,8 +293,8 @@ export interface PowerSearchOperatorBase {
* `string` or `string_list` operator without a `searchSource` offers the
* typed text, an `enum` or `enum_list` operator the values with a word that
* starts with it, and an operator with a `searchSource` the items that
* source returns for it. The field's `isValueMatchAllowed: false` turns
* these off too. @default false
* source returns for it. The config's `valueOnlyMatches` must be set; the
* field's `isValueMatchAllowed: false` turns these off too. @default false
*/
readonly isValueOnlyMatchAllowed?: boolean;
}
Expand Down Expand Up @@ -355,6 +355,26 @@ export interface PowerSearchConfig {
readonly fields: ReadonlyArray<PowerSearchField>;
/** Key of the field used for content/text search. */
readonly contentSearchFieldKey?: string;
/**
* The value-only matcher: pass `powerSearchValueOnlyMatches`. Operators that
* set `isValueOnlyMatchAllowed` answer a typed value with no field label
* only when the config has it, so a page that never passes it ships none
* of its code.
*/
readonly valueOnlyMatches?: PowerSearchValueOnlyMatches;
}

/**
* PowerSearch's value-only matcher. Callers import it as
* `powerSearchValueOnlyMatches` and pass it only as a config's
* `valueOnlyMatches`; its contents are not public.
*/
export interface PowerSearchValueOnlyMatches {
/**
* A brand that is never present, so the matcher types of the package and a
* swizzled copy match.
*/
readonly '@astryxdesign/core/power-search/value-only-matches/v1'?: never;
}

// =============================================================================
Expand Down
Loading