Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions app/layout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,11 @@ export default function RootLayout({
}>) {
return (
<html lang="en" suppressHydrationWarning>
<head>
{/* Highlight stylesheet cannot be loaded via CSS preprocessor (not supported yet) */}
{/* eslint-disable-next-line @next/next/no-css-tags */}
<link rel="stylesheet" href="/highlights.css" />
</head>
<body
className={`${geistSans.variable} ${geistMono.variable} antialiased`}
>
Expand Down
48 changes: 48 additions & 0 deletions lib/useHighlight.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
"use client";
import { useEffect, useRef } from "react";

export function useHighlight(query: string, dependencies: unknown[] = []) {
const ref = useRef(null);

useEffect(() => {
if (!ref.current || !query) {
CSS.highlights.delete("search");
return;
}

const treeWalker = document.createTreeWalker(
ref.current,
NodeFilter.SHOW_TEXT,
);
const ranges: Range[] = [];

while (treeWalker.nextNode()) {
const node = treeWalker.currentNode;
const text = node.textContent?.toLowerCase() ?? "";
let startIdx = 0;

while ((startIdx = text.indexOf(query.toLowerCase(), startIdx)) !== -1) {
const range = new Range();
range.setStart(node, startIdx);
range.setEnd(node, startIdx + query.length);
ranges.push(range);
startIdx += query.length;
}
}

if (ranges.length > 0) {
console.log(`Highlighting ${ranges.length} occurrences of "${query}"`);
CSS.highlights.set("search", new Highlight(...ranges));
} else {
console.log(`No occurrences of "${query}" found`);
CSS.highlights.delete("search");
}

return () => {
CSS.highlights.delete("search");
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [query, ...dependencies]);

return ref;
}
4 changes: 4 additions & 0 deletions public/highlights.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
::highlight(search) {
background-color: #fbbf24;
color: black;
}