controls.js 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854
  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. var searchRenderers = {
  17. 'rowkey': { //class to tag selection
  18. select: /[^\,\{\[]+(([\{\[][^\}\]]+[\}\]])+|)([^\,]+|)/g, //select the substring to process, useful as JS has no lookbehinds old: ([^,]+\[([^,]+(,|)+)+\]|[^,]+)
  19. tag: /.+/g, //select the matches to wrap with tags
  20. nested: {
  21. 'scan': { select: /(([^\\]|\b)\+[0-9]+)/g, tag: /\+[0-9]+/g},
  22. 'columns': { select: /\[.+\]/g, tag: /[^:,\[\]]+:([^,\[\]]+|)/g}, //forced to do this select due to lack of lookbehinds /[\[\]]/g
  23. 'prefix': { select: /[^\*\\]+\*/g, tag: /\*/g},
  24. 'filter': {
  25. select: /\{[^\{\}]+\}/,
  26. tag:/[^\{\}]+/g,
  27. nested: {
  28. 'linker': {
  29. select: /\ (AND|OR|SKIP|WHILE)\ /g,
  30. tag: /.+/g
  31. }/*,
  32. 'compare_op': {
  33. select: /[\<\=\!\>]{1,2}/g,
  34. tag: /.+/g
  35. }*/ //will be added eventually after html bug is figured out
  36. }
  37. }
  38. }
  39. }
  40. };
  41. var DataTableViewModel = function(options) {
  42. var self = this, _defaults = {
  43. name: '',
  44. columns: [],
  45. items: [],
  46. reload: function() {
  47. },
  48. el:''
  49. };
  50. options = ko.utils.extend(_defaults,options);
  51. ListViewModel.apply(this, [options]);
  52. self.name = ko.observable(options.name);
  53. self.searchQuery.subscribe(function(value) {
  54. self._table.fnFilter(value);
  55. });
  56. self.columns = ko.observableArray(options.columns);
  57. self._el = $('table[data-datasource="' + options.el + '"]');
  58. self._table = null;
  59. self._initTable = function() {
  60. if(!self._table) {
  61. self._table = self._el.dataTable({
  62. "aoColumnDefs": [ { "bSortable": false, "aTargets": [ 0 ] }
  63. ],
  64. "sDom": 'tr',//this has to be in, change to sDom so you can call filter()
  65. 'bAutoWidth':false,
  66. "iDisplayLength": -1});
  67. return self._table;
  68. }
  69. };
  70. self.sort = function(viewModel, event) {
  71. var el = $(event.currentTarget);
  72. };
  73. var _reload = self.reload;
  74. self.reload = function(callback) {
  75. logGA('view_cluster');
  76. if(self._table) {
  77. self._table.fnClearTable();
  78. self._table.fnDestroy();
  79. self._table = null;
  80. }
  81. _reload(function() {
  82. self._initTable();
  83. if(callback!=null)
  84. callback();
  85. });
  86. };
  87. self.canDrop = ko.computed(function() {
  88. var selected = self.selected();
  89. if(selected.length <= 0) return false;
  90. for(var i=0; i<selected.length; i++) {
  91. if(selected[i].enabled()) return false;
  92. }
  93. return true;
  94. });
  95. self.canDisable = ko.computed(function() {
  96. var selected = self.selected();
  97. if(selected.length <= 0) return false;
  98. for(var i=0; i<selected.length; i++) {
  99. if(!selected[i].enabled()) return false;
  100. }
  101. return true;
  102. });
  103. self.canEnable = ko.computed(function() {
  104. var selected = self.selected();
  105. if(selected.length <= 0) return false;
  106. for(var i=0; i<selected.length; i++) {
  107. if(selected[i].enabled()) return false;
  108. }
  109. return true;
  110. });
  111. };
  112. //a Listview of Listviews
  113. var SmartViewModel = function(options) {
  114. var self = this;
  115. options = ko.utils.extend({
  116. name: '',
  117. items: [],
  118. reload: function() {
  119. },
  120. el:'',
  121. sortFields: {
  122. 'Row Key': function(a, b) {
  123. return a.row.localeCompare(b.row);
  124. },
  125. 'Column Count': function(a, b) {
  126. a = a.items().length;
  127. b = b.items().length;
  128. if(a > b)
  129. return 1;
  130. if(a < b)
  131. return -1;
  132. return 0;
  133. },
  134. 'Row Key Length': function(a, b) {
  135. a = a.row.length;
  136. b = b.row.length;
  137. if(a > b)
  138. return 1;
  139. if(a < b)
  140. return -1;
  141. return 0;
  142. }
  143. }
  144. }, options);
  145. ListViewModel.apply(this, [options]); //items: [ListView.items[],ListView.items[]]
  146. self.columnFamilies = ko.observableArray();
  147. self.name = ko.observable(options.name);
  148. self.name.subscribe(function(){
  149. self.columnFamilies([]);
  150. self._reloadcfs();
  151. if(app.station() == 'table')
  152. return;
  153. self.querySet.removeAll();
  154. self.evaluateQuery();
  155. }); //fix and decouple
  156. self.lastReloadTime = ko.observable(1);
  157. self.searchQuery.subscribe(function goToRow(value) //make this as nice as the renderfucnction and split into two, also fire not down on keyup events
  158. {
  159. if(app.station() != 'table')
  160. return;
  161. if(value.replace(/\s/g, "") == '' || value == null)
  162. routie(app.cluster() + '/' + app.views.tabledata.name());
  163. var inputs = value.match(searchRenderers['rowkey']['select']);
  164. self.querySet.removeAll();
  165. if(inputs) {
  166. for(var i=0; i<inputs.length; i++) {
  167. if(inputs[i].trim() != "" && inputs[i].trim() != ',') {
  168. //pull out columns
  169. var extract = inputs[i].match(searchRenderers['rowkey']['nested']['columns']['select']);
  170. var columns = extract != null ? extract[0].match(searchRenderers['rowkey']['nested']['columns']['tag']) : [];
  171. inputs[i] = inputs[i].replace(extract, '');
  172. //pull out scan
  173. var p = pullFromRenderer(inputs[i], searchRenderers['rowkey']['nested']['scan']);
  174. inputs[i] = inputs[i].replace(p, '');
  175. p = p.split('+');
  176. var scan = p.length > 1 ? parseInt(p[1].trim()) : 0;
  177. //pull out filters
  178. var filter = inputs[i].match(searchRenderers['rowkey']['nested']['filter']['select']) || "";
  179. filter = filter != null && filter.length > 0 ? escape(filter[0].trim().slice(1, -1)) : "";
  180. //pull out column filters
  181. function filterPostfix(postfix) {
  182. return (filter != null && filter.length > 0 ? ' AND ' : ' ' ) + postfix;
  183. }
  184. var cfs = [];
  185. $(columns).each(function(i, o) {
  186. var colscan = pullFromRenderer(o, searchRenderers['rowkey']['nested']['scan']);
  187. if(colscan) {
  188. colscan = parseInt(colscan.split('+')[1]) + 1;
  189. filter += filterPostfix("ColumnPaginationFilter(" + colscan + ", 0)");
  190. }
  191. var fc = o.replace(pullFromRenderer(o, searchRenderers['rowkey']['nested']['prefix']), '');
  192. if(fc != o) {
  193. filter += filterPostfix("ColumnPrefixFilter('" + fc.slice(fc.indexOf(':') + 1).match(/[0-9]+/g)[0] + "')");
  194. columns[i] = fc.slice(0, fc.indexOf(':'));
  195. }
  196. });
  197. self.querySet.push(new QuerySetPiece({
  198. 'row_key': inputs[i].replace(/\\(\+|\*|\,)/g, '$1').replace(/[\[\{].+[\]\}]|\*/g,'').trim(), //clean up with column regex selectors instead
  199. 'scan_length': scan ? scan + 1 : 1,
  200. 'columns': columns,
  201. 'prefix': inputs[i].match(searchRenderers['rowkey']['nested']['prefix']['select']) != null,
  202. 'filter': filter.length > 0 ? filter : null
  203. }));
  204. }
  205. }
  206. }
  207. self.evaluateQuery();
  208. });
  209. self._reloadcfs = function() {
  210. return API.queryTable("getColumnDescriptors").done(function(data) {
  211. self.columnFamilies.removeAll();
  212. var keys = Object.keys(data);
  213. for(var i=0;i<keys.length;i++) {
  214. self.columnFamilies.push(new ColumnFamily({name:keys[i], enabled:false}));
  215. }
  216. self.reload();
  217. });
  218. };
  219. self.columnQuery = ko.observable("");
  220. self.columnQuery.subscribe(function(query) {
  221. $(self.items()).each(function() {
  222. table_search(query);
  223. });
  224. });
  225. self.rows = ko.computed(function() {
  226. var a = [];
  227. var items = this.items();
  228. for(var i=0; i<items.length; i++) {
  229. a.push(items[i].row);
  230. }
  231. return a;
  232. }, self);
  233. self.querySet = ko.observableArray();
  234. self.validateQuery = function() {
  235. if(self.querySet().length == 0) {
  236. self.querySet.push(new QuerySetPiece({
  237. 'row_key': 'null',
  238. 'scan_length': 10,
  239. 'prefix': 'false'
  240. }));
  241. } else {
  242. $(self.querySet()).each(function() {
  243. this.validate();
  244. this.editing(false);
  245. });
  246. }
  247. };
  248. self.addQuery = function() {
  249. self.validateQuery();
  250. self.querySet.push(new QuerySetPiece({onValidate: function() {
  251. //self.reload();
  252. }}))
  253. };
  254. self.evaluateQuery = function(callback) {
  255. self.validateQuery();
  256. self.reload(callback);
  257. };
  258. var _reload = self.reload;
  259. self.reload = function(callback) {
  260. logGA('view_table');
  261. var queryStart = new Date();
  262. _reload(function() {
  263. self.lastReloadTime((new Date() - queryStart)/1000);
  264. if(callback!=null)
  265. callback();
  266. self.isLoading(false);
  267. });
  268. };
  269. self.truncateLimit = ko.observable(1500);
  270. };
  271. var SmartViewDataRow = function(options) {
  272. var self = this;
  273. options = ko.utils.extend({
  274. sortFields: {
  275. 'Column Family': function(a, b) {
  276. return a.name.localeCompare(b.name);
  277. },
  278. 'Column Name': function(a, b) {
  279. return a.name.split(':')[1].localeCompare(b.name.split(':')[1]);
  280. },
  281. 'Cell Size': function(a, b) {
  282. a = a.value().length;
  283. b = b.value().length;
  284. if(a > b)
  285. return 1;
  286. if(a < b)
  287. return -1;
  288. return 0;
  289. },
  290. 'Cell Value': function(a, b) {
  291. return a.value().localeCompare(b.value());
  292. },
  293. 'Timestamp': function(a, b) {
  294. a = parseInt(a.timestamp);
  295. b = parseInt(b.timestamp);
  296. if(a > b)
  297. return 1;
  298. if(a < b)
  299. return -1;
  300. return 0;
  301. },
  302. 'Column Name Length': function(a, b) {
  303. a = a.name.split(':')[1].length;
  304. b = b.name.split(':')[1].length;
  305. if(a > b)
  306. return 1;
  307. if(a < b)
  308. return -1;
  309. return 0;
  310. }
  311. }
  312. }, options);
  313. DataRow.apply(self,[options]);
  314. ListViewModel.apply(self,[options]);
  315. self.displayedItems = ko.observableArray();
  316. self.displayRangeStart = 0;
  317. self.displayRangeLength = 20;
  318. self.items.subscribe(function() {
  319. self.displayedItems([]);
  320. self.updateDisplayedItems();
  321. });
  322. self.searchQuery.subscribe(function(searchValue) {
  323. self.scrollLoadSource = ko.computed(function(){
  324. return self.items().filter(function(column) {
  325. return column.name.toLowerCase().indexOf(searchValue.toLowerCase()) != -1;
  326. });
  327. });
  328. self.displayRangeLength = 20;
  329. self.updateDisplayedItems();
  330. });
  331. self.scrollLoadSource = self.items;
  332. self.updateDisplayedItems = function() {
  333. var x = self.displayRangeStart;
  334. self.displayedItems(self.scrollLoadSource().slice(x, x + self.displayRangeLength));
  335. };
  336. self.resetScrollLoad = function() {
  337. self.scrollLoadSource = self.items;
  338. self.updateDisplayedItems();
  339. };
  340. self.toggleSelectedCollapse = function() {
  341. if(self.displayedItems().length == self.displayRangeStart + self.displayRangeLength) {
  342. self.displayedItems(self.displayedItems().filter(function(item) {
  343. return item.isSelected();
  344. }));
  345. self.scrollLoadSource = self.displayedItems;
  346. }
  347. else {
  348. self.resetScrollLoad();
  349. }
  350. };
  351. self.onScroll = function(target, ev) {
  352. if($(ev.target).scrollLeft() == ev.target.scrollWidth - ev.target.clientWidth && self.displayedItems().length < self.scrollLoadSource().length) {
  353. self.displayRangeLength += 15;
  354. self.updateDisplayedItems();
  355. }
  356. };
  357. self.drop = function(cont) {
  358. function doDrop() {
  359. self.isLoading(true);
  360. return API.queryTable('deleteAllRow', self.row, "{}").complete(function() {
  361. app.views.tabledata.items.remove(self); //decouple later
  362. self.isLoading(false);
  363. });
  364. }
  365. (cont === true) ? doDrop() : confirm("Confirm Delete", 'Delete row ' + self.row + '? (This cannot be undone)', doDrop);
  366. };
  367. self.setItems = function(cols) {
  368. var colKeys = Object.keys(cols);
  369. var items = [];
  370. for(var q=0; q<colKeys.length; q++) {
  371. items.push(new ColumnRow({name: colKeys[q],
  372. timestamp: cols[colKeys[q]].timestamp,
  373. value: cols[colKeys[q]].value,
  374. parent: self}));
  375. }
  376. self.items(items);
  377. return self.items();
  378. };
  379. self.selectAllVisible = function(){
  380. for(t=0; t<self.displayedItems().length; t++)
  381. self.displayedItems()[t].isSelected(true);
  382. return self;
  383. };
  384. self.toggleSelectAllVisible = function() {
  385. if(self.selected().length != self.displayedItems().length)
  386. return self.selectAllVisible();
  387. return self.deselectAll();
  388. };
  389. self.push = function(item) {
  390. var column = new ColumnRow(item);
  391. self.items.push(column);
  392. };
  393. var _reload = self.reload;
  394. self.reload = function(callback) {
  395. logGA('get_row');
  396. _reload(function() {
  397. if(callback!=null)
  398. callback();
  399. self.isLoading(false);
  400. });
  401. };
  402. };
  403. var ColumnRow = function(options) {
  404. var self = this;
  405. ko.utils.extend(self,options);
  406. DataRow.apply(self,[options]);
  407. self.value = ko.observable(self.value);
  408. self.history = new CellHistoryPage({row: self.parent.row, column: self.name, timestamp: self.timestamp, items: []});
  409. self.drop = function(cont) {
  410. function doDrop() {
  411. logGA('filter_columns');
  412. self.parent.isLoading(true);
  413. return API.queryTable('deleteColumn', self.parent.row, self.name).done(function(data) {
  414. self.parent.items.remove(self);
  415. if(self.parent.items().length > 0)
  416. self.parent.reload(); //change later
  417. self.parent.isLoading(false);
  418. });
  419. }
  420. (cont === true) ? doDrop() : confirm("Confirm Delete", "Are you sure you want to drop this column?", doDrop);
  421. };
  422. self.reload = function(callback, skipPut) {
  423. self.isLoading(true);
  424. API.queryTable('get', self.parent.row, self.name, 'null').done(function(data) {
  425. if(data.length > 0 && !skipPut)
  426. self.value(data[0].value);
  427. if(typeof callback !== "undefined" && callback != null)
  428. callback();
  429. self.isLoading(false);
  430. });
  431. };
  432. self.value.subscribe(function(value) {
  433. //change transport prep to object wrapper
  434. logGA('put_column');
  435. API.queryTable('putColumn', self.parent.row, self.name, "hbase-post-key-" + JSON.stringify(value)).done(function(data) {
  436. self.reload(function(){}, true);
  437. });
  438. self.editing(false);
  439. });
  440. self.editing = ko.observable(false);
  441. self.isLoading = ko.observable(false); //move to baseclass
  442. };
  443. var SortDropDownView = function(options) {
  444. var self = this;
  445. options = ko.utils.extend({
  446. sortFields: {},
  447. target: null
  448. }, options);
  449. BaseModel.apply(self,[options]);
  450. self.target = options.target;
  451. self.sortAsc = ko.observable(true);
  452. self.sortAsc.subscribe(function(){self.sort()});
  453. self.sortField = ko.observable("");
  454. self.sortField.subscribe(function(){self.sort()});
  455. self.sortFields = ko.observableArray(Object.keys(options.sortFields)); // change to ko.computed?
  456. self.sortFunctionHash = ko.observable(options.sortFields);
  457. self.toggleSortMode = function() {
  458. self.sortAsc(!self.sortAsc());
  459. };
  460. self.sort = function() {
  461. if (!self.target || !(self.sortFields().length > 0)) return;
  462. self.target.sort(function(a, b) {
  463. return (self.sortAsc() ? 1 : -1) * self.sortFunctionHash()[self.sortField() ? self.sortField() : self.sortFields()[0]](a,b); //all sort functions must sort by ASC for default
  464. });
  465. };
  466. };
  467. var TableDataRow = function(options) {
  468. var self = this;
  469. options = ko.utils.extend({
  470. name:"",
  471. enabled:true
  472. }, options);
  473. DataRow.apply(self,[options]);
  474. self.name = options['name'];
  475. self.enabled = ko.observable(options['enabled']);
  476. self.toggle = function(viewModel,event){
  477. var action = ['enable','disable'][self.enabled() << 0], el = $(event.currentTarget);
  478. confirm("Confirm "+action, "Are you sure you want to " + action + " this table?", function() //gotta i18n this!
  479. {
  480. el.showIndicator();
  481. return self[action](el).complete(function() {
  482. el.hideIndicator();
  483. });
  484. });
  485. };
  486. self.enable = function(el) {
  487. return API.queryCluster('enableTable',self.name).complete(function() {
  488. self.enabled(true);
  489. });
  490. };
  491. self.disable = function(callback) {
  492. return API.queryCluster('disableTable',self.name).complete(function() {
  493. self.enabled(false);
  494. if($.isFunction(callback)) callback();
  495. });
  496. };
  497. self.drop = function(el) {
  498. return API.queryCluster('deleteTable',self.name);
  499. };
  500. };
  501. var QuerySetPiece = function(options) {
  502. var self = this;
  503. options = ko.utils.extend({
  504. row_key: "null",
  505. scan_length: 1,
  506. prefix: false,
  507. columns: [],
  508. filter: null,
  509. onValidate: function(){}
  510. }, options);
  511. BaseModel.apply(self,[options]);
  512. self.row_key = ko.observable(options.row_key);
  513. self.scan_length = ko.observable(options.scan_length);
  514. self.columns = ko.observableArray(options.columns);
  515. self.prefix = ko.observable(options.prefix);
  516. self.filter = ko.observable(options.filter);
  517. self.editing = ko.observable(true);
  518. self.validate = function() {
  519. if(self.scan_length() <= 0 || self.row_key() == "")
  520. return app.views.tabledata.querySet.remove(self); //change later
  521. return options.onValidate();
  522. };
  523. self.row_key.subscribe(self.validate.bind());
  524. self.scan_length.subscribe(self.validate.bind());
  525. };
  526. var ColumnFamily = function(options) {
  527. this.name = options.name;
  528. this.enabled = ko.observable(options.enabled);
  529. this.toggle = function() {
  530. this.enabled(!this.enabled());
  531. app.views.tabledata.reload();
  532. };
  533. }
  534. //tagsearch
  535. var tagsearch = function() {
  536. var self = this;
  537. self.tags = ko.observableArray();
  538. self.mode = ko.observable('idle');
  539. self.cur_input = ko.observable('');
  540. self.submitted = ko.observable(false);
  541. self.filters = ["KeyOnlyFilter ()", "FirstKeyOnlyFilter ()", "PrefixFilter (‘row_prefix’)", "ColumnPrefixFilter(‘column_prefix’)", "MultipleColumnPrefixFilter(‘column_prefix’, ‘column_prefix’, …, ‘column_prefix’)", "ColumnCountGetFilter (‘limit’)", "PageFilter (‘page_size’)", "ColumnPaginationFilter(‘limit’, ‘offest')", "InclusiveStopFilter(‘stop_row_key’)", "TimeStampsFilter (timestamp, timestamp, ... ,timestamp)", "RowFilter (compareOp, ‘row_comparator’)", "QualifierFilter (compareOp, ‘qualifier_comparator’)", "QualifierFilter (compareOp,‘qualifier_comparator’)", "ValueFilter (compareOp,‘value_comparator’)", "DependentColumnFilter (‘family’, ‘qualifier’, boolean, compare operator, ‘value comparator’)", "DependentColumnFilter (‘family’, ‘qualifier’, boolean)", "DependentColumnFilter (‘family’, ‘qualifier’)", "SingleColumnValueFilter(‘family’, ‘qualifier’, compare operator, ‘comparator’, filterIfColumnMissing_boolean, latest_version_boolean)", "SingleColumnValueFilter(‘family’, ‘qualifier, compare operator, ‘comparator’)", "SingleColumnValueExcludeFilter('family', 'qualifier', compare operator, 'comparator', latest_version_boolean, filterIfColumnMissing_boolean)", "SingleColumnValueExcludeFilter('family', 'qualifier', compare operator, 'comparator')", "ColumnRangeFilter (‘minColumn’, minColumnInclusive_bool, ‘maxColumn’, maxColumnInclusive_bool)"];
  542. self.hints = ko.observableArray([ {
  543. hint: 'End Query',
  544. shortcut: ',',
  545. mode: ['rowkey', 'prefix', 'scan'],
  546. selected: false
  547. }, {
  548. hint: 'Mark Row/Column Prefix',
  549. shortcut: '*',
  550. mode: ['rowkey'],
  551. selected: false
  552. }, {
  553. hint: 'Start Row/Column Scan',
  554. shortcut: '+',
  555. mode: ['rowkey', 'prefix'],
  556. selected: false
  557. }, {
  558. hint: 'Start Select Columns',
  559. shortcut: '[',
  560. mode: ['rowkey', 'prefix'],
  561. selected: false
  562. }, {
  563. hint: 'End Column/Family',
  564. shortcut: ',',
  565. mode: ['columns'],
  566. selected: false
  567. }, {
  568. hint: 'End Select Columns',
  569. shortcut: ']',
  570. mode: ['columns'],
  571. selected: false
  572. },
  573. {
  574. hint: 'Start FilterString',
  575. shortcut: '{',
  576. mode: ['rowkey'],
  577. selected: false
  578. },
  579. {
  580. hint: 'End FilterString',
  581. shortcut: '}',
  582. mode: ['filter'],
  583. selected: false
  584. }
  585. ]);
  586. self.activeHints = ko.computed(function() {
  587. var ret = [];
  588. $(self.hints()).each(function(i, hint) {
  589. if (hint.mode.indexOf(self.mode()) > -1)
  590. ret.push(hint);
  591. });
  592. return ret;
  593. });
  594. self.activeHint = ko.observable(-1);
  595. self.modes = {
  596. 'rowkey': {
  597. hint: 'Row Key Value',
  598. type: 'String'
  599. },
  600. 'scan': {
  601. hint: 'Length of Scan or Row Key',
  602. type: 'Integer'
  603. },
  604. 'columns': {
  605. hint: 'Column Family: Column Name',
  606. type: 'String'
  607. },
  608. 'prefix': {
  609. hint: 'Rows starting with',
  610. type: 'String'
  611. },
  612. 'filter': {
  613. hint: 'Thrift FilterString',
  614. type: 'String'
  615. }
  616. }
  617. self.modeQueue = ['idle'];
  618. self.focused = ko.observable(false);
  619. self.activeSuggestions = ko.observableArray();
  620. self.insertTag = function(tag) {
  621. var mode = tag.indexOf('+') != -1 ? 'scan' : 'rowkey';
  622. var tag = {value: tag, tag: mode} //parse mode
  623. self.tags.push(tag);
  624. }
  625. self.render = function(input, renderers) {
  626. var keys = Object.keys(renderers);
  627. for(var i=0; i<keys.length; i++) {
  628. input = input.replace(renderers[keys[i]].select, function(selected) {
  629. var hasMatched = false;
  630. var processed = selected.replace(renderers[keys[i]].tag, function(tagged) {
  631. hasMatched = true;
  632. return "<span class='" + keys[i] + " tagsearchTag' title='" + keys[i] + "' data-toggle='tooltip'>" + ('nested' in renderers[keys[i]] ? self.render(tagged, renderers[keys[i]].nested) : tagged) + "</span>";
  633. });
  634. if(hasMatched && renderers[keys[i]]['strip'])
  635. processed = processed.replace(renderers[keys[i]].strip, '');
  636. return processed;
  637. });
  638. }
  639. return input;
  640. };
  641. self.updateMode = function(value) {
  642. self.submitted(false);
  643. var selection = value.slice(0, self.selectionEnd());
  644. var endindex = selection.slice(selection.lastIndexOf(',')).indexOf(',');
  645. if(endindex == -1) endindex = selection.length;
  646. var lastbit = value.substring(selection.lastIndexOf(','), endindex).trim();
  647. if(lastbit == "," || lastbit == "") {
  648. self.mode('idle');
  649. return;
  650. }
  651. var tokens = "[]+*{}";
  652. var m = 'rowkey';
  653. for(var i=selection.length - 1; i>=0; i--) {
  654. if(tokens.indexOf(selection[i]) != -1) {
  655. if(selection[i] == '{')
  656. m = 'filter';
  657. else if(selection[i] == '[')
  658. m = 'columns';
  659. else if(selection[i] == ']' || selection[i] == '}')
  660. m = 'rowkey';
  661. else if(selection[i] == '+')
  662. m = 'scan';
  663. else if(selection[i] == '-')
  664. m = 'prefix';
  665. break;
  666. }
  667. }
  668. self.mode(m.trim());
  669. };
  670. self.selectionStart = ko.observable(0);
  671. self.selectionEnd = ko.observable(0);
  672. self.hintText = ko.computed(function() {
  673. var pre, s, e;
  674. try {
  675. var r = window.getSelection().getRangeAt(0);
  676. pre = r.startContainer.nodeValue;
  677. s = r.startOffset;
  678. e = r.endOffset;
  679. return pre.slice(0, s) + "<span class='selection'>" + pre.slice(s, e) + "</span>" + pre.slice(e);
  680. } catch (e) {
  681. var value = self.cur_input();
  682. var selection = value.slice(0, self.selectionEnd());
  683. var index = selection.lastIndexOf(',') + 1;
  684. var endindex = value.slice(index).indexOf(',');
  685. endindex = endindex == -1 ? value.length : endindex;
  686. pre = value.substring(index, index + endindex);
  687. s = self.selectionStart() - index;
  688. e = self.selectionEnd() - index;
  689. if(s == e)
  690. e += 1;
  691. s = s < 0 ? 0 : s;
  692. e = e > pre.length ? pre.length : e;
  693. }
  694. return pre.slice(0, s) + "<span class='selection'>" + pre.slice(s, e) + "</span>" + pre.slice(e);
  695. });
  696. self.onKeyDown = function(target, ev) {
  697. if(ev.keyCode == 13 && self.cur_input().slice(self.cur_input().lastIndexOf(',')).trim() != ",") {
  698. self.evaluate();
  699. return false;
  700. }
  701. setTimeout(self.updateMenu, 1);
  702. return true;
  703. };
  704. self.updateMenu = function() {
  705. try{
  706. var pos = getEditablePosition(document.getElementById('search-tags'));
  707. self.selectionStart(pos);
  708. self.selectionEnd(pos);
  709. } catch (err) {}
  710. self.updateMode(self.cur_input());
  711. self.updateSuggestions();
  712. };
  713. self.replaceFocusNode = function(text) {
  714. window.getSelection().getRangeAt(0).startContainer.nodeValue = text;
  715. };
  716. self.updateSuggestions = function() {
  717. var val = window.getSelection().getRangeAt(0).startContainer.nodeValue;
  718. switch(self.mode()) {
  719. case 'filter':
  720. var focus = val.replace(/\{|\}|\s|&[^;]+?;/g,"").split(/(AND|OR|SKIP|WHILE)/).slice(-1)[0];
  721. self.activeSuggestions(self.filters.filter(function(a) {
  722. return a.replace(" ","").indexOf(focus) != -1;
  723. }));
  724. return;
  725. case 'rowkey':
  726. var validate = window.getSelection().getRangeAt(0).startContainer.nodeValue;
  727. function cancel() {
  728. return window.getSelection().getRangeAt(0).startContainer.nodeValue != validate;
  729. }
  730. function callback() {
  731. if(cancel()) return false;
  732. API.queryTable('getAutocompleteRows', 10, prepForTransport(validate.trim())).done(function(data) {
  733. if(cancel()) return false;
  734. self.activeSuggestions(data);
  735. });
  736. }
  737. setTimeout(callback, 200);
  738. return;
  739. default:
  740. self.activeSuggestions([]);
  741. return;
  742. }
  743. }
  744. self.evaluate = function() {
  745. table_search(self.cur_input());
  746. self.submitted(true);
  747. self.mode('idle');
  748. };
  749. $('#search-tags').blur(function(){
  750. self.focused(false);
  751. });
  752. self.doBlur = function() {
  753. if(self.cur_input().trim() == "") {
  754. function doClick() {
  755. if(self.cur_input().trim() != "") return false;
  756. setTimeout(function() {
  757. $('#search-tags').focus();
  758. }, 1);
  759. }
  760. $('#search-tags').html('<small>' + $('#search-tags').data("placeholder") + '</small>').one('click', doClick).find('small').on('mousedown', doClick);
  761. }
  762. }
  763. $('#search-tags').focus(function(){
  764. self.focused(true);
  765. });
  766. };
  767. var CellHistoryPage = function(options) {
  768. var self = this;
  769. self.items = ko.observableArray(options.items);
  770. self.loading = ko.observable(false);
  771. self.reload = function(timestamp, append) {
  772. if(!timestamp)
  773. timestamp = options.timestamp
  774. API.queryTable("getVerTs", options.row, options.column, timestamp, 10, 'null').done(function(res) {
  775. self.loading = ko.observable(true);
  776. if(!append)
  777. self.items(res);
  778. else
  779. self.items(self.items() + res);
  780. self.loading = ko.observable(false);
  781. });
  782. };
  783. };