Skip to content

Commit

Permalink
fix(layout): highlight works with empty query (#6357)
Browse files Browse the repository at this point in the history
  • Loading branch information
takethefake committed Jul 22, 2022
1 parent be24c82 commit fcbf5e7
Show file tree
Hide file tree
Showing 3 changed files with 66 additions and 2 deletions.
5 changes: 5 additions & 0 deletions .changeset/slow-insects-sing.md
@@ -0,0 +1,5 @@
---
"@chakra-ui/layout": patch
---

Adjust `Highlight` to not show any highlights if `query` is empty
11 changes: 10 additions & 1 deletion packages/layout/src/highlight.tsx
Expand Up @@ -23,12 +23,21 @@ const escapeRegexp = (term: string): string =>
term.replace(/[|\\{}()[\]^$+*?.-]/g, (char: string) => `\\${char}`)

function buildRegex(query: string[]) {
const _query = query.map((text) => escapeRegexp(text.trim()))
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 }: Options): Chunk[] {
const regex = buildRegex(Array.isArray(query) ? query : [query])
if (!regex) {
return []
}
const result = text.split(regex).filter(Boolean)
return result.map((str) => ({ text: str, match: regex.test(str) }))
}
Expand Down
52 changes: 51 additions & 1 deletion packages/layout/tests/layout.test.tsx
Expand Up @@ -7,7 +7,16 @@ import {
} from "@chakra-ui/test-utils"
import * as React from "react"
import { ChakraProvider, extendTheme } from "@chakra-ui/react"
import { Box, Badge, Container, Divider, Flex, Stack } from "../src"
import {
Box,
Badge,
Container,
Divider,
Flex,
Stack,
useHighlight,
} from "../src"
import { renderHook } from "@testing-library/react-hooks"

describe("<Box />", () => {
test("passes a11y test", async () => {
Expand Down Expand Up @@ -165,3 +174,44 @@ describe("<Divider />", () => {
render(<Divider variant="dashed" />)
})
})

describe("<Highlight/>", () => {
test.each([[], ""])(
"useHighlight returns no matches if queries is empty %p ",
(query) => {
const { result } = renderHook(() =>
useHighlight({
query: query,
text: "this is an ordinary text which should not have any matches",
}),
)
expect(result.current).toHaveLength(0)
},
)

test("useHighlight matches correctly", () => {
const query = ["", "text"]
const { result } = renderHook(() =>
useHighlight({
query: query,
text: "this is an ordinary text which should have one match ",
}),
)
expect(result.current).toMatchInlineSnapshot(`
Array [
Object {
"match": false,
"text": "this is an ordinary ",
},
Object {
"match": true,
"text": "text",
},
Object {
"match": false,
"text": " which should have one match ",
},
]
`)
})
})

1 comment on commit fcbf5e7

@vercel
Copy link

@vercel vercel bot commented on fcbf5e7 Jul 22, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please sign in to comment.