globalSearch.js 19 KB

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