Skip to content

Commit 97bfd10

Browse files
committed
Clear results on page change
1 parent 09b2638 commit 97bfd10

File tree

1 file changed

+20
-4
lines changed

1 file changed

+20
-4
lines changed

devdocs-macos/user-scripts/page-search.js

Lines changed: 20 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,10 @@
11
(function() {
22
const DATA_TEXTCONTENT = 'data-dd-original-textcontent';
33

4+
const rootSearchNode = function() {
5+
return document.querySelector('main[role="main"]');
6+
};
7+
48
// From:
59
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions
610
const escapeRegExp = function(string) {
@@ -49,7 +53,7 @@
4953
};
5054

5155
const reset = function() {
52-
var mainNode = document.querySelector('main[role="main"]');
56+
var mainNode = rootSearchNode();
5357
var treeWalker = document.createTreeWalker(mainNode, NodeFilter.SHOW_ELEMENT, {
5458
acceptNode: function(node) {
5559
if (node.hasAttribute(DATA_TEXTCONTENT)) {
@@ -66,12 +70,10 @@
6670
};
6771

6872
const search = function(term) {
69-
var mainNode = document.querySelector('main[role="main"]');
73+
var mainNode = rootSearchNode();
7074
var treeWalker = document.createTreeWalker(mainNode, NodeFilter.SHOW_TEXT, {
7175
acceptNode: function(node) {
7276
var parent = node.parentNode;
73-
// TODO switching docs doesn't invalidate the nodes.
74-
// MutationObserver to track?
7577
if (parent.tagName === 'MARK') {
7678
return NodeFilter.FILTER_REJECT;
7779
}
@@ -92,6 +94,20 @@
9294
return mutateDOM(domMutations);
9395
};
9496

97+
// hacky, but seems to be the only reliable way to clear search results on
98+
// page change.
99+
(function() {
100+
const observer = new MutationObserver(() => {
101+
reset();
102+
});
103+
const titleEl = document.querySelector('title');
104+
observer.observe(titleEl, {
105+
childList: true,
106+
characterData: true,
107+
subtree: true,
108+
});
109+
})();
110+
95111
window.search = function(term) {
96112
if (term === '' || typeof term !== 'string') {
97113
return;

0 commit comments

Comments
 (0)