globalSearch.js 17 KB

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