diff --git a/scripts/smoke.mjs b/scripts/smoke.mjs index 02f90be..c0f7a90 100644 --- a/scripts/smoke.mjs +++ b/scripts/smoke.mjs @@ -154,4 +154,23 @@ check('search matches an author name', () => { assert.ok(hits[0].matched.includes('nirodbaran')); }); +check('snippet fills the full context window when the matched term is near the start', () => { + // term at position 0; text is much longer than the default contextChars (120) + const body = 'equanimity ' + 'x '.repeat(65); // ~141 chars, term at idx 0 + const s = snippet({ body }, ['equanimity']); + const bare = s.replace(/ …$/, ''); + // With the fix: window is [0, 120]. Without it: window was only [0, 60]. + assert.ok(bare.length >= 110, `expected ≥110 chars, got ${bare.length}`); +}); + +check('snippet fills the full context window when the matched term is near the end', () => { + // term near the end; text is longer than contextChars (120) + const prefix = 'x '.repeat(65); // 130 chars + const body = prefix + 'equanimity'; // 140 chars, term at idx 130 + const s = snippet({ body }, ['equanimity']); + const bare = s.replace(/^… /, ''); + // With the fix: window slides back to cover ~120 chars. Without it: only ~70 chars. + assert.ok(bare.length >= 110, `expected ≥110 chars, got ${bare.length}`); +}); + console.log(`\n${passed} checks passed.`); diff --git a/src/search.js b/src/search.js index 73ab647..f700dbc 100644 --- a/src/search.js +++ b/src/search.js @@ -127,8 +127,10 @@ export function snippet(article, terms = [], { contextChars = 120 } = {}) { if (at !== -1 && (idx === -1 || at < idx)) idx = at; } if (idx === -1) continue; - const start = Math.max(0, idx - half); - const end = Math.min(text.length, idx + half); + // Slide the window so it always spans contextChars when the text is long + // enough, rather than halving when the match is near the start or end. + const start = Math.max(0, Math.min(idx - half, text.length - contextChars)); + const end = Math.min(text.length, start + contextChars); let s = text.slice(start, end).trim(); if (start > 0) s = `… ${s}`; if (end < text.length) s = `${s} …`;