From d4aa84e239eba82ffd4022a125011755448e7771 Mon Sep 17 00:00:00 2001 From: Nico Albanese Date: Thu, 10 Oct 2024 16:15:30 +0100 Subject: [PATCH] update query explanation implementation --- components/ui/query-with-tooltips.tsx | 59 +++++++++++++++++++-------- 1 file changed, 41 insertions(+), 18 deletions(-) diff --git a/components/ui/query-with-tooltips.tsx b/components/ui/query-with-tooltips.tsx index 925c5e7..6ee2d12 100644 --- a/components/ui/query-with-tooltips.tsx +++ b/components/ui/query-with-tooltips.tsx @@ -13,34 +13,57 @@ export function QueryWithTooltips({ query: string; queryExplanations: QueryExplanation[]; }) { + const segments = segmentQuery(query, queryExplanations); + return (
- {queryExplanations.map((explanation, index) => { - const startIndex = query.indexOf(explanation.section); - if (startIndex === -1) return null; - - return ( - - {/* - {explanation.section} - */} - + {segments.map((segment, index) => ( + + {segment.explanation ? ( + - - {explanation.section} + + {segment.text} -

{explanation.explanation}

+

{segment.explanation}

-
- ); - })} + ) : ( + segment.text + )} +
+ ))}
); } + +function segmentQuery(query: string, explanations: QueryExplanation[]): Array<{ text: string; explanation?: string }> { + const segments: Array<{ text: string; explanation?: string }> = []; + let lastIndex = 0; + + // Sort explanations by their position in the query + const sortedExplanations = explanations + .map(exp => ({ ...exp, index: query.indexOf(exp.section) })) + .filter(exp => exp.index !== -1) + .sort((a, b) => a.index - b.index); + + sortedExplanations.forEach(exp => { + if (exp.index > lastIndex) { + // Add any text before the current explanation as a segment without explanation + segments.push({ text: query.slice(lastIndex, exp.index) }); + } + segments.push({ text: exp.section, explanation: exp.explanation }); + lastIndex = exp.index + exp.section.length; + }); + + // Add any remaining text after the last explanation + if (lastIndex < query.length) { + segments.push({ text: query.slice(lastIndex) }); + } + + return segments; +}