OLD | NEW |
(Empty) | |
| 1 // Copyright (c) 2010 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 // TODO(arv): Move to shared/js once namespaced and tested. |
| 6 |
| 7 var global = this; |
| 8 const IS_MAC = /$Mac/.test(navigator.platform); |
| 9 |
| 10 function $(id) { |
| 11 return document.getElementById(id); |
| 12 } |
| 13 |
| 14 function bind(fn, selfObj, var_args) { |
| 15 var boundArgs = Array.prototype.slice.call(arguments, 2); |
| 16 return function() { |
| 17 var args = Array.prototype.slice.call(arguments); |
| 18 args.unshift.apply(args, boundArgs); |
| 19 return fn.apply(selfObj, args); |
| 20 } |
| 21 } |
| 22 |
| 23 function url(s) { |
| 24 // http://www.w3.org/TR/css3-values/#uris |
| 25 // Parentheses, commas, whitespace characters, single quotes (') and double |
| 26 // quotes (") appearing in a URI must be escaped with a backslash |
| 27 var s2 = s.replace(/(\(|\)|\,|\s|\'|\"|\\)/g, '\\$1'); |
| 28 // WebKit has a bug when it comes to URLs that end with \ |
| 29 // https://bugs.webkit.org/show_bug.cgi?id=28885 |
| 30 if (/\\\\$/.test(s2)) { |
| 31 // Add a space to work around the WebKit bug. |
| 32 s2 += ' '; |
| 33 } |
| 34 return 'url("' + s2 + '")'; |
| 35 } |
| 36 |
| 37 function findAncestorByClass(el, className) { |
| 38 return findAncestor(el, function(el) { |
| 39 if (el.classList) |
| 40 return el.classList.contains(className); |
| 41 return null; |
| 42 }); |
| 43 } |
| 44 |
| 45 /** |
| 46 * Return the first ancestor for which the {@code predicate} returns true. |
| 47 * @param {Node} node The node to check. |
| 48 * @param {function(Node) : boolean} predicate The function that tests the |
| 49 * nodes. |
| 50 * @return {Node} The found ancestor or null if not found. |
| 51 */ |
| 52 function findAncestor(node, predicate) { |
| 53 var last = false; |
| 54 while (node != null && !(last = predicate(node))) { |
| 55 node = node.parentNode; |
| 56 } |
| 57 return last ? node : null; |
| 58 } |
| 59 |
| 60 function swapDomNodes(a, b) { |
| 61 var afterA = a.nextSibling; |
| 62 if (afterA == b) { |
| 63 swapDomNodes(b, a); |
| 64 return; |
| 65 } |
| 66 var aParent = a.parentNode; |
| 67 b.parentNode.replaceChild(a, b); |
| 68 aParent.insertBefore(b, afterA); |
| 69 } |
| 70 |
| 71 /** |
| 72 * Calls chrome.send with a callback and restores the original afterwards. |
| 73 */ |
| 74 function chromeSend(name, params, callbackName, callback) { |
| 75 var old = global[callbackName]; |
| 76 global[callbackName] = function() { |
| 77 // restore |
| 78 global[callbackName] = old; |
| 79 |
| 80 var args = Array.prototype.slice.call(arguments); |
| 81 return callback.apply(global, args); |
| 82 }; |
| 83 chrome.send(name, params); |
| 84 } |
| 85 |
| 86 |
OLD | NEW |