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
12 changes: 12 additions & 0 deletions .changeset/39560-free-text-row-last.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
---
"@object-ui/fields": patch
---

fix(fields): the notification topic and channel pickers put a real match before the typed text

Clause-②: no
Metadata-protocol: none

Who sees it: an administrator editing a notification preference or a notification template, in the topic and channel pickers.

- **A listed value that matches what you typed comes first.** Once you type in the topic or channel picker, a listed value whose name or shown words are what you typed (in any case) comes first, then one that starts with it, then one that only contains it. The "Use «text»" row is now last, so pressing Enter after typing part of a topic, a channel in another case (`Inbox`), or the words a value is shown by (`All topics`) stores that listed value instead of the typed text. With no match the row is the only one, and Enter still stores exactly what you typed. The row stays available whenever the typed text is not itself a listed value, so a value outside the list can still be entered.
Original file line number Diff line number Diff line change
@@ -0,0 +1,325 @@
/**
* 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.
*/

/**
* Census: every combobox that offers a FREE-TEXT ROW, and where that row sits
* (objectstack#39560).
*
* A free-text row is a row of a search-as-you-type list that commits, or
* shows, the text the person typed: "Use «text»", "Add «text»", "Create
* «text» as …". Drawn FIRST, it is the row the list highlights, so typing part
* of a listed option and pressing Enter commits the typed text instead of the
* option it matched — a name nothing declares. Drawn LAST, Enter commits the
* real match whenever there is one, and the typed text whenever there is
* none. objectstack#39413 and objectstack#39560 measured the defect in two
* pickers; this census makes the next one visible.
*
* ## What it reads
*
* Every `.tsx` source under `ui/packages/<pkg>/src` and `ui/apps/<app>/src`,
* tests and stories left out, comments blanked (`ui/scripts/js-comment-mask.mjs`). In each file:
*
* 1. the SEARCH STATE — the identifier a `<CommandInput>` or an
* `<input role="combobox">` takes as its `value={…}`, plus every `const`
* whose initialiser reads it (`trimmed = search.trim()`, `addText = …`);
* 2. the ROWS — each `<CommandItem>` element, and each element whose opening
* tag says `role="option"`;
* 3. a row is a FREE-TEXT ROW when it names the search state (it commits or
* shows the typed text), except where a `.map` callback rebinds that name
* just above the row;
* 4. what FOLLOWS each free-text row: how many other row elements of the
* same list (`<CommandList>`, or the element that says `role="listbox"`)
* start after it in the source. A free-text row is LAST when none does.
* A row element drawn by a `.map` counts once, however many rows it
* draws.
*
* ## What it holds
*
* - The set of files with a free-text row equals {@link SITES}, both ways: a
* new site fails until it is listed here, and a listed site that no longer
* offers the row fails until its entry goes.
* - A site listed `last` keeps its free-text row last. A site listed
* `{ trailing }` keeps exactly that many row elements after it, each named
* in `why`: a fixed action row, never a listed option.
* - A site listed `open` is a KNOWN free-text-first site, named with what
* carries it; its order is not asserted either way, so the change that
* fixes it lands without editing this file, and deletes the entry after.
*
* It reads source, not behaviour: a row drawn by another shape (a hand-rolled
* list of `<div>`s with no `role="option"`) is outside what it can see, and
* the detector cases at the bottom pin what it does see. The behaviour of the
* fillable `RegistryRefField` arm is pinned by
* `RegistryRefField.freeTextLast-39560.test.tsx`.
*/
import { describe, it, expect } from 'vitest';
// @ts-expect-error — plain-JS shared helper, intentionally untyped (`allowJs: false`)
import { maskComments } from '../../../../scripts/js-comment-mask.mjs';

/** Local annotation, since the import above is untyped — the call site stays checked. */
const mask: (source: string) => string = maskComments;

/*
* The sources are read through Vite's `import.meta.glob`, not `node:fs`: this
* package's test program carries no Node typings on purpose (its
* `tsconfig.test.json`), and the glob is what Vitest resolves at transform
* time. Typed here, for this one call shape, rather than by pulling in all of
* `vite/client`.
*/
declare global {
interface ImportMeta {
glob(
patterns: string[],
options: { query: '?raw'; import: 'default'; eager: true },
): Record<string, string>;
}
}

/** For each free-text row, how many other row elements of its list follow it. */
type Trailing = number[];
type Site = 'last' | { trailing: number; why: string } | { open: string };

/**
* Every file under `ui/` that offers a free-text row, by its `ui/`-relative
* path. ⛔ Never add a new site as `open` to turn this file green: rank the
* real matches first and draw the free-text row last instead.
*/
const SITES: Record<string, Site> = {
// The fillable `notification-topic` / `notification-channel` arm: "Use «text»".
'packages/fields/src/widgets/RegistryRefField.tsx': 'last',
// The command palette's "Create «text» as OBJECT" rows, below every result.
'packages/app-shell/src/chrome/CommandPalette.tsx': {
trailing: 1,
why: 'the "full search" action row, which reads no result and closes the list',
},
// The metadata inspectors' combobox: "Use «text»", last since objectstack#39413.
'packages/app-shell/src/views/metadata-admin/inspectors/InspectorComboField.tsx': 'last',
// The in-cell option list's "Add «text»" row LEADS by its own documented
// choice ("so Enter after typing a new tag adds it rather than toggling a
// longer tag that contains the text"). Not ruled here: reported on
// objectstack#39560 for the seat to decide.
'packages/fields/src/widgets/InCellOptionList.tsx': {
open: 'leads by its own documented choice; reported on objectstack#39560, undecided',
},
};

/* ─── the detector ─── */

/** The end (exclusive) of the JSX opening tag that starts at `start`, braces respected. */
function openingTagEnd(text: string, start: number): number {
let depth = 0;
for (let i = start + 1; i < text.length; i++) {
const c = text[i];
if (c === '{') depth++;
else if (c === '}') depth--;
else if (c === '>' && depth === 0) return i + 1;
}
return text.length;
}

interface Span {
start: number;
end: number;
}

/** Every element whose tag is `tag` (or any tag, when `tag` is null) and whose opening tag passes `when`. */
function elements(text: string, tag: string | null, when: (open: string) => boolean): Span[] {
const spans: Span[] = [];
const opener = new RegExp(`<(${tag ?? '[A-Za-z][\\w.]*'})\\b`, 'g');
for (const m of text.matchAll(opener)) {
const start = m.index!;
const openEnd = openingTagEnd(text, start);
const open = text.slice(start, openEnd);
if (!when(open)) continue;
if (open.endsWith('/>')) {
spans.push({ start, end: openEnd });
continue;
}
const close = text.indexOf(`</${m[1]}>`, openEnd);
spans.push({ start, end: close < 0 ? openEnd : close + m[1].length + 3 });
}
return spans;
}

const escapeRe = (s: string) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
/** `name` used as an identifier: not a member (`x.name`), a key (`name:`), or part of a string or a dashed word. */
const usesName = (name: string) => new RegExp(`(?<![\\w.$'"\`-])${escapeRe(name)}\\b(?!\\s*:)`);

function searchState(text: string): Set<string> {
const names = new Set<string>();
const value = /\bvalue=\{(\w+)\}/;
for (const span of elements(text, 'CommandInput', () => true)) {
const m = value.exec(text.slice(span.start, openingTagEnd(text, span.start)));
if (m) names.add(m[1]);
}
for (const span of elements(text, 'input', (open) => /\brole="combobox"/.test(open))) {
const m = value.exec(text.slice(span.start, openingTagEnd(text, span.start)));
if (m) names.add(m[1]);
}
if (names.size === 0) return names;
const direct = [...names];
for (const m of text.matchAll(/\bconst (\w+)\s*=\s*([^;]*);/g)) {
if (direct.some((name) => usesName(name).test(m[2]))) names.add(m[1]);
}
return names;
}

/** Whether a `.map` (or any arrow) callback just above `at` rebinds `name` as a parameter. */
function shadowed(text: string, at: number, name: string): boolean {
const before = text.slice(Math.max(0, at - 300), at);
return new RegExp(`\\(\\s*\\(?\\s*\\{?[^()=]*\\b${escapeRe(name)}\\b[^()=]*\\}?\\s*\\)?\\s*=>`).test(before);
}

/** What follows each free-text row a source offers, in source order; `[]` when it offers none. */
function freeTextRows(source: string): Trailing {
const text = mask(source);
const names = searchState(text);
if (names.size === 0) return [];
const rows = [
...elements(text, 'CommandItem', () => true),
...elements(text, null, (open) => /\brole="option"/.test(open) && !open.startsWith('<CommandItem')),
].sort((a, b) => a.start - b.start);
const lists = [
...elements(text, 'CommandList', () => true),
...elements(text, null, (open) => /\brole="listbox"/.test(open)),
];
const isFree = (row: Span) =>
[...names].some((name) => usesName(name).test(text.slice(row.start, row.end)) && !shadowed(text, row.start, name));
const trailing: Trailing = [];
for (const row of rows) {
if (!isFree(row)) continue;
const list = lists
.filter((l) => l.start < row.start && l.end >= row.end)
.sort((a, b) => b.start - a.start)[0] ?? { start: 0, end: text.length };
trailing.push(rows.filter((other) => other.start >= row.end && other.end <= list.end && !isFree(other)).length);
}
return trailing;
}

/* ─── the census ─── */

// Keys are relative to this file, which Vite shortens to the nearest form
// (`../widgets/…` for this package's own sources).
const SOURCES = import.meta.glob(
[
'../../../*/src/**/*.tsx',
'../../../../apps/*/src/**/*.tsx',
'!**/node_modules/**',
'!**/dist/**',
'!**/__tests__/**',
'!**/*.test.tsx',
'!**/*.spec.tsx',
'!**/*.stories.tsx',
],
{ query: '?raw', import: 'default', eager: true },
);

/** This file's directory, relative to `ui/`. */
const HERE_IN_UI = ['packages', 'fields', 'src', '__tests__'];

/** A glob key as its `ui/`-relative path. */
function uiPath(key: string): string {
const segments = [...HERE_IN_UI];
for (const part of key.split('/')) {
if (part === '..') {
if (segments.length === 0) throw new Error(`glob key leaves the ui tree: ${key}`);
segments.pop();
} else if (part !== '.') segments.push(part);
}
return segments.join('/');
}

const census = new Map<string, Trailing>();
for (const [key, source] of Object.entries(SOURCES)) {
const trailing = freeTextRows(source);
if (trailing.length > 0) census.set(uiPath(key), trailing);
}

describe('free-text rows: the census (objectstack#39560)', () => {
it('reads the tree: both roots, hundreds of sources', () => {
const paths = Object.keys(SOURCES).map(uiPath);
expect(paths.length).toBeGreaterThan(500);
expect(paths).toContain('packages/fields/src/widgets/RegistryRefField.tsx');
expect(paths.some((path) => path.startsWith('apps/'))).toBe(true);
});

it('every combobox that offers a free-text row is listed, and every listed one still offers it', () => {
expect([...census.keys()].sort()).toEqual(Object.keys(SITES).sort());
});

it.each(Object.entries(SITES).filter(([, site]) => site === 'last'))(
'%s draws its free-text row after every listed option',
(path) => {
expect(census.get(path)).toBeDefined();
expect(census.get(path)!.every((after) => after === 0)).toBe(true);
},
);

it.each(
Object.entries(SITES).flatMap(([path, site]) =>
typeof site === 'object' && 'trailing' in site ? [[path, site.trailing, site.why] as const] : [],
),
)('%s keeps exactly %i fixed row(s) after its free-text rows: %s', (path, trailing) => {
expect(census.get(path)).toBeDefined();
expect(census.get(path)!.every((after) => after === trailing)).toBe(true);
});
});

/* ─── the detector's own cases ─── */

describe('free-text rows: what the detector sees', () => {
const picker = (rowsJsx: string) => `
const [search, setSearch] = React.useState('');
const trimmed = search.trim();
return (
<Command>
<CommandInput value={search} onValueChange={(next) => setSearch(next)} />
<CommandList>
${rowsJsx}
</CommandList>
</Command>
);`;
const listed = `{options.map((option) => (
<CommandItem key={option.value} onSelect={() => commit(option.value)}>{option.label}</CommandItem>
))}`;
const typed = `<CommandItem value={\`typed:\${trimmed}\`} onSelect={() => commit(trimmed)}>Use {trimmed}</CommandItem>`;

it('a free-text row before the listed options has them after it', () => {
expect(freeTextRows(picker(`${typed}\n${listed}`))).toEqual([1]);
});

it('a free-text row after the listed options is LAST', () => {
expect(freeTextRows(picker(`${listed}\n${typed}`))).toEqual([0]);
});

it('a list with no free-text row offers none, and a commented-out one does not count', () => {
expect(freeTextRows(picker(listed))).toEqual([]);
expect(freeTextRows(picker(`{/* ${typed} */}\n${listed}`))).toEqual([]);
});

it('a row whose `.map` callback rebinds the name is not a free-text row', () => {
const rebinding = `{hits.map((search) => (
<CommandItem key={search.id} onSelect={() => open(search)}>{search.title}</CommandItem>
))}`;
expect(freeTextRows(picker(rebinding))).toEqual([]);
});

it('an `<input role="combobox">` list with a leading "Add" `<li role="option">` has the options after it', () => {
const source = `
const addText = query.trim() ? query.trim() : null;
return (
<>
<input role="combobox" value={query} onChange={(e) => setQuery(e.target.value)} />
<ul role="listbox">
{addText !== null ? <li role="option" onClick={() => onAdd(addText)}>Add {addText}</li> : null}
{shown.map((o) => <li key={o.value} role="option" onClick={() => onPick(o.value)}>{o.label}</li>)}
</ul>
</>
);`;
expect(freeTextRows(source)).toEqual([1]);
});
});
Loading
Loading