globalSearch.js 19 KB

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