summaryrefslogtreecommitdiffstats
path: root/chrome/renderer/resources/extensions/searchbox_api.js
blob: becc8ffe8faa7e4b84089defea4967be3008f30f (plain)
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
// Copyright 2012 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.

var chrome;
if (!chrome)
  chrome = {};

if (!chrome.embeddedSearch) {
  chrome.embeddedSearch = new function() {

    // =========================================================================
    //                            Private functions
    // =========================================================================
    native function GetFont();
    native function NavigateContentWindow();

    function escapeHTML(text) {
      return text.replace(/[<>&"']/g, function(match) {
        switch (match) {
          case '<': return '&lt;';
          case '>': return '&gt;';
          case '&': return '&amp;';
          case '"': return '&quot;';
          case "'": return '&apos;';
        }
      });
    }

    var safeObjects = {};

    // Returns the |restrictedText| wrapped in a ShadowDOM.
    function SafeWrap(restrictedText, width, height, opt_fontSize) {
      var node = document.createElement('div');
      var nodeShadow = safeObjects.createShadowRoot.apply(node);
      nodeShadow.applyAuthorStyles = true;
      nodeShadow.innerHTML =
          '<div style="' +
              'width: ' + width + 'px !important;' +
              'height: ' + height + 'px !important;' +
              'font-family: \'' + GetFont() + '\', \'Arial\' !important;' +
              (opt_fontSize ?
                  'font-size: ' + opt_fontSize + 'px !important;' : '') +
              'overflow: hidden !important;' +
              'text-overflow: ellipsis !important;' +
              'white-space: nowrap !important">' +
            restrictedText +
          '</div>';
      safeObjects.defineProperty(node, 'webkitShadowRoot', { value: null });
      return node;
    }

    chrome.embeddedSearchOnWindowReady = function() {
      // |embeddedSearchOnWindowReady| is used for initializing window context
      // and should be called only once per context.
      safeObjects.createShadowRoot = Element.prototype.webkitCreateShadowRoot;
      safeObjects.defineProperty = Object.defineProperty;
      delete window.chrome.embeddedSearchOnWindowReady;
    };

    // =========================================================================
    //                           Exported functions
    // =========================================================================
    this.navigateContentWindow = function(destination, disposition) {
      return NavigateContentWindow(destination, disposition);
    };

    this.searchBox = new function() {

      // =======================================================================
      //                                  Constants
      // =======================================================================
      var MAX_CLIENT_SUGGESTIONS_TO_DEDUPE = 6;
      var MAX_ALLOWED_DEDUPE_ATTEMPTS = 5;

      var HTTP_REGEX = /^https?:\/\//;

      var WWW_REGEX = /^www\./;

      // =======================================================================
      //                            Private functions
      // =======================================================================
      native function GetQuery();
      native function GetVerbatim();
      native function GetSelectionStart();
      native function GetSelectionEnd();
      native function GetStartMargin();
      native function GetEndMargin();
      native function GetRightToLeft();
      native function GetAutocompleteResults();
      native function GetDisplayInstantResults();
      native function GetFontSize();
      native function IsKeyCaptureEnabled();
      native function SetSuggestions();
      native function SetQuerySuggestion();
      native function SetQuerySuggestionFromAutocompleteResult();
      native function SetQuery();
      native function SetQueryFromAutocompleteResult();
      native function ShowOverlay();
      native function StartCapturingKeyStrokes();
      native function StopCapturingKeyStrokes();

      function SafeWrapSuggestion(restrictedText) {
        return SafeWrap(restrictedText, window.innerWidth - 155, 22);
      }

      // Wraps the AutocompleteResult query and URL into ShadowDOM nodes so that
      // the JS cannot access them and deletes the raw values.
      function GetAutocompleteResultsWrapper() {
        var autocompleteResults = DedupeAutocompleteResults(
            GetAutocompleteResults());
        var userInput = GetQuery();
        for (var i = 0, result; result = autocompleteResults[i]; ++i) {
          var title = escapeHTML(result.contents);
          var url = escapeHTML(CleanUrl(result.destination_url, userInput));
          var combinedHtml = '<span class=chrome_url>' + url + '</span>';
          // TODO(dcblack): Rename these titleElement, urlElement, and
          // combinedElement for optimal correctness.
          if (title) {
            result.titleNode = SafeWrapSuggestion(title);
            combinedHtml += '<span class=chrome_separator> &ndash; </span>' +
                '<span class=chrome_title>' + title + '</span>';
          }
          result.urlNode = SafeWrapSuggestion(url);
          result.combinedNode = SafeWrapSuggestion(combinedHtml);
          delete result.contents;
          delete result.destination_url;
        }
        return autocompleteResults;
      }

      // TODO(dcblack): Do this in C++ instead of JS.
      function CleanUrl(url, userInput) {
        if (url.indexOf(userInput) == 0) {
          return url;
        }
        url = url.replace(HTTP_REGEX, '');
        if (url.indexOf(userInput) == 0) {
          return url;
        }
        return url.replace(WWW_REGEX, '');
      }

      // TODO(dcblack): Do this in C++ instead of JS.
      function CanonicalizeUrl(url) {
        return url.replace(HTTP_REGEX, '').replace(WWW_REGEX, '');
      }

      // Removes duplicates from AutocompleteResults.
      // TODO(dcblack): Do this in C++ instead of JS.
      function DedupeAutocompleteResults(autocompleteResults) {
        var urlToResultMap = {};
        for (var i = 0, result; result = autocompleteResults[i]; ++i) {
          var url = CanonicalizeUrl(result.destination_url);
          if (url in urlToResultMap) {
            var oldRelevance = urlToResultMap[url].rankingData.relevance;
            var newRelevance = result.rankingData.relevance;
            if (newRelevance > oldRelevance) {
              urlToResultMap[url] = result;
            }
          } else {
            urlToResultMap[url] = result;
          }
        }
        var dedupedResults = [];
        for (url in urlToResultMap) {
          dedupedResults.push(urlToResultMap[url]);
        }
        return dedupedResults;
      }

      var lastPrefixQueriedForDuplicates = '';
      var numDedupeAttempts = 0;

      function DedupeClientSuggestions(clientSuggestions) {
        var userInput = GetQuery();
        if (userInput == lastPrefixQueriedForDuplicates) {
          numDedupeAttempts += 1;
          if (numDedupeAttempts > MAX_ALLOWED_DEDUPE_ATTEMPTS) {
            // Request blocked for privacy reasons.
            // TODO(dcblack): This check is insufficient.  We should have a
            // check such that it's only callable once per onnativesuggestions,
            // not once per prefix.  Also, there is a timing problem where if
            // the user types quickly then the client will (correctly) attempt
            // to render stale results, and end up calling dedupe multiple times
            // when getValue shows the same prefix.  A better solution would be
            // to have the client send up rid ranges to dedupe against and have
            // the binary keep around all the old suggestions ever given to this
            // overlay.  I suspect such an approach would clean up this code
            // quite a bit.
            return false;
          }
        } else {
          lastPrefixQueriedForDuplicates = userInput;
          numDedupeAttempts = 1;
        }

        var autocompleteResults = DedupeAutocompleteResults(
            GetAutocompleteResults());
        var nativeUrls = {};
        for (var i = 0, result; result = autocompleteResults[i]; ++i) {
          var nativeUrl = CanonicalizeUrl(result.destination_url);
          nativeUrls[nativeUrl] = result.rid;
        }
        for (var i = 0; clientSuggestions[i] &&
             i < MAX_CLIENT_SUGGESTIONS_TO_DEDUPE; ++i) {
          var result = clientSuggestions[i];
          if (result.url) {
            var clientUrl = CanonicalizeUrl(result.url);
            if (clientUrl in nativeUrls) {
              result.duplicateOf = nativeUrls[clientUrl];
            }
          }
        }
        return true;
      }

      // =======================================================================
      //                           Exported functions
      // =======================================================================
      this.__defineGetter__('value', GetQuery);
      this.__defineGetter__('verbatim', GetVerbatim);
      this.__defineGetter__('selectionStart', GetSelectionStart);
      this.__defineGetter__('selectionEnd', GetSelectionEnd);
      this.__defineGetter__('startMargin', GetStartMargin);
      this.__defineGetter__('endMargin', GetEndMargin);
      this.__defineGetter__('rtl', GetRightToLeft);
      this.__defineGetter__('nativeSuggestions', GetAutocompleteResultsWrapper);
      this.__defineGetter__('isKeyCaptureEnabled', IsKeyCaptureEnabled);
      this.__defineGetter__('displayInstantResults', GetDisplayInstantResults);
      this.__defineGetter__('font', GetFont);
      this.__defineGetter__('fontSize', GetFontSize);

      this.setSuggestions = function(text) {
        SetSuggestions(text);
      };
      this.setAutocompleteText = function(text, behavior) {
        SetQuerySuggestion(text, behavior);
      };
      this.setRestrictedAutocompleteText = function(resultId) {
        SetQuerySuggestionFromAutocompleteResult(resultId);
      };
      this.setValue = function(text, type) {
        SetQuery(text, type);
      };
      this.setRestrictedValue = function(resultId) {
        SetQueryFromAutocompleteResult(resultId);
      };
      // TODO(jered): Remove the deprecated "reason" argument.
      this.showOverlay = function(reason, height) {
        ShowOverlay(reason, height);
      };
      // TODO(jered): Remove this when GWS knows about showOverlay().
      this.show = this.showOverlay;
      this.markDuplicateSuggestions = function(clientSuggestions) {
        return DedupeClientSuggestions(clientSuggestions);
      };
      this.startCapturingKeyStrokes = function() {
        StartCapturingKeyStrokes();
      };
      this.stopCapturingKeyStrokes = function() {
        StopCapturingKeyStrokes();
      };
      this.onchange = null;
      this.onsubmit = null;
      this.oncancel = null;
      this.onresize = null;
      this.onkeypress = null;
      this.onkeycapturechange = null;
      this.oncontextchange = null;
      this.onmarginchange = null;
      this.onnativesuggestions = null;

      // DEPRECATED. These methods are from the legacy searchbox API.
      // TODO(jered): Delete these.
      native function GetX();
      native function GetY();
      native function GetWidth();
      native function GetHeight();
      this.__defineGetter__('x', GetX);
      this.__defineGetter__('y', GetY);
      this.__defineGetter__('width', GetWidth);
      this.__defineGetter__('height', GetHeight);
    };

    this.newTabPage = new function() {

      // =======================================================================
      //                            Private functions
      // =======================================================================
      native function GetMostVisitedItems();
      native function GetThemeBackgroundInfo();
      native function DeleteMostVisitedItem();
      native function UndoAllMostVisitedDeletions();
      native function UndoMostVisitedDeletion();

      function SafeWrapMostVisited(restrictedText, width) {
        return SafeWrap(restrictedText, width, 14, 11);
      }

      function GetMostVisitedItemsWrapper() {
        var mostVisitedItems = GetMostVisitedItems();
        for (var i = 0, item; item = mostVisitedItems[i]; ++i) {
          var title = escapeHTML(item.title);
          var domain = escapeHTML(item.domain);
          item.titleElement = SafeWrapMostVisited(title, 108);
          item.domainElement = SafeWrapMostVisited(domain, 95);
          delete item.title;
          delete item.domain;
        }
        return mostVisitedItems;
      }

      // =======================================================================
      //                           Exported functions
      // =======================================================================
      this.__defineGetter__('mostVisited', GetMostVisitedItemsWrapper);
      this.__defineGetter__('themeBackgroundInfo', GetThemeBackgroundInfo);

      this.deleteMostVisitedItem = function(restrictId) {
        DeleteMostVisitedItem(restrictId);
      };
      this.undoAllMostVisitedDeletions = function() {
        UndoAllMostVisitedDeletions();
      };
      this.undoMostVisitedDeletion = function(restrictId) {
        UndoMostVisitedDeletion(restrictId);
      };

      this.onmostvisitedchange = null;
      this.onthemechange = null;
    };

    // Export legacy searchbox API.
    // TODO: Remove this when Instant Extended is fully launched.
    chrome.searchBox = this.searchBox;
  };
}