Files
t3code/apps/web/src/components/ThreadSearchMatch.tsx
T
2026-09-24 10:49:04 -07:00

67 lines
1.8 KiB
TypeScript

function foldAsciiCase(value: string): string {
return value.replace(/[A-Z]/g, (character) => character.toLowerCase());
}
function HighlightedSearchText(props: { text: string; query: string }) {
const query = props.query.trim();
if (query.length === 0) return props.text;
const normalizedText = foldAsciiCase(props.text);
const normalizedQuery = foldAsciiCase(query);
const parts: Array<{
readonly text: string;
readonly highlighted: boolean;
readonly start: number;
}> = [];
let cursor = 0;
while (cursor < props.text.length) {
const matchIndex = normalizedText.indexOf(normalizedQuery, cursor);
if (matchIndex === -1) {
parts.push({ text: props.text.slice(cursor), highlighted: false, start: cursor });
break;
}
if (matchIndex > cursor) {
parts.push({
text: props.text.slice(cursor, matchIndex),
highlighted: false,
start: cursor,
});
}
parts.push({
text: props.text.slice(matchIndex, matchIndex + query.length),
highlighted: true,
start: matchIndex,
});
cursor = matchIndex + query.length;
}
return parts.map((part) =>
part.highlighted ? (
<mark className="bg-transparent font-semibold text-foreground" key={part.start}>
{part.text}
</mark>
) : (
part.text
),
);
}
export function ThreadSearchMatchExcerpt(props: {
match: {
readonly source: "user" | "assistant";
readonly snippet: string;
readonly query: string;
};
}) {
const isUser = props.match.source === "user";
return (
<span className="truncate text-xs text-muted-foreground/85">
<span className={isUser ? "text-info-foreground" : "text-success-foreground"}>
{isUser ? "You:" : "Agent:"}
</span>{" "}
<HighlightedSearchText text={props.match.snippet} query={props.match.query} />
</span>
);
}