globalSearch.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488
  1. const subManager = new SubsManager();
  2. BlazeComponent.extendComponent({
  3. events() {
  4. return [
  5. {
  6. 'click .js-due-cards-view-change': Popup.open('globalSearchViewChange'),
  7. },
  8. ];
  9. },
  10. }).register('globalSearchHeaderBar');
  11. Template.globalSearch.helpers({
  12. userId() {
  13. return Meteor.userId();
  14. },
  15. });
  16. BlazeComponent.extendComponent({
  17. events() {
  18. return [
  19. {
  20. 'click .js-due-cards-view-me'() {
  21. Utils.setDueCardsView('me');
  22. Popup.close();
  23. },
  24. 'click .js-due-cards-view-all'() {
  25. Utils.setDueCardsView('all');
  26. Popup.close();
  27. },
  28. },
  29. ];
  30. },
  31. }).register('globalSearchViewChangePopup');
  32. BlazeComponent.extendComponent({
  33. onCreated() {
  34. this.searching = new ReactiveVar(false);
  35. this.hasResults = new ReactiveVar(false);
  36. this.hasQueryErrors = new ReactiveVar(false);
  37. this.query = new ReactiveVar('');
  38. this.resultsHeading = new ReactiveVar('');
  39. this.searchLink = new ReactiveVar(null);
  40. this.myLists = new ReactiveVar([]);
  41. this.myLabelNames = new ReactiveVar([]);
  42. this.myBoardNames = new ReactiveVar([]);
  43. this.results = new ReactiveVar([]);
  44. this.queryParams = null;
  45. this.parsingErrors = [];
  46. this.resultsCount = 0;
  47. this.totalHits = 0;
  48. this.queryErrors = null;
  49. this.colorMap = null;
  50. // this.colorMap = {};
  51. // for (const color of Boards.simpleSchema()._schema['labels.$.color']
  52. // .allowedValues) {
  53. // this.colorMap[TAPi18n.__(`color-${color}`)] = color;
  54. // }
  55. // // eslint-disable-next-line no-console
  56. // console.log('colorMap:', this.colorMap);
  57. Meteor.call('myLists', (err, data) => {
  58. if (!err) {
  59. this.myLists.set(data);
  60. }
  61. });
  62. Meteor.call('myLabelNames', (err, data) => {
  63. if (!err) {
  64. this.myLabelNames.set(data);
  65. }
  66. });
  67. Meteor.call('myBoardNames', (err, data) => {
  68. if (!err) {
  69. this.myBoardNames.set(data);
  70. }
  71. });
  72. },
  73. onRendered() {
  74. Meteor.subscribe('setting');
  75. if (Session.get('globalQuery')) {
  76. this.searchAllBoards(Session.get('globalQuery'));
  77. }
  78. },
  79. resetSearch() {
  80. this.searching.set(false);
  81. this.results.set([]);
  82. this.hasResults.set(false);
  83. this.hasQueryErrors.set(false);
  84. this.resultsHeading.set('');
  85. this.parsingErrors = [];
  86. this.resultsCount = 0;
  87. this.totalHits = 0;
  88. this.queryErrors = null;
  89. },
  90. getResults() {
  91. // eslint-disable-next-line no-console
  92. // console.log('getting results');
  93. if (this.queryParams) {
  94. const sessionData = SessionData.findOne({
  95. userId: Meteor.userId(),
  96. sessionId: SessionData.getSessionId(),
  97. });
  98. // eslint-disable-next-line no-console
  99. console.log('session data:', sessionData);
  100. const cards = Cards.find({ _id: { $in: sessionData.cards } });
  101. this.queryErrors = sessionData.errorMessages;
  102. // eslint-disable-next-line no-console
  103. // console.log('errors:', this.queryErrors);
  104. if (this.parsingErrors.length) {
  105. this.queryErrors = this.errorMessages();
  106. this.hasQueryErrors.set(true);
  107. return null;
  108. }
  109. if (this.queryErrors.length) {
  110. this.hasQueryErrors.set(true);
  111. return null;
  112. }
  113. if (cards) {
  114. this.totalHits = sessionData.totalHits;
  115. this.resultsCount = cards.count();
  116. this.resultsHeading.set(this.getResultsHeading());
  117. this.results.set(cards);
  118. }
  119. }
  120. this.resultsCount = 0;
  121. return null;
  122. },
  123. errorMessages() {
  124. const messages = [];
  125. if (this.parsingErrors.length) {
  126. this.parsingErrors.forEach(err => {
  127. messages.push(TAPi18n.__(err.tag, err.value));
  128. });
  129. }
  130. return messages;
  131. },
  132. searchAllBoards(query) {
  133. query = query.trim();
  134. // eslint-disable-next-line no-console
  135. console.log('query:', query);
  136. this.query.set(query);
  137. this.resetSearch();
  138. if (!query) {
  139. return;
  140. }
  141. this.searching.set(true);
  142. if (!this.colorMap) {
  143. this.colorMap = {};
  144. for (const color of Boards.simpleSchema()._schema['labels.$.color']
  145. .allowedValues) {
  146. this.colorMap[TAPi18n.__(`color-${color}`)] = color;
  147. }
  148. }
  149. const reOperator1 = /^((?<operator>\w+):|(?<abbrev>[#@]))(?<value>\w+)(\s+|$)/;
  150. const reOperator2 = /^((?<operator>\w+):|(?<abbrev>[#@]))(?<quote>["']*)(?<value>.*?)\k<quote>(\s+|$)/;
  151. const reText = /^(?<text>\S+)(\s+|$)/;
  152. const reQuotedText = /^(?<quote>["'])(?<text>\w+)\k<quote>(\s+|$)/;
  153. const operators = {
  154. 'operator-board': 'boards',
  155. 'operator-board-abbrev': 'boards',
  156. 'operator-swimlane': 'swimlanes',
  157. 'operator-swimlane-abbrev': 'swimlanes',
  158. 'operator-list': 'lists',
  159. 'operator-list-abbrev': 'lists',
  160. 'operator-label': 'labels',
  161. 'operator-label-abbrev': 'labels',
  162. 'operator-user': 'users',
  163. 'operator-user-abbrev': 'users',
  164. 'operator-member': 'members',
  165. 'operator-member-abbrev': 'members',
  166. 'operator-assignee': 'assignees',
  167. 'operator-assignee-abbrev': 'assignees',
  168. 'operator-is': 'is',
  169. 'operator-due': 'dueAt',
  170. 'operator-created': 'createdAt',
  171. 'operator-modified': 'modifiedAt',
  172. 'operator-comment': 'comments',
  173. };
  174. const operatorMap = {};
  175. Object.entries(operators).forEach(([key, value]) => {
  176. operatorMap[TAPi18n.__(key).toLowerCase()] = value;
  177. });
  178. // eslint-disable-next-line no-console
  179. // console.log('operatorMap:', operatorMap);
  180. const params = {
  181. boards: [],
  182. swimlanes: [],
  183. lists: [],
  184. users: [],
  185. members: [],
  186. assignees: [],
  187. labels: [],
  188. is: [],
  189. dueAt: null,
  190. createdAt: null,
  191. modifiedAt: null,
  192. comments: [],
  193. };
  194. let text = '';
  195. while (query) {
  196. m = query.match(reOperator1);
  197. if (!m) {
  198. m = query.match(reOperator2);
  199. if (m) {
  200. query = query.replace(reOperator2, '');
  201. }
  202. } else {
  203. query = query.replace(reOperator1, '');
  204. }
  205. if (m) {
  206. let op;
  207. if (m.groups.operator) {
  208. op = m.groups.operator.toLowerCase();
  209. } else {
  210. op = m.groups.abbrev;
  211. }
  212. if (operatorMap.hasOwnProperty(op)) {
  213. let value = m.groups.value;
  214. if (operatorMap[op] === 'labels') {
  215. if (value in this.colorMap) {
  216. value = this.colorMap[value];
  217. }
  218. } else if (
  219. ['dueAt', 'createdAt', 'modifiedAt'].includes(operatorMap[op])
  220. ) {
  221. let days = parseInt(value, 10);
  222. let duration = null;
  223. if (isNaN(days)) {
  224. if (['day', 'week', 'month', 'quarter', 'year'].includes(value)) {
  225. duration = value;
  226. value = moment();
  227. } else if (value === 'overdue') {
  228. value = moment();
  229. duration = 'days';
  230. days = 0;
  231. } else {
  232. this.parsingErrors.push({
  233. tag: 'operator-number-expected',
  234. value: { operator: op, value },
  235. });
  236. value = null;
  237. }
  238. } else {
  239. value = moment();
  240. }
  241. if (value) {
  242. if (operatorMap[op] === 'dueAt') {
  243. value = value.add(days, duration ? duration : 'days').format();
  244. } else {
  245. value = value
  246. .subtract(days, duration ? duration : 'days')
  247. .format();
  248. }
  249. }
  250. } else if (operatorMap[op] === 'sort') {
  251. if (!['due', 'modified', 'created', 'system'].includes(value)) {
  252. this.parsingErrors.push({
  253. tag: 'operator-sort-invalid',
  254. value,
  255. });
  256. }
  257. }
  258. if (Array.isArray(params[operatorMap[op]])) {
  259. params[operatorMap[op]].push(value);
  260. } else {
  261. params[operatorMap[op]] = value;
  262. }
  263. } else {
  264. this.parsingErrors.push({
  265. tag: 'operator-unknown-error',
  266. value: op,
  267. });
  268. }
  269. continue;
  270. }
  271. m = query.match(reQuotedText);
  272. if (!m) {
  273. m = query.match(reText);
  274. if (m) {
  275. query = query.replace(reText, '');
  276. }
  277. } else {
  278. query = query.replace(reQuotedText, '');
  279. }
  280. if (m) {
  281. text += (text ? ' ' : '') + m.groups.text;
  282. }
  283. }
  284. // eslint-disable-next-line no-console
  285. // console.log('text:', text);
  286. params.text = text;
  287. // eslint-disable-next-line no-console
  288. console.log('params:', params);
  289. this.queryParams = params;
  290. if (this.parsingErrors.length) {
  291. this.searching.set(false);
  292. this.queryErrors = this.errorMessages();
  293. this.hasQueryErrors.set(true);
  294. return;
  295. }
  296. this.autorun(() => {
  297. const handle = subManager.subscribe(
  298. 'globalSearch',
  299. SessionData.getSessionId(),
  300. params,
  301. );
  302. Tracker.nonreactive(() => {
  303. Tracker.autorun(() => {
  304. if (handle.ready()) {
  305. this.getResults();
  306. this.searching.set(false);
  307. this.hasResults.set(true);
  308. }
  309. });
  310. });
  311. });
  312. },
  313. getResultsHeading() {
  314. if (this.resultsCount === 0) {
  315. return TAPi18n.__('no-cards-found');
  316. } else if (this.resultsCount === 1) {
  317. return TAPi18n.__('one-card-found');
  318. } else if (this.resultsCount === this.totalHits) {
  319. return TAPi18n.__('n-cards-found', this.resultsCount);
  320. }
  321. return TAPi18n.__('n-n-of-n-cards-found', {
  322. start: 1,
  323. end: this.resultsCount,
  324. total: this.totalHits,
  325. });
  326. },
  327. getSearchHref() {
  328. const baseUrl = window.location.href.replace(/([?#].*$|\s*$)/, '');
  329. return `${baseUrl}?q=${encodeURIComponent(this.query.get())}`;
  330. },
  331. searchInstructions() {
  332. tags = {
  333. operator_board: TAPi18n.__('operator-board'),
  334. operator_list: TAPi18n.__('operator-list'),
  335. operator_swimlane: TAPi18n.__('operator-swimlane'),
  336. operator_label: TAPi18n.__('operator-label'),
  337. operator_label_abbrev: TAPi18n.__('operator-label-abbrev'),
  338. operator_user: TAPi18n.__('operator-user'),
  339. operator_user_abbrev: TAPi18n.__('operator-user-abbrev'),
  340. operator_member: TAPi18n.__('operator-member'),
  341. operator_member_abbrev: TAPi18n.__('operator-member-abbrev'),
  342. operator_assignee: TAPi18n.__('operator-assignee'),
  343. operator_assignee_abbrev: TAPi18n.__('operator-assignee-abbrev'),
  344. };
  345. text = `# ${TAPi18n.__('globalSearch-instructions-heading')}`;
  346. text += `\n${TAPi18n.__('globalSearch-instructions-description', tags)}`;
  347. text += `\n${TAPi18n.__('globalSearch-instructions-operators', tags)}`;
  348. text += `\n* ${TAPi18n.__(
  349. 'globalSearch-instructions-operator-board',
  350. tags,
  351. )}`;
  352. text += `\n* ${TAPi18n.__(
  353. 'globalSearch-instructions-operator-list',
  354. tags,
  355. )}`;
  356. text += `\n* ${TAPi18n.__(
  357. 'globalSearch-instructions-operator-swimlane',
  358. tags,
  359. )}`;
  360. text += `\n* ${TAPi18n.__(
  361. 'globalSearch-instructions-operator-label',
  362. tags,
  363. )}`;
  364. text += `\n* ${TAPi18n.__(
  365. 'globalSearch-instructions-operator-hash',
  366. tags,
  367. )}`;
  368. text += `\n* ${TAPi18n.__(
  369. 'globalSearch-instructions-operator-user',
  370. tags,
  371. )}`;
  372. text += `\n* ${TAPi18n.__('globalSearch-instructions-operator-at', tags)}`;
  373. text += `\n* ${TAPi18n.__(
  374. 'globalSearch-instructions-operator-member',
  375. tags,
  376. )}`;
  377. text += `\n* ${TAPi18n.__(
  378. 'globalSearch-instructions-operator-assignee',
  379. tags,
  380. )}`;
  381. text += `\n## ${TAPi18n.__('heading-notes')}`;
  382. text += `\n* ${TAPi18n.__('globalSearch-instructions-notes-1', tags)}`;
  383. text += `\n* ${TAPi18n.__('globalSearch-instructions-notes-2', tags)}`;
  384. text += `\n* ${TAPi18n.__('globalSearch-instructions-notes-3', tags)}`;
  385. text += `\n* ${TAPi18n.__('globalSearch-instructions-notes-4', tags)}`;
  386. text += `\n* ${TAPi18n.__('globalSearch-instructions-notes-5', tags)}`;
  387. return text;
  388. },
  389. labelColors() {
  390. return Boards.simpleSchema()._schema['labels.$.color'].allowedValues.map(
  391. color => {
  392. return { color, name: TAPi18n.__(`color-${color}`) };
  393. },
  394. );
  395. },
  396. events() {
  397. return [
  398. {
  399. 'submit .js-search-query-form'(evt) {
  400. evt.preventDefault();
  401. this.searchAllBoards(evt.target.searchQuery.value);
  402. },
  403. 'click .js-label-color'(evt) {
  404. evt.preventDefault();
  405. const input = document.getElementById('global-search-input');
  406. this.query.set(
  407. `${input.value} ${TAPi18n.__('operator-label')}:"${
  408. evt.currentTarget.textContent
  409. }"`,
  410. );
  411. document.getElementById('global-search-input').focus();
  412. },
  413. 'click .js-board-title'(evt) {
  414. evt.preventDefault();
  415. const input = document.getElementById('global-search-input');
  416. this.query.set(
  417. `${input.value} ${TAPi18n.__('operator-board')}:"${
  418. evt.currentTarget.textContent
  419. }"`,
  420. );
  421. document.getElementById('global-search-input').focus();
  422. },
  423. 'click .js-list-title'(evt) {
  424. evt.preventDefault();
  425. const input = document.getElementById('global-search-input');
  426. this.query.set(
  427. `${input.value} ${TAPi18n.__('operator-list')}:"${
  428. evt.currentTarget.textContent
  429. }"`,
  430. );
  431. document.getElementById('global-search-input').focus();
  432. },
  433. 'click .js-label-name'(evt) {
  434. evt.preventDefault();
  435. const input = document.getElementById('global-search-input');
  436. this.query.set(
  437. `${input.value} ${TAPi18n.__('operator-label')}:"${
  438. evt.currentTarget.textContent
  439. }"`,
  440. );
  441. document.getElementById('global-search-input').focus();
  442. },
  443. },
  444. ];
  445. },
  446. }).register('globalSearch');