(text: string, query: string, maxLength = 160)
| 26 | * Returns a short excerpt (up to maxLength chars) centred around the first match. |
| 27 | */ |
| 28 | export function excerpt(text: string, query: string, maxLength = 160): string { |
| 29 | if (!query.trim()) return text.slice(0, maxLength); |
| 30 | |
| 31 | const terms = tokenize(query); |
| 32 | if (terms.length === 0) return text.slice(0, maxLength); |
| 33 | |
| 34 | const lowerText = text.toLowerCase(); |
| 35 | let matchIndex = -1; |
| 36 | |
| 37 | for (const term of terms) { |
| 38 | const idx = lowerText.indexOf(term.toLowerCase()); |
| 39 | if (idx !== -1) { |
| 40 | matchIndex = idx; |
| 41 | break; |
| 42 | } |
| 43 | } |
| 44 | |
| 45 | if (matchIndex === -1) return text.slice(0, maxLength); |
| 46 | |
| 47 | const half = Math.floor(maxLength / 2); |
| 48 | const start = Math.max(0, matchIndex - half); |
| 49 | const end = Math.min(text.length, start + maxLength); |
| 50 | const slice = text.slice(start, end); |
| 51 | |
| 52 | return (start > 0 ? "…" : "") + slice + (end < text.length ? "…" : ""); |
| 53 | } |
| 54 | |
| 55 | /** Tokenise a query string into non-empty lowercase words. */ |
| 56 | export function tokenize(query: string): string[] { |
no test coverage detected