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
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
|
// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
cr.define('options', function() {
const OptionsPage = options.OptionsPage;
/**
* Encapsulated handling of a search bubble.
* @constructor
*/
function SearchBubble(text) {
var el = cr.doc.createElement('div');
SearchBubble.decorate(el);
el.textContent = text;
return el;
}
SearchBubble.decorate = function(el) {
el.__proto__ = SearchBubble.prototype;
el.decorate();
};
SearchBubble.prototype = {
__proto__: HTMLDivElement.prototype,
decorate: function() {
this.className = 'search-bubble';
// We create a timer to periodically update the position of the bubbles.
// While this isn't all that desirable, it's the only sure-fire way of
// making sure the bubbles stay in the correct location as sections
// may dynamically change size at any time.
var self = this;
this.intervalId = setInterval(this.updatePosition.bind(this), 250);
},
/**
* Clear the interval timer and remove the element from the page.
*/
dispose: function() {
clearInterval(this.intervalId);
var parent = this.parentNode;
if (parent)
parent.removeChild(this);
},
/**
* Update the position of the bubble. Called at creation time and then
* periodically while the bubble remains visible.
*/
updatePosition: function() {
// This bubble is 'owned' by the next sibling.
var owner = this.nextSibling;
// If there isn't an offset parent, we have nothing to do.
if (!owner.offsetParent)
return;
// Position the bubble below the location of the owner.
var left = owner.offsetLeft + owner.offsetWidth / 2 -
this.offsetWidth / 2;
var top = owner.offsetTop + owner.offsetHeight;
// Update the position in the CSS. Cache the last values for
// best performance.
if (left != this.lastLeft) {
this.style.left = left + 'px';
this.lastLeft = left;
}
if (top != this.lastTop) {
this.style.top = top + 'px';
this.lastTop = top;
}
}
}
/**
* Encapsulated handling of the search page.
* @constructor
*/
function SearchPage() {
OptionsPage.call(this, 'search', templateData.searchPage, 'searchPage');
this.searchActive = false;
}
cr.addSingletonGetter(SearchPage);
SearchPage.prototype = {
// Inherit SearchPage from OptionsPage.
__proto__: OptionsPage.prototype,
/**
* Initialize the page.
*/
initializePage: function() {
// Call base class implementation to start preference initialization.
OptionsPage.prototype.initializePage.call(this);
var self = this;
// Create a search field element.
var searchField = document.createElement('input');
searchField.id = 'search-field';
searchField.type = 'search';
searchField.setAttribute('autosave', 'org.chromium.options.search');
searchField.setAttribute('results', '10');
searchField.setAttribute('incremental', 'true');
this.searchField = searchField;
// Replace the contents of the navigation tab with the search field.
self.tab.textContent = '';
self.tab.appendChild(searchField);
self.tab.onclick = self.tab.onkeypress = undefined;
// Handle search events. (No need to throttle, WebKit's search field
// will do that automatically.)
searchField.onsearch = function(e) {
self.setSearchText_(SearchPage.canonicalizeQuery(this.value));
};
// We update the history stack every time the search field blurs. This way
// we get a history entry for each search, roughly, but not each letter
// typed.
searchField.onblur = function(e) {
var query = SearchPage.canonicalizeQuery(searchField.value);
if (!query)
return;
// Don't push the same page onto the history stack more than once (if
// the user clicks in the search field and away several times).
var currentHash = location.hash;
var newHash = '#' + escape(query);
if (currentHash == newHash)
return;
// If there is no hash on the current URL, the history entry has no
// search query. Replace the history entry with no search with an entry
// that does have a search. Otherwise, add it onto the history stack.
var historyFunction = currentHash ? window.history.pushState :
window.history.replaceState;
historyFunction.call(
window.history,
{pageName: self.name},
self.title,
'/' + self.name + newHash);
};
// Install handler for key presses.
document.addEventListener('keydown',
this.keyDownEventHandler_.bind(this));
// Focus the search field by default.
searchField.focus();
},
/**
* @inheritDoc
*/
get sticky() {
return true;
},
/**
* Called after this page has shown.
*/
didShowPage: function() {
// This method is called by the Options page after all pages have
// had their visibilty attribute set. At this point we can perform the
// search specific DOM manipulation.
this.setSearchActive_(true);
},
/**
* Called before this page will be hidden.
*/
willHidePage: function() {
// This method is called by the Options page before all pages have
// their visibilty attribute set. Before that happens, we need to
// undo the search specific DOM manipulation that was performed in
// didShowPage.
this.setSearchActive_(false);
},
/**
* Update the UI to reflect whether we are in a search state.
* @param {boolean} active True if we are on the search page.
* @private
*/
setSearchActive_: function(active) {
// It's fine to exit if search wasn't active and we're not going to
// activate it now.
if (!this.searchActive_ && !active)
return;
this.searchActive_ = active;
if (active) {
var hash = location.hash;
if (hash)
this.searchField.value = unescape(hash.slice(1));
} else {
// Just wipe out any active search text since it's no longer relevant.
this.searchField.value = '';
}
var pagesToSearch = this.getSearchablePages_();
for (var key in pagesToSearch) {
var page = pagesToSearch[key];
if (!active)
page.visible = false;
// Update the visible state of all top-level elements that are not
// sections (ie titles, button strips). We do this before changing
// the page visibility to avoid excessive re-draw.
for (var i = 0, childDiv; childDiv = page.pageDiv.children[i]; i++) {
if (active) {
if (childDiv.tagName != 'SECTION')
childDiv.classList.add('search-hidden');
} else {
childDiv.classList.remove('search-hidden');
}
}
if (active) {
// When search is active, remove the 'hidden' tag. This tag may have
// been added by the OptionsPage.
page.pageDiv.classList.remove('hidden');
}
}
if (active) {
this.setSearchText_(this.searchField.value);
} else {
// After hiding all page content, remove any search results.
this.unhighlightMatches_();
this.removeSearchBubbles_();
}
},
/**
* Set the current search criteria.
* @param {string} text Search text.
* @private
*/
setSearchText_: function(text) {
// Toggle the search page if necessary.
if (text.length) {
if (!this.searchActive_)
OptionsPage.navigateToPage(this.name);
} else {
if (this.searchActive_)
OptionsPage.showDefaultPage();
return;
}
var foundMatches = false;
var bubbleControls = [];
// Remove any prior search results.
this.unhighlightMatches_();
this.removeSearchBubbles_();
// Generate search text by applying lowercase and escaping any characters
// that would be problematic for regular expressions.
var searchText =
text.toLowerCase().replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
// Generate a regular expression and replace string for hilighting
// search terms.
var regEx = new RegExp('(' + searchText + ')', 'ig');
var replaceString = '<span class="search-highlighted">$1</span>';
// Initialize all sections. If the search string matches a title page,
// show sections for that page.
var page, pageMatch, childDiv, length;
var pagesToSearch = this.getSearchablePages_();
for (var key in pagesToSearch) {
page = pagesToSearch[key];
pageMatch = false;
if (searchText.length) {
pageMatch = this.performReplace_(regEx, replaceString, page.tab);
}
if (pageMatch)
foundMatches = true;
for (var i = 0, childDiv; childDiv = page.pageDiv.children[i]; i++) {
if (childDiv.tagName == 'SECTION') {
if (pageMatch) {
childDiv.classList.remove('search-hidden');
} else {
childDiv.classList.add('search-hidden');
}
}
}
}
if (searchText.length) {
// Search all top-level sections for anchored string matches.
for (var key in pagesToSearch) {
page = pagesToSearch[key];
for (var i = 0, childDiv; childDiv = page.pageDiv.children[i]; i++) {
if (childDiv.tagName == 'SECTION' &&
this.performReplace_(regEx, replaceString, childDiv)) {
childDiv.classList.remove('search-hidden');
foundMatches = true;
}
}
}
// Search all sub-pages, generating an array of top-level sections that
// we need to make visible.
var subPagesToSearch = this.getSearchableSubPages_();
var control, node;
for (var key in subPagesToSearch) {
page = subPagesToSearch[key];
if (this.performReplace_(regEx, replaceString, page.pageDiv)) {
// Reveal the section for this search result.
section = page.associatedSection;
if (section)
section.classList.remove('search-hidden');
// Identify any controls that should have bubbles.
var controls = page.associatedControls;
if (controls) {
length = controls.length;
for (var i = 0; i < length; i++)
bubbleControls.push(controls[i]);
}
foundMatches = true;
}
}
}
// Configure elements on the search results page based on search results.
if (foundMatches)
$('searchPageNoMatches').classList.add('search-hidden');
else
$('searchPageNoMatches').classList.remove('search-hidden');
// Create search balloons for sub-page results.
length = bubbleControls.length;
for (var i = 0; i < length; i++)
this.createSearchBubble_(bubbleControls[i], text);
},
/**
* Performs a string replacement based on a regex and replace string.
* @param {RegEx} regex A regular expression for finding search matches.
* @param {String} replace A string to apply the replace operation.
* @param {Element} element An HTML container element.
* @returns {Boolean} true if the element was changed.
* @private
*/
performReplace_: function(regex, replace, element) {
var found = false;
var div, child, tmp;
// Walk the tree, searching each TEXT node.
var walker = document.createTreeWalker(element,
NodeFilter.SHOW_TEXT,
null,
false);
var node = walker.nextNode();
while (node) {
// Perform a search and replace on the text node value.
var newValue = node.nodeValue.replace(regex, replace);
if (newValue != node.nodeValue) {
// The text node has changed so that means we found at least one
// match.
found = true;
// Create a temporary div element and set the innerHTML to the new
// value.
div = document.createElement('div');
div.innerHTML = newValue;
// Insert all the child nodes of the temporary div element into the
// document, before the original node.
child = div.firstChild;
while (child = div.firstChild) {
node.parentNode.insertBefore(child, node);
};
// Delete the old text node and advance the walker to the next
// node.
tmp = node;
node = walker.nextNode();
tmp.parentNode.removeChild(tmp);
} else {
node = walker.nextNode();
}
}
return found;
},
/**
* Removes all search highlight tags from the document.
* @private
*/
unhighlightMatches_: function() {
// Find all search highlight elements.
var elements = document.querySelectorAll('.search-highlighted');
// For each element, remove the highlighting.
var parent, i;
for (var i = 0, node; node = elements[i]; i++) {
parent = node.parentNode;
// Replace the highlight element with the first child (the text node).
parent.replaceChild(node.firstChild, node);
// Normalize the parent so that multiple text nodes will be combined.
parent.normalize();
}
},
/**
* Creates a search result bubble attached to an element.
* @param {Element} element An HTML element, usually a button.
* @param {string} text A string to show in the bubble.
* @private
*/
createSearchBubble_: function(element, text) {
// avoid appending multiple ballons to a button.
var sibling = element.previousElementSibling;
if (sibling && sibling.classList.contains('search-bubble'))
return;
var parent = element.parentElement;
if (parent) {
var bubble = new SearchBubble(text);
parent.insertBefore(bubble, element);
bubble.updatePosition();
}
},
/**
* Removes all search match bubbles.
* @private
*/
removeSearchBubbles_: function() {
var elements = document.querySelectorAll('.search-bubble');
var length = elements.length;
for (var i = 0; i < length; i++)
elements[i].dispose();
},
/**
* Builds a list of top-level pages to search. Omits the search page and
* all sub-pages.
* @returns {Array} An array of pages to search.
* @private
*/
getSearchablePages_: function() {
var name, page, pages = [];
for (name in OptionsPage.registeredPages) {
if (name != this.name) {
page = OptionsPage.registeredPages[name];
if (!page.parentPage)
pages.push(page);
}
}
return pages;
},
/**
* Builds a list of sub-pages (and overlay pages) to search. Ignore pages
* that have no associated controls.
* @returns {Array} An array of pages to search.
* @private
*/
getSearchableSubPages_: function() {
var name, pageInfo, page, pages = [];
for (name in OptionsPage.registeredPages) {
page = OptionsPage.registeredPages[name];
if (page.parentPage && page.associatedSection)
pages.push(page);
}
for (name in OptionsPage.registeredOverlayPages) {
page = OptionsPage.registeredOverlayPages[name];
if (page.associatedSection && page.pageDiv != undefined)
pages.push(page);
}
return pages;
},
/**
* A function to handle key press events.
* @return {Event} a keydown event.
* @private
*/
keyDownEventHandler_: function(event) {
// Focus the search field on an unused forward-slash.
if (event.keyCode == 191 &&
!/INPUT|SELECT|BUTTON|TEXTAREA/.test(event.target.tagName)) {
this.searchField.focus();
event.stopPropagation();
event.preventDefault();
}
},
};
/**
* Standardizes a user-entered text query by removing extra whitespace.
* @param {string} The user-entered text.
* @return {string} The trimmed query.
*/
SearchPage.canonicalizeQuery = function(text) {
// Trim beginning and ending whitespace.
return text.replace(/^\s+|\s+$/g, '');
};
// Export
return {
SearchPage: SearchPage
};
});
|