globalSearch.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658
  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.hasNextPage = new ReactiveVar(false);
  45. this.hasPreviousPage = new ReactiveVar(false);
  46. this.queryParams = null;
  47. this.parsingErrors = [];
  48. this.resultsCount = 0;
  49. this.totalHits = 0;
  50. this.queryErrors = null;
  51. this.colorMap = null;
  52. this.resultsPerPage = 25;
  53. Meteor.call('myLists', (err, data) => {
  54. if (!err) {
  55. this.myLists.set(data);
  56. }
  57. });
  58. Meteor.call('myLabelNames', (err, data) => {
  59. if (!err) {
  60. this.myLabelNames.set(data);
  61. }
  62. });
  63. Meteor.call('myBoardNames', (err, data) => {
  64. if (!err) {
  65. this.myBoardNames.set(data);
  66. }
  67. });
  68. },
  69. onRendered() {
  70. Meteor.subscribe('setting');
  71. this.colorMap = {};
  72. for (const color of Boards.simpleSchema()._schema['labels.$.color']
  73. .allowedValues) {
  74. this.colorMap[TAPi18n.__(`color-${color}`)] = color;
  75. }
  76. // // eslint-disable-next-line no-console
  77. // console.log('colorMap:', this.colorMap);
  78. if (Session.get('globalQuery')) {
  79. this.searchAllBoards(Session.get('globalQuery'));
  80. }
  81. },
  82. resetSearch() {
  83. this.searching.set(false);
  84. this.results.set([]);
  85. this.hasResults.set(false);
  86. this.hasQueryErrors.set(false);
  87. this.resultsHeading.set('');
  88. this.parsingErrors = [];
  89. this.resultsCount = 0;
  90. this.totalHits = 0;
  91. this.queryErrors = null;
  92. },
  93. getSessionData() {
  94. return SessionData.findOne({
  95. userId: Meteor.userId(),
  96. sessionId: SessionData.getSessionId(),
  97. });
  98. },
  99. getResults() {
  100. // eslint-disable-next-line no-console
  101. // console.log('getting results');
  102. if (this.queryParams) {
  103. const sessionData = this.getSessionData();
  104. // eslint-disable-next-line no-console
  105. console.log('selector:', sessionData.getSelector());
  106. // console.log('session data:', sessionData);
  107. const cards = Cards.find({ _id: { $in: sessionData.cards } });
  108. this.queryErrors = sessionData.errors;
  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.resultsStart = sessionData.lastHit - this.resultsCount + 1;
  117. this.resultsEnd = sessionData.lastHit;
  118. this.resultsHeading.set(this.getResultsHeading());
  119. this.results.set(cards);
  120. this.hasNextPage.set(sessionData.lastHit < sessionData.totalHits);
  121. this.hasPreviousPage.set(
  122. sessionData.lastHit - sessionData.resultsCount > 0,
  123. );
  124. }
  125. }
  126. this.resultsCount = 0;
  127. return null;
  128. },
  129. errorMessages() {
  130. if (this.parsingErrors.length) {
  131. return this.parsingErrorMessages();
  132. }
  133. return this.queryErrorMessages();
  134. },
  135. parsingErrorMessages() {
  136. const messages = [];
  137. if (this.parsingErrors.length) {
  138. this.parsingErrors.forEach(err => {
  139. messages.push(TAPi18n.__(err.tag, err.value));
  140. });
  141. }
  142. return messages;
  143. },
  144. queryErrorMessages() {
  145. messages = [];
  146. this.queryErrors.forEach(err => {
  147. let value = err.color ? TAPi18n.__(`color-${err.value}`) : err.value;
  148. if (!value) {
  149. value = err.value;
  150. }
  151. messages.push(TAPi18n.__(err.tag, value));
  152. });
  153. return messages;
  154. },
  155. searchAllBoards(query) {
  156. query = query.trim();
  157. // eslint-disable-next-line no-console
  158. console.log('query:', query);
  159. this.query.set(query);
  160. this.resetSearch();
  161. if (!query) {
  162. return;
  163. }
  164. this.searching.set(true);
  165. const reOperator1 = new RegExp(
  166. '^((?<operator>[\\p{Letter}\\p{Mark}]+):|(?<abbrev>[#@]))(?<value>[\\p{Letter}\\p{Mark}]+)(\\s+|$)',
  167. 'iu',
  168. );
  169. const reOperator2 = new RegExp(
  170. '^((?<operator>[\\p{Letter}\\p{Mark}]+):|(?<abbrev>[#@]))(?<quote>["\']*)(?<value>.*?)\\k<quote>(\\s+|$)',
  171. 'iu',
  172. );
  173. const reText = new RegExp('^(?<text>\\S+)(\\s+|$)', 'u');
  174. const reQuotedText = new RegExp(
  175. '^(?<quote>["\'])(?<text>.*?)\\k<quote>(\\s+|$)',
  176. 'u',
  177. );
  178. const operators = {
  179. 'operator-board': 'boards',
  180. 'operator-board-abbrev': 'boards',
  181. 'operator-swimlane': 'swimlanes',
  182. 'operator-swimlane-abbrev': 'swimlanes',
  183. 'operator-list': 'lists',
  184. 'operator-list-abbrev': 'lists',
  185. 'operator-label': 'labels',
  186. 'operator-label-abbrev': 'labels',
  187. 'operator-user': 'users',
  188. 'operator-user-abbrev': 'users',
  189. 'operator-member': 'members',
  190. 'operator-member-abbrev': 'members',
  191. 'operator-assignee': 'assignees',
  192. 'operator-assignee-abbrev': 'assignees',
  193. 'operator-status': 'status',
  194. 'operator-due': 'dueAt',
  195. 'operator-created': 'createdAt',
  196. 'operator-modified': 'modifiedAt',
  197. 'operator-comment': 'comments',
  198. };
  199. const predicates = {
  200. due: {
  201. 'predicate-overdue': 'overdue',
  202. },
  203. durations: {
  204. 'predicate-week': 'week',
  205. 'predicate-month': 'month',
  206. 'predicate-quarter': 'quarter',
  207. 'predicate-year': 'year',
  208. },
  209. status: {
  210. 'predicate-archived': 'archived',
  211. 'predicate-all': 'all',
  212. 'predicate-ended': 'ended',
  213. },
  214. sorts: {
  215. 'predicate-due': 'dueAt',
  216. 'predicate-created': 'createdAt',
  217. 'predicate-modified': 'modifiedAt',
  218. },
  219. };
  220. const predicateTranslations = {};
  221. Object.entries(predicates).forEach(([category, catPreds]) => {
  222. predicateTranslations[category] = {};
  223. Object.entries(catPreds).forEach(([tag, value]) => {
  224. predicateTranslations[category][TAPi18n.__(tag)] = value;
  225. });
  226. });
  227. // eslint-disable-next-line no-console
  228. // console.log('predicateTranslations:', predicateTranslations);
  229. const operatorMap = {};
  230. Object.entries(operators).forEach(([key, value]) => {
  231. operatorMap[TAPi18n.__(key).toLowerCase()] = value;
  232. });
  233. // eslint-disable-next-line no-console
  234. // console.log('operatorMap:', operatorMap);
  235. const params = {
  236. limit: this.resultsPerPage,
  237. boards: [],
  238. swimlanes: [],
  239. lists: [],
  240. users: [],
  241. members: [],
  242. assignees: [],
  243. labels: [],
  244. status: [],
  245. dueAt: null,
  246. createdAt: null,
  247. modifiedAt: null,
  248. comments: [],
  249. };
  250. let text = '';
  251. while (query) {
  252. m = query.match(reOperator1);
  253. if (!m) {
  254. m = query.match(reOperator2);
  255. if (m) {
  256. query = query.replace(reOperator2, '');
  257. }
  258. } else {
  259. query = query.replace(reOperator1, '');
  260. }
  261. if (m) {
  262. let op;
  263. if (m.groups.operator) {
  264. op = m.groups.operator.toLowerCase();
  265. } else {
  266. op = m.groups.abbrev;
  267. }
  268. if (operatorMap.hasOwnProperty(op)) {
  269. let value = m.groups.value;
  270. if (operatorMap[op] === 'labels') {
  271. if (value in this.colorMap) {
  272. value = this.colorMap[value];
  273. }
  274. } else if (
  275. ['dueAt', 'createdAt', 'modifiedAt'].includes(operatorMap[op])
  276. ) {
  277. let days = parseInt(value, 10);
  278. let duration = null;
  279. if (isNaN(days)) {
  280. if (predicateTranslations.durations[value]) {
  281. duration = predicateTranslations.durations[value];
  282. value = moment();
  283. } else if (predicateTranslations.due[value] === 'overdue') {
  284. value = moment();
  285. duration = 'days';
  286. days = 0;
  287. } else {
  288. this.parsingErrors.push({
  289. tag: 'operator-number-expected',
  290. value: { operator: op, value },
  291. });
  292. value = null;
  293. }
  294. } else {
  295. value = moment();
  296. }
  297. if (value) {
  298. if (operatorMap[op] === 'dueAt') {
  299. value = value.add(days, duration ? duration : 'days').format();
  300. } else {
  301. value = value
  302. .subtract(days, duration ? duration : 'days')
  303. .format();
  304. }
  305. }
  306. } else if (operatorMap[op] === 'sort') {
  307. if (!predicateTranslations.sorts[value]) {
  308. this.parsingErrors.push({
  309. tag: 'operator-sort-invalid',
  310. value,
  311. });
  312. } else {
  313. value = predicateTranslations.sorts[value];
  314. }
  315. } else if (operatorMap[op] === 'status') {
  316. if (!predicateTranslations.status[value]) {
  317. this.parsingErrors.push({
  318. tag: 'operator-status-invalid',
  319. value,
  320. });
  321. } else {
  322. value = predicateTranslations.status[value];
  323. }
  324. }
  325. if (Array.isArray(params[operatorMap[op]])) {
  326. params[operatorMap[op]].push(value);
  327. } else {
  328. params[operatorMap[op]] = value;
  329. }
  330. } else {
  331. this.parsingErrors.push({
  332. tag: 'operator-unknown-error',
  333. value: op,
  334. });
  335. }
  336. continue;
  337. }
  338. m = query.match(reQuotedText);
  339. if (!m) {
  340. m = query.match(reText);
  341. if (m) {
  342. query = query.replace(reText, '');
  343. }
  344. } else {
  345. query = query.replace(reQuotedText, '');
  346. }
  347. if (m) {
  348. text += (text ? ' ' : '') + m.groups.text;
  349. }
  350. }
  351. // eslint-disable-next-line no-console
  352. // console.log('text:', text);
  353. params.text = text;
  354. // eslint-disable-next-line no-console
  355. // console.log('params:', params);
  356. this.queryParams = params;
  357. if (this.parsingErrors.length) {
  358. this.searching.set(false);
  359. this.queryErrors = this.parsingErrorMessages();
  360. this.hasResults.set(true);
  361. this.hasQueryErrors.set(true);
  362. return;
  363. }
  364. this.autorun(() => {
  365. const handle = Meteor.subscribe(
  366. 'globalSearch',
  367. SessionData.getSessionId(),
  368. params,
  369. );
  370. Tracker.nonreactive(() => {
  371. Tracker.autorun(() => {
  372. if (handle.ready()) {
  373. this.getResults();
  374. this.searching.set(false);
  375. this.hasResults.set(true);
  376. }
  377. });
  378. });
  379. });
  380. },
  381. nextPage() {
  382. sessionData = this.getSessionData();
  383. const params = {
  384. limit: this.resultsPerPage,
  385. selector: sessionData.getSelector(),
  386. skip: sessionData.lastHit,
  387. };
  388. this.autorun(() => {
  389. const handle = Meteor.subscribe(
  390. 'globalSearch',
  391. SessionData.getSessionId(),
  392. params,
  393. );
  394. Tracker.nonreactive(() => {
  395. Tracker.autorun(() => {
  396. if (handle.ready()) {
  397. this.getResults();
  398. this.searching.set(false);
  399. this.hasResults.set(true);
  400. }
  401. });
  402. });
  403. });
  404. },
  405. previousPage() {
  406. sessionData = this.getSessionData();
  407. const params = {
  408. limit: this.resultsPerPage,
  409. selector: sessionData.getSelector(),
  410. skip:
  411. sessionData.lastHit - sessionData.resultsCount - this.resultsPerPage,
  412. };
  413. this.autorun(() => {
  414. const handle = Meteor.subscribe(
  415. 'globalSearch',
  416. SessionData.getSessionId(),
  417. params,
  418. );
  419. Tracker.nonreactive(() => {
  420. Tracker.autorun(() => {
  421. if (handle.ready()) {
  422. this.getResults();
  423. this.searching.set(false);
  424. this.hasResults.set(true);
  425. }
  426. });
  427. });
  428. });
  429. },
  430. getResultsHeading() {
  431. if (this.resultsCount === 0) {
  432. return TAPi18n.__('no-cards-found');
  433. } else if (this.resultsCount === 1) {
  434. return TAPi18n.__('one-card-found');
  435. } else if (this.resultsCount === this.totalHits) {
  436. return TAPi18n.__('n-cards-found', this.resultsCount);
  437. }
  438. return TAPi18n.__('n-n-of-n-cards-found', {
  439. start: this.resultsStart,
  440. end: this.resultsEnd,
  441. total: this.totalHits,
  442. });
  443. },
  444. getSearchHref() {
  445. const baseUrl = window.location.href.replace(/([?#].*$|\s*$)/, '');
  446. return `${baseUrl}?q=${encodeURIComponent(this.query.get())}`;
  447. },
  448. searchInstructions() {
  449. tags = {
  450. operator_board: TAPi18n.__('operator-board'),
  451. operator_list: TAPi18n.__('operator-list'),
  452. operator_swimlane: TAPi18n.__('operator-swimlane'),
  453. operator_comment: TAPi18n.__('operator-comment'),
  454. operator_label: TAPi18n.__('operator-label'),
  455. operator_label_abbrev: TAPi18n.__('operator-label-abbrev'),
  456. operator_user: TAPi18n.__('operator-user'),
  457. operator_user_abbrev: TAPi18n.__('operator-user-abbrev'),
  458. operator_member: TAPi18n.__('operator-member'),
  459. operator_member_abbrev: TAPi18n.__('operator-member-abbrev'),
  460. operator_assignee: TAPi18n.__('operator-assignee'),
  461. operator_assignee_abbrev: TAPi18n.__('operator-assignee-abbrev'),
  462. operator_due: TAPi18n.__('operator-due'),
  463. operator_created: TAPi18n.__('operator-created'),
  464. operator_modified: TAPi18n.__('operator-modified'),
  465. operator_status: TAPi18n.__('operator-status'),
  466. predicate_overdue: TAPi18n.__('predicate-overdue'),
  467. predicate_archived: TAPi18n.__('predicate-archived'),
  468. predicate_all: TAPi18n.__('predicate-all'),
  469. predicate_ended: TAPi18n.__('predicate-ended'),
  470. predicate_week: TAPi18n.__('predicate-week'),
  471. predicate_month: TAPi18n.__('predicate-month'),
  472. predicate_quarter: TAPi18n.__('predicate-quarter'),
  473. predicate_year: TAPi18n.__('predicate-year'),
  474. };
  475. text = `# ${TAPi18n.__('globalSearch-instructions-heading')}`;
  476. text += `\n${TAPi18n.__('globalSearch-instructions-description', tags)}`;
  477. text += `\n${TAPi18n.__('globalSearch-instructions-operators', tags)}`;
  478. text += `\n* ${TAPi18n.__(
  479. 'globalSearch-instructions-operator-board',
  480. tags,
  481. )}`;
  482. text += `\n* ${TAPi18n.__(
  483. 'globalSearch-instructions-operator-list',
  484. tags,
  485. )}`;
  486. text += `\n* ${TAPi18n.__(
  487. 'globalSearch-instructions-operator-swimlane',
  488. tags,
  489. )}`;
  490. text += `\n* ${TAPi18n.__(
  491. 'globalSearch-instructions-operator-comment',
  492. tags,
  493. )}`;
  494. text += `\n* ${TAPi18n.__(
  495. 'globalSearch-instructions-operator-label',
  496. tags,
  497. )}`;
  498. text += `\n* ${TAPi18n.__(
  499. 'globalSearch-instructions-operator-hash',
  500. tags,
  501. )}`;
  502. text += `\n* ${TAPi18n.__(
  503. 'globalSearch-instructions-operator-user',
  504. tags,
  505. )}`;
  506. text += `\n* ${TAPi18n.__('globalSearch-instructions-operator-at', tags)}`;
  507. text += `\n* ${TAPi18n.__(
  508. 'globalSearch-instructions-operator-member',
  509. tags,
  510. )}`;
  511. text += `\n* ${TAPi18n.__(
  512. 'globalSearch-instructions-operator-assignee',
  513. tags,
  514. )}`;
  515. text += `\n* ${TAPi18n.__('globalSearch-instructions-operator-due', tags)}`;
  516. text += `\n* ${TAPi18n.__(
  517. 'globalSearch-instructions-operator-created',
  518. tags,
  519. )}`;
  520. text += `\n* ${TAPi18n.__(
  521. 'globalSearch-instructions-operator-modified',
  522. tags,
  523. )}`;
  524. text += `\n* ${TAPi18n.__(
  525. 'globalSearch-instructions-status-archived',
  526. tags,
  527. )}`;
  528. text += `\n* ${TAPi18n.__('globalSearch-instructions-status-all', tags)}`;
  529. text += `\n* ${TAPi18n.__('globalSearch-instructions-status-ended', tags)}`;
  530. text += `\n## ${TAPi18n.__('heading-notes')}`;
  531. text += `\n* ${TAPi18n.__('globalSearch-instructions-notes-1', tags)}`;
  532. text += `\n* ${TAPi18n.__('globalSearch-instructions-notes-2', tags)}`;
  533. text += `\n* ${TAPi18n.__('globalSearch-instructions-notes-3', tags)}`;
  534. text += `\n* ${TAPi18n.__('globalSearch-instructions-notes-3-2', tags)}`;
  535. text += `\n* ${TAPi18n.__('globalSearch-instructions-notes-4', tags)}`;
  536. text += `\n* ${TAPi18n.__('globalSearch-instructions-notes-5', tags)}`;
  537. return text;
  538. },
  539. labelColors() {
  540. return Boards.simpleSchema()._schema['labels.$.color'].allowedValues.map(
  541. color => {
  542. return { color, name: TAPi18n.__(`color-${color}`) };
  543. },
  544. );
  545. },
  546. events() {
  547. return [
  548. {
  549. 'submit .js-search-query-form'(evt) {
  550. evt.preventDefault();
  551. this.searchAllBoards(evt.target.searchQuery.value);
  552. },
  553. 'click .js-next-page'(evt) {
  554. evt.preventDefault();
  555. this.nextPage();
  556. },
  557. 'click .js-previous-page'(evt) {
  558. evt.preventDefault();
  559. this.previousPage();
  560. },
  561. 'click .js-label-color'(evt) {
  562. evt.preventDefault();
  563. const input = document.getElementById('global-search-input');
  564. this.query.set(
  565. `${input.value} ${TAPi18n.__('operator-label')}:"${
  566. evt.currentTarget.textContent
  567. }"`,
  568. );
  569. document.getElementById('global-search-input').focus();
  570. },
  571. 'click .js-board-title'(evt) {
  572. evt.preventDefault();
  573. const input = document.getElementById('global-search-input');
  574. this.query.set(
  575. `${input.value} ${TAPi18n.__('operator-board')}:"${
  576. evt.currentTarget.textContent
  577. }"`,
  578. );
  579. document.getElementById('global-search-input').focus();
  580. },
  581. 'click .js-list-title'(evt) {
  582. evt.preventDefault();
  583. const input = document.getElementById('global-search-input');
  584. this.query.set(
  585. `${input.value} ${TAPi18n.__('operator-list')}:"${
  586. evt.currentTarget.textContent
  587. }"`,
  588. );
  589. document.getElementById('global-search-input').focus();
  590. },
  591. 'click .js-label-name'(evt) {
  592. evt.preventDefault();
  593. const input = document.getElementById('global-search-input');
  594. this.query.set(
  595. `${input.value} ${TAPi18n.__('operator-label')}:"${
  596. evt.currentTarget.textContent
  597. }"`,
  598. );
  599. document.getElementById('global-search-input').focus();
  600. },
  601. },
  602. ];
  603. },
  604. }).register('globalSearch');