globalSearch.js 20 KB

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