ko.hue-bindings.js 38 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121
  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. ko.bindingHandlers.slideVisible = {
  17. init: function (element, valueAccessor) {
  18. var value = valueAccessor();
  19. $(element).toggle(ko.unwrap(value));
  20. },
  21. update: function (element, valueAccessor) {
  22. var value = valueAccessor();
  23. ko.unwrap(value) ? $(element).slideDown(100) : $(element).slideUp(100);
  24. }
  25. };
  26. ko.bindingHandlers.fadeVisible = {
  27. init: function (element, valueAccessor) {
  28. var value = valueAccessor();
  29. $(element).toggle(ko.unwrap(value));
  30. },
  31. update: function (element, valueAccessor) {
  32. var value = valueAccessor();
  33. $(element).stop();
  34. ko.unwrap(value) ? $(element).fadeIn() : $(element).hide();
  35. }
  36. };
  37. ko.extenders.numeric = function (target, precision) {
  38. var result = ko.computed({
  39. read: target,
  40. write: function (newValue) {
  41. var current = target(),
  42. roundingMultiplier = Math.pow(10, precision),
  43. newValueAsNum = isNaN(newValue) ? 0 : parseFloat(+newValue),
  44. valueToWrite = Math.round(newValueAsNum * roundingMultiplier) / roundingMultiplier;
  45. if (valueToWrite !== current) {
  46. target(valueToWrite);
  47. } else {
  48. if (newValue !== current) {
  49. target.notifySubscribers(valueToWrite);
  50. }
  51. }
  52. }
  53. }).extend({ notify: 'always' });
  54. result(target());
  55. return result;
  56. };
  57. ko.bindingHandlers.freshereditor = {
  58. init: function (element, valueAccessor, allBindingsAccessor, viewModel) {
  59. var _el = $(element);
  60. var options = $.extend(valueAccessor(), {});
  61. _el.html(options.data());
  62. _el.freshereditor({
  63. excludes: ['strikethrough', 'removeFormat', 'insertorderedlist', 'justifyfull', 'insertheading1', 'insertheading2', 'superscript', 'subscript']
  64. });
  65. _el.freshereditor("edit", true);
  66. _el.on("mouseup", function () {
  67. storeSelection();
  68. updateValues();
  69. });
  70. var sourceDelay = -1;
  71. _el.on("keyup", function () {
  72. clearTimeout(sourceDelay);
  73. storeSelection();
  74. sourceDelay = setTimeout(function () {
  75. updateValues();
  76. }, 100);
  77. });
  78. $(".chosen-select").chosen({
  79. disable_search_threshold: 10,
  80. width: "75%"
  81. });
  82. $(document).on("addFieldToVisual", function (e, field) {
  83. _el.focus();
  84. pasteHtmlAtCaret("{{" + field.name() + "}}");
  85. });
  86. $(document).on("addFunctionToVisual", function (e, fn) {
  87. _el.focus();
  88. pasteHtmlAtCaret(fn);
  89. });
  90. function updateValues() {
  91. $("[data-template]")[0].editor.setValue(stripHtmlFromFunctions(_el.html()));
  92. valueAccessor().data(_el.html());
  93. }
  94. function storeSelection() {
  95. if (window.getSelection) {
  96. // IE9 and non-IE
  97. sel = window.getSelection();
  98. if (sel.getRangeAt && sel.rangeCount) {
  99. range = sel.getRangeAt(0);
  100. _el.data("range", range);
  101. }
  102. }
  103. else if (document.selection && document.selection.type != "Control") {
  104. // IE < 9
  105. _el.data("selection", document.selection);
  106. }
  107. }
  108. function pasteHtmlAtCaret(html) {
  109. var sel, range;
  110. if (window.getSelection) {
  111. // IE9 and non-IE
  112. sel = window.getSelection();
  113. if (sel.getRangeAt && sel.rangeCount) {
  114. if (_el.data("range")) {
  115. range = _el.data("range");
  116. }
  117. else {
  118. range = sel.getRangeAt(0);
  119. }
  120. range.deleteContents();
  121. // Range.createContextualFragment() would be useful here but is
  122. // non-standard and not supported in all browsers (IE9, for one)
  123. var el = document.createElement("div");
  124. el.innerHTML = html;
  125. var frag = document.createDocumentFragment(), node, lastNode;
  126. while ((node = el.firstChild)) {
  127. lastNode = frag.appendChild(node);
  128. }
  129. range.insertNode(frag);
  130. // Preserve the selection
  131. if (lastNode) {
  132. range = range.cloneRange();
  133. range.setStartAfter(lastNode);
  134. range.collapse(true);
  135. sel.removeAllRanges();
  136. sel.addRange(range);
  137. }
  138. }
  139. } else if (document.selection && document.selection.type != "Control") {
  140. // IE < 9
  141. if (_el.data("selection")) {
  142. _el.data("selection").createRange().pasteHTML(html);
  143. }
  144. else {
  145. document.selection.createRange().pasteHTML(html);
  146. }
  147. }
  148. }
  149. }
  150. };
  151. ko.bindingHandlers.slider = {
  152. init: function (element, valueAccessor) {
  153. var _el = $(element);
  154. var _options = $.extend(valueAccessor(), {});
  155. _el.slider({
  156. min: !isNaN(parseFloat(_options.start())) ? parseFloat(_options.start()) : 0,
  157. max: !isNaN(parseFloat(_options.end())) ? parseFloat(_options.end()) : 10,
  158. step: !isNaN(parseFloat(_options.gap())) ? parseFloat(_options.gap()) : 1,
  159. handle: _options.handle ? _options.handle : 'triangle',
  160. start: parseFloat(_options.min()),
  161. end: parseFloat(_options.max()),
  162. tooltip_split: true,
  163. tooltip: 'always'
  164. });
  165. _el.on("slide", function (e) {
  166. _options.start(e.min);
  167. _options.end(e.max);
  168. _options.min(e.start);
  169. _options.max(e.end);
  170. _options.gap(e.step);
  171. });
  172. _el.on("slideStop", function (e) {
  173. viewModel.search();
  174. });
  175. },
  176. update: function (element, valueAccessor) {
  177. var _options = $.extend(valueAccessor(), {});
  178. }
  179. }
  180. ko.bindingHandlers.daterangepicker = {
  181. INTERVAL_OPTIONS: [
  182. {
  183. value: "+200MILLISECONDS",
  184. label: "200ms"
  185. },
  186. {
  187. value: "+1SECONDS",
  188. label: "1s"
  189. },
  190. {
  191. value: "+1MINUTES",
  192. label: "1m"
  193. },
  194. {
  195. value: "+5MINUTES",
  196. label: "5m"
  197. },
  198. {
  199. value: "+10MINUTES",
  200. label: "10m"
  201. },
  202. {
  203. value: "+30MINUTES",
  204. label: "30m"
  205. },
  206. {
  207. value: "+1HOURS",
  208. label: "1h"
  209. },
  210. {
  211. value: "+3HOURS",
  212. label: "3h"
  213. },
  214. {
  215. value: "+6HOURS",
  216. label: "6h"
  217. },
  218. {
  219. value: "+12HOURS",
  220. label: "12h"
  221. },
  222. {
  223. value: "+1DAYS",
  224. label: "1d"
  225. },
  226. {
  227. value: "+7DAYS",
  228. label: "7d"
  229. },
  230. {
  231. value: "+1MONTHS",
  232. label: "1M"
  233. },
  234. {
  235. value: "+6MONTHS",
  236. label: "6M"
  237. },
  238. {
  239. value: "+1YEARS",
  240. label: "1y"
  241. }
  242. ],
  243. init: function (element, valueAccessor, allBindingsAccessor, viewModel) {
  244. var DATE_FORMAT = "YYYY-MM-DD";
  245. var TIME_FORMAT = "HH:mm:ss";
  246. var DATETIME_FORMAT = DATE_FORMAT + " " + TIME_FORMAT;
  247. var _el = $(element);
  248. var _options = $.extend(valueAccessor(), {});
  249. var _intervalOptions = [];
  250. ko.bindingHandlers.daterangepicker.INTERVAL_OPTIONS.forEach(function (interval) {
  251. _intervalOptions.push('<option value="' + interval.value + '">' + interval.label + '</option>');
  252. });
  253. function enableOptions() {
  254. var _opts = [];
  255. var _tmp = $("<div>").html(_intervalOptions.join(""))
  256. $.each(arguments, function (cnt, item) {
  257. if (_tmp.find("option[value='+" + item + "']").length > 0) {
  258. _opts.push('<option value="+' + item + '">' + _tmp.find("option[value='+" + item + "']").eq(0).text() + '</option>');
  259. }
  260. });
  261. return _opts;
  262. }
  263. function renderOptions(opts) {
  264. var _html = "";
  265. for (var i = 0; i < opts.length; i++) {
  266. _html += opts[i];
  267. }
  268. return _html;
  269. }
  270. var _tmpl = $('<div class="simpledaterangepicker">' +
  271. '<div class="facet-field-cnt picker">' +
  272. '<div class="facet-field-label facet-field-label-fixed-width">' + KO_DATERANGEPICKER_LABELS.START + '</div>' +
  273. '<div class="input-prepend input-group">' +
  274. '<span class="add-on input-group-addon"><i class="fa fa-calendar"></i></span>' +
  275. '<input type="text" class="input-small form-control start-date" />' +
  276. '</div>' +
  277. '<div class="input-prepend input-group left-margin">' +
  278. '<span class="add-on input-group-addon"><i class="fa fa-clock-o"></i></span>' +
  279. '<input type="text" class="input-mini form-control start-time" />' +
  280. '</div>' +
  281. '</div>' +
  282. '<div class="facet-field-cnt picker">' +
  283. '<div class="facet-field-label facet-field-label-fixed-width">' + KO_DATERANGEPICKER_LABELS.END + '</div>' +
  284. '<div class="input-prepend input-group">' +
  285. '<span class="add-on input-group-addon"><i class="fa fa-calendar"></i></span>' +
  286. '<input type="text" class="input-small form-control end-date" />' +
  287. '</div>' +
  288. '<div class="input-prepend input-group left-margin">' +
  289. '<span class="add-on input-group-addon"><i class="fa fa-clock-o"></i></span>' +
  290. '<input type="text" class="input-mini form-control end-time" />' +
  291. '</div>' +
  292. '</div>' +
  293. '<div class="facet-field-cnt picker">' +
  294. '<div class="facet-field-label facet-field-label-fixed-width">' + KO_DATERANGEPICKER_LABELS.INTERVAL + '</div>' +
  295. '<div class="input-prepend input-group"><span class="add-on input-group-addon"><i class="fa fa-repeat"></i></span></div>&nbsp;' +
  296. '<select class="input-small interval-select" style="margin-right: 6px">' +
  297. renderOptions(_intervalOptions) +
  298. '</select>' +
  299. '<input class="input interval hide" type="hidden" value="" />' +
  300. '</div>' +
  301. '<div class="facet-field-cnt picker">' +
  302. '<div class="facet-field-label facet-field-label-fixed-width"></div>' +
  303. '<div class="facet-field-switch"><a href="javascript:void(0)"><i class="fa fa-calendar-o"></i> ' + KO_DATERANGEPICKER_LABELS.CUSTOM_FORMAT + '</a></div>' +
  304. '</div>' +
  305. '<div class="facet-field-cnt custom">' +
  306. '<div class="facet-field-label facet-field-label-fixed-width">' + KO_DATERANGEPICKER_LABELS.START + '</div>' +
  307. '<div class="input-prepend input-group">' +
  308. '<span class="add-on input-group-addon"><i class="fa fa-calendar"></i></span>' +
  309. '<input type="text" class="input-large form-control start-date-custom" />' +
  310. '</div>' +
  311. '</div>' +
  312. '<div class="facet-field-cnt custom">' +
  313. '<div class="facet-field-label facet-field-label-fixed-width">' + KO_DATERANGEPICKER_LABELS.END + '</div>' +
  314. '<div class="input-prepend input-group">' +
  315. '<span class="add-on input-group-addon"><i class="fa fa-calendar"></i></span>' +
  316. '<input type="text" class="input-large form-control end-date-custom" />' +
  317. '</div>' +
  318. '</div>' +
  319. '<div class="facet-field-cnt custom">' +
  320. '<div class="facet-field-label facet-field-label-fixed-width">' + KO_DATERANGEPICKER_LABELS.INTERVAL + '</div>' +
  321. '<div class="input-prepend input-group">' +
  322. '<span class="add-on input-group-addon"><i class="fa fa-repeat"></i></span>' +
  323. '<input type="text" class="input-large form-control interval-custom" />' +
  324. '</div>' +
  325. '</div>' +
  326. '<div class="facet-field-cnt custom">' +
  327. '<div class="facet-field-label facet-field-label-fixed-width"></div>' +
  328. '<div class="facet-field-switch"><a href="javascript:void(0)"><i class="fa fa-calendar"></i> ' + KO_DATERANGEPICKER_LABELS.DATE_PICKERS + '</a></div>' +
  329. '</div>' +
  330. '</div>'
  331. );
  332. _tmpl.insertAfter(_el);
  333. var _minMoment = moment(_options.min());
  334. var _maxMoment = moment(_options.max());
  335. if (_minMoment.isValid() && _maxMoment.isValid()) {
  336. _tmpl.find(".facet-field-cnt.custom").hide();
  337. _tmpl.find(".facet-field-cnt.picker").show();
  338. _tmpl.find(".start-date").val(_minMoment.utc().format(DATE_FORMAT));
  339. _tmpl.find(".start-time").val(_minMoment.utc().format(TIME_FORMAT));
  340. _tmpl.find(".end-date").val(_maxMoment.utc().format(DATE_FORMAT));
  341. _tmpl.find(".end-time").val(_maxMoment.utc().format(TIME_FORMAT));
  342. _tmpl.find(".interval").val(_options.gap());
  343. _tmpl.find(".interval-custom").val(_options.gap());
  344. }
  345. else {
  346. _tmpl.find(".facet-field-cnt.custom").show();
  347. _tmpl.find(".facet-field-cnt.picker").hide();
  348. _tmpl.find(".start-date-custom").val(_options.min())
  349. _tmpl.find(".end-date-custom").val(_options.max())
  350. _tmpl.find(".interval-custom").val(_options.gap())
  351. }
  352. _tmpl.find(".start-date").datepicker({
  353. format: DATE_FORMAT.toLowerCase()
  354. }).on("changeDate", function () {
  355. rangeHandler(true);
  356. });
  357. _tmpl.find(".start-date").on("change", function () {
  358. rangeHandler(true);
  359. });
  360. _tmpl.find(".start-time").timepicker({
  361. minuteStep: 1,
  362. showSeconds: true,
  363. showMeridian: false,
  364. defaultTime: false
  365. });
  366. _tmpl.find(".end-date").datepicker({
  367. format: DATE_FORMAT.toLowerCase()
  368. }).on("changeDate", function () {
  369. rangeHandler(false);
  370. });
  371. _tmpl.find(".end-date").on("change", function () {
  372. rangeHandler(true);
  373. });
  374. _tmpl.find(".end-time").timepicker({
  375. minuteStep: 1,
  376. showSeconds: true,
  377. showMeridian: false,
  378. defaultTime: false
  379. });
  380. _tmpl.find(".start-time").on("change", function () {
  381. // the timepicker plugin doesn't have a change event handler
  382. // so we need to wait a bit to handle in with the default field event
  383. window.setTimeout(function () {
  384. rangeHandler(true)
  385. }, 200);
  386. });
  387. _tmpl.find(".end-time").on("change", function () {
  388. window.setTimeout(function () {
  389. rangeHandler(false)
  390. }, 200);
  391. });
  392. if (_minMoment.isValid() && _maxMoment.isValid()) {
  393. rangeHandler(true);
  394. }
  395. _tmpl.find(".facet-field-cnt.picker .facet-field-switch a").on("click", function () {
  396. _tmpl.find(".facet-field-cnt.custom").show();
  397. _tmpl.find(".facet-field-cnt.picker").hide();
  398. });
  399. _tmpl.find(".facet-field-cnt.custom .facet-field-switch a").on("click", function () {
  400. _tmpl.find(".facet-field-cnt.custom").hide();
  401. _tmpl.find(".facet-field-cnt.picker").show();
  402. });
  403. _tmpl.find(".start-date-custom").on("change", function () {
  404. _options.min(_tmpl.find(".start-date-custom").val());
  405. _tmpl.find(".start-date").val(moment(_options.min()).utc().format(DATE_FORMAT));
  406. _tmpl.find(".start-time").val(moment(_options.min()).utc().format(TIME_FORMAT));
  407. _options.start(_options.min());
  408. });
  409. _tmpl.find(".end-date-custom").on("change", function () {
  410. _options.max(_tmpl.find(".end-date-custom").val());
  411. _tmpl.find(".end-date").val(moment(_options.max()).utc().format(DATE_FORMAT));
  412. _tmpl.find(".end-time").val(moment(_options.max()).utc().format(TIME_FORMAT));
  413. _options.end(_options.max());
  414. });
  415. _tmpl.find(".interval-custom").on("change", function () {
  416. _options.gap(_tmpl.find(".interval-custom").val());
  417. matchIntervals();
  418. });
  419. function matchIntervals() {
  420. _tmpl.find(".interval-select").val(_options.gap());
  421. if (_tmpl.find(".interval-select").val() == null) {
  422. _tmpl.find(".interval-select").val(_tmpl.find(".interval-select option:first").val());
  423. _options.gap(_tmpl.find(".interval-select").val());
  424. _tmpl.find(".interval-custom").val(_options.gap());
  425. }
  426. }
  427. _tmpl.find(".interval-select").on("change", function () {
  428. _options.gap(_tmpl.find(".interval-select").val());
  429. _tmpl.find(".interval").val(_options.gap());
  430. _tmpl.find(".interval-custom").val(_options.gap());
  431. });
  432. function rangeHandler(isStart) {
  433. var startDate = moment(_tmpl.find(".start-date").val() + " " + _tmpl.find(".start-time").val(), DATETIME_FORMAT);
  434. var endDate = moment(_tmpl.find(".end-date").val() + " " + _tmpl.find(".end-time").val(), DATETIME_FORMAT);
  435. if (startDate.valueOf() > endDate.valueOf()) {
  436. if (isStart) {
  437. _tmpl.find(".end-date").val(startDate.utc().format(DATE_FORMAT));
  438. _tmpl.find(".end-date").datepicker('setValue', startDate.utc().format(DATE_FORMAT));
  439. _tmpl.find(".end-date").data("original-val", _tmpl.find(".end-date").val());
  440. _tmpl.find(".end-time").val(startDate.utc().format(TIME_FORMAT));
  441. }
  442. else {
  443. if (_tmpl.find(".end-date").val() == _tmpl.find(".start-date").val()) {
  444. _tmpl.find(".end-time").val(startDate.utc().format(TIME_FORMAT));
  445. _tmpl.find(".end-time").data("timepicker").setValues(startDate.format(TIME_FORMAT));
  446. }
  447. else {
  448. _tmpl.find(".end-date").val(_tmpl.find(".end-date").data("original-val"));
  449. _tmpl.find(".end-date").datepicker("setValue", _tmpl.find(".end-date").data("original-val"));
  450. }
  451. // non-sticky error notification
  452. $.jHueNotify.notify({
  453. level: "ERROR",
  454. message: "The end cannot be before the starting moment"
  455. });
  456. }
  457. }
  458. else {
  459. _tmpl.find(".end-date").data("original-val", _tmpl.find(".end-date").val());
  460. _tmpl.find(".start-date").datepicker("hide");
  461. _tmpl.find(".end-date").datepicker("hide");
  462. }
  463. var _calculatedStartDate = moment(_tmpl.find(".start-date").val() + " " + _tmpl.find(".start-time").val(), DATETIME_FORMAT);
  464. var _calculatedEndDate = moment(_tmpl.find(".end-date").val() + " " + _tmpl.find(".end-time").val(), DATETIME_FORMAT);
  465. _options.min(_calculatedStartDate.format("YYYY-MM-DD[T]HH:mm:ss[Z]"));
  466. _options.start(_options.min());
  467. _options.max(_calculatedEndDate.format("YYYY-MM-DD[T]HH:mm:ss[Z]"));
  468. _options.end(_options.max());
  469. _tmpl.find(".start-date-custom").val(_options.min());
  470. _tmpl.find(".end-date-custom").val(_options.max());
  471. var _opts = [];
  472. // hide not useful options from interval
  473. if (_calculatedEndDate.diff(_calculatedStartDate, 'minutes') > 1 && _calculatedEndDate.diff(_calculatedStartDate, 'minutes') <= 60) {
  474. _opts = enableOptions("200MILLISECONDS", "1SECONDS", "1MINUTES", "5MINUTES", "10MINUTES", "30MINUTES");
  475. }
  476. if (_calculatedEndDate.diff(_calculatedStartDate, 'hours') > 1 && _calculatedEndDate.diff(_calculatedStartDate, 'hours') <= 12) {
  477. _opts = enableOptions("5MINUTES", "10MINUTES", "30MINUTES", "1HOURS", "3HOURS");
  478. }
  479. if (_calculatedEndDate.diff(_calculatedStartDate, 'hours') > 12 && _calculatedEndDate.diff(_calculatedStartDate, 'hours') < 36) {
  480. _opts = enableOptions("10MINUTES", "30MINUTES", "1HOURS", "3HOURS", "6HOURS", "12HOURS");
  481. }
  482. if (_calculatedEndDate.diff(_calculatedStartDate, 'days') > 1 && _calculatedEndDate.diff(_calculatedStartDate, 'days') <= 7) {
  483. _opts = enableOptions("30MINUTES", "1HOURS", "3HOURS", "6HOURS", "12HOURS", "1DAYS");
  484. }
  485. if (_calculatedEndDate.diff(_calculatedStartDate, 'days') > 7 && _calculatedEndDate.diff(_calculatedStartDate, 'days') <= 14) {
  486. _opts = enableOptions("3HOURS", "6HOURS", "12HOURS", "1DAYS");
  487. }
  488. if (_calculatedEndDate.diff(_calculatedStartDate, 'days') > 14 && _calculatedEndDate.diff(_calculatedStartDate, 'days') <= 31) {
  489. _opts = enableOptions("12HOURS", "1DAYS", "7DAYS");
  490. }
  491. if (_calculatedEndDate.diff(_calculatedStartDate, 'months') >= 1) {
  492. _opts = enableOptions("1DAYS", "7DAYS", "1MONTHS");
  493. }
  494. if (_calculatedEndDate.diff(_calculatedStartDate, 'months') > 6) {
  495. _opts = enableOptions("1DAYS", "7DAYS", "1MONTHS", "6MONTHS");
  496. }
  497. if (_calculatedEndDate.diff(_calculatedStartDate, 'months') > 12) {
  498. _opts = enableOptions("7DAYS", "1MONTHS", "6MONTHS", "1YEARS");
  499. }
  500. $(".interval-select").html(renderOptions(_opts));
  501. matchIntervals();
  502. }
  503. }
  504. }
  505. ko.bindingHandlers.augmenthtml = {
  506. render: function (element, valueAccessor, allBindingsAccessor, viewModel) {
  507. var _val = ko.unwrap(valueAccessor());
  508. var _enc = $("<span>").html(_val);
  509. if (_enc.find("style").length > 0) {
  510. var parser = new less.Parser();
  511. $(_enc.find("style")).each(function (cnt, item) {
  512. var _less = "#result-container {" + $(item).text() + "}";
  513. try {
  514. parser.parse(_less, function (err, tree) {
  515. $(item).text(tree.toCSS());
  516. });
  517. }
  518. catch (e) {
  519. }
  520. });
  521. $(element).html(_enc.html());
  522. }
  523. else {
  524. $(element).html(_val);
  525. }
  526. },
  527. init: function (element, valueAccessor, allBindingsAccessor, viewModel) {
  528. ko.bindingHandlers.augmenthtml.render(element, valueAccessor, allBindingsAccessor, viewModel);
  529. },
  530. update: function (element, valueAccessor, allBindingsAccessor) {
  531. ko.bindingHandlers.augmenthtml.render(element, valueAccessor, allBindingsAccessor, viewModel);
  532. }
  533. }
  534. ko.bindingHandlers.clearable = {
  535. init: function (element, valueAccessor, allBindingsAccessor, viewModel) {
  536. var _el = $(element);
  537. function tog(v) {
  538. return v ? "addClass" : "removeClass";
  539. }
  540. _el.addClass("clearable");
  541. _el
  542. .on("input", function () {
  543. _el[tog(this.value)]("x");
  544. })
  545. .on("change", function () {
  546. valueAccessor()(_el.val());
  547. })
  548. .on("blur", function () {
  549. valueAccessor()(_el.val());
  550. })
  551. .on("mousemove", function (e) {
  552. _el[tog(this.offsetWidth - 18 < e.clientX - this.getBoundingClientRect().left)]("onX");
  553. })
  554. .on("click", function (e) {
  555. if (this.offsetWidth - 18 < e.clientX - this.getBoundingClientRect().left) {
  556. _el.removeClass("x onX").val("");
  557. valueAccessor()("");
  558. }
  559. });
  560. if (allBindingsAccessor().valueUpdate != null && allBindingsAccessor().valueUpdate == "afterkeydown") {
  561. _el.on("keyup", function () {
  562. valueAccessor()(_el.val());
  563. });
  564. }
  565. },
  566. update: function (element, valueAccessor, allBindingsAccessor) {
  567. $(element).val(ko.unwrap(valueAccessor()));
  568. }
  569. }
  570. ko.bindingHandlers.spinedit = {
  571. init: function (element, valueAccessor, allBindingsAccessor, viewModel) {
  572. $(element).spinedit({
  573. minimum: 0,
  574. maximum: 10000,
  575. step: 5,
  576. value: ko.unwrap(valueAccessor()),
  577. numberOfDecimals: 0
  578. });
  579. $(element).on("valueChanged", function (e) {
  580. valueAccessor()(e.value);
  581. });
  582. },
  583. update: function (element, valueAccessor, allBindingsAccessor) {
  584. $(element).spinedit("setValue", ko.unwrap(valueAccessor()));
  585. }
  586. }
  587. ko.bindingHandlers.codemirror = {
  588. init: function (element, valueAccessor, allBindingsAccessor, viewModel) {
  589. var options = $.extend(valueAccessor(), {});
  590. var editor = CodeMirror.fromTextArea(element, options);
  591. element.editor = editor;
  592. editor.setValue(options.data());
  593. editor.refresh();
  594. var wrapperElement = $(editor.getWrapperElement());
  595. $(document).on("refreshCodemirror", function () {
  596. editor.setSize("100%", 300);
  597. editor.refresh();
  598. });
  599. $(document).on("addFieldToSource", function (e, field) {
  600. if ($(element).data("template")) {
  601. editor.replaceSelection("{{" + field.name() + "}}");
  602. }
  603. });
  604. $(document).on("addFunctionToSource", function (e, fn) {
  605. if ($(element).data("template")) {
  606. editor.replaceSelection(fn);
  607. }
  608. });
  609. $(".chosen-select").chosen({
  610. disable_search_threshold: 10,
  611. width: "75%"
  612. });
  613. $('.chosen-select').trigger('chosen:updated');
  614. var sourceDelay = -1;
  615. editor.on("change", function (cm) {
  616. clearTimeout(sourceDelay);
  617. var _cm = cm;
  618. sourceDelay = setTimeout(function () {
  619. valueAccessor().data(_cm.getValue());
  620. if ($(".widget-html-pill").parent().hasClass("active")) {
  621. $("[contenteditable=true]").html(stripHtmlFromFunctions(valueAccessor().data()));
  622. }
  623. }, 100);
  624. });
  625. ko.utils.domNodeDisposal.addDisposeCallback(element, function () {
  626. wrapperElement.remove();
  627. });
  628. },
  629. update: function (element, valueAccessor, allBindingsAccessor) {
  630. var editor = element.editor;
  631. editor.refresh();
  632. }
  633. };
  634. ko.bindingHandlers.chosen = {
  635. init: function (element) {
  636. ko.bindingHandlers.options.init(element);
  637. $(element).chosen({disable_search_threshold: 5});
  638. },
  639. update: function (element, valueAccessor, allBindings) {
  640. ko.bindingHandlers.options.update(element, valueAccessor, allBindings);
  641. $(element).trigger('chosen:updated');
  642. }
  643. };
  644. ko.bindingHandlers.tooltip = {
  645. init: function (element, valueAccessor) {
  646. var local = ko.utils.unwrapObservable(valueAccessor()),
  647. options = {};
  648. ko.utils.extend(options, local);
  649. $(element).tooltip(options);
  650. ko.utils.domNodeDisposal.addDisposeCallback(element, function () {
  651. $(element).tooltip("destroy");
  652. });
  653. }
  654. };
  655. ko.bindingHandlers.typeahead = {
  656. init: function (element, valueAccessor) {
  657. var binding = this;
  658. var elem = $(element);
  659. var valueAccessor = valueAccessor();
  660. var _options = {
  661. source: function () {
  662. var _source = ko.utils.unwrapObservable(valueAccessor.source);
  663. if (valueAccessor.extraKeywords) {
  664. _source = _source.concat(valueAccessor.extraKeywords.split(" "))
  665. }
  666. if (valueAccessor.sourceSuffix && _source) {
  667. var _tmp = [];
  668. _source.forEach(function(item){
  669. _tmp.push(item + valueAccessor.sourceSuffix);
  670. });
  671. _source = _tmp;
  672. }
  673. return _source;
  674. },
  675. onselect: function (val) {
  676. if (typeof valueAccessor.target == "function") {
  677. valueAccessor.target(val);
  678. }
  679. else {
  680. valueAccessor.target = val;
  681. }
  682. }
  683. }
  684. function extractor(query) {
  685. var result = /([^ ]+)$/.exec(query);
  686. if (result && result[1])
  687. return result[1].trim();
  688. return "";
  689. }
  690. if (valueAccessor.multipleValues) {
  691. _options.updater = function (item) {
  692. var _val = this.$element.val();
  693. var _separator = (valueAccessor.multipleValuesSeparator || ":");
  694. if (valueAccessor.extraKeywords && valueAccessor.extraKeywords.split(" ").indexOf(item) > -1) {
  695. _separator = "";
  696. }
  697. if (_val.indexOf(" ") > -1) {
  698. return _val.substring(0, _val.lastIndexOf(" ")) + " " + item + _separator;
  699. }
  700. else {
  701. return item + _separator;
  702. }
  703. }
  704. _options.matcher = function (item) {
  705. var _tquery = extractor(this.query);
  706. if (!_tquery) return false;
  707. return ~item.toLowerCase().indexOf(_tquery.toLowerCase());
  708. },
  709. _options.highlighter = function (item) {
  710. var _query = extractor(this.query).replace(/[\-\[\]{}()*+?.:\\\^$|#\s]/g, '\\$&');
  711. return item.replace(new RegExp('(' + _query + ')', 'ig'), function ($1, match) {
  712. return '<strong>' + match + '</strong>'
  713. });
  714. }
  715. }
  716. if (valueAccessor.completeSolrRanges) {
  717. elem.on("keyup", function (e) {
  718. if (e.keyCode != 8 && e.which != 8 && elem.val() && (elem.val().slice(-1) == "[" || elem.val().slice(-1) == "{")) {
  719. var _index = elem.val().length;
  720. elem.val(elem.val() + " TO " + (elem.val().slice(-1) == "[" ? "]" : "}"));
  721. if (element.createTextRange) {
  722. var range = element.createTextRange();
  723. range.move("character", _index);
  724. range.select();
  725. } else if (element.selectionStart != null) {
  726. element.focus();
  727. element.setSelectionRange(_index, _index);
  728. }
  729. }
  730. });
  731. }
  732. if (valueAccessor.triggerOnFocus) {
  733. _options.minLength = 0;
  734. }
  735. elem.typeahead(_options);
  736. if (valueAccessor.triggerOnFocus) {
  737. elem.on('focus', function () {
  738. elem.trigger("keyup");
  739. });
  740. }
  741. elem.blur(function () {
  742. if (typeof valueAccessor.target == "function") {
  743. valueAccessor.target(elem.val());
  744. }
  745. else {
  746. valueAccessor.target = elem.val();
  747. }
  748. });
  749. },
  750. update: function (element, valueAccessor) {
  751. var elem = $(element);
  752. var value = valueAccessor();
  753. if (typeof value.target == "function") {
  754. elem.val(value.target());
  755. }
  756. else {
  757. elem.val(value.target);
  758. }
  759. }
  760. };
  761. ko.bindingHandlers.select2 = {
  762. init: function (element, valueAccessor, allBindingsAccessor, vm) {
  763. var options = ko.toJS(valueAccessor()) || {};
  764. if (typeof valueAccessor().update != "undefined") {
  765. if (options.type == "user" && viewModel.selectableHadoopUsers().indexOf(options.update) == -1) {
  766. viewModel.availableHadoopUsers.push({
  767. username: options.update
  768. });
  769. }
  770. if (options.type == "group") {
  771. if (options.update instanceof Array) {
  772. options.update.forEach(function (opt) {
  773. if (viewModel.selectableHadoopGroups().indexOf(opt) == -1) {
  774. viewModel.availableHadoopGroups.push({
  775. name: opt
  776. });
  777. }
  778. });
  779. }
  780. else if (viewModel.selectableHadoopGroups().indexOf(options.update) == -1) {
  781. viewModel.availableHadoopGroups.push({
  782. name: options.update
  783. });
  784. }
  785. }
  786. if (options.type == "action" && viewModel.availableActions().indexOf(options.update) == -1) {
  787. viewModel.availableActions.push(options.update);
  788. }
  789. if (options.type == "scope" && viewModel.availablePrivileges().indexOf(options.update) == -1) {
  790. viewModel.availablePrivileges.push(options.update);
  791. }
  792. }
  793. $(element)
  794. .select2(options)
  795. .on("change", function (e) {
  796. if (typeof e.val != "undefined" && typeof valueAccessor().update != "undefined") {
  797. valueAccessor().update(e.val);
  798. }
  799. })
  800. .on("select2-focus", function (e) {
  801. if (typeof options.onFocus != "undefined") {
  802. options.onFocus();
  803. }
  804. })
  805. .on("select2-blur", function (e) {
  806. if (typeof options.onBlur != "undefined") {
  807. options.onBlur();
  808. }
  809. })
  810. .on("select2-open", function () {
  811. $(".select2-input").off("keyup").data("type", options.type).on("keyup", function (e) {
  812. if (e.keyCode === 13) {
  813. var _isArray = options.update instanceof Array;
  814. var _newVal = $(this).val();
  815. var _type = $(this).data("type");
  816. if ($.trim(_newVal) != "") {
  817. if (_type == "user") {
  818. viewModel.availableHadoopUsers.push({
  819. username: _newVal
  820. });
  821. }
  822. if (_type == "group") {
  823. viewModel.availableHadoopGroups.push({
  824. name: _newVal
  825. });
  826. }
  827. if (_type == "action") {
  828. viewModel.availableActions.push(_newVal);
  829. }
  830. if (_type == "scope") {
  831. viewModel.availablePrivileges.push(_newVal);
  832. }
  833. if (_type == "role") {
  834. var _r = new Role(viewModel, { name: _newVal });
  835. viewModel.tempRoles.push(_r);
  836. viewModel.roles.push(_r);
  837. }
  838. if (_isArray) {
  839. var _vals = $(element).select2("val");
  840. _vals.push(_newVal);
  841. $(element).select2("val", _vals, true);
  842. }
  843. else {
  844. $(element).select2("val", _newVal, true);
  845. }
  846. $(element).select2("close");
  847. }
  848. }
  849. });
  850. })
  851. },
  852. update: function (element, valueAccessor, allBindingsAccessor, vm) {
  853. if (typeof valueAccessor().update != "undefined") {
  854. $(element).select2("val", valueAccessor().update());
  855. }
  856. if (typeof valueAccessor().readonly != "undefined") {
  857. $(element).select2("readonly", valueAccessor().readonly);
  858. if (typeof valueAccessor().readonlySetTo != "undefined") {
  859. valueAccessor().readonlySetTo();
  860. }
  861. }
  862. }
  863. };
  864. ko.bindingHandlers.hivechooser = {
  865. init: function (element, valueAccessor, allBindingsAccessor, vm) {
  866. var self = $(element);
  867. self.val(valueAccessor()());
  868. function setPathFromAutocomplete(path) {
  869. self.val(path);
  870. valueAccessor()(path);
  871. self.blur();
  872. }
  873. self.on("blur", function () {
  874. valueAccessor()(self.val());
  875. });
  876. self.jHueHiveAutocomplete({
  877. skipColumns: true,
  878. showOnFocus: true,
  879. home: "/",
  880. onPathChange: function (path) {
  881. setPathFromAutocomplete(path);
  882. },
  883. onEnter: function (el) {
  884. setPathFromAutocomplete(el.val());
  885. },
  886. onBlur: function () {
  887. if (self.val().lastIndexOf(".") == self.val().length - 1) {
  888. self.val(self.val().substr(0, self.val().length - 1));
  889. }
  890. valueAccessor()(self.val());
  891. }
  892. });
  893. }
  894. }
  895. ko.bindingHandlers.hdfsAutocomplete = {
  896. init: function (element, valueAccessor, allBindingsAccessor, vm) {
  897. var stripHashes = function (str) {
  898. return str.replace(/#/gi, encodeURIComponent("#"));
  899. };
  900. var self = $(element);
  901. self.attr("autocomplete", "off");
  902. self.jHueHdfsAutocomplete({});
  903. }
  904. };
  905. ko.bindingHandlers.filechooser = {
  906. init: function (element, valueAccessor, allBindingsAccessor, vm) {
  907. var self = $(element);
  908. self.attr("autocomplete", "off");
  909. if (typeof valueAccessor() == "function" || typeof valueAccessor().value == "function") {
  910. self.val(valueAccessor().value ? valueAccessor().value(): valueAccessor()());
  911. self.data("fullPath", self.val());
  912. self.attr("data-original-title", self.val());
  913. if (valueAccessor().displayJustLastBit){
  914. var _val = self.val();
  915. self.val(_val.split("/")[_val.split("/").length - 1]);
  916. }
  917. self.on("blur", function () {
  918. if (valueAccessor().value){
  919. if (valueAccessor().displayJustLastBit){
  920. var _val = self.data("fullPath");
  921. valueAccessor().value(_val.substr(0, _val.lastIndexOf("/")) + "/" + self.val());
  922. }
  923. else {
  924. valueAccessor().value(self.val());
  925. }
  926. self.data("fullPath", valueAccessor().value());
  927. }
  928. else {
  929. valueAccessor()(self.val());
  930. self.data("fullPath", valueAccessor()());
  931. }
  932. self.attr("data-original-title", self.data("fullPath"));
  933. });
  934. }
  935. else {
  936. self.val(valueAccessor());
  937. self.on("blur", function () {
  938. valueAccessor(self.val());
  939. });
  940. }
  941. self.after(getFileBrowseButton(self, true, valueAccessor, true, allBindingsAccessor));
  942. }
  943. };
  944. function getFileBrowseButton(inputElement, selectFolder, valueAccessor, stripHdfsPrefix, allBindingsAccessor) {
  945. var _btn = $("<button>").addClass("btn").addClass("fileChooserBtn").text("..").click(function (e) {
  946. e.preventDefault();
  947. // check if it's a relative path
  948. callFileChooser();
  949. function callFileChooser() {
  950. var _initialPath = $.trim(inputElement.val()) != "" ? inputElement.val() : "/";
  951. if ((allBindingsAccessor().filechooserOptions && allBindingsAccessor().filechooserOptions.skipInitialPathIfEmpty && inputElement.val() == "") || allBindingsAccessor().filechooserPrefixSeparator){
  952. _initialPath = "";
  953. }
  954. if (inputElement.data("fullPath")){
  955. _initialPath = inputElement.data("fullPath");
  956. }
  957. if (_initialPath.indexOf("hdfs://") > -1) {
  958. _initialPath = _initialPath.substring(7);
  959. }
  960. $("#filechooser").jHueFileChooser({
  961. suppressErrors: true,
  962. selectFolder: (selectFolder) ? true : false,
  963. onFolderChoose: function (filePath) {
  964. handleChoice(filePath, stripHdfsPrefix);
  965. if (selectFolder) {
  966. $("#chooseFile").modal("hide");
  967. }
  968. },
  969. onFileChoose: function (filePath) {
  970. handleChoice(filePath, stripHdfsPrefix);
  971. $("#chooseFile").modal("hide");
  972. },
  973. createFolder: allBindingsAccessor().filechooserOptions && allBindingsAccessor().filechooserOptions.createFolder,
  974. uploadFile: allBindingsAccessor().filechooserOptions && allBindingsAccessor().filechooserOptions.uploadFile,
  975. initialPath: _initialPath,
  976. errorRedirectPath: "",
  977. forceRefresh: true,
  978. showExtraHome: allBindingsAccessor().filechooserOptions && allBindingsAccessor().filechooserOptions.showExtraHome,
  979. extraHomeProperties: allBindingsAccessor().filechooserOptions && allBindingsAccessor().filechooserOptions.extraHomeProperties ? allBindingsAccessor().filechooserOptions.extraHomeProperties : {}
  980. });
  981. $("#chooseFile").modal("show");
  982. }
  983. function handleChoice(filePath, stripHdfsPrefix) {
  984. if (allBindingsAccessor().filechooserPrefixSeparator){
  985. filePath = inputElement.val().split(allBindingsAccessor().filechooserPrefixSeparator)[0] + '=' + filePath;
  986. }
  987. if (stripHdfsPrefix){
  988. inputElement.val(filePath);
  989. }
  990. else {
  991. inputElement.val("hdfs://" + filePath);
  992. }
  993. inputElement.change();
  994. if (typeof valueAccessor() == "function" || typeof valueAccessor().value == "function") {
  995. if (valueAccessor().value){
  996. valueAccessor().value(inputElement.val());
  997. if (valueAccessor().displayJustLastBit){
  998. inputElement.data("fullPath", inputElement.val());
  999. inputElement.attr("data-original-title", inputElement.val());
  1000. var _val = inputElement.val();
  1001. inputElement.val(_val.split("/")[_val.split("/").length - 1])
  1002. }
  1003. }
  1004. else {
  1005. valueAccessor()(inputElement.val());
  1006. }
  1007. }
  1008. else {
  1009. valueAccessor(inputElement.val());
  1010. }
  1011. }
  1012. });
  1013. if (allBindingsAccessor().filechooserDisabled){
  1014. _btn.addClass("disabled").attr("disabled", "disabled");
  1015. }
  1016. return _btn;
  1017. }
  1018. ko.bindingHandlers.tooltip = {
  1019. update: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
  1020. var options = ko.utils.unwrapObservable(valueAccessor());
  1021. var self = $(element);
  1022. self.tooltip(options);
  1023. }
  1024. };