An open source design system that's fully customizable and agent ready
TypeScript
fix(cli): template — a typo's near name comes first in the suggestions (#10712)
Joey31ae99075f0c
diff --git a/.changeset/template-typo-suggestions.md b/.changeset/template-typo-suggestions.mdnew file mode 100644index 0000000000..2d7431f225--- /dev/null+++ b/.changeset/template-typo-suggestions.md@@ -0,0 +1,7 @@+---+'@astryxdesign/cli': patch+---++[fix] `astryx template <name>` puts the template a typo slips from first in its suggestions: a name one or two slips away (a letter added, dropped or changed, or two letters swapped, as in `AppShellCotnentOnly` or `dasbhoard`) ranks just below the templates that carry every typed word. The suggestion list is never longer than before.++@josephfarinadiff --git a/packages/cli/api/template/template.mjs b/packages/cli/api/template/template.mjsindex 98e4bbcfbc..49a005f15b 100644--- a/packages/cli/api/template/template.mjs+++ b/packages/cli/api/template/template.mjs@@ -193,6 +193,7 @@ export async function template(name, options = {}) {`Unknown template "${name}"`,orderByAffinity(name, templates, t => [t.dirName, t.name], {closest: true,+ typos: 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.mjsindex 78f43e9739..ddb9177ba4 100644--- a/packages/cli/api/template/unknown-name.test.mjs+++ b/packages/cli/api/template/unknown-name.test.mjs@@ -60,4 +60,30 @@ describe('unknown template suggestions', () => {},SLOW,);++ it.each([+ ['AppShellContentOnxy', 'AppShellContentOnly'],+ ['AppShellCotnentOnly', 'AppShellContentOnly'],+ ['ApsPhellShowcase', 'AppShellShowcase'],+ ['ai-chat-ladning', 'ai-chat-landing'],+ ['dasbhoard', 'dashboard'],+ ])(+ 'puts the template a typo of %s slips from first',+ async (typed, meant) => {+ expect((await suggested(typed))[0]).toBe(meant);+ },+ SLOW,+ );++ it(+ 'keeps a template that carries every typed word ahead of its near-name siblings',+ async () => {+ // DragToSnapPointsCard carries drag, snap, point and card, and is also+ // two slips from the typed name; it keeps its full-match rank.+ expect((await suggested('drag-snap-point-card'))[0]).toBe(+ 'DragToSnapPointsCard',+ );+ },+ SLOW,+ );});diff --git a/packages/cli/foundation/text/levenshtein.mjs b/packages/cli/foundation/text/levenshtein.mjsindex 0a764bc3e8..4b538c0148 100644--- a/packages/cli/foundation/text/levenshtein.mjs+++ b/packages/cli/foundation/text/levenshtein.mjs@@ -19,11 +19,15 @@* @param {number} [max] - The largest distance the caller can use. When* given, a larger distance answers `max + 1`, and only the cells within* `max` of the diagonal are computed.+ * @param {{swaps?: boolean}} [options] - With `swaps` and a `max`, two+ * adjacent letters swapped cost one edit, not two (the optimal string+ * alignment distance).* @returns {number}*/-export function levenshteinDistance(a, b, max) {- if (max !== undefined) return distanceWithin(a, b, max);- const m = a.length, n = b.length;+export function levenshteinDistance(a, b, max, {swaps = false} = {}) {+ if (max !== undefined) return distanceWithin(a, b, max, swaps);+ const m = a.length,+ n = b.length;// Early exit: the distance is always ≥ |m − n|, so once the length gap// exceeds the loosest fuzzy-match threshold any caller uses (the hook// suggester keeps distance ≤ 5) the pair can never match — skip the O(m·n)@@ -36,9 +40,10 @@ export function levenshteinDistance(a, b, max) {for (let j = 0; j <= n; j++) dp[0][j] = j;for (let i = 1; i <= m; i++) {for (let j = 1; j <= n; j++) {- dp[i][j] = a[i-1] === b[j-1]- ? dp[i-1][j-1]- : 1 + Math.min(dp[i-1][j], dp[i][j-1], dp[i-1][j-1]);+ dp[i][j] =+ a[i - 1] === b[j - 1]+ ? dp[i - 1][j - 1]+ : 1 + Math.min(dp[i - 1][j], dp[i][j - 1], dp[i - 1][j - 1]);}}return dp[m][n];@@ -51,11 +56,13 @@ export function levenshteinDistance(a, b, max) {* @param {string} a* @param {string} b* @param {number} max+ * @param {boolean} swaps - two adjacent letters swapped cost one edit* @returns {number}*/-function distanceWithin(a, b, max) {+function distanceWithin(a, b, max, swaps) {const over = max + 1;if (Math.abs(a.length - b.length) > max) return over;+ let before = new Array(b.length + 1).fill(over);let previous = new Array(b.length + 1).fill(over);let current = new Array(b.length + 1).fill(over);for (let j = 0; j <= Math.min(b.length, max); j++) previous[j] = j;@@ -67,18 +74,27 @@ function distanceWithin(a, b, max) {let rowMin = current[0];for (let j = from; j <= to; j++) {const cost = a[i - 1] === b[j - 1] ? 0 : 1;- const value = Math.min(+ let value = Math.min(previous[j - 1] + cost,previous[j] + 1,current[j - 1] + 1,over,);+ if (+ swaps &&+ i > 1 &&+ j > 1 &&+ a[i - 1] === b[j - 2] &&+ a[i - 2] === b[j - 1]+ ) {+ value = Math.min(value, before[j - 2] + 1);+ }current[j] = value;if (value < rowMin) rowMin = value;}// Every later cell costs at least this row's least.if (rowMin >= over) return over;- [previous, current] = [current, previous];+ [before, previous, current] = [previous, current, before];}return Math.min(previous[b.length], over);}diff --git a/packages/cli/foundation/text/levenshtein.test.mjs b/packages/cli/foundation/text/levenshtein.test.mjsindex 0116f2a0ec..91e54b72de 100644--- a/packages/cli/foundation/text/levenshtein.test.mjs+++ b/packages/cli/foundation/text/levenshtein.test.mjs@@ -64,3 +64,24 @@ describe('levenshteinDistance', () => {});});+describe('levenshteinDistance with swaps', () => {+ it('counts two adjacent letters swapped as one edit', () => {+ expect(d('gorup', 'group', 2, {swaps: true})).toBe(1);+ expect(d('gorup', 'group', 2)).toBe(2);+ });++ it('agrees with the plain distance when nothing is swapped', () => {+ for (const [a, b] of [+ ['button', 'buton'],+ ['dashboard', 'dashbord'],+ ['card', 'cart'],+ ['abc', 'xyz'],+ ]) {+ expect(d(a, b, 3, {swaps: true})).toBe(d(a, b, 3));+ }+ });++ it('answers max + 1 past the cap', () => {+ expect(d('abcdef', 'badcfe', 2, {swaps: true})).toBe(3);+ });+});diff --git a/packages/cli/foundation/text/suggest-order.mjs b/packages/cli/foundation/text/suggest-order.mjsindex 7964cfe28c..bf466ca276 100644--- a/packages/cli/foundation/text/suggest-order.mjs+++ b/packages/cli/foundation/text/suggest-order.mjs@@ -19,6 +19,12 @@import {levenshteinDistance} from './levenshtein.mjs';+/**+ * The score of a near name (nearNameSlips), less a little per slip: above any+ * name that carries only some of the typed words, below one that carries all+ * of them.+ */+const NEAR_NAME_SCORE = 19.6;/** 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. */@@ -59,17 +65,22 @@ export function nameWords(text) {* 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.+ * the typed name (or the reverse) gets a small lift. With `typos`, a near name+ * (one or two slips from the typed name) ranks just below the names that+ * carry every typed word.* @param {string[]} typed - {@link nameWords} of the typed name* @param {string} name+ * @param {{typos?: boolean}} [options]* @returns {number}*/-function affinityOf(typed, name) {+function affinityOf(typed, name, {typos = false} = {}) {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 slips = typos ? nearNameSlips(typedJoined, joined) : 0;+ const near = slips > 0 ? NEAR_NAME_SCORE - slips * 0.2 : 0;const have = new Set(words);const want = new Set(typed);const covered = typed.filter(w => have.has(w)).length / typed.length;@@ -77,7 +88,29 @@ function affinityOf(typed, name) {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;+ // A near name keeps its word score when that is higher: a name that also+ // carries every typed word ranks among the other full matches.+ return Math.max(+ near,+ tier * 10 + covered * 4 + precise * 2 + prefix + precise * 0.01,+ );+}++/**+ * How many slips separate a typed name from a candidate, both with their+ * words joined, when it is a near name: an edit or two adjacent letters+ * swapped count as one slip, one slip is allowed from five letters and two from+ * eight. Zero when it is not a near name.+ * @param {string} typed+ * @param {string} name+ * @returns {number}+ */+function nearNameSlips(typed, name) {+ const shorter = Math.min(typed.length, name.length);+ const cap = shorter >= 8 ? 2 : shorter >= 5 ? 1 : 0;+ if (cap === 0 || Math.abs(typed.length - name.length) > cap) return 0;+ const slips = levenshteinDistance(typed, name, cap, {swaps: true});+ return slips <= cap ? slips : 0;}/**@@ -87,14 +120,15 @@ function affinityOf(typed, name) {* @param {string} typedName* @param {T[]} items* @param {(item: T) => Array<string | undefined>} namesOf+ * @param {{typos?: boolean}} [options]* @returns {Array<{item: T, best: number}>}*/-function scoreByAffinity(typedName, items, namesOf) {+function scoreByAffinity(typedName, items, namesOf, options = {}) {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));+ if (name) best = Math.max(best, affinityOf(typed, name, options));}return {item, index, best};});@@ -112,14 +146,46 @@ function scoreByAffinity(typedName, items, namesOf) {* 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.+ *+ * With `typos`, a near name (one or two slips from the typed name, as+ * `ButonGroup` or `ButtonGorup` for ButtonGroup) ranks just below the names+ * that carry every typed word and above the rest. With `closest` too, near+ * names stay in the list whatever the cut leaves out, and the list is never+ * longer than it is without `typos`.* @template T* @param {string} typedName* @param {T[]} items* @param {(item: T) => Array<string | undefined>} namesOf- * @param {{closest?: boolean}} [options]+ * @param {{closest?: boolean, typos?: boolean}} [options]* @returns {T[]}*/export function orderByAffinity(typedName, items, namesOf, options = {}) {+ if (!options.typos) return orderByWords(typedName, items, namesOf, options);+ const scored = scoreByAffinity(typedName, items, namesOf, {typos: true});+ if (!options.closest) return scored.map(s => s.item);+ const kept = new Set(orderByWords(typedName, items, namesOf, options));+ return scored+ .filter(s => kept.has(s.item) || isNearScore(s.best))+ .slice(0, kept.size)+ .map(s => s.item);+}++/**+ * Whether a score is a near name's.+ * @param {number} score+ */+const isNearScore = score => score < 20 && score > NEAR_NAME_SCORE - 1;++/**+ * {@link orderByAffinity} without `typos`.+ * @template T+ * @param {string} typedName+ * @param {T[]} items+ * @param {(item: T) => Array<string | undefined>} namesOf+ * @param {{closest?: boolean}} options+ * @returns {T[]}+ */+function orderByWords(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 whichdiff --git a/packages/cli/foundation/text/suggest-order.test.mjs b/packages/cli/foundation/text/suggest-order.test.mjsindex d084ffe90a..b5fe12d924 100644--- a/packages/cli/foundation/text/suggest-order.test.mjs+++ b/packages/cli/foundation/text/suggest-order.test.mjs@@ -310,3 +310,43 @@ describe('orderRouteSuggestions', () => {);});});++describe('orderByAffinity with typos', () => {+ const items = [+ {name: 'AvatarGroup'},+ {name: 'AvatarGroupShowcase'},+ {name: 'ButtonGroup'},+ {name: 'HStackShowcase'},+ {name: 'VStackShowcase'},+ {name: 'Badge'},+ ];+ /** @param {{name: string}[]} list */+ const names = list => list.map(i => i.name);+ /** @param {string} typed @param {boolean} typos */+ const order = (typed, typos) =>+ names(orderByAffinity(typed, items, i => [i.name], {closest: true, typos}));++ it('puts a name one slip away first', () => {+ expect(order('ButonGroup', false)[0]).toBe('AvatarGroup');+ expect(order('ButonGroup', true)[0]).toBe('ButtonGroup');+ });++ it('counts two swapped letters as one slip', () => {+ // Five letters allow one slip, so `Bagde` is a near name of Badge only+ // when the swap counts as one edit rather than two.+ expect(order('Bagde', false)[0]).not.toBe('Badge');+ expect(order('Bagde', true)[0]).toBe('Badge');+ });++ it('puts the name with fewer slips first', () => {+ expect(order('VStxckShowcase', true)[0]).toBe('VStackShowcase');+ });++ it('never lists more than without typos', () => {+ for (const typed of ['ButonGroup', 'VStxckShowcase', 'Group', 'zzz']) {+ expect(order(typed, true).length).toBeLessThanOrEqual(+ order(typed, false).length,+ );+ }+ });+});