search.ko.js 30 KB

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