An open source design system that's fully customizable and agent ready
TypeScript
search: a family word lists the family's first members (#7955)
Joey626f01ec76df
diff --git a/.changeset/search-family-word-members.md b/.changeset/search-family-word-members.mdnew file mode 100644index 0000000000..79048add2d--- /dev/null+++ b/.changeset/search-family-word-members.md@@ -0,0 +1,7 @@+---+'@astryxdesign/cli': patch+---++[fix] `astryx search` lists the first three members a family's doc names for a query that is the family's name ("table" lists three Table parts after Table; "chat" lists Chat parts though no Chat component exists), for Core and integration families alike.++@josephfarinadiff --git a/packages/cli/api/search/_candidate-score.mjs b/packages/cli/api/search/_candidate-score.mjsindex 3b8735f362..0ce426ee0f 100644--- a/packages/cli/api/search/_candidate-score.mjs+++ b/packages/cli/api/search/_candidate-score.mjs@@ -91,6 +91,9 @@ function headOfLetters(term, name) {);}+/** How many of a family's members a query naming the family lists. */+const FAMILY_MEMBERS = 3;+/*** Score a single candidate against the search term across name, keywords,* and prose signals. Returns the best (highest) score plus a human reason,@@ -107,7 +110,9 @@ function headOfLetters(term, name) {* @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, 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.+ * @param {string} [candidate._family] - The family whose doc lists the entry as a member.+ * @param {number} [candidate._familyIndex] - The entry's place among that family's members.+ * @param {{fuzzy?: boolean, joins?: boolean, part?: boolean, synonym?: 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. `synonym`: the term stands in for a word of the query, so it names no family.* @returns {{score: number, reason: string, alias?: 'partial' | 'keyword'} | null}* `alias` marks a hit that read the query's words joined.*/@@ -122,8 +127,10 @@ export function scoreCandidate(description = '',prose = [],guidance = [],+ _family,+ _familyIndex,},- {fuzzy = true, joins = true, part = false} = {},+ {fuzzy = true, joins = true, part = false, synonym = false} = {},) {let best = 0;let reason = '';@@ -213,6 +220,23 @@ export function scoreCandidate(}}+ // ── Family signal ───────────────────────────────────────────────+ // A query naming a family lists its first members as a keyword would: the+ // family doc names them, whether or not a component of the family's name+ // exists ("chat" lists ChatMessage and its siblings). Only the whole query+ // names the family: a word of a longer query lifts no member.+ if (+ !part &&+ !synonym &&+ _family &&+ (_familyIndex ?? Infinity) < FAMILY_MEMBERS &&+ (term === _family.toLowerCase() ||+ term === wordsOf(_family).join(' ') ||+ term.replace(/\s+/g, '') === _family.toLowerCase())+ ) {+ consider(90, `member of ${_family}`);+ }+// ── Keyword signals ─────────────────────────────────────────────const termJoined = joined(term);for (const kw of keywords) {diff --git a/packages/cli/api/search/_gather-components.mjs b/packages/cli/api/search/_gather-components.mjsindex b5f7b86b93..c70d7f0521 100644--- a/packages/cli/api/search/_gather-components.mjs+++ b/packages/cli/api/search/_gather-components.mjs@@ -5,6 +5,8 @@* integrations contribute, read from their docs. Imported only by the adapter.*/+import fs from 'node:fs';+import path from 'node:path';import {discoverExternalPackages} from '../../foundation/fs/paths.mjs';import {discoverComponents,@@ -29,6 +31,28 @@ import {loadModuleDoc, guidanceFrom} from './_module-doc.mjs';/** @typedef {import('./_lexical.mjs').Candidate} Candidate */+/**+ * The members a family doc names, each with the family and its place among+ * the members (the family's own entry left out). A query naming the family+ * lists its first members (see scoreCandidate).+ * @param {any} docs+ * @returns {Map<string, {_family: string, _familyIndex: number}>}+ */+function familyPlaces(docs) {+ /** @type {Map<string, {_family: string, _familyIndex: number}>} */+ const out = new Map();+ if (!docs || typeof docs.name !== 'string') return out;+ (Array.isArray(docs.components) ? docs.components : [])+ .map((/** @type {any} */ m) => (typeof m === 'string' ? m : m?.name))+ .filter(+ (/** @type {unknown} */ n) => typeof n === 'string' && n !== docs.name,+ )+ .forEach((/** @type {string} */ n, /** @type {number} */ i) =>+ out.set(n, {_family: docs.name, _familyIndex: i}),+ );+ return out;+}+/*** Build component candidates from core's own tree: name + keywords +* usage/description from the component's .doc.mjs.@@ -40,6 +64,8 @@ async function gatherCoreComponents(coreDir) {const names = Object.values(grouped).flat();/** @type {Candidate[]} */const candidates = [];+ /** @type {Map<string, {_family: string, _familyIndex: number}>} */+ const places = new Map();for (const comp of names) {const readme = findComponentReadme(coreDir, comp);/** @type {string[]} */@@ -58,6 +84,7 @@ async function gatherCoreComponents(coreDir) {description = doc.usage?.description || doc.description || '';guidance = guidanceFrom(doc);}+ for (const [n, place] of familyPlaces(loaded)) places.set(n, place);}candidates.push({domain: 'component',@@ -69,7 +96,17 @@ async function gatherCoreComponents(coreDir) {_import: resolveImportPath(coreDir, comp),});}- return candidates;+ // A family doc with no component of its own name (Chat) names members too.+ const srcDir = path.join(coreDir, 'src');+ const listed = new Set(names);+ for (const dir of fs.existsSync(srcDir) ? fs.readdirSync(srcDir) : []) {+ const doc = path.join(srcDir, dir, `${dir}.doc.mjs`);+ if (listed.has(dir) || !fs.existsSync(doc)) continue;+ for (const [n, place] of familyPlaces(await loadModuleDoc(doc)))+ places.set(n, place);+ }+ // A family doc names its members, whose own docs may sit elsewhere.+ return candidates.map(c => ({...c, ...places.get(c.name)}));}/**@@ -105,9 +142,18 @@ async function gatherIntegrationComponents(loadedIntegrations) {.filter(rec => !isIntegrationMember(rec)).map(rec => rec.docPath),);+ /** @type {string[]} */+ const docPaths = [];forEachIntegrationDoc(integration.components, (docPath, stem) => {if (!renamed.has(docPath)) hold(fileNamed, stem, docPath);+ docPaths.push(docPath);});+ // A family doc names its members, whose own docs may sit beside it.+ /** @type {Map<string, {_family: string, _familyIndex: number}>} */+ const places = new Map();+ for (const docPath of docPaths)+ for (const [n, place] of familyPlaces(await loadModuleDoc(docPath)))+ places.set(n, place);for (const rec of components) {const loaded = await loadModuleDoc(rec.docPath);// A family member is indexed from its own entry: the family's keywords@@ -132,6 +178,7 @@ async function gatherIntegrationComponents(loadedIntegrations) {keywords: doc && Array.isArray(doc.keywords) ? doc.keywords : [],description: doc ? doc.usage?.description || doc.description || '' : '',guidance: guidanceFrom(doc),+ ...places.get(rec.name),_package: rec.package ?? integration.name,// Exactly what `component` reports: a doc may state its own specifier// (one entry point exporting several components), and only when itdiff --git a/packages/cli/api/search/_lexical.mjs b/packages/cli/api/search/_lexical.mjsindex 76905fef49..f9d188bcba 100644--- a/packages/cli/api/search/_lexical.mjs+++ b/packages/cli/api/search/_lexical.mjs@@ -90,6 +90,9 @@ import {toResult, searchedComponentsOf} from './_result.mjs';* Core's package for its components, hooks, and templates, the integration's* for what it contributed, and for a doc part the package that wrote it.* @property {string} [_displayName]+ * @property {string} [_family] - The family whose doc lists a component as a+ * member; a query naming the family lists its first members.+ * @property {number} [_familyIndex] - The member's place in that doc's list.* @property {'page'|'block'} [_kind]* @property {string} [_resultName]* @property {string} [_commandName]diff --git a/packages/cli/api/search/_priority.mjs b/packages/cli/api/search/_priority.mjsindex 471f93900a..8493985f4e 100644--- a/packages/cli/api/search/_priority.mjs+++ b/packages/cli/api/search/_priority.mjs@@ -130,10 +130,12 @@ export function domainPriority(return 1;}const fuzzy = tokens.length <= 1;+ // The whole query is read as the whole query; its words are parts of it+ // only when there are several.return words.some(- w =>- (bestForToken(w, candidate, {fuzzy, part: words.length > 1})?.score ??- 0) >= STRONG_TOKEN_SCORE,+ (w, i) =>+ (bestForToken(w, candidate, {fuzzy, part: i > 0 && tokens.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 3b2b2b675f..75c6637cc7 100644--- a/packages/cli/api/search/_score.mjs+++ b/packages/cli/api/search/_score.mjs@@ -47,7 +47,8 @@ export function bestForToken(tok, candidate, opts = {}) {const syns = SYNONYM_INDEX.get(tok);if (syns) {for (const s of syns) {- const h = scoreCandidate(s, candidate, opts);+ // A synonym of a family's name names no family: its members stay put.+ const h = scoreCandidate(s, candidate, {...opts, synonym: true});if (h) {const score = Math.round(h.score * 0.85);if (!best || score > best.score)diff --git a/packages/cli/api/search/search.family-word.test.mjs b/packages/cli/api/search/search.family-word.test.mjsnew file mode 100644index 0000000000..be2236a455--- /dev/null+++ b/packages/cli/api/search/search.family-word.test.mjs@@ -0,0 +1,146 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file A query naming a family lists the first three members its family doc+ * names, after the family's own entry: the family doc names them, so+ * this holds with no component of the family's name (Chat) and for any+ * integration's family, 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;++/** @param {{name: string, reason: string}[]} results */+const members = results =>+ results.filter(r => /^member of /.test(r.reason)).map(r => r.name);++describe('a family word lists its first members', () => {+ it('`table` keeps Table first and lists three of its members', async () => {+ const {results} = (await search('table')).data;+ expect(results[0]).toMatchObject({domain: 'component', name: 'Table'});+ expect(members(results)).toHaveLength(3);+ });++ it('`chat` lists Chat members though no Chat component exists', async () => {+ const {results} = (await search('chat')).data;+ const top = results.slice(0, 5).map(r => r.name);+ expect(top.filter(n => n.startsWith('Chat')).length).toBeGreaterThan(0);+ expect(members(results)).toHaveLength(3);+ });+});++describe('a family word keeps its members ahead of passing doc sections', () => {+ it('`selector` lists SelectorOption before any doc section', async () => {+ const {results} = (await search('selector')).data;+ const member = results.findIndex(r => r.name === 'SelectorOption');+ const section = results.findIndex(r => r.domain === 'doc');+ expect(member).toBeGreaterThan(-1);+ expect(member).toBeLessThan(5);+ if (section !== -1) expect(section).toBeGreaterThan(member);+ });+});++describe('a synonym of a family name names no family', () => {+ it.each(['message', 'messages'])(+ '`%s` lists no member above the entries that declare it',+ async query => {+ const {results} = (await search(query)).data;+ const top = results.slice(0, 5);+ expect(top.some(r => /^member of /.test(r.reason))).toBe(false);+ },+ );+});++describe("an integration's family (cold start)", () => {+ /** @type {string} */+ let dir;+ beforeAll(() => {+ dir = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-family-word-'));+ const pkg = path.join(dir, 'node_modules', '@acme', 'plots');+ 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/plots'] };\n",+ );+ fs.writeFileSync(+ path.join(pkg, 'package.json'),+ '{"name":"@acme/plots","version":"1.0.0","main":"components/Plot.tsx"}',+ );+ fs.writeFileSync(+ path.join(pkg, 'astryx.integration.mjs'),+ "export default { components: './components' };\n",+ );+ const names = ['Plot', 'PlotAxis', 'PlotLegend', 'PlotLine', 'PlotTooltip'];+ // A member with a doc of its own, which the family doc names by name.+ fs.writeFileSync(+ path.join(pkg, 'components', 'PlotTitle.doc.mjs'),+ `export default {+ type: 'component',+ name: 'PlotTitle',+ usage: {description: 'The title above a plot.'},+ props: [],+ };\n`,+ );+ fs.writeFileSync(+ path.join(pkg, 'components', 'PlotTitle.tsx'),+ 'export function PlotTitle() {\n return null;\n}\n',+ );+ fs.writeFileSync(+ path.join(pkg, 'components', 'Plot.doc.mjs'),+ `export default {+ type: 'component',+ name: 'Plot',+ import: '@acme/plots',+ usage: {description: 'A plot of data series.'},+ props: [],+ components: ${JSON.stringify([+ ...names.slice(0, 1).map(name => ({+ name,+ usage: {description: `The ${name} part of a plot.`},+ props: [],+ })),+ {name: 'PlotTitle'},+ ...names.slice(1).map(name => ({+ name,+ usage: {description: `The ${name} part of a plot.`},+ props: [],+ })),+ ])},+ };\n`,+ );+ fs.writeFileSync(+ path.join(pkg, 'components', 'Plot.tsx'),+ names.map(n => `export function ${n}() {\n return null;\n}\n`).join(''),+ );+ });+ afterAll(() => fs.rmSync(dir, {recursive: true, force: true}));++ it(+ '`plot` lists the first three members its doc names, after Plot',+ async () => {+ const {results} = (await search('plot', {cwd: dir, type: 'component'}))+ .data;+ // The first three members the doc lists, one with a doc of its own.+ expect(results[0]).toMatchObject({name: 'Plot'});+ expect(+ results+ .slice(1, 4)+ .map(r => r.name)+ .sort(),+ ).toEqual(['PlotAxis', 'PlotLegend', 'PlotTitle']);+ },+ SLOW,+ );+});