globalSearch.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525
  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>[\w\p{L}]+):|(?<abbrev>[#@]))(?<value>[\w\p{L}]+)(\s+|$)/iu;
  153. const reOperator2 = /^((?<operator>[\w\p{L}]+):|(?<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-is': 'is',
  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. 'predicate-day': 'day',
  181. 'predicate-week': 'week',
  182. 'predicate-month': 'month',
  183. 'predicate-quarter': 'quarter',
  184. 'predicate-year': 'year',
  185. },
  186. date: {
  187. 'predicate-day': 'day',
  188. 'predicate-week': 'week',
  189. 'predicate-month': 'month',
  190. 'predicate-quarter': 'quarter',
  191. 'predicate-year': 'year',
  192. },
  193. is: {
  194. 'predicate-archived': 'archived',
  195. 'predicate-active': 'active',
  196. },
  197. };
  198. const predicateTranslations = {};
  199. Object.entries(predicates, ([category, predicates]) => {
  200. predicateTranslations[category] = {};
  201. Object.entries(predicates, ([tag, value]) => {
  202. predicateTranslations[category][TAPi18n.__(tag)] = value;
  203. });
  204. });
  205. const operatorMap = {};
  206. Object.entries(operators).forEach(([key, value]) => {
  207. operatorMap[TAPi18n.__(key).toLowerCase()] = value;
  208. });
  209. // eslint-disable-next-line no-console
  210. // console.log('operatorMap:', operatorMap);
  211. const params = {
  212. boards: [],
  213. swimlanes: [],
  214. lists: [],
  215. users: [],
  216. members: [],
  217. assignees: [],
  218. labels: [],
  219. is: [],
  220. dueAt: null,
  221. createdAt: null,
  222. modifiedAt: null,
  223. comments: [],
  224. };
  225. let text = '';
  226. while (query) {
  227. m = query.match(reOperator1);
  228. if (!m) {
  229. m = query.match(reOperator2);
  230. if (m) {
  231. query = query.replace(reOperator2, '');
  232. }
  233. } else {
  234. query = query.replace(reOperator1, '');
  235. }
  236. if (m) {
  237. let op;
  238. if (m.groups.operator) {
  239. op = m.groups.operator.toLowerCase();
  240. } else {
  241. op = m.groups.abbrev;
  242. }
  243. if (operatorMap.hasOwnProperty(op)) {
  244. let value = m.groups.value;
  245. if (operatorMap[op] === 'labels') {
  246. if (value in this.colorMap) {
  247. value = this.colorMap[value];
  248. }
  249. } else if (
  250. ['dueAt', 'createdAt', 'modifiedAt'].includes(operatorMap[op])
  251. ) {
  252. let days = parseInt(value, 10);
  253. let duration = null;
  254. if (isNaN(days)) {
  255. if (predicateTranslations.date.keys().includes(value)) {
  256. duration = predicateTranslations.date[value];
  257. value = moment();
  258. } else if (predicateTranslations.due[value] === 'overdue') {
  259. value = moment();
  260. duration = 'days';
  261. days = 0;
  262. } else {
  263. this.parsingErrors.push({
  264. tag: 'operator-number-expected',
  265. value: { operator: op, value },
  266. });
  267. value = null;
  268. }
  269. } else {
  270. value = moment();
  271. }
  272. if (value) {
  273. if (operatorMap[op] === 'dueAt') {
  274. value = value.add(days, duration ? duration : 'days').format();
  275. } else {
  276. value = value
  277. .subtract(days, duration ? duration : 'days')
  278. .format();
  279. }
  280. }
  281. } else if (operatorMap[op] === 'sort') {
  282. if (!['due', 'modified', 'created', 'system'].includes(value)) {
  283. this.parsingErrors.push({
  284. tag: 'operator-sort-invalid',
  285. value,
  286. });
  287. }
  288. }
  289. if (Array.isArray(params[operatorMap[op]])) {
  290. params[operatorMap[op]].push(value);
  291. } else {
  292. params[operatorMap[op]] = value;
  293. }
  294. } else {
  295. this.parsingErrors.push({
  296. tag: 'operator-unknown-error',
  297. value: op,
  298. });
  299. }
  300. continue;
  301. }
  302. m = query.match(reQuotedText);
  303. if (!m) {
  304. m = query.match(reText);
  305. if (m) {
  306. query = query.replace(reText, '');
  307. }
  308. } else {
  309. query = query.replace(reQuotedText, '');
  310. }
  311. if (m) {
  312. text += (text ? ' ' : '') + m.groups.text;
  313. }
  314. }
  315. // eslint-disable-next-line no-console
  316. // console.log('text:', text);
  317. params.text = text;
  318. // eslint-disable-next-line no-console
  319. // console.log('params:', params);
  320. this.queryParams = params;
  321. if (this.parsingErrors.length) {
  322. this.searching.set(false);
  323. this.queryErrors = this.parsingErrorMessages();
  324. this.hasQueryErrors.set(true);
  325. return;
  326. }
  327. this.autorun(() => {
  328. const handle = subManager.subscribe(
  329. 'globalSearch',
  330. SessionData.getSessionId(),
  331. params,
  332. );
  333. Tracker.nonreactive(() => {
  334. Tracker.autorun(() => {
  335. if (handle.ready()) {
  336. this.getResults();
  337. this.searching.set(false);
  338. this.hasResults.set(true);
  339. }
  340. });
  341. });
  342. });
  343. },
  344. getResultsHeading() {
  345. if (this.resultsCount === 0) {
  346. return TAPi18n.__('no-cards-found');
  347. } else if (this.resultsCount === 1) {
  348. return TAPi18n.__('one-card-found');
  349. } else if (this.resultsCount === this.totalHits) {
  350. return TAPi18n.__('n-cards-found', this.resultsCount);
  351. }
  352. return TAPi18n.__('n-n-of-n-cards-found', {
  353. start: 1,
  354. end: this.resultsCount,
  355. total: this.totalHits,
  356. });
  357. },
  358. getSearchHref() {
  359. const baseUrl = window.location.href.replace(/([?#].*$|\s*$)/, '');
  360. return `${baseUrl}?q=${encodeURIComponent(this.query.get())}`;
  361. },
  362. searchInstructions() {
  363. tags = {
  364. operator_board: TAPi18n.__('operator-board'),
  365. operator_list: TAPi18n.__('operator-list'),
  366. operator_swimlane: TAPi18n.__('operator-swimlane'),
  367. operator_label: TAPi18n.__('operator-label'),
  368. operator_label_abbrev: TAPi18n.__('operator-label-abbrev'),
  369. operator_user: TAPi18n.__('operator-user'),
  370. operator_user_abbrev: TAPi18n.__('operator-user-abbrev'),
  371. operator_member: TAPi18n.__('operator-member'),
  372. operator_member_abbrev: TAPi18n.__('operator-member-abbrev'),
  373. operator_assignee: TAPi18n.__('operator-assignee'),
  374. operator_assignee_abbrev: TAPi18n.__('operator-assignee-abbrev'),
  375. };
  376. text = `# ${TAPi18n.__('globalSearch-instructions-heading')}`;
  377. text += `\n${TAPi18n.__('globalSearch-instructions-description', tags)}`;
  378. text += `\n${TAPi18n.__('globalSearch-instructions-operators', tags)}`;
  379. text += `\n* ${TAPi18n.__(
  380. 'globalSearch-instructions-operator-board',
  381. tags,
  382. )}`;
  383. text += `\n* ${TAPi18n.__(
  384. 'globalSearch-instructions-operator-list',
  385. tags,
  386. )}`;
  387. text += `\n* ${TAPi18n.__(
  388. 'globalSearch-instructions-operator-swimlane',
  389. tags,
  390. )}`;
  391. text += `\n* ${TAPi18n.__(
  392. 'globalSearch-instructions-operator-label',
  393. tags,
  394. )}`;
  395. text += `\n* ${TAPi18n.__(
  396. 'globalSearch-instructions-operator-hash',
  397. tags,
  398. )}`;
  399. text += `\n* ${TAPi18n.__(
  400. 'globalSearch-instructions-operator-user',
  401. tags,
  402. )}`;
  403. text += `\n* ${TAPi18n.__('globalSearch-instructions-operator-at', tags)}`;
  404. text += `\n* ${TAPi18n.__(
  405. 'globalSearch-instructions-operator-member',
  406. tags,
  407. )}`;
  408. text += `\n* ${TAPi18n.__(
  409. 'globalSearch-instructions-operator-assignee',
  410. tags,
  411. )}`;
  412. text += `\n## ${TAPi18n.__('heading-notes')}`;
  413. text += `\n* ${TAPi18n.__('globalSearch-instructions-notes-1', tags)}`;
  414. text += `\n* ${TAPi18n.__('globalSearch-instructions-notes-2', tags)}`;
  415. text += `\n* ${TAPi18n.__('globalSearch-instructions-notes-3', tags)}`;
  416. text += `\n* ${TAPi18n.__('globalSearch-instructions-notes-4', tags)}`;
  417. text += `\n* ${TAPi18n.__('globalSearch-instructions-notes-5', tags)}`;
  418. return text;
  419. },
  420. labelColors() {
  421. return Boards.simpleSchema()._schema['labels.$.color'].allowedValues.map(
  422. color => {
  423. return { color, name: TAPi18n.__(`color-${color}`) };
  424. },
  425. );
  426. },
  427. events() {
  428. return [
  429. {
  430. 'submit .js-search-query-form'(evt) {
  431. evt.preventDefault();
  432. this.searchAllBoards(evt.target.searchQuery.value);
  433. },
  434. 'click .js-label-color'(evt) {
  435. evt.preventDefault();
  436. const input = document.getElementById('global-search-input');
  437. this.query.set(
  438. `${input.value} ${TAPi18n.__('operator-label')}:"${
  439. evt.currentTarget.textContent
  440. }"`,
  441. );
  442. document.getElementById('global-search-input').focus();
  443. },
  444. 'click .js-board-title'(evt) {
  445. evt.preventDefault();
  446. const input = document.getElementById('global-search-input');
  447. this.query.set(
  448. `${input.value} ${TAPi18n.__('operator-board')}:"${
  449. evt.currentTarget.textContent
  450. }"`,
  451. );
  452. document.getElementById('global-search-input').focus();
  453. },
  454. 'click .js-list-title'(evt) {
  455. evt.preventDefault();
  456. const input = document.getElementById('global-search-input');
  457. this.query.set(
  458. `${input.value} ${TAPi18n.__('operator-list')}:"${
  459. evt.currentTarget.textContent
  460. }"`,
  461. );
  462. document.getElementById('global-search-input').focus();
  463. },
  464. 'click .js-label-name'(evt) {
  465. evt.preventDefault();
  466. const input = document.getElementById('global-search-input');
  467. this.query.set(
  468. `${input.value} ${TAPi18n.__('operator-label')}:"${
  469. evt.currentTarget.textContent
  470. }"`,
  471. );
  472. document.getElementById('global-search-input').focus();
  473. },
  474. },
  475. ];
  476. },
  477. }).register('globalSearch');