[dyad] Added keyword highlighting - wrote 3 file(s)
This commit is contained in:
35
src/components/keyword-highlighter.tsx
Normal file
35
src/components/keyword-highlighter.tsx
Normal file
@@ -0,0 +1,35 @@
|
||||
"use client";
|
||||
|
||||
import React from "react";
|
||||
|
||||
interface KeywordHighlighterProps {
|
||||
text: string;
|
||||
keyword: string | null | undefined;
|
||||
}
|
||||
|
||||
export function KeywordHighlighter({ text, keyword }: KeywordHighlighterProps) {
|
||||
if (!keyword || !text || keyword.trim() === "") {
|
||||
return <>{text}</>;
|
||||
}
|
||||
|
||||
const escapedKeyword = keyword.replace(/[-\/\\^$*+?.()|[\]{}]/g, "\\$&");
|
||||
const regex = new RegExp(`(${escapedKeyword})`, "gi");
|
||||
const parts = text.split(regex);
|
||||
|
||||
return (
|
||||
<>
|
||||
{parts.map((part, i) =>
|
||||
regex.test(part) ? (
|
||||
<mark
|
||||
key={i}
|
||||
className="bg-yellow-200 text-yellow-900 dark:bg-yellow-700 dark:text-yellow-50 rounded px-1 mx-px font-semibold"
|
||||
>
|
||||
{part}
|
||||
</mark>
|
||||
) : (
|
||||
part
|
||||
)
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user