-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsearcher.js
424 lines (377 loc) · 15.6 KB
/
searcher.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
/**
* Finds nodes within the domNode that match the supplied search text
*
* Spaces are replaced by wildcards
*
* @param mixed searchText
* @param mixed domNode
*
* @return array of matching nodes
*/
window.controlCenterSearchModule.getNodesThatContain = function (searchText, domNode) {
let searchString = searchText.trim().replaceAll(/\s+/g, '.*?');
let searchRE = new RegExp(searchString, 'gi');
return $(domNode).find('#control_center_window').find(":not(iframe, script, style, option)")
.contents()
.map(function () {
let text = this.textContent;
this.markedText = text.replace(searchRE, (match) => `<span class="marked ccsearch">${match}</span>`);
this.matched = text !== this.markedText;
this.hash = this.matched ? window.controlCenterSearchModule.hash(text) : -1;
return this;
})
.filter(function () {
return this.nodeType == 3 && this.matched;
})
.toArray();
}
/**
* Scrapes control center page for links and grabs the associated html
*
* @return promise resolving to array of objects like:
* {
* link: href of the link,
* name: text content of the link,
* text: the html as a string
* }
*/
window.controlCenterSearchModule.getText = function (domNode = null) {
const origin = new URL(window.location).origin;
let aArr;
if (domNode) {
aArr = Array.from($(domNode).find('div.cc_menu_item a'));
} else {
aArr = Array.from($('div.cc_menu_item a'))
}
const links = aArr.filter(a => {
return a.href.startsWith(origin) &&
a.textContent !== "REDCap Home Page" &&
a.textContent !== "My Projects" &&
a.textContent !== "API Documentation" &&
a.textContent !== "Configuration Check"
});
const results = links.map(async (a) => {
let text = await fetch(a.href).then(result => result.text());
return {
link: a.href,
name: a.textContent,
text: text
};
});
return Promise.all(results);
}
/**
* Text needs to be gotten.
*
* Prevents using the search box until then.
*
* @return void
*/
window.controlCenterSearchModule.initText = async function (domNode = null) {
$('#cc-search-searchInput').val('Please Wait...');
$('#cc-search-searchInput').attr('readonly', true);
this.getText(domNode)
.then(results => {
this.link_data = results;
$('#cc-search-searchInput').val('');
$('#cc-search-searchInput').attr('readonly', false);
this.initialized = true;
this.ajax('storeLinkData', { linkData: JSON.stringify(this.link_data) })
.then(result => {
console.log("Control Center Search: Stored link data.");
})
.catch(error => console.error(error));
console.log("Control Center Search: Initialized text.");
});
}
window.controlCenterSearchModule.search = function (searchTerm) {
return this.link_data.map(ld => {
let ld2 = ld;
ld2.searchResults = this.searchLinkText(ld2.text, searchTerm);
ld2.searchTerm = searchTerm;
return ld2;
}).filter(ld2 => ld2.searchResults.length > 0);
}
window.controlCenterSearchModule.searchLinkText = function (linkText, searchTerm) {
let dom = $('<html>')[0];
$(dom).html(linkText);
return this.getNodesThatContain(searchTerm, dom);
}
window.controlCenterSearchModule.hideModules = function () {
const el = $('.cc_menu_header:contains("External Modules")');
el.nextAll().hide();
el.hide();
}
window.controlCenterSearchModule.showModules = function () {
const el = $('.cc_menu_header:contains("External Modules")');
el.nextAll().show();
el.show();
}
window.controlCenterSearchModule.showDividers = function () {
$('#control_center_menu div.cc_menu_divider').show();
}
window.controlCenterSearchModule.safeParse = function (text) {
if (typeof text !== "string") {
return null;
}
try {
return JSON.parse(text);
} catch (error) {
return null;
}
}
window.controlCenterSearchModule.storeLinks = async function (links) {
if (links === null) return sessionStorage.removeItem('ccsl');
const linksToStore = [];
for (let linkIndex = 0; linkIndex < links.length; linkIndex++) {
const link = links[linkIndex];
const searchResults = [];
for (let resultIndex = 0; resultIndex < link.searchResults.length; resultIndex++) {
const result = link.searchResults[resultIndex];
if (typeof result.hash === 'undefined') {
result.hash = await window.controlCenterSearchModule.hash(result.text);
} else {
result.hash = await result.hash;
}
searchResults.push(result);
}
link.searchResults = searchResults;
linksToStore.push(link);
}
sessionStorage.setItem('ccsl', JSON.stringify(linksToStore));
}
window.controlCenterSearchModule.debounce = function (cb, interval, immediate) {
var timeout;
return function () {
var context = this, args = arguments;
var later = function () {
timeout = null;
if (!immediate) cb.apply(context, args);
};
var callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, interval);
if (callNow) cb.apply(context, args);
};
}
window.controlCenterSearchModule.hash = async function (str) {
if (crypto?.subtle?.digest === undefined) {
return -1;
}
const strUint8 = new TextEncoder().encode(str);
const hashBuffer = await crypto.subtle.digest('SHA-256', strUint8);
const hashArray = Array.from(new Uint8Array(hashBuffer));
return hashArray.map(b => b.toString(16).padStart(2, '0')).join('');
}
window.controlCenterSearchModule.display = function (searchResults) {
// Store links in session storage
window.controlCenterSearchModule.storeLinks(searchResults)
// Reset panel to original status
$('div.cc_menu_item').show();
$('div.cc_menu_section').show();
this.showModules();
this.showDividers();
// Do nothing if search is null
if (searchResults === null) return;
let linksToShow = searchResults.map(el => el.name);
this.hideModules();
if (typeof(bootstrap) !== 'undefined') {
bootstrap.Tooltip.Default.allowList.div.push('onclick');
} else {
$.fn.popover.Constructor.Default.whiteList.div.push('onclick');
}
const popoverDelayMs = 200;
$('div.cc_menu_item').each((i, el) => {
const isSearchItem = el.id === "cc-search-item";
if (!isSearchItem && !linksToShow.includes(el.textContent.trim())) {
$(el).hide();
} else if (!isSearchItem) {
const thisResult = searchResults.filter(result => result.name === el.textContent.trim())[0];
const popoverContainer = $('<div class="col">');
const popoverTitleIcon = $(el).find('i').get(0).outerHTML;
const popoverTitle = popoverTitleIcon+$(el).text();
Promise.all(thisResult.searchResults.map(async (res, j) => {
const hash = await res.hash;
const url = new URL(thisResult.link);
const newContainer = $(`<div class="card ccs-card bg-light mb-1" onclick="sessionStorage.setItem('ccsh', '${hash}');document.location.href='${url.href}'">`);
const p = $(`<p>`).html(res.markedText.trim());
newContainer.append(p);
popoverContainer.append(newContainer);
})).then(() => {
$(el).unbind('mouseenter mouseleave');
$(el).attr('data-bs-placement','right');
$(el).popover({
title: popoverTitle,
trigger: "manual",
placement: "right",
html: true,
content: popoverContainer.html(),
animation: false,
fallbackPlacements: ['right'],
container: 'body',
template: '<div class="popover ccs-popover" role="tooltip"><h3 class="popover-header"></h3><div class="arrow popover-arrow"></div><div class="popover-body row row-cols-1 highlight m-1"></div></div>',
})
.on("mouseenter", function() {
var _this = this;
setTimeout(function() {
if ($(_this).is(":hover")) {
$(_this).popover("show");
var popoverId = $(_this).attr('aria-describedby');
$('#'+popoverId).on("mouseleave", function() {
$(_this).popover('hide');
});
}
}, popoverDelayMs);
})
.on("mouseleave", function() {
var _this = this;
var popoverId = $(_this).attr('aria-describedby');
setTimeout(function() {
if (!$("#"+popoverId+":hover").length) {
$(_this).popover("hide");
}
}, popoverDelayMs);
});
});
}
})
$('div.cc_menu_section').each((i, el) => {
if (Array.from($(el).children('div.cc_menu_item')).every(el2 => $(el2).is(":hidden"))) {
$(el).hide();
$(el).prev('div.cc_menu_divider').hide();
}
});
}
window.controlCenterSearchModule.tryToOpenModals = function (element) {
const dialog = $(element).closest('.simpleDialog');
if (dialog.length > 0) {
window.controlCenterSearchModule.scrollTo(dialog.siblings(':visible').get(0).getBoundingClientRect().y);
let position = null
const checkIfScrollIsStatic = setInterval(() => {
if (position === window.scrollY) {
clearInterval(checkIfScrollIsStatic);
simpleDialog(null, null, dialog.attr('id'), 1000);
}
position = window.scrollY;
}, 50);
return;
}
const hidden = $(element).closest('div:hidden');
if (hidden.length > 0) {
window.controlCenterSearchModule.scrollTo(hidden.siblings(':visible').get(0).getBoundingClientRect().y);
let position = null
const checkIfScrollIsStatic = setInterval(() => {
if (position === window.scrollY) {
clearInterval(checkIfScrollIsStatic);
simpleDialog(null, null, hidden.attr('id'), 1000);
}
position = window.scrollY;
}, 50);
return;
}
const hidden2 = $(element).css('display') === 'none' ? $(element) : null;
if (hidden2 !== null) {
window.controlCenterSearchModule.scrollTo(hidden2.siblings(':visible').get(0).getBoundingClientRect().y);
let position = null
const checkIfScrollIsStatic = setInterval(() => {
if (position === window.scrollY) {
clearInterval(checkIfScrollIsStatic);
simpleDialog(null, null, hidden2.attr('id'), 500);
}
position = window.scrollY;
}, 50);
return;
}
return window.controlCenterSearchModule.scrollTo(element.getBoundingClientRect().y);
}
window.controlCenterSearchModule.findMatchInCurrentPage = async function (searchTerm, matchHash) {
const searchString = searchTerm.trim().replaceAll(/\s+/g, '.*?');
const searchRE = new RegExp(searchString, 'gi');
const nodes = await Promise.all($(document.getElementById('control_center_window')).find(":not(iframe, script, style, option)")
.contents()
.toArray()
.map(async function (el) {
if (el.nodeType !== 3) return el;
let text = el.textContent;
el.markedText = text.replaceAll(searchRE, (match) => `<span class="marked ccsearch">${match}</span>`);
el.matched = text !== el.markedText;
el.hash = el.matched ? (await window.controlCenterSearchModule.hash(text)) : -1;
el.hashMatched = await matchHash === el.hash;
return el;
}));
for (let node of nodes) {
if (node.hashMatched) {
setTimeout(() => {
const element = node.parentElement;
$(element).html($(element).html().replaceAll(searchRE, (match) => `<span class="marked ccsearch">${match}</span>`));
let rect = element.getBoundingClientRect();
// Element is hidden, might be part of a modal / dialog
if (rect.height === 0) {
window.controlCenterSearchModule.tryToOpenModals(element);
} else {
const elY = rect.y;
window.controlCenterSearchModule.scrollTo(elY);
}
}, 0);
return true;
}
}
return false;
}
window.controlCenterSearchModule.scrollTo = function (elY) {
const scrollHeight = document.querySelector('body').scrollHeight;
const clientHeight = document.documentElement.clientHeight/2;
const scrollY = elY - min(clientHeight, scrollHeight, elY);
window.scrollTo({top:scrollY, behavior: 'smooth'});
}
window.controlCenterSearchModule.keyupHandler = function () {
// remove popovers
$('div.cc_menu_item').popover('dispose')
const module = window.controlCenterSearchModule;
const searchTerm = document.querySelector("#cc-search-searchInput").value.trim();
sessionStorage.setItem('ccss', searchTerm);
if (searchTerm === "" || !module.initialized) return module.display(null);
module.display(module.search(searchTerm));
}
window.controlCenterSearchModule.runControlCenter = function () {
// Scroll to selected element if applicable
const params = new URLSearchParams(window.location.search);
const searchInput = document.querySelector('#cc-search-searchInput');
const matchHash = sessionStorage.getItem('ccsh');
const searchTerm = sessionStorage.getItem('ccss');
const links = window.controlCenterSearchModule.safeParse(sessionStorage.getItem('ccsl'));
let filtered = false;
if (links !== null) {
window.controlCenterSearchModule.display(links);
searchInput.value = searchTerm ?? '';
filtered = true;
}
if (matchHash && searchTerm) {
window.controlCenterSearchModule.findMatchInCurrentPage(searchTerm, matchHash);
} else {
sessionStorage.removeItem('ccsh');
sessionStorage.removeItem('ccss');
}
searchInput.onkeyup = this.debounce(this.keyupHandler, 250);
searchInput.onsearch = this.keyupHandler;
window.controlCenterSearchModule.ajax('getLinkData', {})
.then(result => {
if (result == '') {
console.log("Control Center Search: Initializing text...");
this.initText();
} else {
this.link_data = JSON.parse(result);
this.initialized = true;
!filtered && controlCenterSearchModule.keyupHandler();
}
})
.catch(error => console.error(error));
// Append link to top of menu
document.querySelector('#control_center_menu').prepend(document.querySelector('#cc-search-container'));
$('#cc-search-searchInput').width($("#pid-go-project").width());
// Add a section divider before the Control Center Home section
$('div.cc_menu_header:contains("Control Center Home")').parent().prepend('<div class="cc_menu_divider"></div>');
}
$(document).ready(function () {
window.controlCenterSearchModule.runControlCenter();
});