File size: 1,257 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
"use client"

import { type HighlightChunk, useHighlight } from "@ark-ui/react/highlight"
import { Fragment, type JSX } from "react"
import { type SystemStyleObject } from "../../styled-system"
import { For } from "../for"
import { Mark } from "../mark"

export interface HighlightProps {
  query: string | string[]
  children: string | ((props: HighlightChunk[]) => React.ReactNode)
  styles?: SystemStyleObject | undefined
  ignoreCase?: boolean | undefined
  matchAll?: boolean | undefined
}

/**
 * `Highlight` allows you to highlight substrings of a text.
 *
 * @see Docs https://chakra-ui.com/docs/components/highlight
 */
export function Highlight(props: HighlightProps): JSX.Element {
  const { children, query, ignoreCase, matchAll, styles } = props

  if (typeof children !== "string") {
    throw new Error("The children prop of Highlight must be a string")
  }

  const chunks = useHighlight({
    query,
    text: children,
    matchAll,
    ignoreCase,
  })

  return (
    <For each={chunks}>
      {(chunk, index) => {
        return chunk.match ? (
          <Mark key={index} css={styles}>
            {chunk.text}
          </Mark>
        ) : (
          <Fragment key={index}>{chunk.text}</Fragment>
        )
      }}
    </For>
  )
}