1 // Copyright 2014 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.
5 cr
.define('print_preview', function() {
9 * Component that renders a search box for searching through destinations.
10 * @param {string} searchBoxPlaceholderText Search box placeholder text.
12 * @extends {print_preview.Component}
14 function SearchBox(searchBoxPlaceholderText
) {
15 print_preview
.Component
.call(this);
18 * Search box placeholder text.
21 this.searchBoxPlaceholderText_
= searchBoxPlaceholderText
;
24 * Timeout used to control incremental search.
30 * Input box where the query is entered.
31 * @private {HTMLInputElement}
37 * Enumeration of event types dispatched from the search box.
40 SearchBox
.EventType
= {
41 SEARCH
: 'print_preview.SearchBox.SEARCH'
45 * Delay in milliseconds before dispatching a SEARCH event.
49 SearchBox
.SEARCH_DELAY_
= 150;
51 SearchBox
.prototype = {
52 __proto__
: print_preview
.Component
.prototype,
54 /** @param {?string} query New query to set the search box's query to. */
55 setQuery: function(query
) {
57 this.input_
.value
= query
.trim();
60 /** Sets the input element of the search box in focus. */
66 createDom: function() {
67 this.setElementInternal(this.cloneTemplateInternal(
68 'search-box-template'));
69 this.input_
= assertInstanceof(this.getChildElement('.search-box-input'),
71 this.input_
.setAttribute('placeholder', this.searchBoxPlaceholderText_
);
75 enterDocument: function() {
76 print_preview
.Component
.prototype.enterDocument
.call(this);
77 this.tracker
.add(assert(this.input_
), 'input',
78 this.onInputInput_
.bind(this));
82 exitDocument: function() {
83 print_preview
.Component
.prototype.exitDocument
.call(this);
88 * @return {string} The current query of the search box.
91 getQuery_: function() {
92 return this.input_
.value
.trim();
96 * Dispatches a SEARCH event.
99 dispatchSearchEvent_: function() {
100 this.timeout_
= null;
101 var searchEvent
= new Event(SearchBox
.EventType
.SEARCH
);
102 var query
= this.getQuery_();
103 searchEvent
.query
= query
;
105 // Generate regexp-safe query by escaping metacharacters.
106 var safeQuery
= query
.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
107 searchEvent
.queryRegExp
= new RegExp('(' + safeQuery
+ ')', 'ig');
109 searchEvent
.queryRegExp
= null;
111 this.dispatchEvent(searchEvent
);
115 * Called when the input element's value changes. Dispatches a search event.
118 onInputInput_: function() {
120 clearTimeout(this.timeout_
);
121 this.timeout_
= setTimeout(
122 this.dispatchSearchEvent_
.bind(this), SearchBox
.SEARCH_DELAY_
);