OLD | NEW |
(Empty) | |
| 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. |
| 4 |
| 5 /** |
| 6 * The global object. |
| 7 * @type {!Object} |
| 8 * @const |
| 9 */ |
| 10 var global = this; |
| 11 |
| 12 /** @typedef {{eventName: string, uid: number}} */ |
| 13 var WebUIListener; |
| 14 |
| 15 /** Platform, package, object property, and Event support. **/ |
| 16 var cr = cr || function() { |
| 17 'use strict'; |
| 18 |
| 19 /** |
| 20 * Builds an object structure for the provided namespace path, |
| 21 * ensuring that names that already exist are not overwritten. For |
| 22 * example: |
| 23 * "a.b.c" -> a = {};a.b={};a.b.c={}; |
| 24 * @param {string} name Name of the object that this file defines. |
| 25 * @param {*=} opt_object The object to expose at the end of the path. |
| 26 * @param {Object=} opt_objectToExportTo The object to add the path to; |
| 27 * default is {@code global}. |
| 28 * @return {!Object} The last object exported (i.e. exportPath('cr.ui') |
| 29 * returns a reference to the ui property of window.cr). |
| 30 * @private |
| 31 */ |
| 32 function exportPath(name, opt_object, opt_objectToExportTo) { |
| 33 var parts = name.split('.'); |
| 34 var cur = opt_objectToExportTo || global; |
| 35 |
| 36 for (var part; parts.length && (part = parts.shift());) { |
| 37 if (!parts.length && opt_object !== undefined) { |
| 38 // last part and we have an object; use it |
| 39 cur[part] = opt_object; |
| 40 } else if (part in cur) { |
| 41 cur = cur[part]; |
| 42 } else { |
| 43 cur = cur[part] = {}; |
| 44 } |
| 45 } |
| 46 return cur; |
| 47 } |
| 48 |
| 49 /** |
| 50 * Fires a property change event on the target. |
| 51 * @param {EventTarget} target The target to dispatch the event on. |
| 52 * @param {string} propertyName The name of the property that changed. |
| 53 * @param {*} newValue The new value for the property. |
| 54 * @param {*} oldValue The old value for the property. |
| 55 */ |
| 56 function dispatchPropertyChange(target, propertyName, newValue, oldValue) { |
| 57 var e = new Event(propertyName + 'Change'); |
| 58 e.propertyName = propertyName; |
| 59 e.newValue = newValue; |
| 60 e.oldValue = oldValue; |
| 61 target.dispatchEvent(e); |
| 62 } |
| 63 |
| 64 /** |
| 65 * Converts a camelCase javascript property name to a hyphenated-lower-case |
| 66 * attribute name. |
| 67 * @param {string} jsName The javascript camelCase property name. |
| 68 * @return {string} The equivalent hyphenated-lower-case attribute name. |
| 69 */ |
| 70 function getAttributeName(jsName) { |
| 71 return jsName.replace(/([A-Z])/g, '-$1').toLowerCase(); |
| 72 } |
| 73 |
| 74 /** |
| 75 * The kind of property to define in {@code defineProperty}. |
| 76 * @enum {string} |
| 77 * @const |
| 78 */ |
| 79 var PropertyKind = { |
| 80 /** |
| 81 * Plain old JS property where the backing data is stored as a "private" |
| 82 * field on the object. |
| 83 * Use for properties of any type. Type will not be checked. |
| 84 */ |
| 85 JS: 'js', |
| 86 |
| 87 /** |
| 88 * The property backing data is stored as an attribute on an element. |
| 89 * Use only for properties of type {string}. |
| 90 */ |
| 91 ATTR: 'attr', |
| 92 |
| 93 /** |
| 94 * The property backing data is stored as an attribute on an element. If the |
| 95 * element has the attribute then the value is true. |
| 96 * Use only for properties of type {boolean}. |
| 97 */ |
| 98 BOOL_ATTR: 'boolAttr' |
| 99 }; |
| 100 |
| 101 /** |
| 102 * Helper function for defineProperty that returns the getter to use for the |
| 103 * property. |
| 104 * @param {string} name The name of the property. |
| 105 * @param {PropertyKind} kind The kind of the property. |
| 106 * @return {function():*} The getter for the property. |
| 107 */ |
| 108 function getGetter(name, kind) { |
| 109 switch (kind) { |
| 110 case PropertyKind.JS: |
| 111 var privateName = name + '_'; |
| 112 return function() { |
| 113 return this[privateName]; |
| 114 }; |
| 115 case PropertyKind.ATTR: |
| 116 var attributeName = getAttributeName(name); |
| 117 return function() { |
| 118 return this.getAttribute(attributeName); |
| 119 }; |
| 120 case PropertyKind.BOOL_ATTR: |
| 121 var attributeName = getAttributeName(name); |
| 122 return function() { |
| 123 return this.hasAttribute(attributeName); |
| 124 }; |
| 125 } |
| 126 |
| 127 // TODO(dbeam): replace with assertNotReached() in assert.js when I can coax |
| 128 // the browser/unit tests to preprocess this file through grit. |
| 129 throw 'not reached'; |
| 130 } |
| 131 |
| 132 /** |
| 133 * Helper function for defineProperty that returns the setter of the right |
| 134 * kind. |
| 135 * @param {string} name The name of the property we are defining the setter |
| 136 * for. |
| 137 * @param {PropertyKind} kind The kind of property we are getting the |
| 138 * setter for. |
| 139 * @param {function(*, *):void=} opt_setHook A function to run after the |
| 140 * property is set, but before the propertyChange event is fired. |
| 141 * @return {function(*):void} The function to use as a setter. |
| 142 */ |
| 143 function getSetter(name, kind, opt_setHook) { |
| 144 switch (kind) { |
| 145 case PropertyKind.JS: |
| 146 var privateName = name + '_'; |
| 147 return function(value) { |
| 148 var oldValue = this[name]; |
| 149 if (value !== oldValue) { |
| 150 this[privateName] = value; |
| 151 if (opt_setHook) |
| 152 opt_setHook.call(this, value, oldValue); |
| 153 dispatchPropertyChange(this, name, value, oldValue); |
| 154 } |
| 155 }; |
| 156 |
| 157 case PropertyKind.ATTR: |
| 158 var attributeName = getAttributeName(name); |
| 159 return function(value) { |
| 160 var oldValue = this[name]; |
| 161 if (value !== oldValue) { |
| 162 if (value == undefined) |
| 163 this.removeAttribute(attributeName); |
| 164 else |
| 165 this.setAttribute(attributeName, value); |
| 166 if (opt_setHook) |
| 167 opt_setHook.call(this, value, oldValue); |
| 168 dispatchPropertyChange(this, name, value, oldValue); |
| 169 } |
| 170 }; |
| 171 |
| 172 case PropertyKind.BOOL_ATTR: |
| 173 var attributeName = getAttributeName(name); |
| 174 return function(value) { |
| 175 var oldValue = this[name]; |
| 176 if (value !== oldValue) { |
| 177 if (value) |
| 178 this.setAttribute(attributeName, name); |
| 179 else |
| 180 this.removeAttribute(attributeName); |
| 181 if (opt_setHook) |
| 182 opt_setHook.call(this, value, oldValue); |
| 183 dispatchPropertyChange(this, name, value, oldValue); |
| 184 } |
| 185 }; |
| 186 } |
| 187 |
| 188 // TODO(dbeam): replace with assertNotReached() in assert.js when I can coax |
| 189 // the browser/unit tests to preprocess this file through grit. |
| 190 throw 'not reached'; |
| 191 } |
| 192 |
| 193 /** |
| 194 * Defines a property on an object. When the setter changes the value a |
| 195 * property change event with the type {@code name + 'Change'} is fired. |
| 196 * @param {!Object} obj The object to define the property for. |
| 197 * @param {string} name The name of the property. |
| 198 * @param {PropertyKind=} opt_kind What kind of underlying storage to use. |
| 199 * @param {function(*, *):void=} opt_setHook A function to run after the |
| 200 * property is set, but before the propertyChange event is fired. |
| 201 */ |
| 202 function defineProperty(obj, name, opt_kind, opt_setHook) { |
| 203 if (typeof obj == 'function') |
| 204 obj = obj.prototype; |
| 205 |
| 206 var kind = /** @type {PropertyKind} */ (opt_kind || PropertyKind.JS); |
| 207 |
| 208 if (!obj.__lookupGetter__(name)) |
| 209 obj.__defineGetter__(name, getGetter(name, kind)); |
| 210 |
| 211 if (!obj.__lookupSetter__(name)) |
| 212 obj.__defineSetter__(name, getSetter(name, kind, opt_setHook)); |
| 213 } |
| 214 |
| 215 /** |
| 216 * Counter for use with createUid |
| 217 */ |
| 218 var uidCounter = 1; |
| 219 |
| 220 /** |
| 221 * @return {number} A new unique ID. |
| 222 */ |
| 223 function createUid() { |
| 224 return uidCounter++; |
| 225 } |
| 226 |
| 227 /** |
| 228 * Returns a unique ID for the item. This mutates the item so it needs to be |
| 229 * an object |
| 230 * @param {!Object} item The item to get the unique ID for. |
| 231 * @return {number} The unique ID for the item. |
| 232 */ |
| 233 function getUid(item) { |
| 234 if (item.hasOwnProperty('uid')) |
| 235 return item.uid; |
| 236 return item.uid = createUid(); |
| 237 } |
| 238 |
| 239 /** |
| 240 * Dispatches a simple event on an event target. |
| 241 * @param {!EventTarget} target The event target to dispatch the event on. |
| 242 * @param {string} type The type of the event. |
| 243 * @param {boolean=} opt_bubbles Whether the event bubbles or not. |
| 244 * @param {boolean=} opt_cancelable Whether the default action of the event |
| 245 * can be prevented. Default is true. |
| 246 * @return {boolean} If any of the listeners called {@code preventDefault} |
| 247 * during the dispatch this will return false. |
| 248 */ |
| 249 function dispatchSimpleEvent(target, type, opt_bubbles, opt_cancelable) { |
| 250 var e = new Event(type, { |
| 251 bubbles: opt_bubbles, |
| 252 cancelable: opt_cancelable === undefined || opt_cancelable |
| 253 }); |
| 254 return target.dispatchEvent(e); |
| 255 } |
| 256 |
| 257 /** |
| 258 * Calls |fun| and adds all the fields of the returned object to the object |
| 259 * named by |name|. For example, cr.define('cr.ui', function() { |
| 260 * function List() { |
| 261 * ... |
| 262 * } |
| 263 * function ListItem() { |
| 264 * ... |
| 265 * } |
| 266 * return { |
| 267 * List: List, |
| 268 * ListItem: ListItem, |
| 269 * }; |
| 270 * }); |
| 271 * defines the functions cr.ui.List and cr.ui.ListItem. |
| 272 * @param {string} name The name of the object that we are adding fields to. |
| 273 * @param {!Function} fun The function that will return an object containing |
| 274 * the names and values of the new fields. |
| 275 */ |
| 276 function define(name, fun) { |
| 277 var obj = exportPath(name); |
| 278 var exports = fun(); |
| 279 for (var propertyName in exports) { |
| 280 // Maybe we should check the prototype chain here? The current usage |
| 281 // pattern is always using an object literal so we only care about own |
| 282 // properties. |
| 283 var propertyDescriptor = Object.getOwnPropertyDescriptor(exports, |
| 284 propertyName); |
| 285 if (propertyDescriptor) |
| 286 Object.defineProperty(obj, propertyName, propertyDescriptor); |
| 287 } |
| 288 } |
| 289 |
| 290 /** |
| 291 * Adds a {@code getInstance} static method that always return the same |
| 292 * instance object. |
| 293 * @param {!Function} ctor The constructor for the class to add the static |
| 294 * method to. |
| 295 */ |
| 296 function addSingletonGetter(ctor) { |
| 297 ctor.getInstance = function() { |
| 298 return ctor.instance_ || (ctor.instance_ = new ctor()); |
| 299 }; |
| 300 } |
| 301 |
| 302 /** |
| 303 * Forwards public APIs to private implementations. |
| 304 * @param {Function} ctor Constructor that have private implementations in its |
| 305 * prototype. |
| 306 * @param {Array<string>} methods List of public method names that have their |
| 307 * underscored counterparts in constructor's prototype. |
| 308 * @param {string=} opt_target Selector for target node. |
| 309 */ |
| 310 function makePublic(ctor, methods, opt_target) { |
| 311 methods.forEach(function(method) { |
| 312 ctor[method] = function() { |
| 313 var target = opt_target ? document.getElementById(opt_target) : |
| 314 ctor.getInstance(); |
| 315 return target[method + '_'].apply(target, arguments); |
| 316 }; |
| 317 }); |
| 318 } |
| 319 |
| 320 /** |
| 321 * The mapping used by the sendWithPromise mechanism to tie the Promise |
| 322 * returned to callers with the corresponding WebUI response. The mapping is |
| 323 * from ID to the PromiseResolver helper; the ID is generated by |
| 324 * sendWithPromise and is unique across all invocations of said method. |
| 325 * @type {!Object<!PromiseResolver>} |
| 326 */ |
| 327 var chromeSendResolverMap = {}; |
| 328 |
| 329 /** |
| 330 * The named method the WebUI handler calls directly in response to a |
| 331 * chrome.send call that expects a response. The handler requires no knowledge |
| 332 * of the specific name of this method, as the name is passed to the handler |
| 333 * as the first argument in the arguments list of chrome.send. The handler |
| 334 * must pass the ID, also sent via the chrome.send arguments list, as the |
| 335 * first argument of the JS invocation; additionally, the handler may |
| 336 * supply any number of other arguments that will be included in the response. |
| 337 * @param {string} id The unique ID identifying the Promise this response is |
| 338 * tied to. |
| 339 * @param {boolean} isSuccess Whether the request was successful. |
| 340 * @param {*} response The response as sent from C++. |
| 341 */ |
| 342 function webUIResponse(id, isSuccess, response) { |
| 343 var resolver = chromeSendResolverMap[id]; |
| 344 delete chromeSendResolverMap[id]; |
| 345 |
| 346 if (isSuccess) |
| 347 resolver.resolve(response); |
| 348 else |
| 349 resolver.reject(response); |
| 350 } |
| 351 |
| 352 /** |
| 353 * A variation of chrome.send, suitable for messages that expect a single |
| 354 * response from C++. |
| 355 * @param {string} methodName The name of the WebUI handler API. |
| 356 * @param {...*} var_args Varibale number of arguments to be forwarded to the |
| 357 * C++ call. |
| 358 * @return {!Promise} |
| 359 */ |
| 360 function sendWithPromise(methodName, var_args) { |
| 361 var args = Array.prototype.slice.call(arguments, 1); |
| 362 var promiseResolver = new PromiseResolver(); |
| 363 var id = methodName + '_' + createUid(); |
| 364 chromeSendResolverMap[id] = promiseResolver; |
| 365 chrome.send(methodName, [id].concat(args)); |
| 366 return promiseResolver.promise; |
| 367 } |
| 368 |
| 369 /** |
| 370 * A map of maps associating event names with listeners. The 2nd level map |
| 371 * associates a listener ID with the callback function, such that individual |
| 372 * listeners can be removed from an event without affecting other listeners of |
| 373 * the same event. |
| 374 * @type {!Object<!Object<!Function>>} |
| 375 */ |
| 376 var webUIListenerMap = {}; |
| 377 |
| 378 /** |
| 379 * The named method the WebUI handler calls directly when an event occurs. |
| 380 * The WebUI handler must supply the name of the event as the first argument |
| 381 * of the JS invocation; additionally, the handler may supply any number of |
| 382 * other arguments that will be forwarded to the listener callbacks. |
| 383 * @param {string} event The name of the event that has occurred. |
| 384 * @param {...*} var_args Additional arguments passed from C++. |
| 385 */ |
| 386 function webUIListenerCallback(event, var_args) { |
| 387 var eventListenersMap = webUIListenerMap[event]; |
| 388 if (!eventListenersMap) { |
| 389 // C++ event sent for an event that has no listeners. |
| 390 // TODO(dpapad): Should a warning be displayed here? |
| 391 return; |
| 392 } |
| 393 |
| 394 var args = Array.prototype.slice.call(arguments, 1); |
| 395 for (var listenerId in eventListenersMap) { |
| 396 eventListenersMap[listenerId].apply(null, args); |
| 397 } |
| 398 } |
| 399 |
| 400 /** |
| 401 * Registers a listener for an event fired from WebUI handlers. Any number of |
| 402 * listeners may register for a single event. |
| 403 * @param {string} eventName The event to listen to. |
| 404 * @param {!Function} callback The callback run when the event is fired. |
| 405 * @return {!WebUIListener} An object to be used for removing a listener via |
| 406 * cr.removeWebUIListener. Should be treated as read-only. |
| 407 */ |
| 408 function addWebUIListener(eventName, callback) { |
| 409 webUIListenerMap[eventName] = webUIListenerMap[eventName] || {}; |
| 410 var uid = createUid(); |
| 411 webUIListenerMap[eventName][uid] = callback; |
| 412 return {eventName: eventName, uid: uid}; |
| 413 } |
| 414 |
| 415 /** |
| 416 * Removes a listener. Does nothing if the specified listener is not found. |
| 417 * @param {!WebUIListener} listener The listener to be removed (as returned by |
| 418 * addWebUIListener). |
| 419 * @return {boolean} Whether the given listener was found and actually |
| 420 * removed. |
| 421 */ |
| 422 function removeWebUIListener(listener) { |
| 423 var listenerExists = webUIListenerMap[listener.eventName] && |
| 424 webUIListenerMap[listener.eventName][listener.uid]; |
| 425 if (listenerExists) { |
| 426 delete webUIListenerMap[listener.eventName][listener.uid]; |
| 427 return true; |
| 428 } |
| 429 return false; |
| 430 } |
| 431 |
| 432 return { |
| 433 addSingletonGetter: addSingletonGetter, |
| 434 createUid: createUid, |
| 435 define: define, |
| 436 defineProperty: defineProperty, |
| 437 dispatchPropertyChange: dispatchPropertyChange, |
| 438 dispatchSimpleEvent: dispatchSimpleEvent, |
| 439 exportPath: exportPath, |
| 440 getUid: getUid, |
| 441 makePublic: makePublic, |
| 442 PropertyKind: PropertyKind, |
| 443 |
| 444 // C++ <-> JS communication related methods. |
| 445 addWebUIListener: addWebUIListener, |
| 446 removeWebUIListener: removeWebUIListener, |
| 447 sendWithPromise: sendWithPromise, |
| 448 webUIListenerCallback: webUIListenerCallback, |
| 449 webUIResponse: webUIResponse, |
| 450 |
| 451 get doc() { |
| 452 return document; |
| 453 }, |
| 454 |
| 455 /** Whether we are using a Mac or not. */ |
| 456 get isMac() { |
| 457 return /Mac/.test(navigator.platform); |
| 458 }, |
| 459 |
| 460 /** Whether this is on the Windows platform or not. */ |
| 461 get isWindows() { |
| 462 return /Win/.test(navigator.platform); |
| 463 }, |
| 464 |
| 465 /** Whether this is on chromeOS or not. */ |
| 466 get isChromeOS() { |
| 467 return /CrOS/.test(navigator.userAgent); |
| 468 }, |
| 469 |
| 470 /** Whether this is on vanilla Linux (not chromeOS). */ |
| 471 get isLinux() { |
| 472 return /Linux/.test(navigator.userAgent); |
| 473 }, |
| 474 |
| 475 /** Whether this is on Android. */ |
| 476 get isAndroid() { |
| 477 return /Android/.test(navigator.userAgent); |
| 478 } |
| 479 }; |
| 480 }(); |
| 481 |
OLD | NEW |