1 // Copyright (c) 2013 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 base.require('base.iteration_helpers');
8 base.require('base.rect');
10 base.exportTo('base', function() {
12 * Adds a {@code getInstance} static method that always return the same
14 * @param {!Function} ctor The constructor for the class to add the static
17 function addSingletonGetter(ctor) {
18 ctor.getInstance = function() {
19 return ctor.instance_ || (ctor.instance_ = new ctor());
23 function instantiateTemplate(selector) {
24 return document.querySelector(selector).content.cloneNode(true);
27 function tracedFunction(fn, name, opt_this) {
31 fn.apply(opt_this, arguments);
33 console.timeEnd(name);
39 function normalizeException(e) {
40 if (typeof(e) == 'string') {
49 stack: e.stack ? e.stack : ['<unknown>']
53 function stackTrace() {
54 var stack = new Error().stack + '';
55 stack = stack.split('\n');
56 return stack.slice(2);
59 function windowRectForElement(element) {
60 var position = [element.offsetLeft, element.offsetTop];
61 var size = [element.offsetWidth, element.offsetHeight];
62 var node = element.offsetParent;
64 position[0] += node.offsetLeft;
65 position[1] += node.offsetTop;
66 node = node.offsetParent;
68 return base.Rect.fromXYWH(position[0], position[1], size[0], size[1]);
71 function clamp(x, lo, hi) {
72 return Math.min(Math.max(x, lo), hi);
75 function lerp(percentage, lo, hi) {
77 return lo + percentage * range;
80 function deg2rad(deg) {
81 return (Math.PI * deg) / 180.0;
84 function scrollIntoViewIfNeeded(el) {
85 var pr = el.parentElement.getBoundingClientRect();
86 var cr = el.getBoundingClientRect();
87 if (cr.top < pr.top) {
88 el.scrollIntoView(true);
89 } else if (cr.bottom > pr.bottom) {
90 el.scrollIntoView(false);
95 addSingletonGetter: addSingletonGetter,
97 tracedFunction: tracedFunction,
98 normalizeException: normalizeException,
99 instantiateTemplate: instantiateTemplate,
100 stackTrace: stackTrace,
102 windowRectForElement: windowRectForElement,
104 scrollIntoViewIfNeeded: scrollIntoViewIfNeeded,