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 /** |
| 6 * Allows for binding callbacks to a specific scope. |
| 7 * @param {Object} scope Scope to bind to. |
| 8 * @returns {Function} A wrapped call to this function. |
| 9 */ |
| 10 Function.prototype.bind = function(scope) { |
| 11 var func = this; |
| 12 return function() { |
| 13 return func.apply(scope, arguments); |
| 14 }; |
| 15 }; |
| 16 |
| 17 ////////////////////////////////////////////////////////////////////////// |
| 18 |
| 19 /** |
| 20 * Holds the search index and exposes operations to search the API docs. |
| 21 * @constructor |
| 22 */ |
| 23 function APISearchCorpus() { |
| 24 this.corpus_ = []; |
| 25 }; |
| 26 |
| 27 /** |
| 28 * Adds an entry to the index. |
| 29 * @param {String} name Name of the function (e.g. chrome.tabs.get). |
| 30 * @param {String} url Url to the documentation. |
| 31 * @param {String} desc Description (optional). |
| 32 * @param {String} type The type of entry (e.g. method, event). |
| 33 */ |
| 34 APISearchCorpus.prototype.addEntry = function(name, url, desc, type) { |
| 35 this.corpus_.push({ |
| 36 'name' : name, |
| 37 'url' : url, |
| 38 'style' : name, |
| 39 'description' : desc, |
| 40 'type' : type |
| 41 }); |
| 42 }; |
| 43 |
| 44 /** |
| 45 * Locates a match from the supplied keywords against text. |
| 46 * |
| 47 * Keywords are matched in the order supplied, and a non-overlapping |
| 48 * search is used. The matches are returned in a styled string that |
| 49 * can be passed directly to the omnibox API. |
| 50 * |
| 51 * @param {Array.<String>} keywords A list of keywords to check. |
| 52 * @param {String} name The name to search against. |
| 53 * @returns {String|null} A string containing <match> markup |
| 54 * corresponding to the matched text, or null if no match was found. |
| 55 */ |
| 56 APISearchCorpus.prototype.findMatch_ = function(keywords, name) { |
| 57 var style = []; |
| 58 var indexFrom = 0; |
| 59 var lowerName = name.toLowerCase(); |
| 60 for (var i = 0; i < keywords.length; i++) { |
| 61 var keyword = keywords[i].toLowerCase(); |
| 62 var start = lowerName.indexOf(keyword, indexFrom); |
| 63 if (start == -1) { |
| 64 return null; |
| 65 } |
| 66 var end = start + keyword.length + 1; |
| 67 |
| 68 style.push(name.substring(indexFrom, start)) |
| 69 style.push('<match>'); |
| 70 style.push(name.substring(start, end)); |
| 71 style.push('</match>'); |
| 72 |
| 73 indexFrom = end; |
| 74 } |
| 75 style.push(name.substring(indexFrom)); |
| 76 return style.join(''); |
| 77 }; |
| 78 |
| 79 /** |
| 80 * Searches this corpus for the supplied text. |
| 81 * @param {String} text Query text. |
| 82 * @param {Number} limit Max results to return. |
| 83 * @returns {Array.<Object>} A list of entries corresponding with |
| 84 * matches (@see APISearchCorpus.findMatch_ for keyword search |
| 85 * algorithm. Results are returned in a sorted order, first by |
| 86 * length, then alphabetically by name. An exact match will be |
| 87 * returned first. |
| 88 */ |
| 89 APISearchCorpus.prototype.search = function(text, limit) { |
| 90 var results = []; |
| 91 var match = null; |
| 92 if (!text || text.length == 0) { |
| 93 return this.corpus_.slice(0, limit); // No text, start listing APIs. |
| 94 } |
| 95 var searchText = text.toLowerCase(); |
| 96 var keywords = searchText.split(' '); |
| 97 for (var i = 0; i < this.corpus_.length; i++) { |
| 98 var name = this.corpus_[i]['name']; |
| 99 if (results.length < limit) { |
| 100 var result = this.findMatch_(keywords, name); |
| 101 if (result) { |
| 102 this.corpus_[i]['style'] = result; |
| 103 results.push(this.corpus_[i]); |
| 104 } |
| 105 } |
| 106 if (!match && searchText == name) { |
| 107 match = this.corpus_[i]; // An exact match. |
| 108 } |
| 109 if (match && results.length >= limit) { |
| 110 break; // Have an exact match and have reached the search limit. |
| 111 } |
| 112 } |
| 113 if (match) { |
| 114 results.unshift(match); // Add any exact match to the front. |
| 115 } |
| 116 return results; |
| 117 }; |
| 118 |
| 119 /** |
| 120 * Sorts the corpus according to name length, then name alphabetically. |
| 121 */ |
| 122 APISearchCorpus.prototype.sort = function() { |
| 123 function compareLength(a, b) { |
| 124 return a['name'].length - b['name'].length; |
| 125 }; |
| 126 |
| 127 function compareAlpha(a, b) { |
| 128 if (a['name'] < b['name']) return -1; |
| 129 if (a['name'] > b['name']) return 1; |
| 130 return 0; |
| 131 }; |
| 132 |
| 133 function compare(a, b) { |
| 134 var result = compareLength(a, b); |
| 135 if (result == 0) result = compareAlpha(a, b); |
| 136 return result; |
| 137 }; |
| 138 |
| 139 this.corpus_.sort(compare); |
| 140 }; |
| 141 |
| 142 ////////////////////////////////////////////////////////////////////////// |
| 143 |
| 144 /** |
| 145 * Provides an interface to the Chrome Extensions documentation site. |
| 146 * @param {APISearchCorpus} corpus The search corpus to populate. |
| 147 * @constructor |
| 148 */ |
| 149 function DocsManager(corpus) { |
| 150 this.CODE_URL_PREFIX = 'http://code.google.com/chrome/extensions/'; |
| 151 this.API_MANIFEST_URL = [ |
| 152 'https://src.chromium.org/viewvc/chrome/trunk/src/', |
| 153 'chrome/common/extensions/api/extension_api.json' |
| 154 ].join(''); |
| 155 this.corpus_ = corpus; |
| 156 }; |
| 157 |
| 158 /** |
| 159 * Initiates a fetch of the docs and populates the corpus. |
| 160 */ |
| 161 DocsManager.prototype.fetch = function() { |
| 162 this.fetchApi_(this.onApi_.bind(this)); |
| 163 }; |
| 164 |
| 165 /** |
| 166 * Retrieves the API manifest from cache or fetches a new one if none. |
| 167 * @param {Function} callback The function to pass the parsed manifest |
| 168 * data to. |
| 169 */ |
| 170 DocsManager.prototype.fetchApi_ = function(callback) { |
| 171 var currentCacheTime = this.getCacheTime_(); |
| 172 if (localStorage['cache-time'] && localStorage['cache']) { |
| 173 var cacheTime = JSON.parse(localStorage['cache-time']); |
| 174 if (cacheTime < currentCacheTime) { |
| 175 callback(JSON.parse(localStorage['cache'])); |
| 176 return; |
| 177 } |
| 178 } |
| 179 var xhr = new XMLHttpRequest(); |
| 180 xhr.addEventListener('readystatechange', function(evt) { |
| 181 if (xhr.readyState == 4 && xhr.responseText) { |
| 182 localStorage['cache-time'] = JSON.stringify(currentCacheTime); |
| 183 localStorage['cache'] = xhr.responseText; |
| 184 var json = JSON.parse(xhr.responseText); |
| 185 callback(json); |
| 186 } |
| 187 }); |
| 188 xhr.open('GET', this.API_MANIFEST_URL, true); |
| 189 xhr.send(); |
| 190 }; |
| 191 |
| 192 /** |
| 193 * Returns a time which can be used to cache a manifest response. |
| 194 * @returns {Number} A timestamp divided by the number of ms in a day, |
| 195 * rounded to the nearest integer. This means the number should |
| 196 * change only once per day, invalidating the cache that often. |
| 197 */ |
| 198 DocsManager.prototype.getCacheTime_ = function() { |
| 199 var time = new Date().getTime(); |
| 200 time = Math.round(time / (1000 * 60 * 60 * 24)); |
| 201 return time; |
| 202 }; |
| 203 |
| 204 /** |
| 205 * Returns an URL for the documentation given an API element. |
| 206 * @param {String} namespace The namespace (e.g. tabs, windows). |
| 207 * @param {String} type The type of element (e.g. event, method, type). |
| 208 * @param {String} name The name of the element (e.g. onRemoved). |
| 209 * @returns {String} An URL corresponding with the documentation for the |
| 210 * given element. |
| 211 */ |
| 212 DocsManager.prototype.getDocLink_ = function(namespace, type, name) { |
| 213 var linkparts = [ this.CODE_URL_PREFIX, namespace, '.html' ]; |
| 214 if (type && name) { |
| 215 linkparts.push('#', type, '-', name); |
| 216 } |
| 217 return linkparts.join(''); |
| 218 }; |
| 219 |
| 220 /** |
| 221 * Returns a qualified name for an API element. |
| 222 * @param {String} namespace The namespace (e.g. tabs, windows). |
| 223 * @param {String} name The name of the element (e.g. onRemoved). |
| 224 * @returns {String} A qualified API name (e.g. chrome.tabs.onRemoved). |
| 225 */ |
| 226 DocsManager.prototype.getName_ = function(namespace, name) { |
| 227 var nameparts = [ 'chrome', namespace ]; |
| 228 if (name) { |
| 229 nameparts.push(name); |
| 230 } |
| 231 return nameparts.join('.'); |
| 232 }; |
| 233 |
| 234 /** |
| 235 * Parses an API manifest data structure and populates the search index. |
| 236 * @param {Object} api The api manifest, as a JSON-parsed object. |
| 237 */ |
| 238 DocsManager.prototype.onApi_ = function(api) { |
| 239 for (var i = 0; i < api.length; i++) { |
| 240 var module = api[i]; |
| 241 if (module.nodoc) { |
| 242 continue; |
| 243 } |
| 244 var ns = module.namespace; |
| 245 var nsName = this.getName_(ns); |
| 246 var nsUrl = this.getDocLink_(ns); |
| 247 this.corpus_.addEntry(nsName, nsUrl, null, 'namespace'); |
| 248 this.parseAPIArray_('method', ns, module.functions); |
| 249 this.parseAPIArray_('event', ns, module.events); |
| 250 this.parseAPIArray_('type', ns, module.types); |
| 251 this.parseAPIObject_('property', ns, module.properties); |
| 252 this.corpus_.sort(); |
| 253 } |
| 254 }; |
| 255 |
| 256 /** |
| 257 * Parses an API manifest subsection which is formatted as an Array. |
| 258 * @param {String} type The type of data (e.g. method, event, type). |
| 259 * @param {String} ns The namespace (e.g. tabs, windows). |
| 260 * @param {Array} list The list of API elements. |
| 261 */ |
| 262 DocsManager.prototype.parseAPIArray_ = function(type, ns, list) { |
| 263 if (!list) return; |
| 264 for (var j = 0; j < list.length; j++) { |
| 265 var item = list[j]; |
| 266 if (item.nodoc) continue; |
| 267 var name = item.name || item.id; |
| 268 var fullname = this.getName_(ns, name); |
| 269 var url = this.getDocLink_(ns, type, name); |
| 270 var description = item.description; |
| 271 this.corpus_.addEntry(fullname, url, description, type); |
| 272 } |
| 273 }; |
| 274 |
| 275 /** |
| 276 * Parses an API manifest subsection which is formatted as an Object. |
| 277 * @param {String} type The type of data (e.g. property). |
| 278 * @param {String} ns The namespace (e.g. tabs, windows). |
| 279 * @param {Object} list The object containing API elements. |
| 280 */ |
| 281 DocsManager.prototype.parseAPIObject_ = function(type, ns, list) { |
| 282 for (var prop in list) { |
| 283 if (list.hasOwnProperty(prop)) { |
| 284 var name = this.getName_(ns, prop); |
| 285 var url = this.getDocLink_(ns, type, prop); |
| 286 var description = list[prop].description; |
| 287 this.corpus_.addEntry(name, url, description, type); |
| 288 } |
| 289 } |
| 290 }; |
| 291 |
| 292 ////////////////////////////////////////////////////////////////////////// |
| 293 |
| 294 /** |
| 295 * Manages text input into the omnibox and returns search results. |
| 296 * @param {APISearchCorpus} Populated search corpus. |
| 297 * @param {TabManager} Manager to use to open tabs. |
| 298 * @constructor |
| 299 */ |
| 300 function OmniboxManager(corpus, tabManager) { |
| 301 this.SEPARATOR = ' - '; |
| 302 this.corpus_ = corpus; |
| 303 this.tabManager_ = tabManager; |
| 304 chrome.omnibox.onInputChanged.addListener( |
| 305 this.onChanged_.bind(this)); |
| 306 chrome.omnibox.onInputEntered.addListener( |
| 307 this.onEntered_.bind(this)); |
| 308 }; |
| 309 |
| 310 /** |
| 311 * Converts a corpus match to an object suitable for the omnibox API. |
| 312 * @param {Object} match The match to convert. |
| 313 * @returns {Object} A suggestion object formatted for the omnibox API. |
| 314 */ |
| 315 OmniboxManager.prototype.convertMatchToSuggestion_ = function(match) { |
| 316 var suggestion = [ match['style'] ]; |
| 317 if (match['type']) { |
| 318 // Abusing the URL style a little, but want this to stand out. |
| 319 suggestion.push(['<url>', match['type'], '</url>'].join('')); |
| 320 } |
| 321 if (match['description']) { |
| 322 suggestion.push(['<dim>', match['description'], '</dim>'].join('')); |
| 323 } |
| 324 return { |
| 325 'content' : match['name'], |
| 326 'description' : suggestion.join(' - ') |
| 327 } |
| 328 }; |
| 329 |
| 330 /** |
| 331 * Suggests a list of possible matches when omnibox text changes. |
| 332 * @param {String} text Text input from the omnibox. |
| 333 * @param {Function} suggest Callback to execute with a list of |
| 334 * suggestion objects, if any matches were found. |
| 335 */ |
| 336 OmniboxManager.prototype.onChanged_ = function(text, suggest) { |
| 337 var matches = this.corpus_.search(text, 10); |
| 338 var suggestions = []; |
| 339 for (var i = 0; i < matches.length; i++) { |
| 340 var suggestion = this.convertMatchToSuggestion_(matches[i]); |
| 341 suggestions.push(suggestion); |
| 342 } |
| 343 suggest(suggestions); |
| 344 }; |
| 345 |
| 346 /** |
| 347 * Opens the most appropriate URL when enter is pressed in the omnibox. |
| 348 * |
| 349 * Note that the entered text does not have to be exact - the first |
| 350 * search result is automatically opened when enter is pressed. |
| 351 * |
| 352 * @param {String} text The text entered. |
| 353 */ |
| 354 OmniboxManager.prototype.onEntered_ = function(text) { |
| 355 var matches = this.corpus_.search(text, 1); |
| 356 if (matches.length > 0) { |
| 357 this.tabManager_.open(matches[0]['url']); |
| 358 } |
| 359 }; |
| 360 |
| 361 ////////////////////////////////////////////////////////////////////////// |
| 362 |
| 363 /** |
| 364 * Manages opening urls in tabs. |
| 365 * @constructor |
| 366 */ |
| 367 function TabManager() { |
| 368 this.tab_ = null; |
| 369 chrome.tabs.onRemoved.addListener(this.onRemoved_.bind(this)); |
| 370 }; |
| 371 |
| 372 /** |
| 373 * When a tab is removed, see if it was opened by us and null out if yes. |
| 374 * @param {Number} tabid ID of the removed tab. |
| 375 */ |
| 376 TabManager.prototype.onRemoved_ = function(tabid) { |
| 377 if (this.tab_ && tabid == this.tab_.id) this.tab_ = null; |
| 378 }; |
| 379 |
| 380 /** |
| 381 * When a tab opened by us is created, store it for future updates. |
| 382 * @param {Tab} tab The tab which was just opened. |
| 383 */ |
| 384 TabManager.prototype.onTab_ = function(tab) { |
| 385 this.tab_ = tab; |
| 386 }; |
| 387 |
| 388 /** |
| 389 * Opens the supplied URL. |
| 390 * |
| 391 * The first time this method is called a new tab is created. Subsequent |
| 392 * times this is called, the opened tab will be updated. If that tab |
| 393 * is ever closed, then a new tab will be created for the next call. |
| 394 * |
| 395 * @param {String} url The URL to open. |
| 396 */ |
| 397 TabManager.prototype.open = function(url) { |
| 398 if (url) { |
| 399 var args = { 'url' : url, 'selected' : true }; |
| 400 if (this.tab_) { |
| 401 chrome.tabs.update(this.tab_.id, args); |
| 402 } else { |
| 403 chrome.tabs.create(args, this.onTab_.bind(this)); |
| 404 } |
| 405 } |
| 406 }; |
| 407 |
| 408 ////////////////////////////////////////////////////////////////////////// |
| 409 |
| 410 var corpus = new APISearchCorpus(); |
| 411 var docsManager = new DocsManager(corpus); |
| 412 docsManager.fetch(); |
| 413 var tabManager = new TabManager(); |
| 414 var omnibox = new OmniboxManager(corpus, tabManager); |
OLD | NEW |