utils.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367
  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. if(data.content.parent) {
  106. var path = '/hbase/api/putUpload/"' + app.cluster() + '"/"' + app.views.tabledata.name() + '"/"' + data.content.parent.row + '"/"' + data.content.name + '"';
  107. var uploader = new qq.FileUploaderBasic({
  108. button: document.getElementById("file-upload-btn"),
  109. action: path,
  110. fileFieldLabel: 'hbase_file',
  111. multiple: false,
  112. onComplete:function (id, fileName, response) {
  113. data.content.reload();
  114. }
  115. });
  116. }
  117. break;
  118. case 'new_row_modal':
  119. $('a.action_addColumnValue').click(function() {
  120. $(this).parent().find("ul").append("<li><input type=\"text\" name=\"column_values\" class=\"ignore\" placeholder = \"family:column_name\"/> <input type=\"text\" name=\"column_values\" class=\"ignore\" placeholder = \"cell_value\"/></li>")
  121. });
  122. break;
  123. case 'new_column_modal':
  124. var uploader = new qq.FileUploaderBasic({
  125. button: document.getElementById("column-upload-btn"),
  126. action: '',
  127. fileFieldLabel: 'hbase_file',
  128. multiple: false,
  129. onComplete:function (id, fileName, response) {
  130. if(response.status == null) {
  131. data.reload();
  132. element.modal('hide');
  133. } else {
  134. $(document).trigger("error", $(response.response).find('div.alert strong').text());
  135. }
  136. },
  137. onSubmit: function() {
  138. uploader._handler._options.action = '/hbase/api/putUpload/"' + app.cluster() + '"/"' + app.views.tabledata.name() + '"/' + prepForTransport(data.row) + '/"' + element.find('#new_column_name').val() + '"';
  139. }
  140. });
  141. break;
  142. }
  143. if(!element.hasClass('in'))
  144. element.modal('show');
  145. logGA(modal.slice(0, modal.indexOf('_modal') != -1 ? modal.indexOf('_modal') : modal.length));
  146. }
  147. function editCell($data) {
  148. if ($data.parent.canWrite()) {
  149. if ($data.value().length > 146) {
  150. launchModal('cell_edit_modal',{
  151. content: $data,
  152. mime: detectMimeType($data.value())
  153. });
  154. } else {
  155. $data.editing(true);
  156. }
  157. }
  158. }
  159. function parseXML(xml) {
  160. var parser, xmlDoc;
  161. if (window.DOMParser) {
  162. parser = new DOMParser();
  163. xmlDoc = parser.parseFromString(xml,"text/xml");
  164. }
  165. else {
  166. xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
  167. xmlDoc.async = false;
  168. xmlDoc.loadXML(xml);
  169. }
  170. return new XMLSerializer().serializeToString(xmlDoc);
  171. }
  172. function detectMimeType(data) {
  173. var MIME_TESTS = {
  174. 'text/plain':function(data){return !data;},
  175. 'type/int':function(data){return !isNaN(parseInt(data));},
  176. 'text/json':function(data) {
  177. try {
  178. return JSON.parse(data);
  179. }
  180. catch(err){}
  181. },
  182. 'text/xml':function(data) {
  183. return parseXML(data).indexOf('parsererror') == -1;
  184. }
  185. }
  186. var keys = Object.keys(MIME_TESTS);
  187. for(var i=0;i<keys.length;i++) {
  188. if(MIME_TESTS[keys[i]](data))
  189. return keys[i];
  190. }
  191. //images
  192. var types = ['image/png','image/gif','image/jpg','application/pdf']
  193. var b64 = ['iVBORw','R0lG','/9j/','JVBERi']
  194. try {
  195. var decoded = atob(data).toLowerCase().trim();
  196. for(var i=0;i<types.length;i++) {
  197. var location = decoded.indexOf(types[i].split('/')[1]);
  198. if(location >= 0 && location<10) //stupid guess
  199. return types[i];
  200. }
  201. }
  202. catch(error) {
  203. }
  204. for(var i=0;i<types.length;i++) {
  205. if(data.indexOf(b64[i]) >= 0 && data.indexOf(b64[i]) <= 10)
  206. return types[i];
  207. }
  208. return 'type/null';
  209. }
  210. function convertTimestamp(timestamp) {
  211. var date = new Date(parseInt(timestamp));
  212. return date.toLocaleString();
  213. }
  214. function formatTimestamp(timestamp) {
  215. var date = new Date(parseInt(timestamp));
  216. return date.toUTCString();
  217. }
  218. function resetElements() {
  219. $(window).unbind('scroll');
  220. $(window).scroll(function(e) {
  221. $(".subnav.sticky").each(function() {
  222. var padder = $(this).data('padder'), top = $(this).position().top + (padder ? window.scrollY : 0);
  223. if(padder && top <= padder.position().top) {
  224. $(this).removeClass('subnav-fixed').data('padder').remove();
  225. $(this).removeData('padder');
  226. }
  227. else if(!padder && top <= window.scrollY + $('.navbar').outerHeight()) {
  228. $(this).addClass('subnav-fixed').data('padder',$('<div></div>').insertBefore($(this)).css('height',$(this).outerHeight()));
  229. }
  230. });
  231. });
  232. app.views.tabledata.showGrid(false);
  233. };
  234. function resetSearch() {
  235. app.views.tabledata.searchQuery('');
  236. app.search.cur_input('');
  237. };
  238. function prepForTransport(value) {
  239. value = value.replace(/\"/g,'\\\"').replace(/\//g,'\\/');
  240. if(isNaN(parseInt(value)) && value.trim() != '')
  241. value = '"' + value + '"';
  242. return encodeURIComponent(value);
  243. };
  244. function logGA(postfix) {
  245. if (postfix == null)
  246. postfix = "";
  247. if (typeof trackOnGA == 'function') {
  248. window.setTimeout(function () {
  249. trackOnGA('hbase/' + postfix);
  250. }, 10);
  251. }
  252. };
  253. function table_search(value) {
  254. routie(app.cluster() + '/' + app.views.tabledata.name() +'/query/' + value);
  255. }
  256. function getEditablePosition(contentEditable, trimWhitespaceNodes) {
  257. var el = contentEditable;
  258. if(window.getSelection().getRangeAt(0).startContainer == el) //raw reference for FF fix
  259. return 0;
  260. var index = window.getSelection().getRangeAt(0).startOffset; //ff
  261. var cur_node = window.getSelection().getRangeAt(0).startContainer; //ff
  262. while(cur_node != null && cur_node != el) {
  263. var cur_sib = cur_node.previousSibling || cur_node.previousElementSibling;
  264. while(cur_sib != null) {
  265. var val = $(cur_sib).text() || cur_sib.nodeValue;
  266. if(typeof val !== "undefined" && val != null) {
  267. index += trimWhitespaceNodes ? val.length : val.length;
  268. }
  269. cur_sib = cur_sib.previousSibling;
  270. }
  271. cur_node = cur_node.parentNode;
  272. }
  273. return index;
  274. };
  275. function setCursor(node, pos, trimWhitespaceNodes){
  276. var sel = window.getSelection();
  277. var range = document.createRange();
  278. node = function selectNode(node) {
  279. var nodes = node.childNodes;
  280. if(pos > 0) {
  281. for(var i=0; i<nodes.length; i++) {
  282. var val = trimWhitespaceNodes ? nodes[i].nodeValue.trim() : nodes[i].nodeValue;
  283. if(val) {
  284. if(val.length >= pos) {
  285. return nodes[i];
  286. } else {
  287. pos -= val.length;
  288. }
  289. }
  290. var n = selectNode(nodes[i]);
  291. if (n) return n;
  292. }
  293. }
  294. return false;
  295. }(node);
  296. try {
  297. range.setStart(node, pos);
  298. range.setEnd(node, pos);
  299. range.collapse(true);
  300. sel.removeAllRanges();
  301. sel.addRange(range);
  302. return range;
  303. } catch (err) { }
  304. }
  305. function pullFromRenderer(str, renderer) {
  306. try {
  307. return str.match(renderer.select)[0].match(renderer.tag)[0];
  308. } catch (e){
  309. return "";
  310. }
  311. }
  312. window.selectIndex = null;
  313. var fallback = typeof window.getSelection === "undefined";
  314. ko.bindingHandlers.editableText = {
  315. init: function(element, valueAccessor, allBindingsAccessor) {
  316. $(element).on('keydown', function() {
  317. setTimeout(function() {
  318. var modelValue = valueAccessor();
  319. var elementValue = $(element).text();
  320. if (ko.isWriteableObservable(modelValue) && elementValue != modelValue()) {
  321. if(!fallback)
  322. window.selectIndex = getEditablePosition(element); //firefox does some tricky predictive stuff here
  323. modelValue(elementValue);
  324. }
  325. else { //handle non-observable one-way binding
  326. var allBindings = allBindingsAccessor();
  327. if (allBindings['_ko_property_writers'] && allBindings['_ko_property_writers'].htmlValue) allBindings['_ko_property_writers'].htmlValue(elementValue);
  328. }}, 1);
  329. });
  330. },
  331. update: function(element, valueAccessor) {
  332. var value = ko.utils.unwrapObservable(valueAccessor()) || "";
  333. if(value.trim() == "" && !app.search.focused()) {
  334. app.search.doBlur();
  335. } else {
  336. if(!fallback) {
  337. element.innerHTML = app.search.render(value, searchRenderers);
  338. if(window.selectIndex != null) {
  339. setCursor(element, window.selectIndex);
  340. }
  341. }
  342. }
  343. }
  344. };