Skip to content

Commit 723fb2e

Browse files
committed
added HighlightedText component
1 parent c57957f commit 723fb2e

File tree

8 files changed

+329
-136
lines changed

8 files changed

+329
-136
lines changed
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
import { useMemo } from "react"
2+
import { twMerge } from "tailwind-merge"
3+
export function HighlightedText({
4+
text,
5+
highlightedText,
6+
className,
7+
highlightClassName,
8+
style,
9+
containerElement,
10+
}: {
11+
text: string
12+
highlightedText: string[] | string
13+
highlightClassName?: string
14+
className?: string
15+
style?: React.CSSProperties
16+
containerElement?: React.ElementType
17+
}) {
18+
const parts = useMemo(() => {
19+
const highlights = Array.isArray(highlightedText)
20+
? highlightedText.map((it) => it.trim()).filter(Boolean)
21+
: [highlightedText.trim()]
22+
if (!highlights.length) return text
23+
const delimiterRegex = new RegExp(
24+
`(${highlights.map((it) => it.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("|")})`,
25+
"g",
26+
)
27+
return text.split(delimiterRegex).reduce((acc, it, i) => {
28+
if (highlights.includes(it)) {
29+
acc.push(
30+
<span
31+
key={i}
32+
className={twMerge(
33+
"bg-selected-bold text-text-inverse p-0 m-0",
34+
highlightClassName,
35+
)}
36+
>
37+
{it}
38+
</span>,
39+
)
40+
return acc
41+
}
42+
acc.push(it)
43+
return acc
44+
}, [] as React.ReactNode[])
45+
}, [text, highlightClassName, highlightedText])
46+
47+
const ContainerElement = containerElement || "p"
48+
49+
return (
50+
<ContainerElement className={className} style={style}>
51+
{parts}
52+
</ContainerElement>
53+
)
54+
}

library/src/components/index.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,3 +37,4 @@ export * from "./dnd"
3737
export * from "./tour"
3838
export * from "./form"
3939
export * from "./EventList"
40+
export * from "./HighlightedText"

0 commit comments

Comments
 (0)