OLD | NEW |
| (Empty) |
1 // Copyright (c) 2011 The Chromium Authors. All rights reserved. | |
2 // Use of this source code is governed by a BSD-style license that can be | |
3 // found in the LICENSE file. | |
4 | |
5 cr.define('options', function() { | |
6 const OptionsPage = options.OptionsPage; | |
7 | |
8 /** | |
9 * Encapsulated handling of a search bubble. | |
10 * @constructor | |
11 */ | |
12 function SearchBubble(text) { | |
13 var el = cr.doc.createElement('div'); | |
14 SearchBubble.decorate(el); | |
15 el.textContent = text; | |
16 return el; | |
17 } | |
18 | |
19 SearchBubble.decorate = function(el) { | |
20 el.__proto__ = SearchBubble.prototype; | |
21 el.decorate(); | |
22 }; | |
23 | |
24 SearchBubble.prototype = { | |
25 __proto__: HTMLDivElement.prototype, | |
26 | |
27 decorate: function() { | |
28 this.className = 'search-bubble'; | |
29 | |
30 // We create a timer to periodically update the position of the bubbles. | |
31 // While this isn't all that desirable, it's the only sure-fire way of | |
32 // making sure the bubbles stay in the correct location as sections | |
33 // may dynamically change size at any time. | |
34 var self = this; | |
35 this.intervalId = setInterval(this.updatePosition.bind(this), 250); | |
36 }, | |
37 | |
38 /** | |
39 * Attach the bubble to the element. | |
40 */ | |
41 attachTo: function(element) { | |
42 var parent = element.parentElement; | |
43 if (!parent) | |
44 return; | |
45 if (parent.tagName == 'TD') { | |
46 // To make absolute positioning work inside a table cell we need | |
47 // to wrap the bubble div into another div with position:relative. | |
48 // This only works properly if the element is the first child of the | |
49 // table cell which is true for all options pages. | |
50 this.wrapper = cr.doc.createElement('div'); | |
51 this.wrapper.className = 'search-bubble-wrapper'; | |
52 this.wrapper.appendChild(this); | |
53 parent.insertBefore(this.wrapper, element); | |
54 } else { | |
55 parent.insertBefore(this, element); | |
56 } | |
57 }, | |
58 | |
59 /** | |
60 * Clear the interval timer and remove the element from the page. | |
61 */ | |
62 dispose: function() { | |
63 clearInterval(this.intervalId); | |
64 | |
65 var child = this.wrapper || this; | |
66 var parent = child.parentNode; | |
67 if (parent) | |
68 parent.removeChild(child); | |
69 }, | |
70 | |
71 /** | |
72 * Update the position of the bubble. Called at creation time and then | |
73 * periodically while the bubble remains visible. | |
74 */ | |
75 updatePosition: function() { | |
76 // This bubble is 'owned' by the next sibling. | |
77 var owner = (this.wrapper || this).nextSibling; | |
78 | |
79 // If there isn't an offset parent, we have nothing to do. | |
80 if (!owner.offsetParent) | |
81 return; | |
82 | |
83 // Position the bubble below the location of the owner. | |
84 var left = owner.offsetLeft + owner.offsetWidth / 2 - | |
85 this.offsetWidth / 2; | |
86 var top = owner.offsetTop + owner.offsetHeight; | |
87 | |
88 // Update the position in the CSS. Cache the last values for | |
89 // best performance. | |
90 if (left != this.lastLeft) { | |
91 this.style.left = left + 'px'; | |
92 this.lastLeft = left; | |
93 } | |
94 if (top != this.lastTop) { | |
95 this.style.top = top + 'px'; | |
96 this.lastTop = top; | |
97 } | |
98 } | |
99 } | |
100 | |
101 /** | |
102 * Encapsulated handling of the search page. | |
103 * @constructor | |
104 */ | |
105 function SearchPage() { | |
106 OptionsPage.call(this, 'search', templateData.searchPageTabTitle, | |
107 'searchPage'); | |
108 } | |
109 | |
110 cr.addSingletonGetter(SearchPage); | |
111 | |
112 SearchPage.prototype = { | |
113 // Inherit SearchPage from OptionsPage. | |
114 __proto__: OptionsPage.prototype, | |
115 | |
116 /** | |
117 * A boolean to prevent recursion. Used by setSearchText_(). | |
118 * @type {Boolean} | |
119 * @private | |
120 */ | |
121 insideSetSearchText_: false, | |
122 | |
123 /** | |
124 * Initialize the page. | |
125 */ | |
126 initializePage: function() { | |
127 // Call base class implementation to start preference initialization. | |
128 OptionsPage.prototype.initializePage.call(this); | |
129 | |
130 var self = this; | |
131 | |
132 // Create a search field element. | |
133 var searchField = document.createElement('input'); | |
134 searchField.id = 'search-field'; | |
135 searchField.type = 'search'; | |
136 searchField.incremental = true; | |
137 searchField.placeholder = localStrings.getString('searchPlaceholder'); | |
138 searchField.setAttribute('aria-label', searchField.placeholder); | |
139 this.searchField = searchField; | |
140 | |
141 // Replace the contents of the navigation tab with the search field. | |
142 self.tab.textContent = ''; | |
143 self.tab.appendChild(searchField); | |
144 self.tab.onclick = self.tab.onkeydown = self.tab.onkeypress = undefined; | |
145 self.tab.tabIndex = -1; | |
146 self.tab.setAttribute('role', ''); | |
147 | |
148 // Don't allow the focus on the search navbar. http://crbug.com/77989 | |
149 self.tab.onfocus = self.tab.blur; | |
150 | |
151 // Handle search events. (No need to throttle, WebKit's search field | |
152 // will do that automatically.) | |
153 searchField.onsearch = function(e) { | |
154 self.setSearchText_(this.value); | |
155 }; | |
156 | |
157 // We update the history stack every time the search field blurs. This way | |
158 // we get a history entry for each search, roughly, but not each letter | |
159 // typed. | |
160 searchField.onblur = function(e) { | |
161 var query = SearchPage.canonicalizeQuery(searchField.value); | |
162 if (!query) | |
163 return; | |
164 | |
165 // Don't push the same page onto the history stack more than once (if | |
166 // the user clicks in the search field and away several times). | |
167 var currentHash = location.hash; | |
168 var newHash = '#' + escape(query); | |
169 if (currentHash == newHash) | |
170 return; | |
171 | |
172 // If there is no hash on the current URL, the history entry has no | |
173 // search query. Replace the history entry with no search with an entry | |
174 // that does have a search. Otherwise, add it onto the history stack. | |
175 var historyFunction = currentHash ? window.history.pushState : | |
176 window.history.replaceState; | |
177 historyFunction.call( | |
178 window.history, | |
179 {pageName: self.name}, | |
180 self.title, | |
181 '/' + self.name + newHash); | |
182 }; | |
183 | |
184 // Install handler for key presses. | |
185 document.addEventListener('keydown', | |
186 this.keyDownEventHandler_.bind(this)); | |
187 | |
188 // Focus the search field by default. | |
189 searchField.focus(); | |
190 }, | |
191 | |
192 /** | |
193 * @inheritDoc | |
194 */ | |
195 get sticky() { | |
196 return true; | |
197 }, | |
198 | |
199 /** | |
200 * Called after this page has shown. | |
201 */ | |
202 didShowPage: function() { | |
203 // This method is called by the Options page after all pages have | |
204 // had their visibilty attribute set. At this point we can perform the | |
205 // search specific DOM manipulation. | |
206 this.setSearchActive_(true); | |
207 }, | |
208 | |
209 /** | |
210 * Called before this page will be hidden. | |
211 */ | |
212 willHidePage: function() { | |
213 // This method is called by the Options page before all pages have | |
214 // their visibilty attribute set. Before that happens, we need to | |
215 // undo the search specific DOM manipulation that was performed in | |
216 // didShowPage. | |
217 this.setSearchActive_(false); | |
218 }, | |
219 | |
220 /** | |
221 * Update the UI to reflect whether we are in a search state. | |
222 * @param {boolean} active True if we are on the search page. | |
223 * @private | |
224 */ | |
225 setSearchActive_: function(active) { | |
226 // It's fine to exit if search wasn't active and we're not going to | |
227 // activate it now. | |
228 if (!this.searchActive_ && !active) | |
229 return; | |
230 | |
231 this.searchActive_ = active; | |
232 | |
233 if (active) { | |
234 var hash = location.hash; | |
235 if (hash) | |
236 this.searchField.value = unescape(hash.slice(1)); | |
237 } else { | |
238 // Just wipe out any active search text since it's no longer relevant. | |
239 this.searchField.value = ''; | |
240 } | |
241 | |
242 var pagesToSearch = this.getSearchablePages_(); | |
243 for (var key in pagesToSearch) { | |
244 var page = pagesToSearch[key]; | |
245 | |
246 if (!active) | |
247 page.visible = false; | |
248 | |
249 // Update the visible state of all top-level elements that are not | |
250 // sections (ie titles, button strips). We do this before changing | |
251 // the page visibility to avoid excessive re-draw. | |
252 for (var i = 0, childDiv; childDiv = page.pageDiv.children[i]; i++) { | |
253 if (childDiv.classList.contains('displaytable')) { | |
254 childDiv.setAttribute('searching', active ? 'true' : 'false'); | |
255 for (var j = 0, subDiv; subDiv = childDiv.children[j]; j++) { | |
256 if (active) { | |
257 if (subDiv.tagName != 'SECTION') | |
258 subDiv.classList.add('search-hidden'); | |
259 } else { | |
260 subDiv.classList.remove('search-hidden'); | |
261 } | |
262 } | |
263 } else { | |
264 if (active) | |
265 childDiv.classList.add('search-hidden'); | |
266 else | |
267 childDiv.classList.remove('search-hidden'); | |
268 } | |
269 } | |
270 | |
271 if (active) { | |
272 // When search is active, remove the 'hidden' tag. This tag may have | |
273 // been added by the OptionsPage. | |
274 page.pageDiv.hidden = false; | |
275 } | |
276 } | |
277 | |
278 if (active) { | |
279 this.setSearchText_(this.searchField.value); | |
280 } else { | |
281 // After hiding all page content, remove any search results. | |
282 this.unhighlightMatches_(); | |
283 this.removeSearchBubbles_(); | |
284 } | |
285 }, | |
286 | |
287 /** | |
288 * Set the current search criteria. | |
289 * @param {string} text Search text. | |
290 * @private | |
291 */ | |
292 setSearchText_: function(text) { | |
293 // Prevent recursive execution of this method. | |
294 if (this.insideSetSearchText_) return; | |
295 this.insideSetSearchText_ = true; | |
296 | |
297 // Cleanup the search query string. | |
298 text = SearchPage.canonicalizeQuery(text); | |
299 | |
300 // Notify listeners about the new search query, some pages may wish to | |
301 // show/hide elements based on the query. | |
302 var event = new cr.Event('searchChanged'); | |
303 event.searchText = text; | |
304 this.dispatchEvent(event); | |
305 | |
306 // Toggle the search page if necessary. | |
307 if (text.length) { | |
308 if (!this.searchActive_) | |
309 OptionsPage.navigateToPage(this.name); | |
310 } else { | |
311 if (this.searchActive_) | |
312 OptionsPage.showDefaultPage(); | |
313 | |
314 this.insideSetSearchText_ = false; | |
315 return; | |
316 } | |
317 | |
318 var foundMatches = false; | |
319 var bubbleControls = []; | |
320 | |
321 // Remove any prior search results. | |
322 this.unhighlightMatches_(); | |
323 this.removeSearchBubbles_(); | |
324 | |
325 // Generate search text by applying lowercase and escaping any characters | |
326 // that would be problematic for regular expressions. | |
327 var searchText = | |
328 text.toLowerCase().replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&'); | |
329 | |
330 // Generate a regular expression and replace string for hilighting | |
331 // search terms. | |
332 var regEx = new RegExp('(' + searchText + ')', 'ig'); | |
333 var replaceString = '<span class="search-highlighted">$1</span>'; | |
334 | |
335 // Initialize all sections. If the search string matches a title page, | |
336 // show sections for that page. | |
337 var page, pageMatch, childDiv, length; | |
338 var pagesToSearch = this.getSearchablePages_(); | |
339 for (var key in pagesToSearch) { | |
340 page = pagesToSearch[key]; | |
341 pageMatch = false; | |
342 if (searchText.length) { | |
343 pageMatch = this.performReplace_(regEx, replaceString, page.tab); | |
344 } | |
345 if (pageMatch) | |
346 foundMatches = true; | |
347 var elements = page.pageDiv.querySelectorAll('.displaytable > section'); | |
348 for (var i = 0, node; node = elements[i]; i++) { | |
349 if (pageMatch) | |
350 node.classList.remove('search-hidden'); | |
351 else | |
352 node.classList.add('search-hidden'); | |
353 } | |
354 } | |
355 | |
356 if (searchText.length) { | |
357 // Search all top-level sections for anchored string matches. | |
358 for (var key in pagesToSearch) { | |
359 page = pagesToSearch[key]; | |
360 var elements = | |
361 page.pageDiv.querySelectorAll('.displaytable > section'); | |
362 for (var i = 0, node; node = elements[i]; i++) { | |
363 if (this.performReplace_(regEx, replaceString, node)) { | |
364 node.classList.remove('search-hidden'); | |
365 foundMatches = true; | |
366 } | |
367 } | |
368 } | |
369 | |
370 // Search all sub-pages, generating an array of top-level sections that | |
371 // we need to make visible. | |
372 var subPagesToSearch = this.getSearchableSubPages_(); | |
373 var control, node; | |
374 for (var key in subPagesToSearch) { | |
375 page = subPagesToSearch[key]; | |
376 if (this.performReplace_(regEx, replaceString, page.pageDiv)) { | |
377 // Reveal the section for this search result. | |
378 section = page.associatedSection; | |
379 if (section) | |
380 section.classList.remove('search-hidden'); | |
381 | |
382 // Identify any controls that should have bubbles. | |
383 var controls = page.associatedControls; | |
384 if (controls) { | |
385 length = controls.length; | |
386 for (var i = 0; i < length; i++) | |
387 bubbleControls.push(controls[i]); | |
388 } | |
389 | |
390 foundMatches = true; | |
391 } | |
392 } | |
393 } | |
394 | |
395 // Configure elements on the search results page based on search results. | |
396 if (foundMatches) | |
397 $('searchPageNoMatches').classList.add('search-hidden'); | |
398 else | |
399 $('searchPageNoMatches').classList.remove('search-hidden'); | |
400 | |
401 // Create search balloons for sub-page results. | |
402 length = bubbleControls.length; | |
403 for (var i = 0; i < length; i++) | |
404 this.createSearchBubble_(bubbleControls[i], text); | |
405 | |
406 // Cleanup the recursion-prevention variable. | |
407 this.insideSetSearchText_ = false; | |
408 }, | |
409 | |
410 /** | |
411 * Performs a string replacement based on a regex and replace string. | |
412 * @param {RegEx} regex A regular expression for finding search matches. | |
413 * @param {String} replace A string to apply the replace operation. | |
414 * @param {Element} element An HTML container element. | |
415 * @returns {Boolean} true if the element was changed. | |
416 * @private | |
417 */ | |
418 performReplace_: function(regex, replace, element) { | |
419 var found = false; | |
420 var div, child, tmp; | |
421 | |
422 // Walk the tree, searching each TEXT node. | |
423 var walker = document.createTreeWalker(element, | |
424 NodeFilter.SHOW_TEXT, | |
425 null, | |
426 false); | |
427 var node = walker.nextNode(); | |
428 while (node) { | |
429 // Perform a search and replace on the text node value. | |
430 var newValue = node.nodeValue.replace(regex, replace); | |
431 if (newValue != node.nodeValue) { | |
432 // The text node has changed so that means we found at least one | |
433 // match. | |
434 found = true; | |
435 | |
436 // Create a temporary div element and set the innerHTML to the new | |
437 // value. | |
438 div = document.createElement('div'); | |
439 div.innerHTML = newValue; | |
440 | |
441 // Insert all the child nodes of the temporary div element into the | |
442 // document, before the original node. | |
443 child = div.firstChild; | |
444 while (child = div.firstChild) { | |
445 node.parentNode.insertBefore(child, node); | |
446 }; | |
447 | |
448 // Delete the old text node and advance the walker to the next | |
449 // node. | |
450 tmp = node; | |
451 node = walker.nextNode(); | |
452 tmp.parentNode.removeChild(tmp); | |
453 } else { | |
454 node = walker.nextNode(); | |
455 } | |
456 } | |
457 | |
458 return found; | |
459 }, | |
460 | |
461 /** | |
462 * Removes all search highlight tags from the document. | |
463 * @private | |
464 */ | |
465 unhighlightMatches_: function() { | |
466 // Find all search highlight elements. | |
467 var elements = document.querySelectorAll('.search-highlighted'); | |
468 | |
469 // For each element, remove the highlighting. | |
470 var parent, i; | |
471 for (var i = 0, node; node = elements[i]; i++) { | |
472 parent = node.parentNode; | |
473 | |
474 // Replace the highlight element with the first child (the text node). | |
475 parent.replaceChild(node.firstChild, node); | |
476 | |
477 // Normalize the parent so that multiple text nodes will be combined. | |
478 parent.normalize(); | |
479 } | |
480 }, | |
481 | |
482 /** | |
483 * Creates a search result bubble attached to an element. | |
484 * @param {Element} element An HTML element, usually a button. | |
485 * @param {string} text A string to show in the bubble. | |
486 * @private | |
487 */ | |
488 createSearchBubble_: function(element, text) { | |
489 // avoid appending multiple bubbles to a button. | |
490 var sibling = element.previousElementSibling; | |
491 if (sibling && (sibling.classList.contains('search-bubble') || | |
492 sibling.classList.contains('search-bubble-wrapper'))) | |
493 return; | |
494 | |
495 var parent = element.parentElement; | |
496 if (parent) { | |
497 var bubble = new SearchBubble(text); | |
498 bubble.attachTo(element); | |
499 bubble.updatePosition(); | |
500 } | |
501 }, | |
502 | |
503 /** | |
504 * Removes all search match bubbles. | |
505 * @private | |
506 */ | |
507 removeSearchBubbles_: function() { | |
508 var elements = document.querySelectorAll('.search-bubble'); | |
509 var length = elements.length; | |
510 for (var i = 0; i < length; i++) | |
511 elements[i].dispose(); | |
512 }, | |
513 | |
514 /** | |
515 * Builds a list of top-level pages to search. Omits the search page and | |
516 * all sub-pages. | |
517 * @returns {Array} An array of pages to search. | |
518 * @private | |
519 */ | |
520 getSearchablePages_: function() { | |
521 var name, page, pages = []; | |
522 for (name in OptionsPage.registeredPages) { | |
523 if (name != this.name) { | |
524 page = OptionsPage.registeredPages[name]; | |
525 if (!page.parentPage) | |
526 pages.push(page); | |
527 } | |
528 } | |
529 return pages; | |
530 }, | |
531 | |
532 /** | |
533 * Builds a list of sub-pages (and overlay pages) to search. Ignore pages | |
534 * that have no associated controls. | |
535 * @returns {Array} An array of pages to search. | |
536 * @private | |
537 */ | |
538 getSearchableSubPages_: function() { | |
539 var name, pageInfo, page, pages = []; | |
540 for (name in OptionsPage.registeredPages) { | |
541 page = OptionsPage.registeredPages[name]; | |
542 if (page.parentPage && page.associatedSection) | |
543 pages.push(page); | |
544 } | |
545 for (name in OptionsPage.registeredOverlayPages) { | |
546 page = OptionsPage.registeredOverlayPages[name]; | |
547 if (page.associatedSection && page.pageDiv != undefined) | |
548 pages.push(page); | |
549 } | |
550 return pages; | |
551 }, | |
552 | |
553 /** | |
554 * A function to handle key press events. | |
555 * @return {Event} a keydown event. | |
556 * @private | |
557 */ | |
558 keyDownEventHandler_: function(event) { | |
559 const ESCAPE_KEY_CODE = 27; | |
560 const FORWARD_SLASH_KEY_CODE = 191; | |
561 | |
562 switch(event.keyCode) { | |
563 case ESCAPE_KEY_CODE: | |
564 if (event.target == this.searchField) { | |
565 this.setSearchText_(''); | |
566 this.searchField.blur(); | |
567 event.stopPropagation(); | |
568 event.preventDefault(); | |
569 } | |
570 break; | |
571 case FORWARD_SLASH_KEY_CODE: | |
572 if (!/INPUT|SELECT|BUTTON|TEXTAREA/.test(event.target.tagName) && | |
573 !event.ctrlKey && !event.altKey) { | |
574 this.searchField.focus(); | |
575 event.stopPropagation(); | |
576 event.preventDefault(); | |
577 } | |
578 break; | |
579 } | |
580 }, | |
581 }; | |
582 | |
583 /** | |
584 * Standardizes a user-entered text query by removing extra whitespace. | |
585 * @param {string} The user-entered text. | |
586 * @return {string} The trimmed query. | |
587 */ | |
588 SearchPage.canonicalizeQuery = function(text) { | |
589 // Trim beginning and ending whitespace. | |
590 return text.replace(/^\s+|\s+$/g, ''); | |
591 }; | |
592 | |
593 // Export | |
594 return { | |
595 SearchPage: SearchPage | |
596 }; | |
597 | |
598 }); | |
OLD | NEW |