search.ko.js 32 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064
  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. // Start dashboard lib to move out
  17. var Column = function (size, rows) {
  18. var self = this;
  19. self.size = ko.observable(size);
  20. self.rows = ko.observableArray(rows);
  21. self.drops = ko.observableArray(["temp"]);
  22. self.klass = ko.computed(function () {
  23. return "card card-home card-column span" + self.size();
  24. });
  25. self.addEmptyRow = function (atBeginning) {
  26. return self.addRow(null, atBeginning);
  27. };
  28. self.addRow = function (row, atBeginning) {
  29. if (typeof row == "undefined" || row == null) {
  30. row = new Row([]);
  31. }
  32. if (typeof atBeginning == "undefined" || atBeginning == null) {
  33. self.rows.push(row);
  34. }
  35. else {
  36. self.rows.unshift(row);
  37. }
  38. return row;
  39. };
  40. }
  41. var Row = function (widgets) {
  42. var self = this;
  43. self.widgets = ko.observableArray(widgets);
  44. self.addWidget = function (widget) {
  45. self.widgets.push(widget);
  46. };
  47. self.move = function (from, to) {
  48. try {
  49. viewModel.columns()[to].addRow(self);
  50. viewModel.columns()[from].rows.remove(self);
  51. }
  52. catch (exception) {
  53. }
  54. }
  55. self.moveDown = function (col, row) {
  56. var _i = col.rows().indexOf(row);
  57. if (_i < col.rows().length - 1) {
  58. var _arr = col.rows();
  59. col.rows.splice(_i, 2, _arr[_i + 1], _arr[_i]);
  60. }
  61. }
  62. self.moveUp = function (col, row) {
  63. var _i = col.rows().indexOf(row);
  64. if (_i >= 1) {
  65. var _arr = col.rows();
  66. col.rows.splice(_i - 1, 2, _arr[_i], _arr[_i - 1]);
  67. }
  68. }
  69. self.remove = function (col, row) {
  70. $.each(self.widgets(), function(i, widget) {
  71. viewModel.removeWidget(widget);
  72. });
  73. col.rows.remove(row);
  74. }
  75. }
  76. // A widget is generic. It has an id that refer to another object (e.g. facet) with the same id.
  77. var Widget = function (size, id, name, widgetType, properties, offset, loading) {
  78. var self = this;
  79. self.size = ko.observable(size).extend({ numeric: 0 });
  80. self.name = ko.observable(name);
  81. self.id = ko.observable(id);
  82. self.widgetType = ko.observable(typeof widgetType != "undefined" && widgetType != null ? widgetType : "empty-widget");
  83. self.properties = ko.observable(typeof properties != "undefined" && properties != null ? properties : {});
  84. self.offset = ko.observable(typeof offset != "undefined" && offset != null ? offset : 0).extend({ numeric: 0 });
  85. self.isLoading = ko.observable(typeof loading != "undefined" && loading != null ? loading : false);
  86. self.klass = ko.computed(function () {
  87. return "card card-widget span" + self.size() + (self.offset() * 1 > 0 ? " offset" + self.offset() : "");
  88. });
  89. self.expand = function () {
  90. self.size(self.size() + 1);
  91. $("#wdg_" + self.id()).trigger("resize");
  92. }
  93. self.compress = function () {
  94. self.size(self.size() - 1);
  95. $("#wdg_" + self.id()).trigger("resize");
  96. }
  97. self.moveLeft = function () {
  98. self.offset(self.offset() - 1);
  99. }
  100. self.moveRight = function () {
  101. self.offset(self.offset() + 1);
  102. }
  103. self.remove = function (row, widget) {
  104. viewModel.removeWidget(widget);
  105. row.widgets.remove(widget);
  106. }
  107. };
  108. Widget.prototype.clone = function () {
  109. return new Widget(this.size(), UUID(), this.name(), this.widgetType());
  110. };
  111. function fullLayout() {
  112. setLayout([12]);
  113. }
  114. function oneThirdLeftLayout() {
  115. setLayout([2, 10]);
  116. }
  117. function magicLayout(vm) {
  118. loadLayout(vm, vm.initial.layout);
  119. }
  120. function setLayout(colSizes) {
  121. // Save previous widgets
  122. var _allRows = [];
  123. $(viewModel.columns()).each(function (cnt, col) {
  124. var _tRows = [];
  125. $(col.rows()).each(function (icnt, row) {
  126. if (row.widgets().length > 0) {
  127. _tRows.push(row);
  128. }
  129. });
  130. _allRows = _allRows.concat(_tRows);
  131. });
  132. var _cols = [];
  133. var _highestCol = {
  134. idx: -1,
  135. size: -1
  136. };
  137. $(colSizes).each(function (cnt, size) {
  138. _cols.push(new Column(size, []));
  139. if (size > _highestCol.size) {
  140. _highestCol.idx = cnt;
  141. _highestCol.size = size;
  142. }
  143. });
  144. if (_allRows.length > 0 && _highestCol.idx > -1) {
  145. _cols[_highestCol.idx].rows(_allRows);
  146. }
  147. $(_cols).each(function (cnt, col) {
  148. if (col.rows().length == 0) {
  149. col.rows([new Row([])]);
  150. }
  151. });
  152. viewModel.columns(_cols);
  153. }
  154. function loadLayout(viewModel, json_layout) {
  155. var _columns = [];
  156. $(json_layout).each(function (cnt, json_col) {
  157. var _rows = [];
  158. $(json_col.rows).each(function (rcnt, json_row) {
  159. var row = new Row();
  160. $(json_row.widgets).each(function (wcnt, widget) {
  161. row.addWidget(new Widget(widget.size, widget.id, widget.name, widget.widgetType, widget.properties, widget.offset, true));
  162. });
  163. _rows.push(row);
  164. });
  165. var column = new Column(json_col.size, _rows);
  166. _columns = _columns.concat(column);
  167. });
  168. viewModel.columns(_columns);
  169. }
  170. // End dashboard lib
  171. var Query = function (vm, query) {
  172. var self = this;
  173. self.qs = ko.mapping.fromJS(query.qs);
  174. self.fqs = ko.mapping.fromJS(query.fqs);
  175. self.start = ko.mapping.fromJS(query.start);
  176. var defaultMultiqGroup = {'id': 'query', 'label': 'query'};
  177. self.multiqs = ko.computed(function () { // List of widgets supporting multiqs
  178. var histogram_id = vm.collection.getHistogramFacet();
  179. return [defaultMultiqGroup].concat(
  180. $.map($.grep(self.fqs(), function(fq, i) {
  181. return (fq.type() == 'field' || fq.type() == 'range') && (histogram_id == null || histogram_id.id() != fq.id());
  182. }), function(fq) { return {'id': fq.id(), 'label': fq.field()} })
  183. );
  184. });
  185. self.selectedMultiq = ko.observable(defaultMultiqGroup);
  186. self.getFacetFilter = function(widget_id) {
  187. var _fq = null;
  188. $.each(self.fqs(), function (index, fq) {
  189. if (fq.id() == widget_id) {
  190. _fq = fq;
  191. return false;
  192. }
  193. });
  194. return _fq;
  195. };
  196. self.getMultiq = ko.computed(function () {
  197. if (self.selectedMultiq()) {
  198. if (self.selectedMultiq() == 'query') {
  199. if (self.qs().length >= 2) {
  200. return 'query';
  201. }
  202. } else {
  203. var facet = self.getFacetFilter(self.selectedMultiq());
  204. if (facet && facet.filter().length > 0) {
  205. return 'facet';
  206. }
  207. }
  208. }
  209. return null;
  210. });
  211. self.selectedMultiq.subscribe(function () { // To keep below the computed
  212. vm.search();
  213. });
  214. self.addQ = function (data) {
  215. self.qs.push(ko.mapping.fromJS({'q': ''}));
  216. };
  217. self.removeQ = function (query) {
  218. self.qs.remove(query);
  219. };
  220. self.toggleFacet = function (data) {
  221. var fq = self.getFacetFilter(data.widget_id);
  222. if (fq == null) {
  223. self.fqs.push(ko.mapping.fromJS({
  224. 'id': data.widget_id,
  225. 'field': data.facet.cat,
  226. 'filter': [data.facet.value],
  227. 'type': 'field'
  228. }));
  229. } else {
  230. $.each(self.fqs(), function (index, fq) {
  231. if (fq.id() == data.widget_id) {
  232. if (fq.filter.indexOf(data.facet.value) > -1) {
  233. fq.filter.remove(data.facet.value);
  234. if (fq.filter().length == 0) {
  235. self.fqs.remove(fq);
  236. }
  237. } else {
  238. fq.filter.push(data.facet.value);
  239. }
  240. }
  241. });
  242. }
  243. vm.search();
  244. }
  245. self.selectRangeFacet = function (data) {
  246. if (data.force != undefined) {
  247. self.removeFilter(ko.mapping.fromJS({'id': data.widget_id}));
  248. }
  249. var fq = self.getFacetFilter(data.widget_id);
  250. if (fq == null) {
  251. self.fqs.push(ko.mapping.fromJS({
  252. 'id': data.widget_id,
  253. 'field': data.cat,
  254. 'filter': [data.from],
  255. 'properties': [{'from': data.from, 'to': data.to}],
  256. 'type': 'range'
  257. }));
  258. } else {
  259. if (fq.filter().indexOf(data.from) > -1) { // Unselect
  260. fq.filter.remove(data.from);
  261. $.each(fq.properties(), function (index, prop) {
  262. if (prop && prop.from() == data.from) {
  263. fq.properties.remove(prop);
  264. }
  265. });
  266. if (fq.filter().length == 0) {
  267. self.removeFilter(ko.mapping.fromJS({'id': data.widget_id}));
  268. }
  269. } else {
  270. fq.filter.push(data.from);
  271. fq.properties.push(ko.mapping.fromJS({'from': data.from, 'to': data.to}));
  272. }
  273. }
  274. if (data.no_refresh == undefined) {
  275. vm.search();
  276. }
  277. };
  278. self.removeFilter = function (data) {
  279. $.each(self.fqs(), function (index, fq) {
  280. if (fq.id() == data.id()) {
  281. self.fqs.remove(fq);
  282. // Also re-init range select widget
  283. var rangeWidget = vm.collection.getFacetById(fq.id());
  284. if (rangeWidget != null && RANGE_SELECTABLE_WIDGETS.indexOf(rangeWidget.widgetType()) != -1 && fq.type() == 'range') {
  285. vm.collection.timeLineZoom({'id': rangeWidget.id()});
  286. }
  287. return false;
  288. }
  289. });
  290. };
  291. self.paginate = function (direction) {
  292. if (direction == 'next') {
  293. self.start(self.start() + vm.collection.template.rows() * 1.0);
  294. } else {
  295. self.start(self.start() - vm.collection.template.rows() * 1.0);
  296. }
  297. vm.search();
  298. };
  299. };
  300. var Collection = function (vm, collection) {
  301. var self = this;
  302. self.id = collection.id;
  303. self.name = ko.mapping.fromJS(collection.name);
  304. self.label = ko.mapping.fromJS(collection.label);
  305. self.enabled = ko.mapping.fromJS(collection.enabled);
  306. self.idField = ko.observable(collection.idField);
  307. self.template = ko.mapping.fromJS(collection.template);
  308. self.template.fieldsSelected.subscribe(function () {
  309. vm.search();
  310. });
  311. self.template.template.extend({rateLimit: {timeout: 3000, method: "notifyWhenChangesStop"}});
  312. self.template.template.subscribe(function () {
  313. vm.search();
  314. });
  315. self.template.isGridLayout.subscribe(function () {
  316. vm.search();
  317. });
  318. self.template.selectedVisualField = ko.observable();
  319. self.template.selectedVisualFunction = ko.observable();
  320. self.template.selectedVisualFunction.subscribe(function (newValue) {
  321. var _vf = $("#visualFunctions");
  322. _vf.siblings(".muted").text(_vf.find(":selected").attr("title"));
  323. });
  324. self.template.selectedSourceField = ko.observable();
  325. self.template.selectedSourceFunction = ko.observable();
  326. self.template.selectedSourceFunction.subscribe(function (newValue) {
  327. var _sf = $("#sourceFunctions");
  328. _sf.siblings(".muted").text(_sf.find(":selected").attr("title"));
  329. });
  330. self.template.addFieldToVisual = function () {
  331. $(document).trigger("addFieldToVisual", self.template.selectedVisualField());
  332. };
  333. self.template.addFunctionToVisual = function () {
  334. $(document).trigger("addFunctionToVisual", self.template.selectedVisualFunction());
  335. };
  336. self.template.addFieldToSource = function () {
  337. $(document).trigger("addFieldToSource", self.template.selectedSourceField());
  338. };
  339. self.template.addFunctionToSource = function () {
  340. $(document).trigger("addFunctionToSource", self.template.selectedSourceFunction());
  341. };
  342. self.facets = ko.mapping.fromJS(collection.facets);
  343. $.each(self.facets(), function (index, facet) {
  344. facet.field.subscribe(function () {
  345. vm.search();
  346. });
  347. });
  348. self.template.rows.subscribe(function(){
  349. vm.search();
  350. });
  351. self.template.rows.extend({rateLimit: {timeout: 1500, method: "notifyWhenChangesStop"}});
  352. self.fields = ko.mapping.fromJS(collection.fields);
  353. self.availableFacetFields = ko.computed(function() {
  354. var facetFieldNames = $.map(self.facets(), function(facet) {
  355. return facet.field(); //filter out text_general, __version__
  356. });
  357. return $.grep(self.fields(), function(field) {
  358. return facetFieldNames.indexOf(field.name()) == -1;
  359. });
  360. });
  361. self.selectedDocument = ko.observable({});
  362. self.addFacet = function (facet_json) {
  363. self.removeFacet(function(){return facet_json.widget_id});
  364. $.post("/search/template/new_facet", {
  365. "collection": ko.mapping.toJSON(self),
  366. "id": facet_json.widget_id,
  367. "label": facet_json.name,
  368. "field": facet_json.name,
  369. "widget_type": facet_json.widgetType
  370. }, function (data) {
  371. if (data.status == 0) {
  372. var facet = ko.mapping.fromJS(data.facet);
  373. facet.field.subscribe(function () {
  374. vm.search();
  375. });
  376. self.facets.push(facet);
  377. vm.search();
  378. } else {
  379. $(document).trigger("error", data.message);
  380. }
  381. }).fail(function (xhr, textStatus, errorThrown) {});
  382. };
  383. self.removeFacet = function (widget_id) {
  384. $.each(self.facets(), function (index, facet) {
  385. if (facet.id() == widget_id()) {
  386. self.facets.remove(facet);
  387. return false;
  388. }
  389. });
  390. }
  391. self.getFacetById = function (facet_id) {
  392. var _facet = null;
  393. $.each(self.facets(), function (index, facet) {
  394. if (facet.id() == facet_id) {
  395. _facet = facet;
  396. return false;
  397. }
  398. });
  399. return _facet;
  400. }
  401. self.getFacetByType = function (facetType) {
  402. var _facet = null;
  403. $.each(self.facets(), function (index, facet) {
  404. if (facet.widgetType() == facetType) {
  405. _facet = facet;
  406. return false;
  407. }
  408. });
  409. return _facet;
  410. }
  411. self.getHistogramFacet = function () { // Should do multi histogram
  412. return self.getFacetByType('histogram-widget');
  413. }
  414. self.template.fields = ko.computed(function () {
  415. var _fields = [];
  416. $.each(self.template.fieldsAttributes(), function (index, field) {
  417. var position = self.template.fieldsSelected.indexOf(field.name());
  418. if (position != -1) {
  419. _fields[position] = field;
  420. }
  421. });
  422. return _fields;
  423. });
  424. self.getTemplateField = function (name) {
  425. var _field = null;
  426. $.each(self.template.fields(), function (index, field) {
  427. if (field.name() == name) {
  428. _field = field;
  429. return false;
  430. }
  431. });
  432. return _field;
  433. };
  434. self.template.fieldsModalFilter = ko.observable(""); // For UI
  435. self.template.fieldsModalType = ko.observable(""); // For UI
  436. self.template.fieldsAttributesFilter = ko.observable(""); // For UI
  437. self.template.filteredModalFields = ko.observableArray();
  438. self.template.filteredAttributeFields = ko.computed(function() {
  439. var _fields = [];
  440. $.each(self.template.fieldsAttributes(), function (index, field) {
  441. if (self.template.fieldsAttributesFilter() == "" || field.name().toLowerCase().indexOf(self.template.fieldsAttributesFilter().toLowerCase()) > -1){
  442. _fields.push(field);
  443. }
  444. });
  445. return _fields;
  446. });
  447. self.template.availableWidgetFields = ko.computed(function() {
  448. if (self.template.fieldsModalType() == 'histogram-widget') {
  449. return vm.availableDateFields();
  450. }
  451. else if (self.template.fieldsModalType() == 'line-widget') {
  452. return vm.availableNumberFields();
  453. }
  454. else {
  455. return self.availableFacetFields();
  456. }
  457. });
  458. self.template.availableWidgetFieldsNames = ko.computed(function() {
  459. return $.map(self.template.availableWidgetFields(), function(field){
  460. return field.name();
  461. });
  462. });
  463. self.template.fieldsModalFilter.subscribe(function(value) {
  464. var _fields = [];
  465. var _availableFields = self.template.availableWidgetFields();
  466. $.each(_availableFields, function (index, field) {
  467. if (self.template.fieldsModalFilter() == "" || field.name().toLowerCase().indexOf(self.template.fieldsModalFilter().toLowerCase()) > -1){
  468. _fields.push(field);
  469. }
  470. });
  471. self.template.filteredModalFields(_fields);
  472. });
  473. self.switchCollection = function() { // Long term would be to reload the page
  474. $.post("/search/get_collection", {
  475. name: self.name()
  476. }, function (data) {
  477. if (data.status == 0) {
  478. self.idField(data.collection.collection.idField);
  479. self.template.template(data.collection.collection.template.template);
  480. self.template.fieldsAttributes.removeAll();
  481. $.each(data.collection.collection.template.fieldsAttributes, function(index, field) {
  482. self.template.fieldsAttributes.push(ko.mapping.fromJS(field));
  483. });
  484. self.fields.removeAll();
  485. $.each(data.collection.collection.fields, function(index, field) {
  486. self.fields.push(ko.mapping.fromJS(field));
  487. });
  488. }
  489. }).fail(function (xhr, textStatus, errorThrown) {});
  490. };
  491. function diff(A, B) {
  492. return A.filter(function (a) {
  493. return B.indexOf(a) == -1;
  494. });
  495. }
  496. function syncArray(currentObservable, newJson, isDynamic) {
  497. // Get names of fields
  498. var _currentFieldsNames = $.map(
  499. $.grep(currentObservable(), function(field) {
  500. return field.isDynamic() == isDynamic;
  501. }), function(field) {
  502. return field.name();
  503. });
  504. var _newFieldsNames = $.map(
  505. $.grep(newJson, function(field) {
  506. return field.isDynamic == isDynamic;
  507. }), function(field) {
  508. return field.name;
  509. });
  510. var _toDelete = diff(_currentFieldsNames, _newFieldsNames);
  511. var _toAdd = diff(_newFieldsNames, _currentFieldsNames);
  512. // Deleted fields
  513. $.each(currentObservable(), function(index, field) {
  514. if (_toDelete.indexOf(field.name()) != -1) {
  515. currentObservable.remove(field);
  516. }
  517. });
  518. // New fields
  519. $.each(newJson, function(index, field) {
  520. if (_toAdd.indexOf(field.name) != -1) {
  521. currentObservable.push(ko.mapping.fromJS(field));
  522. }
  523. });
  524. }
  525. self.syncFields = function() {
  526. $.post("/search/get_collection", {
  527. name: self.name()
  528. }, function (data) {
  529. if (data.status == 0) {
  530. self.idField(data.collection.collection.idField);
  531. syncArray(self.template.fieldsAttributes, data.collection.collection.template.fieldsAttributes, false);
  532. syncArray(self.fields, data.collection.collection.fields, false);
  533. }
  534. // After sync the dynamic fields
  535. self.syncDynamicFields()
  536. }).fail(function (xhr, textStatus, errorThrown) {});
  537. };
  538. self.syncDynamicFields = function () {
  539. $.post("/search/index/fields/dynamic", {
  540. name: self.name()
  541. }, function (data) {
  542. if (data.status == 0) {
  543. syncArray(self.template.fieldsAttributes, data.gridlayout_header_fields, true);
  544. syncArray(self.fields, data.fields, true);
  545. }
  546. }).fail(function (xhr, textStatus, errorThrown) {});
  547. };
  548. self.toggleSortColumnGridLayout = function (template_field) {
  549. if (! template_field.sort.direction()) {
  550. template_field.sort.direction('desc');
  551. } else if (template_field.sort.direction() == 'desc') {
  552. template_field.sort.direction('asc');
  553. } else {
  554. template_field.sort.direction(null);
  555. }
  556. vm.search();
  557. };
  558. self.toggleSortFacet = function (facet_field, event) {
  559. if (facet_field.properties.sort() == 'desc') {
  560. facet_field.properties.sort('asc');
  561. } else {
  562. facet_field.properties.sort('desc');
  563. }
  564. $(event.target).button('loading');
  565. vm.search();
  566. };
  567. self.toggleRangeFacet = function (facet_field, event) {
  568. vm.query.removeFilter(ko.mapping.fromJS({'id': facet_field.id})); // Reset filter query
  569. if (facet_field.type() == 'field') {
  570. facet_field.type('range');
  571. } else if (facet_field.type() == 'range') {
  572. facet_field.type('field')
  573. }
  574. $(event.target).button('loading');
  575. vm.search();
  576. };
  577. self.selectTimelineFacet = function (data) { // alert(ko.mapping.toJSON(data));
  578. var facet = self.getFacetById(data.widget_id);
  579. facet.properties.start(data.from);
  580. facet.properties.end(data.to);
  581. vm.query.selectRangeFacet({widget_id: data.widget_id, from: data.from, to: data.to, cat: data.cat, no_refresh: true, force: true});
  582. $.ajax({
  583. type: "POST",
  584. url: "/search/get_range_facet",
  585. data: {
  586. collection: ko.mapping.toJSON(self),
  587. facet: ko.mapping.toJSON(facet),
  588. action: 'select'
  589. },
  590. success: function (data) {
  591. if (data.status == 0) {
  592. facet.properties.gap(data.properties.gap);
  593. }
  594. },
  595. async: false
  596. });
  597. vm.search();
  598. }
  599. self.timeLineZoom = function (facet_json) {
  600. var facet = self.getFacetById(facet_json.id);
  601. facet.properties.start(facet.from);
  602. facet.properties.end(facet.to);
  603. $.ajax({
  604. type: "POST",
  605. url: "/search/get_range_facet",
  606. data: {
  607. collection: ko.mapping.toJSON(self),
  608. facet: ko.mapping.toJSON(facet),
  609. action: "zoom_out"
  610. },
  611. success: function (data) {
  612. if (data.status == 0) {
  613. facet.properties.start(data.properties.start);
  614. facet.properties.end(data.properties.end);
  615. facet.properties.gap(data.properties.gap);
  616. }
  617. },
  618. async: false
  619. });
  620. vm.search();
  621. }
  622. self.translateSelectedField = function (index, direction) {
  623. var array = self.template.fieldsSelected();
  624. if (direction == 'left') {
  625. self.template.fieldsSelected.splice(index - 1, 2, array[index], array[index - 1]);
  626. } else {
  627. self.template.fieldsSelected.splice(index, 2, array[index + 1], array[index]);
  628. }
  629. vm.search();
  630. };
  631. self.upDownFacetLimit = function (facet_id, direction) {
  632. var facet = self.getFacetById(facet_id);
  633. if (facet.properties.prevLimit == undefined) {
  634. facet.properties.prevLimit = facet.properties.limit();
  635. }
  636. if (direction == 'up') {
  637. facet.properties.limit(facet.properties.limit() + 10);
  638. } else {
  639. facet.properties.limit(facet.properties.limit() - 10);
  640. }
  641. vm.search();
  642. };
  643. };
  644. var NewTemplate = function (vm, initial) {
  645. var self = this;
  646. self.collections = ko.mapping.fromJS(initial.collections);
  647. self.layout = initial.layout;
  648. self.inited = ko.observable(self.collections().length > 0); // No collection if not a new dashboard
  649. self.init = function() {
  650. if (self.inited()) {
  651. // If new dashboard
  652. vm.collection.name.subscribe(function(newValue) {
  653. vm.collection.label(newValue);
  654. vm.collection.switchCollection();
  655. vm.search();
  656. });
  657. } else {
  658. self.syncCollections();
  659. }
  660. if (initial.autoLoad) {
  661. magicLayout(vm);
  662. }
  663. };
  664. self.syncCollections = function () {
  665. $.post("/search/get_collections", {
  666. },function (data) {
  667. if (data.status == 0) {
  668. // Sync new and old names
  669. $.each(data.collection, function(index, name) {
  670. if (self.collections.indexOf(name) == -1) {
  671. self.collections.push(name);
  672. }
  673. });
  674. $.each(self.collections(), function(index, collection) {
  675. if (data.collection.indexOf(collection) == -1) {
  676. self.collections.remove(collection);
  677. }
  678. });
  679. }
  680. else {
  681. $(document).trigger("error", data.message);
  682. }
  683. }).fail(function (xhr, textStatus, errorThrown) {
  684. $(document).trigger("error", xhr.responseText);
  685. }).done(function() {
  686. self.inited(true);
  687. });
  688. };
  689. };
  690. var DATE_TYPES = ['date', 'tdate'];
  691. var NUMBER_TYPES = ['int', 'tint', 'long', 'tlong', 'float', 'tfloat'];
  692. var RANGE_SELECTABLE_WIDGETS = ['histogram-widget', 'bar-widget', 'line-widget'];
  693. var SearchViewModel = function (collection_json, query_json, initial_json) {
  694. var self = this;
  695. // Models
  696. self.collection = new Collection(self, collection_json.collection);
  697. self.query = new Query(self, query_json);
  698. self.initial = new NewTemplate(self, initial_json);
  699. // UI
  700. self.response = ko.observable({});
  701. self.results = ko.observableArray([]);
  702. self.norm_facets = ko.computed(function () {
  703. return self.response().normalized_facets;
  704. });
  705. self.getFacetFromQuery = function (facet_id) {
  706. var _facet = null;
  707. if (self.norm_facets() !== undefined) {
  708. $.each(self.norm_facets(), function (index, norm_facet) {
  709. if (norm_facet.id == facet_id) {
  710. _facet = norm_facet;
  711. }
  712. });
  713. }
  714. return _facet;
  715. };
  716. self.toggledGridlayoutResultChevron = ko.observable(false);
  717. self.enableGridlayoutResultChevron = function() {
  718. self.toggledGridlayoutResultChevron(true);
  719. };
  720. self.disableGridlayoutResultChevron = function() {
  721. self.toggledGridlayoutResultChevron(false);
  722. };
  723. self.previewColumns = ko.observable("");
  724. self.columns = ko.observable([]);
  725. loadLayout(self, collection_json.layout);
  726. self.isEditing = ko.observable(false);
  727. self.toggleEditing = function () {
  728. self.isEditing(!self.isEditing());
  729. };
  730. self.isRetrievingResults = ko.observable(false);
  731. self.draggableHit = ko.observable(new Widget(12, UUID(), "Hit Count", "hit-widget"));
  732. self.draggableFacet = ko.observable(new Widget(12, UUID(), "Facet", "facet-widget"));
  733. self.draggableResultset = ko.observable(new Widget(12, UUID(), "Grid Results", "resultset-widget"));
  734. self.draggableHtmlResultset = ko.observable(new Widget(12, UUID(), "HTML Results", "html-resultset-widget"));
  735. self.draggableHistogram = ko.observable(new Widget(12, UUID(), "Histogram", "histogram-widget"));
  736. self.draggableBar = ko.observable(new Widget(12, UUID(), "Bar Chart", "bar-widget"));
  737. self.draggableMap = ko.observable(new Widget(12, UUID(), "Map", "map-widget"));
  738. self.draggableLine = ko.observable(new Widget(12, UUID(), "Line Chart", "line-widget"));
  739. self.draggablePie = ko.observable(new Widget(12, UUID(), "Pie Chart", "pie-widget"));
  740. self.draggableFilter = ko.observable(new Widget(12, UUID(), "Filter Bar", "filter-widget"));
  741. self.availableDateFields = ko.computed(function() {
  742. return $.grep(self.collection.availableFacetFields(), function(field) { return DATE_TYPES.indexOf(field.type()) != -1; });
  743. });
  744. self.availableNumberFields = ko.computed(function() {
  745. return $.grep(self.collection.availableFacetFields(), function(field) { return NUMBER_TYPES.indexOf(field.type()) != -1; });
  746. });
  747. function getWidgets(equalsTo) {
  748. return $.map(self.columns(), function (col){return $.map(col.rows(), function(row){ return $.grep(row.widgets(), function(widget){ return equalsTo(widget); });}) ;})
  749. };
  750. self.availableDraggableResultset = ko.computed(function() {
  751. return getWidgets(function(widget){ return ['resultset-widget', 'html-resultset-widget'].indexOf(widget.widgetType()) != -1; }).length == 0;
  752. });
  753. self.availableDraggableFilter = ko.computed(function() {
  754. return getWidgets(function(widget){ return widget.widgetType() == 'filter-widget'; }).length == 0;
  755. });
  756. self.availableDraggableHistogram = ko.computed(function() {
  757. return getWidgets(function(widget){ return widget.widgetType() == 'histogram-widget'; }).length == 0 &&
  758. self.availableDateFields().length > 0;
  759. });
  760. self.availableDraggableNumbers = ko.computed(function() {
  761. return getWidgets(function(widget){ return widget.widgetType() == 'line-widget'; }).length == 0 &&
  762. self.availableNumberFields().length > 0;
  763. });
  764. self.availableDraggableChart = ko.computed(function() {
  765. return self.collection.availableFacetFields().length > 0;
  766. });
  767. self.init = function (callback) {
  768. self.initial.init();
  769. self.collection.syncFields();
  770. self.search(callback);
  771. }
  772. self.searchBtn = function () {
  773. self.query.start(0);
  774. self.search();
  775. };
  776. self.search = function (callback) {
  777. self.isRetrievingResults(true);
  778. $(".jHueNotify").hide();
  779. // Multi queries
  780. var multiQs = [];
  781. var multiQ = self.query.getMultiq();
  782. if (multiQ != null) {
  783. var facet = {};
  784. var queries = [];
  785. if (multiQ == 'query') {
  786. queries = self.query.qs();
  787. } else {
  788. facet = self.query.getFacetFilter(self.query.selectedMultiq());
  789. queries = facet.filter();
  790. }
  791. multiQs = $.map(queries, function(qdata) {
  792. return $.post("/search/get_timeline", {
  793. collection: ko.mapping.toJSON(self.collection),
  794. query: ko.mapping.toJSON(self.query),
  795. facet: ko.mapping.toJSON(facet),
  796. qdata: ko.mapping.toJSON(qdata),
  797. multiQ: multiQ
  798. }, function (data) {return data});
  799. });
  800. }
  801. $.when.apply($, [
  802. $.post("/search/search", {
  803. collection: ko.mapping.toJSON(self.collection),
  804. query: ko.mapping.toJSON(self.query),
  805. layout: ko.mapping.toJSON(self.columns)
  806. }, function (data) {
  807. if (typeof callback != undefined && callback != null){
  808. callback(data);
  809. }
  810. self.response(data);
  811. self.results.removeAll();
  812. if (data.error) {
  813. $(document).trigger("error", data.error);
  814. }
  815. else {
  816. if (self.collection.template.isGridLayout()) {
  817. // Table view
  818. $.each(data.response.docs, function (index, item) {
  819. var row = [];
  820. var fields = self.collection.template.fieldsSelected();
  821. // Display selected fields or whole json document
  822. if (fields.length != 0) {
  823. $.each(self.collection.template.fieldsSelected(), function (index, field) {
  824. row.push(item[field]);
  825. });
  826. } else {
  827. row.push(ko.mapping.toJSON(item));
  828. }
  829. var doc = {'id': item[self.collection.idField()], 'row': row};
  830. self.results.push(doc);
  831. });
  832. }
  833. else {
  834. // Template view
  835. var _mustacheTmpl = fixTemplateDotsAndFunctionNames(self.collection.template.template());
  836. $.each(data.response.docs, function (index, item) {
  837. // fix the fields that contain dots in the name
  838. addTemplateFunctions(item);
  839. self.results.push(Mustache.render(_mustacheTmpl, item));
  840. });
  841. }
  842. self.isRetrievingResults(false);
  843. }
  844. })
  845. ].concat(multiQs)
  846. )
  847. .done(function() {
  848. if (arguments[0] instanceof Array) { // If multi queries
  849. var histoFacetId = self.collection.getHistogramFacet().id();
  850. var histoFacet = self.getFacetFromQuery(histoFacetId);
  851. for (var i = 1; i < arguments.length; i++) {
  852. histoFacet.extraSeries.push(arguments[i][0]['series']);
  853. }
  854. self.response.valueHasMutated();
  855. }
  856. })
  857. .fail(function (xhr, textStatus, errorThrown) {
  858. $(document).trigger("error", xhr.responseText);
  859. })
  860. .always(function () {
  861. $('.btn-loading').button('reset');
  862. });
  863. };
  864. self.removeWidget = function (widget_json) {
  865. self.collection.removeFacet(widget_json.id);
  866. self.query.removeFilter(widget_json);
  867. self.removeWidgetById(widget_json.id());
  868. self.search();
  869. }
  870. self.getWidgetById = function (widget_id) {
  871. var _widget = null;
  872. $.each(self.columns(), function (i, col) {
  873. $.each(col.rows(), function (j, row) {
  874. $.each(row.widgets(), function (z, widget) {
  875. if (widget.id() == widget_id){
  876. _widget = widget;
  877. }
  878. });
  879. });
  880. });
  881. return _widget;
  882. }
  883. self.removeWidgetById = function (widget_id) {
  884. $.each(self.columns(), function (i, col) {
  885. $.each(col.rows(), function (j, row) {
  886. $.each(row.widgets(), function (z, widget) {
  887. if (widget.id() == widget_id){
  888. row.widgets.remove(widget);
  889. }
  890. });
  891. });
  892. });
  893. }
  894. self.getDocument = function (doc) {
  895. $.post("/search/get_document", {
  896. collection: ko.mapping.toJSON(self.collection),
  897. id: doc.id
  898. },function (data) {
  899. if (data.status == 0) {
  900. $(document).trigger("showDoc", data.doc.doc);
  901. }
  902. else if (data.status == 1) {
  903. $(document).trigger("info", data.message);
  904. }
  905. else {
  906. $(document).trigger("error", data.message);
  907. }
  908. }).fail(function (xhr, textStatus, errorThrown) {
  909. $(document).trigger("error", xhr.responseText);
  910. });
  911. };
  912. self.save = function () {
  913. $.post("/search/save", {
  914. collection: ko.mapping.toJSON(self.collection),
  915. layout: ko.mapping.toJSON(self.columns)
  916. },function (data) {
  917. if (data.status == 0) {
  918. self.collection.id = data.id;
  919. $(document).trigger("info", data.message);
  920. if (window.location.search.indexOf("collection") == -1){
  921. window.location.hash = '#collection=' + data.id;
  922. }
  923. }
  924. else {
  925. $(document).trigger("error", data.message);
  926. }
  927. }).fail(function (xhr, textStatus, errorThrown) {
  928. $(document).trigger("error", xhr.responseText);
  929. });
  930. };
  931. };