utils.js 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330
  1. // Licensed to Cloudera, Inc. under one
  2. // or more contributor license agreements. See the NOTICE file
  3. // distributed with this work for additional information
  4. // regarding copyright ownership. Cloudera, Inc. licenses this file
  5. // to you under the Apache License, Version 2.0 (the
  6. // "License"); you may not use this file except in compliance
  7. // with the License. You may obtain a copy of the License at
  8. //
  9. // http://www.apache.org/licenses/LICENSE-2.0
  10. //
  11. // Unless required by applicable law or agreed to in writing, software
  12. // distributed under the License is distributed on an "AS IS" BASIS,
  13. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. // See the License for the specific language governing permissions and
  15. // limitations under the License.
  16. var utils =
  17. {
  18. //take an element with mustache templates as content and re-render
  19. renderElement:function(element,data)
  20. {
  21. element.html(Mustache.render(element.html(), data));
  22. },
  23. renderElements:function(selector,data)
  24. {
  25. if(selector == null || typeof(selector) == "undefined")
  26. selector = '';
  27. $(selector).each(function()
  28. {
  29. utils._renderElement(this);
  30. });
  31. },
  32. renderPage:function(page_selector,data)
  33. {
  34. return utils.renderElements('.' + PAGE_TEMPLATE_PREFIX + page_selector,data);
  35. },
  36. setTitle:function(title)
  37. {
  38. $('.page-title').text(title);
  39. return this;
  40. },
  41. getTitle:function()
  42. {
  43. return $('.page-title').text();
  44. }
  45. }
  46. function hashToArray(hash)
  47. {
  48. var keys = Object.keys(hash);
  49. var output = [];
  50. for(var i=0;i<keys.length;i++)
  51. {
  52. output.push({'key':keys[i],'value':hash[keys[i]]});
  53. }
  54. return output;
  55. }
  56. function stringHashColor(str) {
  57. var r = 0, g = 0, b = 0, a = 0;
  58. for(var i=0;i<str.length;i++)
  59. {
  60. var c = str.charCodeAt(i);
  61. a += c;
  62. r += Math.floor(Math.abs(Math.sin(c)) * a);
  63. g += Math.floor(Math.abs(Math.cos(c)) * a);
  64. b += Math.floor(Math.abs(Math.tan(c)) * a);
  65. }
  66. return 'rgb('+(r%190)+','+(g%190)+','+(b%190)+')'; //always keep values under 180, to keep it darker
  67. }
  68. function scrollTo(posY)
  69. {
  70. $('html, body').animate({scrollTop: posY - 120}, 400);
  71. }
  72. function lockClickOrigin(func, origin)
  73. {
  74. return function(target, ev)
  75. {
  76. if(origin != ev.target)
  77. return function(){};
  78. return func(target, ev);
  79. };
  80. }
  81. function confirm(title, text, callback)
  82. {
  83. var modal = $('#confirm-modal');
  84. ko.cleanNode(modal[0]);
  85. modal.attr('data-bind','template: {name: "confirm_template"}');
  86. ko.applyBindings({
  87. title: title,
  88. text: text
  89. }, modal[0]);
  90. modal.find('.confirm-submit').click(callback);
  91. modal.modal('show');
  92. }
  93. function launchModal(modal, data)
  94. {
  95. var element = $('#'+modal);
  96. ko.cleanNode(element[0]);
  97. element.attr('data-bind','template: {name: "'+modal+'_template"}');
  98. ko.applyBindings(data, element[0]);
  99. element.is('.ajaxSubmit') ? element.submit(bindSubmit) : '';
  100. switch(modal)
  101. {
  102. case 'cell_edit_modal':
  103. if(data.mime.split('/')[0] == 'text')
  104. {
  105. var target = document.getElementById('codemirror_target');
  106. var mime = data.mime;
  107. if(mime == "text/json")
  108. {
  109. mime = {name: "javascript", json: true};
  110. }
  111. var cm = CodeMirror.fromTextArea(target, {
  112. mode: mime,
  113. tabMode: 'indent',
  114. lineNumbers: true
  115. });
  116. setTimeout(function(){cm.refresh()}, 401); //CM invis bug workaround
  117. element.find('input[type=submit]').click(function()
  118. {
  119. cm.save();
  120. });
  121. }
  122. app.focusModel(data.content);
  123. data.content.history.reload();
  124. break;
  125. }
  126. element.modal('show');
  127. logGA(modal.slice(0, modal.indexOf('_modal') != -1 ? modal.indexOf('_modal') : modal.length));
  128. }
  129. function parseXML(xml)
  130. {
  131. var parser, xmlDoc;
  132. if (window.DOMParser)
  133. {
  134. parser = new DOMParser();
  135. xmlDoc = parser.parseFromString(xml,"text/xml");
  136. }
  137. else
  138. {
  139. xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
  140. xmlDoc.async = false;
  141. xmlDoc.loadXML(xml);
  142. }
  143. return new XMLSerializer().serializeToString(xmlDoc);
  144. }
  145. function detectMimeType(data)
  146. {
  147. var MIME_TESTS =
  148. {
  149. 'type/null':function(data){return !data;},
  150. 'type/int':function(data){return !isNaN(parseInt(data));},
  151. 'text/json':function(data)
  152. {
  153. try
  154. {
  155. return JSON.parse(data);
  156. }
  157. catch(err){}
  158. },
  159. 'text/xml':function(data)
  160. {
  161. return parseXML(data).indexOf('parsererror') == -1;
  162. }
  163. }
  164. var keys = Object.keys(MIME_TESTS);
  165. for(var i=0;i<keys.length;i++)
  166. {
  167. if(MIME_TESTS[keys[i]](data))
  168. return keys[i];
  169. }
  170. //images
  171. var types = ['image/png','image/gif','image/jpg','application/pdf']
  172. var b64 = ['iVBORw','R0lG','/9j/','JVBERi']
  173. try
  174. {
  175. var decoded = atob(data).toLowerCase().trim();
  176. for(var i=0;i<types.length;i++)
  177. {
  178. var location = decoded.indexOf(types[i].split('/')[1]);
  179. if(location >= 0 && location<10) //stupid guess
  180. return types[i];
  181. }
  182. }
  183. catch(error)
  184. {
  185. }
  186. for(var i=0;i<types.length;i++)
  187. {
  188. if(data.indexOf(b64[i]) >= 0 && data.indexOf(b64[i]) <= 10)
  189. return types[i];
  190. }
  191. return 'type/null';
  192. }
  193. function convertTimestamp(timestamp)
  194. {
  195. var date = new Date(parseInt(timestamp)*1000);
  196. return date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds();
  197. }
  198. function resetElements()
  199. {
  200. $(window).scroll(function(e)
  201. {
  202. $(".subnav.sticky").each(function()
  203. {
  204. var padder = $(this).data('padder'), top = $(this).position().top;
  205. if(padder && top <= padder.position().top)
  206. {
  207. $(this).removeClass('subnav-fixed').data('padder').remove();
  208. $(this).removeData('padder');
  209. }
  210. else if(!padder && top <= window.scrollY + $('.navbar').outerHeight())
  211. {
  212. $(this).addClass('subnav-fixed').data('padder',$('<div></div>').insertBefore($(this)).css('height',$(this).outerHeight()));
  213. }
  214. });
  215. });
  216. };
  217. function prepForTransport(value)
  218. {
  219. value = value.replace(/\"/g,'\\\"').replace(/\//g,'\\/');
  220. if(isNaN(parseInt(value)) && value.trim() != '')
  221. value = '"' + value + '"';
  222. return encodeURIComponent(value);
  223. };
  224. function logGA(postfix)
  225. {
  226. if(postfix == null)
  227. postfix = ""
  228. if (typeof trackOnGA == 'function'){
  229. trackOnGA('hbase/' + postfix);
  230. }
  231. };
  232. function getEditablePosition(contentEditable, trimWhitespaceNodes) {
  233. var el = contentEditable;
  234. if(window.getSelection().getRangeAt(0).startContainer == el) //raw reference for FF fix
  235. return 0;
  236. var index = window.getSelection().getRangeAt(0).startOffset; //ff
  237. var cur_node = window.getSelection().getRangeAt(0).startContainer; //ff
  238. while(cur_node != null && cur_node != el) {
  239. var cur_sib = cur_node.previousSibling || cur_node.previousElementSibling;
  240. while(cur_sib != null) {
  241. var val = $(cur_sib).text() || cur_sib.nodeValue;
  242. if(typeof val !== "undefined" && val != null) {
  243. index += trimWhitespaceNodes ? val.length : val.length;
  244. }
  245. cur_sib = cur_sib.previousSibling;
  246. }
  247. cur_node = cur_node.parentNode;
  248. }
  249. return index;
  250. };
  251. function setCursor(node, pos, trimWhitespaceNodes){
  252. var sel = window.getSelection();
  253. var range = document.createRange();
  254. node = function selectNode(node) {
  255. var nodes = node.childNodes;
  256. if(pos > 0) {
  257. for(var i=0; i<nodes.length; i++) {
  258. var val = trimWhitespaceNodes ? nodes[i].nodeValue.trim() : nodes[i].nodeValue;
  259. if(val) {
  260. if(val.length >= pos) {
  261. return nodes[i];
  262. } else {
  263. pos -= val.length;
  264. }
  265. }
  266. var n = selectNode(nodes[i]);
  267. if (n) return n;
  268. }
  269. }
  270. return false;
  271. }(node);
  272. try {
  273. range.setStart(node, pos);
  274. range.setEnd(node, pos);
  275. range.collapse(true);
  276. sel.removeAllRanges();
  277. sel.addRange(range);
  278. } catch (err) { }
  279. }
  280. window.selectIndex = null;
  281. var fallback = typeof window.getSelection === "undefined";
  282. ko.bindingHandlers.editableText = {
  283. init: function(element, valueAccessor, allBindingsAccessor) {
  284. $(element).on('keydown', function() {
  285. setTimeout(function() {
  286. var modelValue = valueAccessor();
  287. var elementValue = $(element).text();
  288. if (ko.isWriteableObservable(modelValue) && elementValue != modelValue()) {
  289. if(!fallback)
  290. window.selectIndex = getEditablePosition(element); //firefox does some tricky predictive stuff here
  291. modelValue(elementValue);
  292. }
  293. else { //handle non-observable one-way binding
  294. var allBindings = allBindingsAccessor();
  295. if (allBindings['_ko_property_writers'] && allBindings['_ko_property_writers'].htmlValue) allBindings['_ko_property_writers'].htmlValue(elementValue);
  296. }}, 1);
  297. });
  298. },
  299. update: function(element, valueAccessor) {
  300. var value = ko.utils.unwrapObservable(valueAccessor()) || "";
  301. if(value.trim() == "" && !app.search.focused()) {
  302. app.search.doBlur();
  303. } else {
  304. if(!fallback) {
  305. element.innerHTML = app.search.render(value, searchRenderers);
  306. if(window.selectIndex != null)
  307. {
  308. setCursor(element, window.selectIndex);
  309. }
  310. }
  311. }
  312. }
  313. };