PageSourceSearch

https://lei-qian.com/assets/js/highlight-search-term.js

js lei-qian.com collected 2026-09-28 07:11:43 UTC 4,190 bytes, 110 lines download raw bytes

1/**
2 * This file is a modified version of:
3 * https://github.com/marmelab/highlight-search-term/blob/main/src/index.js
4 * - We return the `nonMatchingElements`
5 * - We fixed a bug: `getRangesForSearchTermInElement` got the `node.parentElement`, which is not working if there are multiple text nodes in one element.
6 *
7 * highlight-search-term is published under MIT License.
8 *
9 * MIT License
10 *
11 * Copyright (c) 2024 marmelab
12 *
13 * Permission is hereby granted, free of charge, to any person obtaining a copy
14 * of this software and associated documentation files (the "Software"), to deal
15 * in the Software without restriction, including without limitation the rights
16 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
17 * copies of the Software, and to permit persons to whom the Software is
18 * furnished to do so, subject to the following conditions:
19 *
20 * The above copyright notice and this permission notice shall be included in all
21 * copies or substantial portions of the Software.
22 *
23 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
24 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
25 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
26 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
27 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
28 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
29 * SOFTWARE.
30 */
31
32/**
33 * Highlight search term in the selected elements
34 *
35 * @example
36 * import { highlightSearchTerm } from "highlight-search-term";
37 * const search = document.getElementById("search");
38 * search.addEventListener("input", () => {
39 *   highlightSearchTerm({ search: search.value, selector: ".content" });
40 * });
41 */
42const highlightSearchTerm = ({ search, selector, customHighlightName = "search" }) => {
43  if (!selector) {
44    throw new Error("The selector argument is required");
45  }
46
47  if (!CSS.highlights) return; // disable feature on Firefox as it does not support CSS Custom Highlight API
48
49  // remove previous highlight
50  CSS.highlights.delete(customHighlightName);
51  if (!search) {
52    // nothing to highlight
53    return;
54  }
55  // find all text nodes containing the search term
56  const ranges = [];
57  const nonMatchingElements = [];
58  const elements = document.querySelectorAll(selector);
59  Array.from(elements).map((element) => {
60    let match = false;
61    getTextNodesInElementContainingText(element, search).forEach((node) => {
62      // Modified variant of highlight-search-term
63      // We return the non-matching elements in addition.
64      const rangesForSearch = getRangesForSearchTermInNode(node, search);
65      ranges.push(...rangesForSearch);
66      if (rangesForSearch.length > 0) {
67        match = true;
68      }
69    });
70    if (!match) {
71      nonMatchingElements.push(element);
72    }
73  });
74  if (ranges.length === 0) return nonMatchingElements; // modified: return `nonMatchingElements`
75  // create a CSS highlight that can be styled with the ::highlight(search) pseudo-element
76  const highlight = new Highlight(...ranges);
77  CSS.highlights.set(customHighlightName, highlight);
78  return nonMatchingElements; // modified: return `nonMatchingElements`
79};
80
81const getTextNodesInElementContainingText = (element, text) => {
82  const nodes = [];
83  const walker = document.createTreeWalker(element, NodeFilter.SHOW_TEXT);
84  let node;
85  while ((node = walker.nextNode())) {
86    if (node.textContent && node.textContent.toLowerCase().includes(text)) {
87      nodes.push(node);
88    }
89  }
90  return nodes;
91};
92
93// Fix: We changed this function to work on the node directly, rather than on its parent element.
94const getRangesForSearchTermInNode = (node, search) => {
95  const ranges = [];
96  const text = (node.textContent ? node.textContent.toLowerCase() : "") || "";
97
98  let start = 0;
99  let index;
100  while ((index = text.indexOf(search, start)) >= 0) {
101    const range = new Range();
102    range.setStart(node, index);
103    range.setEnd(node, index + search.length);
104    ranges.push(range);
105    start = index + search.length;
106  }
107  return ranges;
108};
109
110export { highlightSearchTerm };

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.