Skip to content

An open source design system that's fully customizable and agent ready

TypeScript

fix(cli): stop not-found suggestions where the matches get weaker (#7999)

Joey298a4ce1700d
diff --git a/.changeset/lookup-suggestions-stop-at-weaker.md b/.changeset/lookup-suggestions-stop-at-weaker.md
new file mode 100644
index 0000000000..1e7d86fdad
--- /dev/null
+++ b/.changeset/lookup-suggestions-stop-at-weaker.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/cli': patch
+---
+
+[fix] When `astryx component`, `astryx template` or `astryx docs` names nothing, the suggestions now stop where the matches get weaker, so a strong first suggestion is no longer followed by unrelated entries. A component list keeps its first two suggestions and, after them, only suggestions about as close as the first or a close spelling of the whole typed name. In a template list, and in the docs list for an unknown topic that is not a route, when the closest entry carries every typed word, only entries that carry every typed word stay; when it carries some of them, entries that carry none are left out. One-letter words do not count. A name that shares no word with any entry still gets the full list, and an unknown route still suggests every child of its namespace. Lists only get shorter, and every suggestion still names a real entry.
+
+@josephfarina
diff --git a/packages/cli/api/component/_adapter.mjs b/packages/cli/api/component/_adapter.mjs
index 65539803a8..0c2477d56c 100644
--- a/packages/cli/api/component/_adapter.mjs
+++ b/packages/cli/api/component/_adapter.mjs
@@ -49,12 +49,16 @@ import {
synonymMatches,
} from '../../foundation/text/suggest-order.mjs';
import {AstryxError, coreDirOrThrow} from '../error.mjs';
+import {levenshteinDistance} from '../../foundation/text/levenshtein.mjs';
import {
componentLinkProvider,
linkComponentDoc,
loadDocsCatalog,
} from '../docs/_adapter.mjs';
+/** How far below the first suggestion's score a later one may be. */
+const NEAR_FIRST = 10;
+
/** @type {Record<string, {synonyms?: string[]}> | undefined} */
let cards;
/**
@@ -503,9 +507,20 @@ export async function resolveUnscopedDoc(dirName, {coreDir, cwd, name}) {
Object.values(components).flat(),
synonymMatches(dirName, searchCards()),
).slice(0, count);
+ // Past the first two suggestions, only the ones about as close as
+ // the first (within NEAR_FIRST points), or a close spelling of the
+ // whole typed name (a typo): a weaker match after a strong one reads
+ // as noise. The list only gets shorter and keeps at least two.
+ const typed = dirName.toLowerCase();
+ const nearFirst = candidates.filter(
+ (c, i) =>
+ i < 2 ||
+ c.score >= candidates[0].score - NEAR_FIRST ||
+ levenshteinDistance(c.name.toLowerCase(), typed) <= 2,
+ );
throw new AstryxError(
`No component named "${name}"`,
- candidates.map(c => ({name: c.name, reason: c.reason})),
+ nearFirst.map(c => ({name: c.name, reason: c.reason})),
ERROR_CODES.ERR_UNKNOWN_COMPONENT,
);
}
diff --git a/packages/cli/api/component/component.test.mjs b/packages/cli/api/component/component.test.mjs
index d86f4e7456..d05159b517 100644
--- a/packages/cli/api/component/component.test.mjs
+++ b/packages/cli/api/component/component.test.mjs
@@ -499,3 +499,34 @@ describe('component dispatcher — detail levels on single component (text only)
SLOW,
);
});
+
+describe('component not-found suggestions', () => {
+ const suggested = async (/** @type {string} */ name) => {
+ const error = await component(name, {cwd}).catch(e => e);
+ expect(error).toBeInstanceOf(AstryxError);
+ expect(error.code).toBe('ERR_UNKNOWN_COMPONENT');
+ return error.suggestions.map((/** @type {{name: string}} */ s) => s.name);
+ };
+
+ it(
+ 'leaves out a weaker match after a strong first suggestion',
+ async () => {
+ // FieldLabel is another name for it; past the second suggestion, the
+ // matches on one word of the name ("input", "label") are weaker and add
+ // only noise.
+ const names = await suggested('InputLabel');
+ expect(names[0]).toBe('FieldLabel');
+ expect(names).toHaveLength(2);
+ },
+ SLOW,
+ );
+
+ it(
+ 'keeps a close spelling of the whole name after a stronger first match',
+ async () => {
+ expect(await suggested('Blockqoute')).toContain('Blockquote');
+ expect(await suggested('TextrAea')).toContain('TextArea');
+ },
+ SLOW,
+ );
+});
diff --git a/packages/cli/api/docs/_adapter.mjs b/packages/cli/api/docs/_adapter.mjs
index c80d238f5b..b21de28d59 100644
--- a/packages/cli/api/docs/_adapter.mjs
+++ b/packages/cli/api/docs/_adapter.mjs
@@ -1844,8 +1844,11 @@ function movedRoute(topic, tree) {
/**
* The error for a docs argument that names nothing. For a route, it suggests
- * the children of the deepest namespace the route reaches; otherwise, every
- * topic and every top-level namespace.
+ * every child of the deepest namespace the route reaches, closest first.
+ * Otherwise it suggests the docs the argument names in another spelling, or
+ * failing that the topics and top-level namespaces, closest first and cut
+ * where the matches get weaker (every one of them when none shares a word
+ * with the argument).
* @param {unknown} topic
* @param {DocsCatalog} catalog
* @returns {Promise<AstryxError>}
@@ -1854,6 +1857,8 @@ export async function unknownTopicError(topic, catalog) {
const tree = await projectTree(catalog);
/** @type {Array<{name: string, reason: string}>} */
let suggestions = [];
+ // Route children stay whole (spec:AST-046); only the other lists are cut.
+ let routeChildren = false;
if (typeof topic === 'string' && topic.includes('/')) {
const parts = topic.split('/');
for (
@@ -1863,6 +1868,7 @@ export async function unknownTopicError(topic, catalog) {
) {
const near = tree.get(parts.slice(0, depth).join('/'));
if (near) {
+ routeChildren = true;
suggestions = near.slots.flatMap(slot =>
slot.children.map(route => ({
name: route,
@@ -1894,7 +1900,9 @@ export async function unknownTopicError(topic, catalog) {
];
}
if (typeof topic === 'string') {
- suggestions = orderRouteSuggestions(topic, suggestions);
+ suggestions = orderRouteSuggestions(topic, suggestions, {
+ closest: !routeChildren,
+ });
}
// A route that moved names where it went, ahead of the usual suggestions
// (spec:AST-046 FR9, FR6).
diff --git a/packages/cli/api/docs/docs.test.mjs b/packages/cli/api/docs/docs.test.mjs
index 24d39266c4..a8b01929e7 100644
--- a/packages/cli/api/docs/docs.test.mjs
+++ b/packages/cli/api/docs/docs.test.mjs
@@ -254,6 +254,24 @@ describe('docs() dispatcher routing', () => {
);
}, SLOW);
+ it('an unknown route keeps every child of its namespace, closest first', async () => {
+ const error = await docs('tokens/usage').catch(e => e);
+ expect(error.code).toBe('ERR_UNKNOWN_TOPIC');
+ const names = error.suggestions.map(s => s.name);
+ expect(names[0]).toBe('tokens/tokens-usage');
+ const none = await docs('tokens/zzzz-nope').catch(e => e);
+ expect([...names].sort()).toEqual(none.suggestions.map(s => s.name).sort());
+ }, SLOW);
+
+ it('an unknown flat topic is cut where the matches get weaker', async () => {
+ const error = await docs('authoring-at-meta').catch(e => e);
+ expect(error.suggestions.map(s => s.name)).toEqual(['authoring']);
+ // One-letter words do not narrow it: `a11y` keeps the whole browse list.
+ const browse = await docs('zzzz-nope').catch(e => e);
+ const a11y = await docs('a11y').catch(e => e);
+ expect(a11y.suggestions.length).toBe(browse.suggestions.length);
+ }, SLOW);
+
it('a section no guide of a namespace has -> ERR_UNKNOWN_SECTION, naming its guides', async () => {
const err = await docs('cli', 'zzzz-nope').catch(e => e);
expect(err).toBeInstanceOf(AstryxError);
diff --git a/packages/cli/api/docs/integrationDocs.test.mjs b/packages/cli/api/docs/integrationDocs.test.mjs
index 2e4347a183..96c8d4d029 100644
--- a/packages/cli/api/docs/integrationDocs.test.mjs
+++ b/packages/cli/api/docs/integrationDocs.test.mjs
@@ -450,11 +450,11 @@ describe('integration-contributed topics', () => {
it('offers the contributed topics as suggestions on an unknown one', async () => {
scaffold({'deploying.doc.mjs': topic()});
- await expect(docs('nope-not-a-topic', undefined, {cwd: tmpDir, full: true})).rejects.toBeInstanceOf(
+ await expect(docs('zzqx-qqzz', undefined, {cwd: tmpDir, full: true})).rejects.toBeInstanceOf(
AstryxError,
);
try {
- await docs('nope-not-a-topic', undefined, {cwd: tmpDir, full: true});
+ await docs('zzqx-qqzz', undefined, {cwd: tmpDir, full: true});
} catch (err) {
expect(err.suggestions.map(s => s.name)).toContain('deploying');
}
diff --git a/packages/cli/api/template/template.mjs b/packages/cli/api/template/template.mjs
index 5b1f684134..33e97af45b 100644
--- a/packages/cli/api/template/template.mjs
+++ b/packages/cli/api/template/template.mjs
@@ -190,7 +190,9 @@ export async function template(name, options = {}) {
if (name && candidates.length === 0) {
throw new AstryxError(
`Unknown template "${name}"`,
- orderByAffinity(name, templates, t => [t.dirName, t.name]).map(t => ({
+ orderByAffinity(name, templates, t => [t.dirName, t.name], {
+ closest: true,
+ }).map(t => ({
name: t.dirName,
reason: `${t.type} template`,
})),
diff --git a/packages/cli/api/template/unknown-name.test.mjs b/packages/cli/api/template/unknown-name.test.mjs
new file mode 100644
index 0000000000..78f43e9739
--- /dev/null
+++ b/packages/cli/api/template/unknown-name.test.mjs
@@ -0,0 +1,63 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file The suggestions an unknown template name prints: the closest
+ * templates first, and the list stops where the matches get weaker. A name
+ * that shares no word with any template still lists every template.
+ */
+
+import {describe, it, expect} from 'vitest';
+import * as path from 'node:path';
+import {fileURLToPath} from 'node:url';
+import {template} from './template.mjs';
+import {nameWords} from '../../foundation/text/suggest-order.mjs';
+
+const cwd = path.resolve(
+ path.dirname(fileURLToPath(import.meta.url)),
+ '../../../..',
+);
+const SLOW = 30_000;
+
+/** @param {string} name */
+async function suggested(name) {
+ const error = await template(name, {cwd}).catch(e => e);
+ expect(error.code).toBe('ERR_UNKNOWN_TEMPLATE');
+ return error.suggestions.map((/** @type {{name: string}} */ s) => s.name);
+}
+
+describe('unknown template suggestions', () => {
+ it(
+ 'lists only templates that carry the typed words when one carries them all',
+ async () => {
+ const all = await suggested('zzqx-nothing-like-it');
+ const near = await suggested('settings-panel');
+ expect(near.length).toBeGreaterThan(0);
+ expect(near.length).toBeLessThan(all.length);
+ for (const name of near.slice(1)) {
+ const words = nameWords(name);
+ expect(words).toContain('setting');
+ expect(words).toContain('panel');
+ }
+ },
+ SLOW,
+ );
+
+ it(
+ 'does not narrow the list on a one-letter word',
+ async () => {
+ const all = await suggested('zzqx-nothing-like-it');
+ expect(await suggested('a11y')).toHaveLength(all.length);
+ },
+ SLOW,
+ );
+
+ it(
+ 'lists every template when no template shares a word with the name',
+ async () => {
+ const all = await suggested('zzqx-nothing-like-it');
+ expect(new Set(all).size).toBe(all.length);
+ expect(all.length).toBeGreaterThan(100);
+ },
+ SLOW,
+ );
+});
diff --git a/packages/cli/foundation/text/suggest-order.mjs b/packages/cli/foundation/text/suggest-order.mjs
index e7cd4e3c45..7964cfe28c 100644
--- a/packages/cli/foundation/text/suggest-order.mjs
+++ b/packages/cli/foundation/text/suggest-order.mjs
@@ -5,13 +5,15 @@
*
* 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.
+ * caller most likely meant comes first. Asked for the closest entries only,
+ * it also cuts a list where the matches get weaker. 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
+ * @output the entries, reordered, and cut when asked
* @position lib: shared by the component, template and docs lookup errors
*/
@@ -79,15 +81,15 @@ function affinityOf(typed, name) {
}
/**
- * The same items, closest to the typed name first; each item is as close as
- * its closest name. Equal matches keep their original order.
+ * The items scored against the typed name, closest first; equal matches keep
+ * their original order.
* @template T
* @param {string} typedName
* @param {T[]} items
* @param {(item: T) => Array<string | undefined>} namesOf
- * @returns {T[]}
+ * @returns {Array<{item: T, best: number}>}
*/
-export function orderByAffinity(typedName, items, namesOf) {
+function scoreByAffinity(typedName, items, namesOf) {
const typed = nameWords(typedName);
const scored = items.map((item, index) => {
let best = 0;
@@ -97,30 +99,73 @@ export function orderByAffinity(typedName, items, namesOf) {
return {item, index, best};
});
scored.sort((a, b) => b.best - a.best || a.index - b.index);
- return scored.map(s => s.item);
+ return scored;
+}
+
+/**
+ * The same items, closest to the typed name first; each item is as close as
+ * its closest name. Equal matches keep their original order.
+ *
+ * With `closest`, the list also stops where the matches get weaker. Only
+ * typed words longer than one character count here. When the best item
+ * carries every such word, only the items that carry every one of them stay;
+ * when it carries some of them, the items that carry none are left out. When
+ * no item carries one, nothing is left out. The list only ever gets shorter,
+ * and its order does not change.
+ * @template T
+ * @param {string} typedName
+ * @param {T[]} items
+ * @param {(item: T) => Array<string | undefined>} namesOf
+ * @param {{closest?: boolean}} [options]
+ * @returns {T[]}
+ */
+export function orderByAffinity(typedName, items, namesOf, options = {}) {
+ const scored = scoreByAffinity(typedName, items, namesOf);
+ if (!options.closest) return scored.map(s => s.item);
+ // One-letter words (`a` in `a11y`, `use-a-theme`) say nothing about which
+ // entry was meant, so the cut counts only the longer typed words.
+ const words = nameWords(typedName).filter(w => w.length > 1);
+ const tierOf = (/** @type {T} */ item) => {
+ let best = 0;
+ for (const name of namesOf(item)) {
+ if (name) best = Math.max(best, affinityOf(words, name));
+ }
+ // Tiers: 1 some typed word, 2 every typed word, 4 the same words.
+ return Math.floor(best / 10);
+ };
+ const tiers = scored.map(s => tierOf(s.item));
+ const top = Math.max(0, ...tiers);
+ if (top === 0) return scored.map(s => s.item);
+ const need = Math.min(top, 2);
+ return scored.filter((_, i) => tiers[i] >= need).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.
+ * was meant. Equal matches keep their order. `closest` stops the list where
+ * the matches get weaker, as in {@link orderByAffinity}.
* @template {{name: string}} T
* @param {string} topic - the typed route
* @param {T[]} suggestions
+ * @param {{closest?: boolean}} [options]
* @returns {T[]}
*/
-export function orderRouteSuggestions(topic, suggestions) {
+export function orderRouteSuggestions(topic, suggestions, options = {}) {
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]);
+ ? orderByAffinity(
+ topic.slice(namespace.length),
+ suggestions,
+ s => [s.name.slice(namespace.length)],
+ options,
+ )
+ : orderByAffinity(topic, suggestions, s => [s.name], options);
}
/** Library names a synonym may start with (`MUI TextField`). */
diff --git a/packages/cli/foundation/text/suggest-order.test.mjs b/packages/cli/foundation/text/suggest-order.test.mjs
index 8a09957efe..d084ffe90a 100644
--- a/packages/cli/foundation/text/suggest-order.test.mjs
+++ b/packages/cli/foundation/text/suggest-order.test.mjs
@@ -86,6 +86,50 @@ describe('orderByAffinity', () => {
});
});
+describe('orderByAffinity with closest', () => {
+ const closest = (/** @type {string[]} */ list, /** @type {string} */ typed) =>
+ orderByAffinity(typed, list, n => [n], {closest: true});
+
+ it('keeps the items with every typed word after the same words, and drops the weaker ones', () => {
+ expect(
+ closest(
+ [
+ 'zeta-panel',
+ 'other',
+ 'wide-panel-grid',
+ 'panel-grid',
+ 'grid-panel-x',
+ ],
+ 'PanelGrid',
+ ),
+ ).toEqual(['panel-grid', 'wide-panel-grid', 'grid-panel-x']);
+ });
+
+ it('keeps every item with a typed word when the best has only some of them', () => {
+ expect(closest(['table', 'card-grid', 'list-view'], 'card list')).toEqual([
+ 'card-grid',
+ 'list-view',
+ ]);
+ });
+
+ it('does not count one-letter words', () => {
+ const list = ['use-a-theme', 'author-a-theme', 'card', 'table'];
+ expect(closest(list, 'a11y')).toEqual(list);
+ expect(closest(list, 'make-a-card')).toEqual(['card']);
+ });
+
+ it('keeps the whole list, in its order, when no item has a typed word', () => {
+ expect(closest(['c', 'b', 'a'], 'thing')).toEqual(['c', 'b', 'a']);
+ });
+
+ it('only ever shortens the list', () => {
+ const list = ['alpha-beta', 'beta', 'gamma', 'alpha'];
+ const out = closest(list, 'alpha beta');
+ expect(out.every(n => list.includes(n))).toBe(true);
+ expect(out.length).toBeLessThanOrEqual(list.length);
+ });
+});
+
describe('rankComponentSuggestions', () => {
const all = [
'Zebra',
@@ -250,6 +294,15 @@ describe('orderRouteSuggestions', () => {
);
});
+ it('with closest, keeps only the child the route names', () => {
+ expect(
+ names(orderRouteSuggestions('guide/ship-it', kids, {closest: true})),
+ ).toEqual(['guide/ship']);
+ expect(
+ names(orderRouteSuggestions('guide/theme', kids, {closest: true})),
+ ).toEqual(names(kids));
+ });
+
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(