search.ko.js 28 KB

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