3 Copyright (c) 2014 The Chromium Authors. All rights reserved.
4 Use of this source code is governed by a BSD-style license that can be
5 found in the LICENSE file.
7 <link rel="import" href="/base/iteration_helpers.html">
8 <link rel="import" href="/base/rect.html">
12 tv.exportTo('tv', function() {
14 * Adds a {@code getInstance} static method that always return the same
16 * @param {!Function} ctor The constructor for the class to add the static
19 function addSingletonGetter(ctor) {
20 ctor.getInstance = function() {
21 return ctor.instance_ || (ctor.instance_ = new ctor());
25 function instantiateTemplate(selector, doc) {
26 doc = doc || document;
27 var el = doc.querySelector(selector);
29 throw new Error('Element not found');
30 return el.createInstance();
33 function tracedFunction(fn, name, opt_this) {
37 fn.apply(opt_this, arguments);
39 console.timeEnd(name);
45 function normalizeException(e) {
46 if (typeof(e) == 'string') {
55 stack: e.stack ? e.stack : ['<unknown>']
59 function stackTrace() {
60 var stack = new Error().stack + '';
61 stack = stack.split('\n');
62 return stack.slice(2);
65 function windowRectForElement(element) {
66 var position = [element.offsetLeft, element.offsetTop];
67 var size = [element.offsetWidth, element.offsetHeight];
68 var node = element.offsetParent;
70 position[0] += node.offsetLeft;
71 position[1] += node.offsetTop;
72 node = node.offsetParent;
74 return tv.Rect.fromXYWH(position[0], position[1], size[0], size[1]);
77 function clamp(x, lo, hi) {
78 return Math.min(Math.max(x, lo), hi);
81 function lerp(percentage, lo, hi) {
83 return lo + percentage * range;
86 function deg2rad(deg) {
87 return (Math.PI * deg) / 180.0;
90 function scrollIntoViewIfNeeded(el) {
91 var pr = el.parentElement.getBoundingClientRect();
92 var cr = el.getBoundingClientRect();
93 if (cr.top < pr.top) {
94 el.scrollIntoView(true);
95 } else if (cr.bottom > pr.bottom) {
96 el.scrollIntoView(false);
100 function getUsingPath(path, from_dict) {
101 var parts = path.split('.');
104 for (var part; parts.length && (part = parts.shift());) {
107 } else if (part in cur) {
117 addSingletonGetter: addSingletonGetter,
119 tracedFunction: tracedFunction,
120 normalizeException: normalizeException,
121 instantiateTemplate: instantiateTemplate,
122 stackTrace: stackTrace,
124 windowRectForElement: windowRectForElement,
126 scrollIntoViewIfNeeded: scrollIntoViewIfNeeded,
132 getUsingPath: getUsingPath