An open source design system that's fully customizable and agent ready
TypeScript
feat(cli): put the likely entry first in failed-lookup suggestions (#7876)
Joey296edaf9e11f
diff --git a/.changeset/lookup-suggestion-order.md b/.changeset/lookup-suggestion-order.mdnew file mode 100644index 0000000000..c6fb1dad7c--- /dev/null+++ b/.changeset/lookup-suggestion-order.md@@ -0,0 +1,7 @@+---+'@astryxdesign/cli': patch+---++[feat] A failed `astryx component`, `template` or `docs` lookup lists the entry you most likely meant first. Components that tie on match score are ordered by how early the name you typed appears in their keywords and by how close their names are, instead of alphabetically; among the suggestions offered, a component one of whose other names was typed (including another library's name for it, such as `MUI TextField`, with or without the library's name) comes first; a compound name that does not exist (a family part named with other words, or without one of its family's words) suggests the real part or its family. Templates are ordered by how closely their id or title matches the name you typed, and unknown docs routes by how closely the route matches. Suggestion lists never get longer, every suggestion is a real entry, and a name that resolved before still resolves to the same entry.++@josephfarinadiff --git a/docs/specs/AST-083-result-order/spec.md b/docs/specs/AST-083-result-order/spec.mdindex b6c6d55ace..7584b7d79b 100644--- a/docs/specs/AST-083-result-order/spec.md+++ b/docs/specs/AST-083-result-order/spec.md@@ -28,6 +28,10 @@ their counts. The order of matches that are equally strong is not. That orderis a measured quality, and it may change whenever a measurement shows the neworder is at least as good as the old one.+The not-found errors of `astryx component`, `astryx template` and+`astryx docs` work the same way: the facts of a suggestion list hold, and the+order inside it is a measured quality (FR7).+This record owns that split: the facts every answer must keep, and the rulefor changing the order inside them. Search owns its own matching.`spec:AST-048` owns what build recommends and delegates the order of its@@ -76,6 +80,16 @@ owns response fields and compatibility.shows no row worse than the previous order. A row is worse when the paired95% confidence interval of its change lies entirely below zero. FR1–FR5hold for every change.+- **FR7 — not-found suggestions keep their facts.** When `astryx component`,+ `astryx template` or `astryx docs` names nothing, it suggests at most as+ many entries as its candidate set gives: for a component, the near-top+ matches of the component matcher (at most five, and at least two when two+ exist); for a template, every template; for docs, the routes its error+ gives (for an unknown route, the set `spec:AST-046` FR6 names). Every suggestion is a real catalog entry for that command, and a+ name that resolves keeps resolving to the same entry. Which candidates fill+ a component list and the order of every list change only under FR6,+ measured on the held-out and fresh failed-lookup evaluation sets. FR5 holds+ for this order.## Current-state impact@@ -86,13 +100,14 @@ owns response fields and compatibility.## Verification-| Contract | Verification | Representative states | Mutation or failure expectation |-| -------- | ----------------------------------------------------------------------------------------------------- | -------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------- |-| FR1, FR2 | `api/search/_order.test.mjs` against the lexical ranker; a replay over every real and synthetic query | multi-word queries, doc sections, domain-priority merges | a non-lexical result, a changed score, reason, or count, a cross-band move, or extra results fail |-| FR3 | `api/search/_main-searcher.test.mjs` whole-name cases | exact names, names typed with spaces for dashes | an answer that differs from the lexical ranker's fails |-| FR4 | `api/build/blocks/blocks.test.mjs`, `api/build/tree.test.mjs` | named blocks, integration blocks, unknown blocks | a block outside build's list and search's results, a changed entry, a moved named block, more blocks, or an added block sharing no content word fail |-| FR5 | `_main-searcher.test.mjs` and `tree.test.mjs` offline and repeat checks | network stubbed to throw; repeated runs | a network call or a differing repeat fails |-| FR6 | measured comparison on the evaluation sets, reported in the change's description | held-out, fresh, synthetic | a row whose paired CI lies below zero blocks the change |+| Contract | Verification | Representative states | Mutation or failure expectation |+| -------- | ----------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------- |+| FR1, FR2 | `api/search/_order.test.mjs` against the lexical ranker; a replay over every real and synthetic query | multi-word queries, doc sections, domain-priority merges | a non-lexical result, a changed score, reason, or count, a cross-band move, or extra results fail |+| FR3 | `api/search/_main-searcher.test.mjs` whole-name cases | exact names, names typed with spaces for dashes | an answer that differs from the lexical ranker's fails |+| FR4 | `api/build/blocks/blocks.test.mjs`, `api/build/tree.test.mjs` | named blocks, integration blocks, unknown blocks | a block outside build's list and search's results, a changed entry, a moved named block, more blocks, or an added block sharing no content word fail |+| FR5 | `_main-searcher.test.mjs` and `tree.test.mjs` offline and repeat checks | network stubbed to throw; repeated runs | a network call or a differing repeat fails |+| FR6 | measured comparison on the evaluation sets, reported in the change's description | held-out, fresh, synthetic | a row whose paired CI lies below zero blocks the change |+| FR7 | `foundation/text/suggest-order.test.mjs`; the component, docs and template command tests; a replay over every labeled failed lookup | compound names, other libraries' names, routes under a namespace | a longer list, a suggestion that is not an entry, a changed resolution, or a worse measured row fails |## Decision logdiff --git a/packages/cli/api/component/_adapter.mjs b/packages/cli/api/component/_adapter.mjsindex a633999ef9..47e44d1f47 100644--- a/packages/cli/api/component/_adapter.mjs+++ b/packages/cli/api/component/_adapter.mjs@@ -44,6 +44,10 @@ import {Project} from '../../foundation/config/project.mjs';import {loadComponentDoc as loadValidatedComponentDoc} from '../../foundation/discovery/component-loader.mjs';import {resolveComponentReplacements} from '../../foundation/discovery/component-replacement.mjs';import {searchComponents} from '../../foundation/text/string-utils.mjs';+import {+ rankComponentSuggestions,+ synonymMatches,+} from '../../foundation/text/suggest-order.mjs';import {AstryxError, coreDirOrThrow} from '../error.mjs';import {componentLinkProvider,@@ -51,6 +55,28 @@ import {loadDocsCatalog,} from '../docs/_adapter.mjs';+/** @type {Record<string, {synonyms?: string[]}> | undefined} */+let cards;+/**+ * Search's component cards (each component's other names), read once.+ * @returns {Record<string, {synonyms?: string[]}>}+ */+function searchCards() {+ if (!cards) {+ try {+ cards = JSON.parse(+ fs.readFileSync(+ new URL('../search/_cards.json', import.meta.url),+ 'utf8',+ ),+ );+ } catch {+ cards = {};+ }+ }+ return /** @type {Record<string, {synonyms?: string[]}>} */ (cards);+}+export {CORE_PACKAGE, unscopedComponentOwners};/**@@ -463,12 +489,20 @@ export async function resolveUnscopedDoc(dirName, {coreDir, cwd, name}) {resolvedOwnerPackage = CORE_PACKAGE;resolvedSourcePath = findComponentSource(coreDir, resolvedName);} else {+ // How many to suggest: the near-top results, at most five and at+ // least two. Which ones, and in what order, is the suggestion+ // ranking's call.const threshold = Math.max(topScore - 20, 1);- const candidates = results- .filter(r => r.score >= threshold)- .slice(0, 5);- if (candidates.length < 2)- candidates.push(...results.slice(candidates.length, 2));+ const count = Math.max(+ results.filter(r => r.score >= threshold).slice(0, 5).length,+ Math.min(2, results.length),+ );+ const candidates = rankComponentSuggestions(+ dirName,+ results,+ Object.values(components).flat(),+ synonymMatches(dirName, searchCards()),+ ).slice(0, count);throw new AstryxError(`No component named "${name}"`,candidates.map(c => ({name: c.name, reason: c.reason})),diff --git a/packages/cli/api/docs/_adapter.mjs b/packages/cli/api/docs/_adapter.mjsindex 1ff535cb7c..54195710df 100644--- a/packages/cli/api/docs/_adapter.mjs+++ b/packages/cli/api/docs/_adapter.mjs@@ -71,6 +71,7 @@ import {import {findCoreDir} from '../../foundation/fs/paths.mjs';import {AstryxError} from '../error.mjs';import {ERROR_CODES} from '../../foundation/response/error-codes.mjs';+import {orderRouteSuggestions} from '../../foundation/text/suggest-order.mjs';import {formatCliCommand} from '../../foundation/env/package-manager.mjs';export {OVERLAY_LANGUAGES, overlayLanguages};@@ -1622,6 +1623,9 @@ export async function unknownTopicError(topic, catalog) {...catalog.names().map(name => ({name, reason: 'available topic'})),];}+ if (typeof topic === 'string') {+ suggestions = orderRouteSuggestions(topic, suggestions);+ }// A route that moved names where it went, ahead of the usual suggestions// (spec:AST-046 FR9, FR6).const moved = movedRoute(topic, tree);diff --git a/packages/cli/api/template/template.mjs b/packages/cli/api/template/template.mjsindex 96f88c4e00..a334861419 100644--- a/packages/cli/api/template/template.mjs+++ b/packages/cli/api/template/template.mjs@@ -24,6 +24,7 @@ import {} from '../../foundation/discovery/template-adapter.mjs';import {AstryxError} from '../error.mjs';import {ERROR_CODES} from '../../foundation/response/error-codes.mjs';+import {orderByAffinity} from '../../foundation/text/suggest-order.mjs';import {templateList} from './list/list.mjs';import {templateShow} from './show/show.mjs';import {templateSkeleton} from './skeleton/skeleton.mjs';@@ -188,7 +189,10 @@ export async function template(name, options = {}) {if (name && candidates.length === 0) {throw new AstryxError(`Unknown template "${name}"`,- templates.map(t => ({name: t.dirName, reason: `${t.type} template`})),+ orderByAffinity(name, templates, t => [t.dirName, t.name]).map(t => ({+ name: t.dirName,+ reason: `${t.type} template`,+ })),ERROR_CODES.ERR_UNKNOWN_TEMPLATE,);}diff --git a/packages/cli/foundation/text/string-utils.mjs b/packages/cli/foundation/text/string-utils.mjsindex 0266dc3bb2..e3be844a84 100644--- a/packages/cli/foundation/text/string-utils.mjs+++ b/packages/cli/foundation/text/string-utils.mjs@@ -48,7 +48,8 @@ export function findClosestComponents(name, components, maxDistance = 3) {* 30 keyword Levenshtein distance 2* 20 name Levenshtein distance 3*- * Each result: { name, score, reason }+ * Each result: { name, score, reason }, plus `keywordAt` when a keyword set+ * the component's score: the position of the keyword that set it.** @param {string} needle* @param {string} coreDir@@ -64,6 +65,9 @@ export async function searchComponents(needle, coreDir, components) {const allNames = Object.values(components).flat();/** @type {Map<string, {name: string, score: number, reason: string}>} */const scored = new Map();+ /** Position of the keyword that set each component's score. */+ /** @type {Map<string, number>} */+ const keywordAt = new Map();/*** @param {string} name@@ -146,12 +150,14 @@ export async function searchComponents(needle, coreDir, components) {// Keyword matchingif (docs.keywords && Array.isArray(docs.keywords)) {- for (const kw of docs.keywords) {+ for (const [at, kw] of docs.keywords.entries()) {const kwLower = kw.toLowerCase();+ const before = scored.get(comp)?.score ?? 0;// Exact keywordif (kwLower === term) {addMatch(comp, 90, 'keyword "' + kw + '"');+ if (!keywordAt.has(comp) || before < 90) keywordAt.set(comp, at);break;}@@ -170,6 +176,7 @@ export async function searchComponents(needle, coreDir, components) {addMatch(comp, 70, 'keyword "' + kw + '" (distance ' + dist + ')');else if (dist === 2)addMatch(comp, 30, 'keyword "' + kw + '" (distance ' + dist + ')');+ if ((scored.get(comp)?.score ?? 0) > before) keywordAt.set(comp, at);}}@@ -202,9 +209,13 @@ export async function searchComponents(needle, coreDir, components) {}}- const results = Array.from(scored.values()).sort(- (a, b) => b.score - a.score || a.name.localeCompare(b.name),- );+ const results = Array.from(scored.values())+ .map(r =>+ keywordAt.has(r.name)+ ? {...r, keywordAt: /** @type {number} */ (keywordAt.get(r.name))}+ : r,+ )+ .sort((a, b) => b.score - a.score || a.name.localeCompare(b.name));return results;}diff --git a/packages/cli/foundation/text/suggest-order.mjs b/packages/cli/foundation/text/suggest-order.mjsnew file mode 100644index 0000000000..e7cd4e3c45--- /dev/null+++ b/packages/cli/foundation/text/suggest-order.mjs@@ -0,0 +1,363 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Order the suggestions a failed lookup prints, best first.+ *+ * A failed `component`, `template` or `docs` lookup already knows which+ * entries to suggest; this module decides their order, so the entry the+ * caller most likely meant comes first. It never makes a list longer.+ *+ * Names are compared as words: `DropdownMenuItem`, `dropdown-menu-item` and+ * `Dropdown Menu Items` all read as `dropdown menu item`.+ *+ * @input the name the caller typed and the candidate entries+ * @output the entries, reordered+ * @position lib: shared by the component, template and docs lookup errors+ */++import {levenshteinDistance} from './levenshtein.mjs';++/** The score a synonym match gets: an exact keyword's. */+const SYNONYM_SCORE = 90;+/** The score a name with exactly the typed words gets: an exact name's. */+const SAME_WORDS_SCORE = 100;++/**+ * A word with one trailing plural `s` removed (`tabs` → `tab`), leaving short+ * words and `ss` endings alone.+ * @param {string} word+ * @returns {string}+ */+function singular(word) {+ return word.length > 3 && word.endsWith('s') && !word.endsWith('ss')+ ? word.slice(0, -1)+ : word;+}++/**+ * A name's words, lowercase and singular: camelCase, PascalCase, kebab-case,+ * snake_case, slashes and spaces all split.+ * @param {string} text+ * @returns {string[]}+ */+export function nameWords(text) {+ /** @type {string[]} */+ const words = [];+ for (const part of String(text ?? '').split(/[^A-Za-z0-9]+/)) {+ if (!part) continue;+ const found =+ part.match(/[A-Z]+(?=[A-Z][a-z])|[A-Z]?[a-z]+|[A-Z]+|[0-9]+/g) ?? [];+ for (const w of found) words.push(singular(w.toLowerCase()));+ }+ return words;+}++/**+ * How closely one candidate name matches what the caller typed; higher is+ * closer. Tiers, best first: the same words; every typed word present; some+ * typed word present; none. Within a tier, more of the typed words and more of+ * the candidate's own words matched rank higher, and a name that starts with+ * the typed name (or the reverse) gets a small lift.+ * @param {string[]} typed - {@link nameWords} of the typed name+ * @param {string} name+ * @returns {number}+ */+function affinityOf(typed, name) {+ const words = nameWords(name);+ if (typed.length === 0 || words.length === 0) return 0;+ const typedJoined = typed.join('');+ const joined = words.join('');+ if (joined === typedJoined) return 40;+ const have = new Set(words);+ const want = new Set(typed);+ const covered = typed.filter(w => have.has(w)).length / typed.length;+ const precise = words.filter(w => want.has(w)).length / words.length;+ const prefix =+ joined.startsWith(typedJoined) || typedJoined.startsWith(joined) ? 1 : 0;+ const tier = covered === 1 ? 2 : covered > 0 ? 1 : 0;+ return tier * 10 + covered * 4 + precise * 2 + prefix + precise * 0.01;+}++/**+ * The same items, closest to the typed name first; each item is as close as+ * its closest name. Equal matches keep their original order.+ * @template T+ * @param {string} typedName+ * @param {T[]} items+ * @param {(item: T) => Array<string | undefined>} namesOf+ * @returns {T[]}+ */+export function orderByAffinity(typedName, items, namesOf) {+ const typed = nameWords(typedName);+ const scored = items.map((item, index) => {+ let best = 0;+ for (const name of namesOf(item)) {+ if (name) best = Math.max(best, affinityOf(typed, name));+ }+ return {item, index, best};+ });+ scored.sort((a, b) => b.best - a.best || a.index - b.index);+ return scored.map(s => s.item);+}++/**+ * Docs route suggestions, closest to the typed route first. When every+ * suggestion sits under one namespace the typed route also starts with, that+ * shared part is left out of the comparison: it says nothing about which page+ * was meant. Equal matches keep their order.+ * @template {{name: string}} T+ * @param {string} topic - the typed route+ * @param {T[]} suggestions+ * @returns {T[]}+ */+export function orderRouteSuggestions(topic, suggestions) {+ let shared = suggestions.length > 0 ? suggestions[0].name : '';+ for (const {name} of suggestions) {+ while (shared && !name.startsWith(shared)) shared = shared.slice(0, -1);+ }+ const namespace = shared.slice(0, shared.lastIndexOf('/') + 1);+ return namespace && topic.startsWith(namespace)+ ? orderByAffinity(topic.slice(namespace.length), suggestions, s => [+ s.name.slice(namespace.length),+ ])+ : orderByAffinity(topic, suggestions, s => [s.name]);+}++/** Library names a synonym may start with (`MUI TextField`). */+const LIBRARY_WORDS = new Set([+ 'mui',+ 'material',+ 'chakra',+ 'ant',+ 'antd',+ 'radix',+ 'bootstrap',+ 'mantine',+ 'shadcn',+ 'headless',+ 'aria',+ 'react',+]);++/**+ * The components whose synonyms name what was typed. A synonym matches when+ * its words, with or without a leading library name, are the typed words+ * (`MUI TextField` matches `MUI TextField`, `TextField` and `text-field`).+ * @param {string} needle+ * @param {Record<string, {synonyms?: string[]}>} cards - component name → its search card+ * @returns {Set<string>}+ */+export function synonymMatches(needle, cards) {+ const typed = nameWords(needle).join('');+ /** @type {Set<string>} */+ const found = new Set();+ if (!typed) return found;+ for (const [name, card] of Object.entries(cards ?? {})) {+ for (const synonym of card?.synonyms ?? []) {+ const words = nameWords(synonym);+ const whole = words.join('');+ while (words.length > 1 && LIBRARY_WORDS.has(words[0])) words.shift();+ if (whole === typed || words.join('') === typed) {+ found.add(name);+ break;+ }+ }+ }+ return found;+}++/** Words that name a structural part of a component (`<Family>Footer`). */+const PART_WORDS = new Set([+ 'header',+ 'footer',+ 'body',+ 'content',+ 'title',+ 'heading',+ 'description',+ 'item',+ 'trigger',+ 'action',+ 'close',+ 'group',+ 'cell',+ 'row',+ 'column',+ 'label',+ 'icon',+ 'root',+ 'wrapper',+]);++/** Part words that name the same slot of a component family. */+const SAME_PART = /** @type {Record<string, string[]>} */ ({+ item: ['item', 'option'],+ option: ['option', 'item'],+ header: ['header', 'heading', 'title'],+ heading: ['heading', 'header', 'title'],+ title: ['title', 'heading', 'header'],+});++/**+ * A suggestion score for a component whose name shares the typed compound+ * name's words, on the same scale as `searchComponents`, or null. It covers+ * part names that do not exist: the family part named with other words+ * (`PickerItem` → `PickerOption`), the part named without its family's+ * first word (`RailItem` → `SideRailItem`), the part named without its family's+ * middle word (`FactItem` → `FactListItem`), and the parent of a structural+ * part that is not its own component (`SheetFooter` → `Sheet`, but not+ * `SheetMusic`).+ * @param {string[]} typed - {@link nameWords} of the typed name+ * @param {string} name+ * @returns {{score: number, reason: string} | null}+ */+function compoundMatch(typed, name) {+ if (typed.length < 2) return null;+ const words = nameWords(name);+ const n = words.length;+ const t = typed.length;+ const same = (/** @type {string[]} */ a, /** @type {string[]} */ b) =>+ a.length === b.length && a.every((w, i) => w === b[i]);+ if (+ n >= 2 &&+ same(words.slice(0, -1), typed.slice(0, -1)) &&+ (SAME_PART[typed[t - 1]] ?? []).includes(words[n - 1])+ ) {+ return {score: 79, reason: 'same part of the family'};+ }+ if (n > t && same(words.slice(n - t), typed)) {+ return {score: 78, reason: 'name ends with the words typed'};+ }+ if (n > t && words[0] === typed[0] && words[n - 1] === typed[t - 1]) {+ return {score: 77, reason: 'same part of the family'};+ }+ if (+ n < t &&+ same(typed.slice(0, n), words) &&+ typed.slice(n).every(w => PART_WORDS.has(w))+ ) {+ return {score: 72, reason: 'the family this part belongs to'};+ }+ return null;+}++/**+ * Rank component suggestions for a name that resolved to nothing.+ *+ * Every component `searchComponents` scored keeps its score. A component whose+ * name has exactly the typed words (`chat-messages` for `ChatMessage`) scores+ * like an exact name; one of whose synonyms is the typed name (see+ * {@link synonymMatches}) like an exact keyword; one whose name shares the+ * typed compound name's words (see {@link compoundMatch}) just below a+ * one-letter typo of a name. Equal scores put synonym matches first, then order by how many of the typed words the+ * name carries, then by how early the keyword that matched sits in the+ * component's keywords, then by edit distance, then by shared leading letters,+ * then by name. The caller decides how many to print.+ * @param {string} needle - the typed component name (no `XDS` prefix)+ * @param {Array<{name: string, score: number, reason: string, keywordAt?: number}>} results - `searchComponents` output+ * @param {string[]} allNames - every component name+ * @param {Set<string>} [synonyms] - {@link synonymMatches} for the typed name+ * @returns {Array<{name: string, score: number, reason: string}>}+ */+export function rankComponentSuggestions(+ needle,+ results,+ allNames,+ synonyms = new Set(),+) {+ const term = needle.toLowerCase();+ const typed = nameWords(needle);+ /** @type {Map<string, {name: string, score: number, reason: string, keywordAt: number}>} */+ const byName = new Map();+ for (const r of results) {+ byName.set(r.name, {+ name: r.name,+ score: r.score,+ reason: r.reason,+ keywordAt: r.keywordAt ?? Infinity,+ });+ }+ // The typed words are a name's words (`chat-messages` is `ChatMessage`):+ // that name is meant, ahead of every rule below.+ const joined = typed.join('');+ for (const name of allNames) {+ if (joined && nameWords(name).join('') === joined) {+ byName.set(name, {+ name,+ score: SAME_WORDS_SCORE,+ reason: 'same name',+ keywordAt: -1,+ });+ }+ }+ for (const name of synonyms) {+ if (!allNames.includes(name)) continue;+ const prior = byName.get(name);+ if (!prior || prior.score < SYNONYM_SCORE) {+ byName.set(name, {+ name,+ score: SYNONYM_SCORE,+ reason: 'another name for it',+ keywordAt: Infinity,+ });+ }+ }+ for (const name of allNames) {+ const match = compoundMatch(typed, name);+ if (!match) continue;+ const prior = byName.get(name);+ if (!prior || match.score > prior.score) {+ byName.set(name, {+ name,+ score: match.score,+ reason: match.reason,+ keywordAt: Infinity,+ });+ }+ }+ /** @param {string} name */+ const lead = name => {+ const lower = name.toLowerCase();+ let i = 0;+ while (i < term.length && i < lower.length && term[i] === lower[i]) i++;+ return i / Math.max(term.length, lower.length);+ };+ /**+ * How many typed words the name carries, whole or as a word's start; the+ * last typed word, the one a compound name is a kind of (`PlaceInput` is an+ * input), counts a little more.+ */+ const shared = (/** @type {string} */ name) => {+ const words = nameWords(name);+ const has = (/** @type {string} */ t) =>+ words.some(+ w =>+ w === t ||+ (Math.min(w.length, t.length) >= 3 &&+ (w.startsWith(t) || t.startsWith(w))),+ );+ const count = typed.filter(has).length;+ return typed.length > 1 && has(typed[typed.length - 1])+ ? count + 0.5+ : count;+ };+ return [...byName.values()]+ .map(r => ({+ ...r,+ synonym: synonyms.has(r.name) ? 1 : 0,+ shared: shared(r.name),+ distance: levenshteinDistance(term, r.name.toLowerCase()),+ lead: lead(r.name),+ }))+ .sort(+ (a, b) =>+ b.score - a.score ||+ b.synonym - a.synonym ||+ b.shared - a.shared ||+ a.keywordAt - b.keywordAt ||+ a.distance - b.distance ||+ b.lead - a.lead ||+ a.name.localeCompare(b.name),+ )+ .map(({name, score, reason}) => ({name, score, reason}));+}diff --git a/packages/cli/foundation/text/suggest-order.test.mjs b/packages/cli/foundation/text/suggest-order.test.mjsnew file mode 100644index 0000000000..8a09957efe--- /dev/null+++ b/packages/cli/foundation/text/suggest-order.test.mjs@@ -0,0 +1,259 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++import {describe, expect, it} from 'vitest';+import {+ nameWords,+ orderByAffinity,+ orderRouteSuggestions,+ rankComponentSuggestions,+ synonymMatches,+} from './suggest-order.mjs';++describe('nameWords', () => {+ it('reads every spelling of a name as the same words', () => {+ expect(nameWords('DropdownMenuItems')).toEqual([+ 'dropdown',+ 'menu',+ 'item',+ ]);+ expect(nameWords('dropdown-menu-item')).toEqual([+ 'dropdown',+ 'menu',+ 'item',+ ]);+ expect(nameWords('Dropdown Menu Item')).toEqual([+ 'dropdown',+ 'menu',+ 'item',+ ]);+ expect(nameWords('cli/api_HTMLParser')).toEqual([+ 'cli',+ 'api',+ 'html',+ 'parser',+ ]);+ });++ it('keeps short words and double-s endings', () => {+ expect(nameWords('Gas')).toEqual(['gas']);+ expect(nameWords('Glass')).toEqual(['glass']);+ });+});++describe('orderByAffinity', () => {+ const names = (/** @type {string[]} */ list, /** @type {string} */ typed) =>+ orderByAffinity(typed, list, n => [n]);++ it('puts the same words first, then every typed word, then some', () => {+ expect(+ names(+ ['zeta-panel', 'wide-panel-grid', 'panel-grid', 'grid-panel-x'],+ 'PanelGrid',+ ),+ ).toEqual(['panel-grid', 'wide-panel-grid', 'grid-panel-x', 'zeta-panel']);+ });++ it('matches a title as well as an id', () => {+ const items = [+ {id: 'alpha', title: 'Something Else'},+ {id: 'beta', title: 'Wave Editor'},+ ];+ expect(+ orderByAffinity('Wave Editor', items, i => [i.id, i.title]).map(+ i => i.id,+ ),+ ).toEqual(['beta', 'alpha']);+ });++ it('keeps the original order between equal matches and never changes the list', () => {+ const list = ['c', 'b', 'a', 'route/b-thing', 'route/a-thing'];+ const out = names(list, 'thing');+ expect(out).toEqual(['route/b-thing', 'route/a-thing', 'c', 'b', 'a']);+ expect([...out].sort()).toEqual([...list].sort());+ });++ it('ranks a route by its words', () => {+ expect(+ names(+ ['basics/basics-color', 'basics/basics-size', 'basics/basics-usage'],+ 'basics/usage',+ ),+ ).toEqual([+ 'basics/basics-usage',+ 'basics/basics-color',+ 'basics/basics-size',+ ]);+ });+});++describe('rankComponentSuggestions', () => {+ const all = [+ 'Zebra',+ 'Picker',+ 'MultiPicker',+ 'PickerOption',+ 'Gadget',+ 'SideRailItem',+ 'Sheet',+ ];++ it('breaks a tie by where the typed name sits in the keywords', () => {+ const results = [+ {name: 'MultiPicker', score: 90, reason: 'keyword', keywordAt: 3},+ {name: 'Picker', score: 90, reason: 'keyword', keywordAt: 0},+ {name: 'Gadget', score: 90, reason: 'keyword', keywordAt: 5},+ ];+ expect(+ rankComponentSuggestions('Pick', results, all).map(r => r.name),+ ).toEqual(['Picker', 'MultiPicker', 'Gadget']);+ });++ it('breaks a remaining tie by edit distance, not by the alphabet', () => {+ const results = [+ {name: 'Gadget', score: 70, reason: 'keyword'},+ {name: 'Sheet', score: 70, reason: 'keyword'},+ ];+ expect(+ rankComponentSuggestions('Sheets', results, all).map(r => r.name),+ ).toEqual(['Sheet', 'Gadget']);+ });++ it('finds the family part named with other words', () => {+ const results = [{name: 'Picker', score: 70, reason: 'keyword'}];+ expect(rankComponentSuggestions('PickerItem', results, all)[0].name).toBe(+ 'PickerOption',+ );+ });++ it('finds the part named without its first word', () => {+ expect(rankComponentSuggestions('RailItem', [], all)[0].name).toBe(+ 'SideRailItem',+ );+ });++ it('finds the family of a part that is not its own component', () => {+ expect(rankComponentSuggestions('SheetFooter', [], all)[0].name).toBe(+ 'Sheet',+ );+ });++ it('puts a name with exactly the typed words first, ahead of every rule', () => {+ const results = [{name: 'Picker', score: 80, reason: 'similar name'}];+ const ranked = rankComponentSuggestions(+ 'pickers',+ results,+ all,+ new Set(['Gadget']),+ );+ expect(ranked[0].name).toBe('Picker');+ expect(rankComponentSuggestions('side-rail-item', [], all)[0].name).toBe(+ 'SideRailItem',+ );+ });++ it('names a family only for a structural part', () => {+ expect(+ rankComponentSuggestions('SheetMusic', [], all).map(r => r.name),+ ).not.toContain('Sheet');+ });++ it('does not let a lifted entry borrow a weaker keyword position', () => {+ const results = [+ {name: 'Picker', score: 90, reason: 'keyword', keywordAt: 2},+ {name: 'MultiPicker', score: 70, reason: 'keyword', keywordAt: 0},+ ];+ const ranked = rankComponentSuggestions(+ 'Pick',+ results,+ all,+ new Set(['Picker', 'MultiPicker']),+ );+ expect(ranked.map(r => r.name).slice(0, 2)).toEqual([+ 'Picker',+ 'MultiPicker',+ ]);+ });++ it('never lowers a score search gave', () => {+ const results = [{name: 'Picker', score: 100, reason: 'exact name'}];+ const ranked = rankComponentSuggestions('PickerItem', results, all);+ expect(ranked[0]).toEqual({+ name: 'Picker',+ score: 100,+ reason: 'exact name',+ });+ });++ it('suggests only catalog names', () => {+ const ranked = rankComponentSuggestions('PickerWidgetItem', [], all);+ for (const r of ranked) expect(all).toContain(r.name);+ });+});++describe('synonymMatches', () => {+ const cards = {+ Picker: {synonyms: ['choice box', 'Acme ChoiceBox', 'MUI Choice Field']},+ Sheet: {synonyms: ['side sheet', 'choice']},+ };++ it('matches a synonym in any spelling, without a leading library name', () => {+ expect([...synonymMatches('ChoiceField', cards)]).toEqual(['Picker']);+ expect([...synonymMatches('choice-box', cards)]).toEqual(['Picker']);+ expect([...synonymMatches('SideSheets', cards)]).toEqual(['Sheet']);+ expect([...synonymMatches('MUI Choice Field', cards)]).toEqual(['Picker']);+ });++ it('needs every word to match', () => {+ expect([...synonymMatches('Side', cards)]).toEqual([]);+ expect([...synonymMatches('', cards)]).toEqual([]);+ });++ it('puts a synonym match first among equal scores, and only real names', () => {+ const all = ['Gadget', 'Picker'];+ const results = [+ {name: 'Gadget', score: 90, reason: 'keyword', keywordAt: 0},+ ];+ const ranked = rankComponentSuggestions(+ 'ChoiceField',+ results,+ all,+ new Set(['Picker', 'NotInCatalog']),+ );+ expect(ranked.map(r => r.name)).toEqual(['Picker', 'Gadget']);+ });+});++describe('orderRouteSuggestions', () => {+ const kids = [+ 'guide/start',+ 'guide/building-blocks',+ 'guide/ship',+ 'guide/help',+ ].map(name => ({name}));+ const names = (/** @type {{name: string}[]} */ list) => list.map(s => s.name);++ it('keeps tree order when no child matches, at any depth', () => {+ expect(names(orderRouteSuggestions('guide/theme', kids))).toEqual(+ names(kids),+ );+ expect(names(orderRouteSuggestions('guide/theme/colors', kids))).toEqual(+ names(kids),+ );+ });++ it('puts the child the route names first', () => {+ expect(names(orderRouteSuggestions('guide/ship-it', kids))[0]).toBe(+ 'guide/ship',+ );+ expect(names(orderRouteSuggestions('guide/help/extra', kids))[0]).toBe(+ 'guide/help',+ );+ });++ it('compares whole routes when the suggestions share no namespace', () => {+ const roots = [{name: 'cli'}, {name: 'guide'}, {name: 'theme'}];+ expect(names(orderRouteSuggestions('theme/quick-start', roots))[0]).toBe(+ 'theme',+ );+ });+});