An open source design system that's fully customizable and agent ready
TypeScript
search: find a family member by its name spelled out (#7927)
Joey20230c652780
diff --git a/.changeset/search-family-member-names.md b/.changeset/search-family-member-names.mdnew file mode 100644index 0000000000..1803da8e5d--- /dev/null+++ b/.changeset/search-family-member-names.md@@ -0,0 +1,7 @@+---+'@astryxdesign/cli': patch+---++[fix] `astryx search` finds a family member by its name spelled out, as its own description spells it ("vertical stack" is VStack), and lists a member named by its head word after single letters (VStack, HStack) for that word ("stack").++@josephfarinadiff --git a/packages/cli/api/search/_candidate-score.mjs b/packages/cli/api/search/_candidate-score.mjsindex 87a66d8ad8..3b8735f362 100644--- a/packages/cli/api/search/_candidate-score.mjs+++ b/packages/cli/api/search/_candidate-score.mjs@@ -41,11 +41,56 @@ import {wordForms,sameWord,startsAWordOf,+ wordsOf,joined,isTypo,} from './_words.mjs';import {pluralOf} from './_query.mjs';+/**+ * Whether a multi-word term spells out a name word by word: as many words as+ * the name, each the name's word in order or, for a single-letter word, a word+ * starting with that letter ("vertical" for V) that the entry's own+ * description names. `vertical stack` spells out VStack when its description says+ * "vertical"; `visual stack` does not.+ * @param {string} term+ * @param {string} name+ * @param {string} description+ */+function spellsOut(term, name, description) {+ const words = term.split(/\s+/).filter(Boolean);+ const parts = wordsOf(name);+ if (words.length < 2 || words.length !== parts.length) return false;+ const described = wordsOf(description);+ let expanded = false;+ for (let i = 0; i < words.length; i++) {+ const w = words[i];+ const p = parts[i];+ if (sameWord(w, p)) continue;+ // Only a single-letter word is an abbreviation to spell out: "With" in a+ // name is not spelled out by "without".+ if (p.length !== 1 || !w.startsWith(p)) return false;+ if (!described.some(d => sameWord(d, w))) return false;+ expanded = true;+ }+ return expanded;+}++/**+ * Whether a one-word term is a name's last word and every word before it is a+ * single letter: Stack in VStack and HStack.+ * @param {string} term+ * @param {string} name+ */+function headOfLetters(term, name) {+ const parts = wordsOf(name);+ return (+ parts.length >= 2 &&+ sameWord(term, parts[parts.length - 1]) &&+ parts.slice(0, -1).every(p => p.length === 1)+ );+}+/*** Score a single candidate against the search term across name, keywords,* and prose signals. Returns the best (highest) score plus a human reason,@@ -62,7 +107,7 @@ import {pluralOf} from './_query.mjs';* @param {string} [candidate.description]* @param {string[]} [candidate.prose] - Extra free-text blobs (doc section text, best practices).* @param {string[]} [candidate.guidance] - Usage guidance (features, best practices) — scored a tier below description.- * @param {{fuzzy?: boolean, joins?: boolean}} [opts] - `fuzzy`: allow edit-distance (typo) matches. Default true; multi-word queries pass false. `joins`: read a spaced query joined into a name or keyword (default true); off when the query names an entry outright.+ * @param {{fuzzy?: boolean, joins?: boolean, part?: boolean}} [opts] - `fuzzy`: allow edit-distance (typo) matches. Default true; multi-word queries pass false. `joins`: read a spaced query joined into a name or keyword (default true); off when the query names an entry outright. `part`: the term is one word of a longer query, so a name's head word after single letters (Stack in VStack) does not count as a keyword hit for it.* @returns {{score: number, reason: string, alias?: 'partial' | 'keyword'} | null}* `alias` marks a hit that read the query's words joined.*/@@ -78,7 +123,7 @@ export function scoreCandidate(prose = [],guidance = [],},- {fuzzy = true, joins = true} = {},+ {fuzzy = true, joins = true, part = false} = {},) {let best = 0;let reason = '';@@ -128,6 +173,15 @@ export function scoreCandidate(// Most of the name typed as words, cut short: `complex select` is// ComplexSelector, ahead of a one-word keyword elsewhere.consider(95, `name "${candidateName}" spelled`, 'partial');+ } else if (+ domain !== 'doc' &&+ domain !== 'theme' &&+ spellsOut(term, candidateName, description)+ ) {+ // The name's short words spelled out, in order, as the entry's own+ // description spells them: `vertical stack` is VStack ("Vertical stack+ // for arranging items top-to-bottom").+ consider(95, `name "${candidateName}" spelled out`);} else if (pluralOf(nameLower, term) || pluralOf(term, nameLower)) {// One point under the exact spelling, so the doc named `tokens` still// outranks the Token component for `tokens`.@@ -135,7 +189,16 @@ export function scoreCandidate(} else {if (sameWord(term, nameLower)) consider(95, `name "${candidateName}"`);// The term is a word of the name, or starts one: "input" in TextInput.- else if (startsAWordOf(term, candidateName)) {+ else if (+ !part &&+ domain !== 'doc' &&+ domain !== 'theme' &&+ headOfLetters(term, candidateName)+ ) {+ // The whole query is the name's head word after single letters (Stack+ // in VStack, HStack): a variant named by its head, as a keyword is.+ consider(90, `name "${candidateName}" ends in "${term}"`);+ } else if (startsAWordOf(term, candidateName)) {consider(60, `name contains "${term}"`);}if (fuzzy) {diff --git a/packages/cli/api/search/_priority.mjs b/packages/cli/api/search/_priority.mjsindex ed9a0d792c..471f93900a 100644--- a/packages/cli/api/search/_priority.mjs+++ b/packages/cli/api/search/_priority.mjs@@ -132,7 +132,8 @@ export function domainPriority(const fuzzy = tokens.length <= 1;return words.some(w =>- (bestForToken(w, candidate, {fuzzy})?.score ?? 0) >= STRONG_TOKEN_SCORE,+ (bestForToken(w, candidate, {fuzzy, part: words.length > 1})?.score ??+ 0) >= STRONG_TOKEN_SCORE,)? 1: 0;diff --git a/packages/cli/api/search/_score.mjs b/packages/cli/api/search/_score.mjsindex a701a12ffa..3b2b2b675f 100644--- a/packages/cli/api/search/_score.mjs+++ b/packages/cli/api/search/_score.mjs@@ -39,7 +39,7 @@ const MIN_TOKEN_SCORE = 50;* (synonym hits are discounted so a direct hit always wins).* @param {string} tok* @param {Candidate} candidate- * @param {{fuzzy?: boolean}} [opts]+ * @param {{fuzzy?: boolean, part?: boolean}} [opts] - see scoreCandidate* @returns {{score: number, reason: string} | null}*/export function bestForToken(tok, candidate, opts = {}) {@@ -187,7 +187,7 @@ export function scoreQuery(let alias = false;let aliasWords = 0;for (const tok of tokens) {- let h = bestForToken(tok, candidate, {fuzzy});+ let h = bestForToken(tok, candidate, {fuzzy, part: true});if (compound?.covered.has(joined(tok)) &&compound.score > (h?.score ?? 0)diff --git a/packages/cli/api/search/search.family-members.test.mjs b/packages/cli/api/search/search.family-members.test.mjsnew file mode 100644index 0000000000..e54327e77d--- /dev/null+++ b/packages/cli/api/search/search.family-members.test.mjs@@ -0,0 +1,124 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file A family member named by short words is found by them spelled out:+ * "vertical stack" is VStack, whose own description says so, and a member whose+ * name is its head word after single letters is a match for that head word.+ * The same holds for any integration's members, which no learned weights know.+ */++import fs from 'node:fs';+import os from 'node:os';+import path from 'node:path';+import {afterAll, beforeAll, describe, expect, it} from 'vitest';+import {search} from './search.mjs';++const SLOW = 60_000;++describe('family members found by their spelled-out names', () => {+ it.each([+ ['vertical stack', 'VStack'],+ ['horizontal stack', 'HStack'],+ ])('`%s` ranks %s first', async (query, name) => {+ const {results} = (await search(query)).data;+ expect(results[0], JSON.stringify(results.slice(0, 3))).toMatchObject({+ domain: 'component',+ name,+ });+ });++ it('`stack` keeps Stack first and lists VStack and HStack', async () => {+ const {results} = (await search('stack')).data;+ expect(results[0]).toMatchObject({domain: 'component', name: 'Stack'});+ const top = results.slice(0, 8).map(r => r.name);+ expect(top).toContain('VStack');+ expect(top).toContain('HStack');+ });++ it('only a single-letter word is spelled out', async () => {+ // "without" begins with "With" but spells out no letter of the name.+ const {results} = (await search('checkbox list without end content')).data;+ expect(results[0]?.reason).not.toMatch(/spelled out/);+ });++ it('a longer query keeps Stack first', async () => {+ // Stack in VStack counts as a keyword hit only when it is the whole query.+ const {results} = (await search('vertical stack of cards')).data;+ expect(results[0]).toMatchObject({domain: 'component', name: 'Stack'});+ });++ it("a longer query does not lift a head word's members", async () => {+ const {results} = (await search('stack direction')).data;+ const top = results.slice(0, 3).map(r => r.name);+ expect(top).not.toContain('VStack');+ expect(top).not.toContain('HStack');+ });++ it('a word the description does not spell out is no name', async () => {+ const {results} = (await search('visual stack')).data;+ expect(results[0]?.name).not.toBe('VStack');+ });+});++describe("an integration's family members (cold start)", () => {+ /** @type {string} */+ let dir;+ beforeAll(() => {+ dir = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-family-members-'));+ const pkg = path.join(dir, 'node_modules', '@acme', 'grids');+ fs.mkdirSync(path.join(pkg, 'components'), {recursive: true});+ fs.mkdirSync(+ path.join(dir, 'node_modules', '@astryxdesign', 'core', 'src'),+ {+ recursive: true,+ },+ );+ fs.writeFileSync(path.join(dir, 'package.json'), '{"name":"consumer"}');+ fs.writeFileSync(+ path.join(dir, 'astryx.config.mjs'),+ "export default { integrations: ['@acme/grids'] };\n",+ );+ fs.writeFileSync(+ path.join(pkg, 'package.json'),+ '{"name":"@acme/grids","version":"1.0.0"}',+ );+ fs.writeFileSync(+ path.join(pkg, 'astryx.integration.mjs'),+ "export default { components: './components' };\n",+ );+ for (const [name, description] of [+ ['VGrid', 'Vertical grid for arranging tiles in columns.'],+ ['HGrid', 'Horizontal grid for arranging tiles in rows.'],+ ]) {+ fs.writeFileSync(+ path.join(pkg, 'components', `${name}.doc.mjs`),+ `export default {+ type: 'component',+ name: '${name}',+ usage: {description: '${description}'},+ props: [],+ };\n`,+ );+ fs.writeFileSync(+ path.join(pkg, 'components', `${name}.tsx`),+ `export function ${name}() { return null; }\n`,+ );+ }+ });+ afterAll(() => fs.rmSync(dir, {recursive: true, force: true}));++ it.each([+ ['vertical grid', 'VGrid'],+ ['horizontal grid', 'HGrid'],+ ])(+ '`%s` ranks %s first',+ async (query, name) => {+ const {results} = (await search(query, {cwd: dir, type: 'component'}))+ .data;+ expect(results[0], JSON.stringify(results.slice(0, 3))).toMatchObject({+ name,+ });+ },+ SLOW,+ );+});