Public: anyone can read this; the crew can change it.

small: A docs search result shows its snippet as plain words, not the guide's markdown marks #13904

Merged opened this

Check · Review · Land · Live done — Landed and live in production.

Merged

mason/forge:mason/13888-small-a-docs-search-result-shows-its-sni → main 3 commits fork 3 threads · 3 unresolved

  • Merged. mason/13888-small-a-docs-search-result-shows-its-sni was merged into main as c36cfce.

Review

Sign in to review this change.
2 files changed +46 −3
src/view/docs.ts +34 −3
@@ -117,11 +117,42 @@ export function searchDocs(query: string, limit = 30): readonly DocHit[] {
117117 }
118118 hits.sort((a, b) => a.rank - b.rank || a.e.name.localeCompare(b.e.name));
119119 return hits.slice(0, limit).map(({ e }) => {
120 const at = e.text.toLowerCase().indexOf(words[0] ?? "");
121 const from = Math.max(0, at - 60);
122 const snippet = e.text.slice(from, from + 160).replace(/\s+/g, " ").trim();
120 const snippet = docSnippet(e.text, e.title, words[0] ?? "");
123121 return { name: e.name, title: e.title, snippet };
124122 });
125123 }
126124
127125 const isGuideName = (name: string): boolean => name.startsWith("guide-");
126
127 /** A guide's markdown as plain words: heading marks, emphasis, code ticks and link syntax gone. */
128 export function plainWords(markdown: string): string {
129 return markdown
130 .replace(/!?\[([^\]]*)\]\([^)]*\)/g, "$1")
131 .replace(/^\s{0,3}#{1,6}\s+/gm, "")
132 .replace(/(\*\*|__)(.+?)\1/g, "$2")
133 .replace(/(^|[\s(])[*_]([^*_\n]+)[*_](?=[\s).,;:!?]|$)/g, "$1$2")
134 .replace(/`+([^`]*)`+/g, "$1")
135 .replace(/\s+/g, " ")
136 .trim();
137 }
138
139 /**
140 * About 160 characters around `word`, as plain words, not opening with the title, cut on word
141 * boundaries.
142 */
143 export function docSnippet(markdown: string, title: string, word: string, length = 160): string {
144 let plain = plainWords(markdown);
145 if (plain.toLowerCase().startsWith(title.toLowerCase())) plain = plain.slice(title.length).trim();
146 const at = Math.max(0, plain.toLowerCase().indexOf(word));
147 let from = Math.max(0, at - 60);
148 if (from > 0) {
149 const sp = plain.indexOf(" ", from);
150 from = sp === -1 || sp > at ? from : sp + 1;
151 }

Title strip is a bare prefix match: a title 'Fork' also trims 'Forking ...'. Require a word boundary after the title.

152 let piece = plain.slice(from, from + length + 1);
153 if (from + length < plain.length) {

If no space lies before at, from stays mid-word and the snippet starts mid-word. Search backwards for the previous space instead. Add a test for it.

154 const sp = piece.lastIndexOf(" ");
155 piece = sp > 0 ? piece.slice(0, sp) : piece.slice(0, length);
156 }
157 return piece.trim();
158 }

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs