1 // Copyright (c) 2012 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.
7 cr.define('chrome.sync', function() {
11 * Runs a search with the given query.
13 * @param {string} query The regex to do the search with.
14 * @param {function} callback The callback called with the search results;
15 * not called if doSearch() is called again while the search is running.
17 var doSearch = function(query, callback) {
18 var searchId = ++currSearchId;
20 var regex = new RegExp(query);
21 chrome.sync.getAllNodes(query, function(allNodes) {
22 if (currSearchId != searchId) {
25 callback(allNodes.filter(function(elem) {
26 return regex.test(JSON.stringify(elem, null, 2));
30 // Sometimes the provided regex is invalid. This and other errors will
31 // be caught and handled here.
37 * Decorates the various search controls.
39 * @param {!HTMLInputElement} queryControl The <input> object of
40 * type=search where the user types in his query.
41 * @param {!HTMLElement} statusControl The <span> object display the
43 * @param {!HTMLElement} listControl The <list> object which holds
44 * the list of returned results.
45 * @param {!HTMLPreElement} detailsControl The <pre> object which
46 * holds the details of the selected result.
48 function decorateSearchControls(queryControl, statusControl,
49 resultsControl, detailsControl) {
50 var resultsDataModel = new cr.ui.ArrayDataModel([]);
52 // Decorate search box.
53 queryControl.onsearch = function() {
54 var query = queryControl.value;
55 statusControl.textContent = '';
56 resultsDataModel.splice(0, resultsDataModel.length);
60 statusControl.textContent = 'Searching for ' + query + '...';
61 queryControl.removeAttribute('error');
62 var timer = chrome.sync.makeTimer();
63 doSearch(query, function(nodes, error) {
65 statusControl.textContent = 'Error: ' + error;
66 queryControl.setAttribute('error');
68 statusControl.textContent =
69 'Found ' + nodes.length + ' nodes in ' +
70 timer.elapsedSeconds + 's';
71 queryControl.removeAttribute('error');
73 // TODO(akalin): Write a nicer list display.
74 for (var i = 0; i < nodes.length; ++i) {
75 nodes[i].toString = function() {
76 return this.NON_UNIQUE_NAME;
79 resultsDataModel.push.apply(resultsDataModel, nodes);
80 // Workaround for http://crbug.com/83452 .
81 resultsControl.redraw();
85 queryControl.value = '';
87 // Decorate results list.
88 cr.ui.List.decorate(resultsControl);
89 resultsControl.dataModel = resultsDataModel;
90 resultsControl.selectionModel.addEventListener('change', function(event) {
91 detailsControl.textContent = '';
92 var selected = resultsControl.selectedItem;
94 detailsControl.textContent = JSON.stringify(selected, null, 2);
100 decorateSearchControls: decorateSearchControls