UNPKG

@chakra-ui/layout

Version:

Chakra UI layout components that give you massive speed

63 lines (61 loc) 1.94 kB
'use client' import { Box } from "./chunk-PULVB27S.mjs"; // src/highlight.tsx import { forwardRef, omitThemingProps, useStyleConfig } from "@chakra-ui/system"; import { Fragment, useMemo } from "react"; import { Fragment as Fragment2, jsx } from "react/jsx-runtime"; var escapeRegexp = (term) => term.replace(/[|\\{}()[\]^$+*?.-]/g, (char) => `\\${char}`); function buildRegex(query) { const _query = query.filter((text) => text.length !== 0).map((text) => escapeRegexp(text.trim())); if (!_query.length) { return null; } return new RegExp(`(${_query.join("|")})`, "ig"); } function highlightWords({ text, query }) { const regex = buildRegex(Array.isArray(query) ? query : [query]); if (!regex) { return [{ text, match: false }]; } const result = text.split(regex).filter(Boolean); return result.map((str) => ({ text: str, match: regex.test(str) })); } function useHighlight(props) { const { text, query } = props; return useMemo(() => highlightWords({ text, query }), [text, query]); } var Mark = forwardRef(function Mark2(props, ref) { const styles = useStyleConfig("Mark", props); const ownProps = omitThemingProps(props); return /* @__PURE__ */ jsx( Box, { ref, ...ownProps, as: "mark", __css: { bg: "transparent", whiteSpace: "nowrap", ...styles } } ); }); function Highlight(props) { const { children, query, styles } = props; if (typeof children !== "string") { throw new Error("The children prop of Highlight must be a string"); } const chunks = useHighlight({ query, text: children }); return /* @__PURE__ */ jsx(Fragment2, { children: chunks.map((chunk, index) => { return chunk.match ? /* @__PURE__ */ jsx(Mark, { sx: styles, children: chunk.text }, index) : /* @__PURE__ */ jsx(Fragment, { children: chunk.text }, index); }) }); } export { useHighlight, Mark, Highlight }; //# sourceMappingURL=chunk-6WNMSZKB.mjs.map