search.ko.js 28 KB

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