An open source design system that's fully customizable and agent ready
TypeScript
fix(search): rank components above docs matched only by keyword or heading (#7200)
Joeyfb78fa1fb149
diff --git a/.changeset/search-domain-priority.md b/.changeset/search-domain-priority.mdnew file mode 100644index 0000000000..b3c0bb87f6--- /dev/null+++ b/.changeset/search-domain-priority.md@@ -0,0 +1,7 @@+---+'@astryxdesign/cli': patch+---++[fix] `astryx search` ranks a component, hook, or template that a query word names above a doc that matched only by keyword, heading, or text. `font size` finds Text first again instead of a typography guide. A doc the query names, such as `font setup` or `migration`, or one whose title the query holds, such as `resizable side panels`, keeps its place. Result scores do not change; only the order between domains moves.++@josephfarinadiff --git a/packages/cli/api/search/search.domain-priority.test.mjs b/packages/cli/api/search/search.domain-priority.test.mjsnew file mode 100644index 0000000000..fb7599b48a--- /dev/null+++ b/packages/cli/api/search/search.domain-priority.test.mjs@@ -0,0 +1,247 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Domain priority in `search` ranking (api/search/search.mjs), run+ * against the real docs tree and @astryxdesign/core registry.+ *+ * Splitting a large doc into smaller topics gives each topic its own keywords+ * and headings, and a doc keyword or heading that holds the whole query scores+ * 170-190, above a component that matches one word by keyword (98). Every+ * split then puts another doc above the component a reader asked for. Domain+ * priority ranks a component, hook, template, or theme that a query word hits+ * by name or keyword ahead of docs the reader did not ask for, and keeps a doc+ * the query names, or whose title the query holds, where it was.+ *+ * Both directions are asserted together, so neither can be traded for the+ * other: component queries find the component first, and the obvious question+ * for each guide still finds that guide first.+ */++import {describe, it, expect} from 'vitest';+import * as path from 'node:path';+import {fileURLToPath} from 'node:url';+import {docs} from '../docs/docs.mjs';+import {domainPriority, search, scoreQuery, tokenizeQuery} from './search.mjs';++const REPO = path.resolve(+ path.dirname(fileURLToPath(import.meta.url)),+ '../../../..',+);+const cwd = REPO;+const SLOW = 30_000;++/**+ * @param {string} q+ * @param {object} candidate+ * @returns {0 | 1 | 2}+ */+const priority = (q, candidate) => {+ const tokens = tokenizeQuery(q);+ const hit = scoreQuery(q, tokens, candidate) ?? {+ score: 0,+ matched: 0,+ total: 1,+ };+ return domainPriority(q, tokens, /** @type {any} */ (candidate), hit);+};++/**+ * Every placed guide under a namespace, walked through `docs`.+ * @param {string} route+ * @param {Set<string>} [seen]+ * @returns {Promise<string[]>}+ */+async function placedGuides(route, seen = new Set()) {+ /** @type {any} */+ let node;+ try {+ node = (await docs(route)).data;+ } catch {+ return [];+ }+ /** @type {string[]} */+ const out = [];+ for (const child of (node.slots ?? []).flatMap(+ (/** @type {any} */ slot) => slot.children,+ )) {+ if (!child.route || seen.has(child.route)) continue;+ seen.add(child.route);+ if (child.kind === 'generic' && child.route.includes('/')) {+ out.push(child.route);+ }+ out.push(...(await placedGuides(child.route, seen)));+ }+ return out;+}++describe('search domain priority — the rule', () => {+ it('gives a doc no priority for a keyword or heading match', () => {+ const topic = {+ domain: 'doc',+ name: 'typography/font-setup',+ keywords: ['font size'],+ titles: ['Font Setup', 'Font Sizes'],+ };+ expect(priority('font size', topic)).toBe(0);+ });++ it('gives a doc priority when the query names it', () => {+ const topic = {domain: 'doc', name: 'typography/font-setup'};+ // The whole query spells its last route segment.+ expect(priority('font setup', topic)).toBe(2);+ expect(priority('typography/font-setup', topic)).toBe(2);+ // A word of a longer query is a flat topic's name, or its plural.+ expect(+ priority('product illustration', {domain: 'doc', name: 'illustrations'}),+ ).toBe(1);+ });++ it('names a section by its topic', () => {+ // A section candidate's own name is its section key; the reader names the+ // topic it belongs to.+ const section = {+ domain: 'doc',+ name: 'drop-shadows',+ _topic: 'elevation',+ titles: ['Drop shadows'],+ keywords: ['Drop shadows'],+ };+ expect(priority('elevation', section)).toBe(2);+ expect(priority('elevation for a raised tile', section)).toBe(1);+ });++ it('gives a doc priority when the query holds one of its titles whole', () => {+ const guide = {+ domain: 'doc',+ name: 'layout/side-panels',+ titles: ['Side panels'],+ };+ expect(priority('resizable side panels with a toolbar', guide)).toBe(1);+ });++ it('gives a doc that matches every word priority only when its title names one', () => {+ const titled = {+ domain: 'doc',+ name: 'use-a-theme',+ titles: ['Use a theme'],+ keywords: ['switcher', 'night'],+ description: 'Apply a theme to your app.',+ };+ expect(priority('night theme switcher', titled)).toBe(1);+ // A reference page that holds every word, but whose title names none.+ const reference = {+ domain: 'doc',+ name: 'api/reference',+ titles: ['Response shapes'],+ keywords: ['switcher', 'night', 'theme'],+ };+ expect(priority('night theme switcher', reference)).toBe(0);+ });++ it('gives a component priority for a name or keyword hit, not for prose', () => {+ expect(+ priority('font size', {+ domain: 'component',+ name: 'Text',+ keywords: ['font'],+ }),+ ).toBe(1);+ expect(+ priority('date picker', {domain: 'component', name: 'DatePicker'}),+ ).toBe(1);+ expect(+ priority('font size', {+ domain: 'component',+ name: 'Card',+ description: 'A surface whose font size follows its parent.',+ }),+ ).toBe(0);+ });+});++describe('search domain priority — real docs and components', () => {+ it(+ 'finds the Text component before the typography guides for `font size`',+ async () => {+ for (const q of ['font size', 'font weight']) {+ const results = (await search(q, {cwd})).data.results;+ expect(results[0], q).toMatchObject({+ domain: 'component',+ name: 'Text',+ });+ const guide = results.findIndex(+ r => r.domain === 'doc' && /^typography(?:\/|$)/.test(r.name),+ );+ // The guide still matches, below the component.+ expect(guide, q).toBeGreaterThan(0);+ }+ },+ SLOW,+ );++ it(+ 'reports the text-match score unchanged',+ async () => {+ const results = (await search('font size', {cwd})).data.results;+ const guide = results.find(+ r => r.domain === 'doc' && /^typography(?:\/|$)/.test(r.name),+ );+ expect(guide?.score).toBeGreaterThan(results[0].score);+ },+ SLOW,+ );++ it(+ 'still finds a flat guide first by its name',+ async () => {+ for (const [q, name] of [+ ['motion', 'motion'],+ ['icons', 'icons'],+ ['tokens', 'tokens'],+ ['illustration', 'illustrations'],+ ['use a theme', 'use-a-theme'],+ ['author a theme', 'author-a-theme'],+ ]) {+ const results = (await search(q, {cwd})).data.results;+ expect(results[0], q).toMatchObject({domain: 'doc', name});+ }+ },+ SLOW,+ );++ it(+ 'still finds a split topic first by its own name, in every namespace',+ async () => {+ const guides = [];+ for (const ns of ['layout', 'typography', 'tokens', 'styling', 'cli']) {+ guides.push(...(await placedGuides(ns)));+ }+ // The layout split is in the tree; the walk covers whatever else is.+ expect(guides).toContain('layout/layout-spacing');+ // Each search reads the whole index, so check one guide per namespace+ // (its first, in route order): every split is covered without a search+ // per guide.+ /** @type {Map<string, string>} */+ const firstPerNamespace = new Map();+ for (const route of [...new Set(guides)].sort()) {+ const ns = route.slice(0, route.lastIndexOf('/'));+ if (!firstPerNamespace.has(ns)) firstPerNamespace.set(ns, route);+ }+ const sample = new Set([+ 'layout/layout-spacing',+ ...firstPerNamespace.values(),+ ]);+ /** @type {string[]} */+ const misses = [];+ for (const route of sample) {+ const q = route.slice(route.lastIndexOf('/') + 1).replace(/-/g, ' ');+ const top = (await search(q, {cwd})).data.results[0];+ if (top?.domain !== 'doc' || top.name !== route) {+ misses.push(`${q} -> ${top?.domain}:${top?.name}`);+ }+ }+ expect(misses).toEqual([]);+ },+ SLOW * 2,+ );+});diff --git a/packages/cli/api/search/search.mjs b/packages/cli/api/search/search.mjsindex 3e46d0d664..5066a2646f 100644--- a/packages/cli/api/search/search.mjs+++ b/packages/cli/api/search/search.mjs@@ -54,6 +54,13 @@* description hold both words of `troubleshoot integration` answers it better* than a doc named `integration`.*+ * Between domains, ranking adds one rule ahead of the score: domain priority+ * (see {@link domainPriority}). A component, hook, template, or theme whose+ * name or keyword a query word hits ranks ahead of every doc the reader did not+ * ask for by name or title, so `font size` finds `Text` before a typography+ * topic that declares the phrase. A doc the query names, or whose title the+ * query holds, keeps its place.+ ** Description and guidance are separate tiers on purpose. A component's own* one-line description saying "notification" is a claim about what it IS; the* same word inside another component's best-practice advice is a passing@@ -476,13 +483,107 @@ const FULL_COVERAGE_SCORE = 151;*/const STRONG_TOKEN_SCORE = 70;+/**+ * A match's domain priority: 0 (none), 1, or 2 (a doc the whole query names).+ * A component, hook, template, or theme with priority ranks ahead of any doc+ * without it, whatever the two scores are. Docs among themselves rank by+ * priority, then score; everything else ranks among itself by score.+ *+ * A component, hook, template, or theme has priority (1) when one of the+ * query's words, or the whole query, hits its name or an authored keyword at+ * {@link STRONG_TOKEN_SCORE} or above, or when it matches every word.+ *+ * A doc has priority when the reader asked for that doc:+ * - 2: the whole query spells the topic's name or its last route segment+ * (`font setup` is typography/font-setup, `motion` is the motion guide);+ * - 1: a word of the query is the topic's name (`illustration` in a longer+ * question is the illustrations guide);+ * - 1: the query holds one of the doc's titles whole (`resizable side panels`+ * names "Side panels"; `light dark mode button` names "Light/Dark Mode");+ * - 1: the doc matches every word of the query and one of them is a word of+ * its title (`switch to a dark theme` and "Use a theme").+ * A section answers to its topic's name.+ *+ * A doc that matched only by keyword, by a heading holding the query, or by+ * words spread through its text has no priority. Docs are split into many+ * small topics, and each declares its own keywords and headings, so a common+ * phrase such as `font size` hits a guide's keyword or heading exactly+ * (170-190) while the component the reader is after matches one word by+ * keyword (`Text`, 98). Ranked on text alone, every split adds another doc+ * above the component. Broad reference pages match every word of many queries+ * in their text the same way. The score stays the text-match strength the+ * result reports, so callers that gate on it (`build`) see the same numbers.+ *+ * @param {string} term - Lowercased search term.+ * @param {string[]} tokens - Content tokens from tokenizeQuery(term).+ * @param {Candidate} candidate+ * @param {{score: number, matched: number, total: number}} hit - The+ * candidate's scoreQuery result.+ * @returns {0 | 1 | 2}+ */+export function domainPriority(term, tokens, candidate, hit) {+ const words = [term, ...tokens];+ if (candidate.domain === 'doc') {+ const topic = String(candidate._topic ?? candidate.name).toLowerCase();+ const asWords = (/** @type {string} */ n) =>+ n.replace(/[-_\s]+/g, ' ').trim();+ const spelled = asWords(term);+ if (+ asWords(topic) === spelled ||+ asWords(topic.slice(topic.lastIndexOf('/') + 1)) === spelled+ ) {+ return 2;+ }+ if (+ words.some(+ w =>+ (scoreCandidate(w, {name: topic}, {fuzzy: false})?.score ?? 0) >= 95,+ )+ ) {+ return 1;+ }+ // A whole title inside the query is the only path to 160-169.+ if (hit.score >= TITLE_IN_QUERY_SCORE && hit.score < TITLE_PHRASE_SCORE) {+ return 1;+ }+ // Every word matched, and one of them names the doc in its title.+ if (+ hit.score >= FULL_COVERAGE_SCORE &&+ hit.score < TITLE_IN_QUERY_SCORE &&+ hit.matched === hit.total+ ) {+ const titleWords = phraseWords(candidate.titles?.[0] ?? '');+ if (+ (tokens.length ? tokens : [term]).some(t =>+ titleWords.some(w => samePhraseWord(t, w) || sameWord(t, w)),+ )+ ) {+ return 1;+ }+ }+ return 0;+ }+ if (hit.score >= FULL_COVERAGE_SCORE) return 1;+ const fuzzy = tokens.length <= 1;+ return words.some(+ w =>+ (bestForToken(w, candidate, {fuzzy})?.score ?? 0) >= STRONG_TOKEN_SCORE,+ )+ ? 1+ : 0;+}+/*** The words of a title or query, lowercased, without punctuation or code ticks.* @param {string} text* @returns {string[]}*/function phraseWords(text) {- return unlinkText(text).toLowerCase().match(/[a-z0-9]+/g) ?? [];+ return (+ unlinkText(text)+ .toLowerCase()+ .match(/[a-z0-9]+/g) ?? []+ );}/**@@ -679,9 +780,7 @@ export function scoreQuery(term, tokens, candidate) {score:FULL_COVERAGE_SCORE +Math.min(- Math.floor(- (tokenSum - matched * MIN_TOKEN_SCORE) / (matched * 5),- ),+ Math.floor((tokenSum - matched * MIN_TOKEN_SCORE) / (matched * 5)),8,),reason,@@ -1115,17 +1214,15 @@ export async function componentKeywords(coreDir, cwd) {coreDir,loadedIntegrations,);- const integrations = loadedIntegrations.map(- async integration => {- const {components} = await discoverValidIntegrationComponents(integration);- return Promise.all(- components.map(async rec => ({- name: rec.name,- keywords: keywordsOf(await loadModuleDoc(rec.docPath)),- })),- );- },- );+ const integrations = loadedIntegrations.map(async integration => {+ const {components} = await discoverValidIntegrationComponents(integration);+ return Promise.all(+ components.map(async rec => ({+ name: rec.name,+ keywords: keywordsOf(await loadModuleDoc(rec.docPath)),+ })),+ );+ });return [...(await Promise.all(core)).filter(component => !replacements.forTarget(component.name),@@ -1221,7 +1318,11 @@ async function gatherDocs(cwd) {const packages = new Map([[entry.providerId ?? entry.package, entry.package],...entry.extensions.map(- ext => /** @type {[string, string]} */ ([ext.providerId ?? ext.package, ext.package]),+ ext =>+ /** @type {[string, string]} */ ([+ ext.providerId ?? ext.package,+ ext.package,+ ]),),]);candidates.push(@@ -1299,7 +1400,8 @@ async function gatherDocs(cwd) {_topic: node.route,_title: path.join(' › '),_command: `astryx docs ${node.route}`,- _parent: node.parent == null ? 'astryx docs' : `astryx docs ${node.parent}`,+ _parent:+ node.parent == null ? 'astryx docs' : `astryx docs ${node.parent}`,_package: node.provider,});}@@ -1463,7 +1565,9 @@ function topicCandidates(_title: `${docTitle} › ${section.title}`,_command: `astryx docs ${name} ${key}`,_parent: `astryx docs ${name} --index`,- ...((sectionPackage?.(key) ?? pkg) ? {_package: sectionPackage?.(key) ?? pkg} : {}),+ ...((sectionPackage?.(key) ?? pkg)+ ? {_package: sectionPackage?.(key) ?? pkg}+ : {}),});}return out;@@ -1711,24 +1815,61 @@ export async function search(query, options = {}) {// role (page / block / component) and takes the top of each, so there's no// cross-role competition to engineer — a target page only needs to be the// strongest PAGE, not outrank every component.- const scored = [];+ /** @type {{result: any, priority: 0 | 1 | 2}[]} */+ const ranked = [];for (const candidate of all) {const hit = scoreQuery(term, tokens, candidate);if (hit)- scored.push(- toResult(candidate, hit.score, hit.reason, hit.matched, hit.total),- );+ ranked.push({+ result: toResult(+ candidate,+ hit.score,+ hit.reason,+ hit.matched,+ hit.total,+ ),+ priority: domainPriority(term, tokens, candidate, hit),+ });}- // Sort by score desc, then domain (stable order), then name.+ // Docs and everything else are each sorted by score desc, then domain+ // (stable order), then name. The two are merged: at each step the stronger+ // head goes next, except that a head with domain priority goes ahead of a+ // doc head without it (see domainPriority). Each side keeps its own order./** @type {Record<string, number>} */const domainOrder = {component: 0, hook: 1, doc: 2, template: 3, theme: 4};- scored.sort(- (a, b) =>- b.score - a.score ||- (domainOrder[a.domain] ?? 9) - (domainOrder[b.domain] ?? 9) ||- a.name.localeCompare(b.name),- );+ /**+ * @param {{result: any}} x+ * @param {{result: any}} y+ */+ const byScore = ({result: a}, {result: b}) =>+ b.score - a.score ||+ (domainOrder[a.domain] ?? 9) - (domainOrder[b.domain] ?? 9) ||+ a.name.localeCompare(b.name);+ const others = ranked.filter(r => r.result.domain !== 'doc').sort(byScore);+ // Against other domains, a doc the reader asked for competes ahead of docs+ // they did not, so it is not held behind a broad page that outscores it.+ // Docs alone keep their text-match order, with a doc the whole query names+ // first.+ const docs = ranked+ .filter(r => r.result.domain === 'doc')+ .sort((x, y) =>+ others.length > 0+ ? y.priority - x.priority || byScore(x, y)+ : Number(y.priority === 2) - Number(x.priority === 2) || byScore(x, y),+ );+ const scored = [];+ let i = 0;+ let j = 0;+ while (i < others.length || j < docs.length) {+ const other = others[i];+ const doc = docs[j];+ const otherFirst =+ !doc ||+ (other != null &&+ ((other.priority && !doc.priority) || byScore(other, doc) < 0));+ scored.push(otherFirst ? others[i++].result : docs[j++].result);+ }// `results` is bounded by `limit` so a caller (and the recorded run that// quotes it) never carries an unbounded payload. `matchCount` is the number