ko.hue-bindings.js 38 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126
  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. $("html").addClass("modal-open");
  948. // check if it's a relative path
  949. callFileChooser();
  950. function callFileChooser() {
  951. var _initialPath = $.trim(inputElement.val()) != "" ? inputElement.val() : "/";
  952. if ((allBindingsAccessor().filechooserOptions && allBindingsAccessor().filechooserOptions.skipInitialPathIfEmpty && inputElement.val() == "") || allBindingsAccessor().filechooserPrefixSeparator){
  953. _initialPath = "";
  954. }
  955. if (inputElement.data("fullPath")){
  956. _initialPath = inputElement.data("fullPath");
  957. }
  958. if (_initialPath.indexOf("hdfs://") > -1) {
  959. _initialPath = _initialPath.substring(7);
  960. }
  961. $("#filechooser").jHueFileChooser({
  962. suppressErrors: true,
  963. selectFolder: (selectFolder) ? true : false,
  964. onFolderChoose: function (filePath) {
  965. handleChoice(filePath, stripHdfsPrefix);
  966. if (selectFolder) {
  967. $("#chooseFile").modal("hide");
  968. }
  969. },
  970. onFileChoose: function (filePath) {
  971. handleChoice(filePath, stripHdfsPrefix);
  972. $("#chooseFile").modal("hide");
  973. },
  974. createFolder: allBindingsAccessor().filechooserOptions && allBindingsAccessor().filechooserOptions.createFolder,
  975. uploadFile: allBindingsAccessor().filechooserOptions && allBindingsAccessor().filechooserOptions.uploadFile,
  976. initialPath: _initialPath,
  977. errorRedirectPath: "",
  978. forceRefresh: true,
  979. showExtraHome: allBindingsAccessor().filechooserOptions && allBindingsAccessor().filechooserOptions.showExtraHome,
  980. extraHomeProperties: allBindingsAccessor().filechooserOptions && allBindingsAccessor().filechooserOptions.extraHomeProperties ? allBindingsAccessor().filechooserOptions.extraHomeProperties : {},
  981. filterExtensions: allBindingsAccessor().filechooserFilter ? allBindingsAccessor().filechooserFilter : ""
  982. });
  983. $("#chooseFile").modal("show");
  984. $("#chooseFile").on("hidden", function(){
  985. $("html").removeClass("modal-open");
  986. });
  987. }
  988. function handleChoice(filePath, stripHdfsPrefix) {
  989. if (allBindingsAccessor().filechooserPrefixSeparator){
  990. filePath = inputElement.val().split(allBindingsAccessor().filechooserPrefixSeparator)[0] + '=' + filePath;
  991. }
  992. if (stripHdfsPrefix){
  993. inputElement.val(filePath);
  994. }
  995. else {
  996. inputElement.val("hdfs://" + filePath);
  997. }
  998. inputElement.change();
  999. if (typeof valueAccessor() == "function" || typeof valueAccessor().value == "function") {
  1000. if (valueAccessor().value){
  1001. valueAccessor().value(inputElement.val());
  1002. if (valueAccessor().displayJustLastBit){
  1003. inputElement.data("fullPath", inputElement.val());
  1004. inputElement.attr("data-original-title", inputElement.val());
  1005. var _val = inputElement.val();
  1006. inputElement.val(_val.split("/")[_val.split("/").length - 1])
  1007. }
  1008. }
  1009. else {
  1010. valueAccessor()(inputElement.val());
  1011. }
  1012. }
  1013. else {
  1014. valueAccessor(inputElement.val());
  1015. }
  1016. }
  1017. });
  1018. if (allBindingsAccessor().filechooserDisabled){
  1019. _btn.addClass("disabled").attr("disabled", "disabled");
  1020. }
  1021. return _btn;
  1022. }
  1023. ko.bindingHandlers.tooltip = {
  1024. update: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
  1025. var options = ko.utils.unwrapObservable(valueAccessor());
  1026. var self = $(element);
  1027. self.tooltip(options);
  1028. }
  1029. };