| 1 | export interface Rectangle { |
| 2 | top: number; |
| 3 | left: number; |
| 4 | width: number; |
| 5 | height: number; |
| 6 | } |
| 7 | |
| 8 | export interface SearchMatch { |
| 9 | index: number; |
| 10 | textNode: Text; |
| 11 | overlayRectangle: Rectangle; |
| 12 | } |
| 13 | |
| 14 | interface SearchOptions { |
| 15 | caseSensitive: boolean; |
| 16 | useRegex: boolean; |
| 17 | offsetHeight: number; |
| 18 | } |
| 19 | |
| 20 | export const searchWithinContainer = ( |
| 21 | containerRef: React.RefObject<HTMLDivElement>, |
| 22 | searchQuery: string, |
| 23 | options: SearchOptions, |
| 24 | ): { |
| 25 | results: SearchMatch[]; |
| 26 | closestToMiddle: SearchMatch | null; |
| 27 | } => { |
| 28 | const searchContainer = containerRef.current; |
| 29 | |
| 30 | if (!searchContainer || !searchQuery) { |
| 31 | return { |
| 32 | results: [], |
| 33 | closestToMiddle: null, |
| 34 | }; |
| 35 | } |
| 36 | const query = options.caseSensitive ? searchQuery : searchQuery.toLowerCase(); |
| 37 | |
| 38 | // First grab all text nodes |
| 39 | // Skips any elements with the "find-widget-skip" class |
| 40 | const textNodes: Text[] = []; |
| 41 | const walker = document.createTreeWalker( |
| 42 | searchContainer, |
| 43 | NodeFilter.SHOW_ALL, |
| 44 | { |
| 45 | acceptNode: (node) => { |
| 46 | if (node.nodeType === Node.ELEMENT_NODE) { |
| 47 | if ((node as Element).classList.contains("find-widget-skip")) |
| 48 | return NodeFilter.FILTER_REJECT; |
| 49 | return NodeFilter.FILTER_ACCEPT; |
| 50 | } else if (node.nodeType === Node.TEXT_NODE) { |
| 51 | if (!node.nodeValue) return NodeFilter.FILTER_REJECT; |
| 52 | const nodeValue = options.caseSensitive |
| 53 | ? node.nodeValue |
| 54 | : node.nodeValue.toLowerCase(); |
| 55 | if (nodeValue.includes(query)) return NodeFilter.FILTER_ACCEPT; |
| 56 | } |
| 57 | return NodeFilter.FILTER_REJECT; |
| 58 | }, |
| 59 | }, |
| 60 | ); |
| 61 | |
| 62 | while (walker.nextNode()) { |
| 63 | if (walker.currentNode.nodeType === Node.ELEMENT_NODE) continue; |
| 64 | textNodes.push(walker.currentNode as Text); |
| 65 | } |
| 66 | |
| 67 | // Now walk through each node match and extract search results |
| 68 | // One node can have several matches |
| 69 | const newMatches: SearchMatch[] = []; |
| 70 | textNodes.forEach((textNode, idx) => { |
| 71 | // Hacky way to detect code blocks that be wider than client and cause absolute positioning to fail |
| 72 | const highlightFullLine = |
| 73 | textNode.parentElement?.className.includes("hljs"); |
| 74 | |
| 75 | let nodeTextValue = options.caseSensitive |
| 76 | ? textNode.nodeValue |
| 77 | : textNode.nodeValue.toLowerCase(); |
| 78 | let startIndex = 0; |
| 79 | while ((startIndex = nodeTextValue.indexOf(query, startIndex)) !== -1) { |
| 80 | // Create a range to measure the size and position of the match |
| 81 | const range = document.createRange(); |
| 82 | range.setStart(textNode, startIndex); |
| 83 | const endIndex = startIndex + query.length; |
| 84 | range.setEnd(textNode, endIndex); |
| 85 | const rect = range.getBoundingClientRect(); |
| 86 | range.detach(); |
| 87 | startIndex = endIndex; |
| 88 | |
| 89 | const top = |
| 90 | rect.top + |
| 91 | searchContainer.clientTop + |
| 92 | searchContainer.scrollTop - |
| 93 | options.offsetHeight; |
| 94 | |
| 95 | const left = |
| 96 | rect.left + searchContainer.clientLeft + searchContainer.scrollLeft; |
| 97 | |
| 98 | // Build a match result and push to matches |
| 99 | const newMatch: SearchMatch = { |
| 100 | index: 0, // will set later |
| 101 | textNode, |
| 102 | overlayRectangle: { |
| 103 | top, |
| 104 | left: highlightFullLine ? 2 : left, |
| 105 | width: highlightFullLine |
| 106 | ? searchContainer.clientWidth - 4 |
| 107 | : rect.width, // equivalent of adding 2 px x padding |
| 108 | height: rect.height, |
| 109 | }, |
| 110 | }; |
| 111 | newMatches.push(newMatch); |
| 112 | |
| 113 | if (highlightFullLine) { |
| 114 | break; // Since highlighting full line no need for multiple overlays, will cause darker highlight |
| 115 | } |
| 116 | } |
| 117 | }); |
| 118 | |
| 119 | // There will still be duplicate full lines when multiple text nodes are in the same line (e.g. Code highlights) |
| 120 | // Filter them out by using the overlay rectangle as a hash key |
| 121 | const matchHash = Object.fromEntries( |
| 122 | newMatches.map((match) => [JSON.stringify(match.overlayRectangle), match]), |
| 123 | ); |
| 124 | const filteredMatches = Object.values(matchHash).map((match, index) => ({ |
| 125 | ...match, |
| 126 | index, |
| 127 | })); |
| 128 | |
| 129 | // Find the match closest to the vertical middle of the container |
| 130 | const verticalMiddle = |
| 131 | searchContainer.scrollTop + searchContainer.clientHeight / 2; |
| 132 | let closestDist = Infinity; |
| 133 | let closestMatchToMiddle: SearchMatch | null = null; |
| 134 | filteredMatches.forEach((match) => { |
| 135 | const dist = Math.abs(verticalMiddle - match.overlayRectangle.top); |
| 136 | if (dist < closestDist) { |
| 137 | closestDist = dist; |
| 138 | closestMatchToMiddle = match; |
| 139 | } |
| 140 | }); |
| 141 | |
| 142 | return { |
| 143 | results: filteredMatches, |
| 144 | closestToMiddle: closestMatchToMiddle, |
| 145 | }; |
| 146 | }; |