| 1 | import { describe, expect, it } from "bun:test"; |
| 2 | import { renderToStaticMarkup } from "react-dom/server"; |
| 3 | import type { ThemedToken } from "shiki"; |
| 4 | |
| 5 | import { markMatches } from "./code-search-results"; |
| 6 | |
| 7 | const token = (content: string, offset: number, color: string) => |
| 8 | ({ |
| 9 | content, |
| 10 | offset, |
| 11 | htmlStyle: { "--shiki-light": color }, |
| 12 | }) as unknown as ThemedToken; |
| 13 | |
| 14 | // const findMe = 1; |
| 15 | const tokens = [ |
| 16 | token("const", 0, "red"), |
| 17 | token(" ", 5, "grey"), |
| 18 | token("findMe", 6, "blue"), |
| 19 | token(" = 1;", 12, "grey"), |
| 20 | ]; |
| 21 | |
| 22 | const render = (ranges: { start: number; end: number }[]) => |
| 23 | renderToStaticMarkup(<>{markMatches(tokens, ranges)}</>); |
| 24 | |
| 25 | describe("markMatches", () => { |
| 26 | it("keeps every token as it is when nothing matched", () => { |
| 27 | expect(render([])).toBe( |
| 28 | '<span style="--shiki-light:red">const</span><span style="--shiki-light:grey"> </span><span style="--shiki-light:blue">findMe</span><span style="--shiki-light:grey"> = 1;</span>', |
| 29 | ); |
| 30 | }); |
| 31 | |
| 32 | it("cuts a token where a match starts and ends inside it", () => { |
| 33 | expect(render([{ start: 8, end: 10 }])).toContain( |
| 34 | '<span style="--shiki-light:blue">fi</span><mark class="rounded-xs bg-primary/25"><span style="--shiki-light:blue">nd</span></mark><span style="--shiki-light:blue">Me</span>', |
| 35 | ); |
| 36 | }); |
| 37 | |
| 38 | it("marks a match spanning several tokens as one mark, each piece in its own colour", () => { |
| 39 | expect(render([{ start: 3, end: 9 }])).toBe( |
| 40 | '<span style="--shiki-light:red">con</span><mark class="rounded-xs bg-primary/25"><span style="--shiki-light:red">st</span><span style="--shiki-light:grey"> </span><span style="--shiki-light:blue">fin</span></mark><span style="--shiki-light:blue">dMe</span><span style="--shiki-light:grey"> = 1;</span>', |
| 41 | ); |
| 42 | }); |
| 43 | |
| 44 | it("keeps adjacent matches apart", () => { |
| 45 | expect( |
| 46 | render([ |
| 47 | { start: 0, end: 5 }, |
| 48 | { start: 5, end: 6 }, |
| 49 | ]), |
| 50 | ).toBe( |
| 51 | '<mark class="rounded-xs bg-primary/25"><span style="--shiki-light:red">const</span></mark><mark class="rounded-xs bg-primary/25"><span style="--shiki-light:grey"> </span></mark><span style="--shiki-light:blue">findMe</span><span style="--shiki-light:grey"> = 1;</span>', |
| 52 | ); |
| 53 | }); |
| 54 | }); |