utils.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349
  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. //take an element with mustache templates as content and re-render
  18. renderElement:function(element,data) {
  19. element.html(Mustache.render(element.html(), data));
  20. },
  21. renderElements:function(selector,data) {
  22. if(selector == null || typeof(selector) == "undefined")
  23. selector = '';
  24. $(selector).each(function() {
  25. utils._renderElement(this);
  26. });
  27. },
  28. renderPage:function(page_selector,data) {
  29. return utils.renderElements('.' + PAGE_TEMPLATE_PREFIX + page_selector,data);
  30. },
  31. setTitle:function(title) {
  32. $('.page-title').text(title);
  33. return this;
  34. },
  35. getTitle:function() {
  36. return $('.page-title').text();
  37. }
  38. }
  39. function hashToArray(hash) {
  40. var keys = Object.keys(hash);
  41. var output = [];
  42. for(var i=0;i<keys.length;i++) {
  43. output.push({'key':keys[i],'value':hash[keys[i]]});
  44. }
  45. return output;
  46. }
  47. function stringHashColor(str) {
  48. var r = 0, g = 0, b = 0, a = 0;
  49. for(var i=0;i<str.length;i++) {
  50. var c = str.charCodeAt(i);
  51. a += c;
  52. r += Math.floor(Math.abs(Math.sin(c)) * a);
  53. g += Math.floor(Math.abs(Math.cos(c)) * a);
  54. b += Math.floor(Math.abs(Math.tan(c)) * a);
  55. }
  56. return 'rgb('+(r%190)+','+(g%190)+','+(b%190)+')'; //always keep values under 180, to keep it darker
  57. }
  58. function scrollTo(posY) {
  59. $('html, body').animate({scrollTop: posY - 120}, 400);
  60. }
  61. function lockClickOrigin(func, origin) {
  62. return function(target, ev) {
  63. if(origin != ev.target)
  64. return function(){};
  65. return func(target, ev);
  66. };
  67. }
  68. function confirm(title, text, callback) {
  69. var modal = $('#confirm-modal');
  70. ko.cleanNode(modal[0]);
  71. modal.attr('data-bind','template: {name: "confirm_template"}');
  72. ko.applyBindings({
  73. title: title,
  74. text: text
  75. }, modal[0]);
  76. modal.find('.confirm-submit').click(callback);
  77. modal.modal('show');
  78. }
  79. function launchModal(modal, data) {
  80. var element = $('#'+modal);
  81. ko.cleanNode(element[0]);
  82. element.attr('data-bind','template: {name: "' + modal + '_template"}');
  83. ko.applyBindings(data, element[0]);
  84. element.is('.ajaxSubmit') ? element.submit(bindSubmit) : '';
  85. switch(modal) {
  86. case 'cell_edit_modal':
  87. if(data.mime.split('/')[0] == 'text') {
  88. var target = document.getElementById('codemirror_target');
  89. var mime = data.mime;
  90. if(mime == "text/json") {
  91. mime = {name: "javascript", json: true};
  92. }
  93. var cm = CodeMirror.fromTextArea(target, {
  94. mode: mime,
  95. tabMode: 'indent',
  96. lineNumbers: true
  97. });
  98. setTimeout(function(){cm.refresh()}, 401); //CM invis bug workaround
  99. element.find('input[type=submit]').click(function() {
  100. cm.save();
  101. });
  102. }
  103. app.focusModel(data.content);
  104. data.content.history.reload();
  105. var path = '/hbase/api/putUpload/"' + app.cluster() + '"/"' + app.views.tabledata.name() + '"/"' + data.content.parent.row + '"/"' + data.content.name + '"';
  106. var uploader = new qq.FileUploaderBasic({
  107. button: document.getElementById("file-upload-btn"),
  108. action: path,
  109. fileFieldLabel: 'hbase_file',
  110. multiple: false,
  111. onComplete:function (id, fileName, response) {
  112. data.content.reload();
  113. }
  114. });
  115. break;
  116. case 'new_column_modal':
  117. var uploader = new qq.FileUploaderBasic({
  118. button: document.getElementById("column-upload-btn"),
  119. action: '',
  120. fileFieldLabel: 'hbase_file',
  121. multiple: false,
  122. onComplete:function (id, fileName, response) {
  123. if(response.status == null) {
  124. data.reload();
  125. element.modal('hide');
  126. } else {
  127. $.jHueNotify.error($(response.response).find('div.alert strong').text());
  128. }
  129. },
  130. onSubmit: function() {
  131. uploader._handler._options.action = '/hbase/api/putUpload/"' + app.cluster() + '"/"' + app.views.tabledata.name() + '"/' + prepForTransport(data.row) + '/"' + element.find('#new_column_name').val() + '"';
  132. }
  133. });
  134. break;
  135. }
  136. element.modal('show');
  137. logGA(modal.slice(0, modal.indexOf('_modal') != -1 ? modal.indexOf('_modal') : modal.length));
  138. }
  139. function parseXML(xml) {
  140. var parser, xmlDoc;
  141. if (window.DOMParser) {
  142. parser = new DOMParser();
  143. xmlDoc = parser.parseFromString(xml,"text/xml");
  144. }
  145. else {
  146. xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
  147. xmlDoc.async = false;
  148. xmlDoc.loadXML(xml);
  149. }
  150. return new XMLSerializer().serializeToString(xmlDoc);
  151. }
  152. function detectMimeType(data) {
  153. var MIME_TESTS = {
  154. 'text/plain':function(data){return !data;},
  155. 'type/int':function(data){return !isNaN(parseInt(data));},
  156. 'text/json':function(data) {
  157. try {
  158. return JSON.parse(data);
  159. }
  160. catch(err){}
  161. },
  162. 'text/xml':function(data) {
  163. return parseXML(data).indexOf('parsererror') == -1;
  164. }
  165. }
  166. var keys = Object.keys(MIME_TESTS);
  167. for(var i=0;i<keys.length;i++) {
  168. if(MIME_TESTS[keys[i]](data))
  169. return keys[i];
  170. }
  171. //images
  172. var types = ['image/png','image/gif','image/jpg','application/pdf']
  173. var b64 = ['iVBORw','R0lG','/9j/','JVBERi']
  174. try {
  175. var decoded = atob(data).toLowerCase().trim();
  176. for(var i=0;i<types.length;i++) {
  177. var location = decoded.indexOf(types[i].split('/')[1]);
  178. if(location >= 0 && location<10) //stupid guess
  179. return types[i];
  180. }
  181. }
  182. catch(error) {
  183. }
  184. for(var i=0;i<types.length;i++) {
  185. if(data.indexOf(b64[i]) >= 0 && data.indexOf(b64[i]) <= 10)
  186. return types[i];
  187. }
  188. return 'type/null';
  189. }
  190. function convertTimestamp(timestamp) {
  191. var date = new Date(parseInt(timestamp));
  192. return date.toLocaleString();
  193. }
  194. function formatTimestamp(timestamp) {
  195. var date = new Date(parseInt(timestamp));
  196. return date.toUTCString();
  197. }
  198. function resetElements() {
  199. $(window).unbind('scroll');
  200. $(window).scroll(function(e) {
  201. $(".subnav.sticky").each(function() {
  202. var padder = $(this).data('padder'), top = $(this).position().top + (padder ? window.scrollY : 0);
  203. if(padder && top <= padder.position().top) {
  204. $(this).removeClass('subnav-fixed').data('padder').remove();
  205. $(this).removeData('padder');
  206. }
  207. else if(!padder && top <= window.scrollY + $('.navbar').outerHeight()) {
  208. $(this).addClass('subnav-fixed').data('padder',$('<div></div>').insertBefore($(this)).css('height',$(this).outerHeight()));
  209. }
  210. });
  211. });
  212. resetSearch();
  213. };
  214. function resetSearch() {
  215. app.views.tabledata.searchQuery('');
  216. app.search.cur_input('');
  217. };
  218. function prepForTransport(value) {
  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. function doLog() {
  226. trackOnGA('hbase/' + postfix);
  227. }
  228. if(postfix == null)
  229. postfix = "";
  230. if (typeof trackOnGA == 'function') {
  231. doLog();
  232. } else {
  233. setTimeout(doLog, 10);
  234. }
  235. };
  236. function table_search(value) {
  237. routie(app.cluster() + '/' + app.views.tabledata.name() +'/query/' + value);
  238. };
  239. function getEditablePosition(contentEditable, trimWhitespaceNodes) {
  240. var el = contentEditable;
  241. if(window.getSelection().getRangeAt(0).startContainer == el) //raw reference for FF fix
  242. return 0;
  243. var index = window.getSelection().getRangeAt(0).startOffset; //ff
  244. var cur_node = window.getSelection().getRangeAt(0).startContainer; //ff
  245. while(cur_node != null && cur_node != el) {
  246. var cur_sib = cur_node.previousSibling || cur_node.previousElementSibling;
  247. while(cur_sib != null) {
  248. var val = $(cur_sib).text() || cur_sib.nodeValue;
  249. if(typeof val !== "undefined" && val != null) {
  250. index += trimWhitespaceNodes ? val.length : val.length;
  251. }
  252. cur_sib = cur_sib.previousSibling;
  253. }
  254. cur_node = cur_node.parentNode;
  255. }
  256. return index;
  257. };
  258. function setCursor(node, pos, trimWhitespaceNodes){
  259. var sel = window.getSelection();
  260. var range = document.createRange();
  261. node = function selectNode(node) {
  262. var nodes = node.childNodes;
  263. if(pos > 0) {
  264. for(var i=0; i<nodes.length; i++) {
  265. var val = trimWhitespaceNodes ? nodes[i].nodeValue.trim() : nodes[i].nodeValue;
  266. if(val) {
  267. if(val.length >= pos) {
  268. return nodes[i];
  269. } else {
  270. pos -= val.length;
  271. }
  272. }
  273. var n = selectNode(nodes[i]);
  274. if (n) return n;
  275. }
  276. }
  277. return false;
  278. }(node);
  279. try {
  280. range.setStart(node, pos);
  281. range.setEnd(node, pos);
  282. range.collapse(true);
  283. sel.removeAllRanges();
  284. sel.addRange(range);
  285. return range;
  286. } catch (err) { }
  287. }
  288. function pullFromRenderer(str, renderer) {
  289. try {
  290. return str.match(renderer.select)[0].match(renderer.tag)[0];
  291. } catch (e){
  292. return "";
  293. }
  294. }
  295. window.selectIndex = null;
  296. var fallback = typeof window.getSelection === "undefined";
  297. ko.bindingHandlers.editableText = {
  298. init: function(element, valueAccessor, allBindingsAccessor) {
  299. $(element).on('keydown', function() {
  300. setTimeout(function() {
  301. var modelValue = valueAccessor();
  302. var elementValue = $(element).text();
  303. if (ko.isWriteableObservable(modelValue) && elementValue != modelValue()) {
  304. if(!fallback)
  305. window.selectIndex = getEditablePosition(element); //firefox does some tricky predictive stuff here
  306. modelValue(elementValue);
  307. }
  308. else { //handle non-observable one-way binding
  309. var allBindings = allBindingsAccessor();
  310. if (allBindings['_ko_property_writers'] && allBindings['_ko_property_writers'].htmlValue) allBindings['_ko_property_writers'].htmlValue(elementValue);
  311. }}, 1);
  312. });
  313. },
  314. update: function(element, valueAccessor) {
  315. var value = ko.utils.unwrapObservable(valueAccessor()) || "";
  316. if(value.trim() == "" && !app.search.focused()) {
  317. app.search.doBlur();
  318. } else {
  319. if(!fallback) {
  320. element.innerHTML = app.search.render(value, searchRenderers);
  321. if(window.selectIndex != null) {
  322. setCursor(element, window.selectIndex);
  323. }
  324. }
  325. }
  326. }
  327. };