search.ko.js 30 KB

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