globalSearch.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486
  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.queryParams = null;
  44. this.parsingErrors = [];
  45. this.resultsCount = 0;
  46. this.totalHits = 0;
  47. this.queryErrors = null;
  48. this.colorMap = null;
  49. // this.colorMap = {};
  50. // for (const color of Boards.simpleSchema()._schema['labels.$.color']
  51. // .allowedValues) {
  52. // this.colorMap[TAPi18n.__(`color-${color}`)] = color;
  53. // }
  54. // // eslint-disable-next-line no-console
  55. // console.log('colorMap:', this.colorMap);
  56. Meteor.call('myLists', (err, data) => {
  57. if (!err) {
  58. this.myLists.set(data);
  59. }
  60. });
  61. Meteor.call('myLabelNames', (err, data) => {
  62. if (!err) {
  63. this.myLabelNames.set(data);
  64. }
  65. });
  66. Meteor.call('myBoardNames', (err, data) => {
  67. if (!err) {
  68. this.myBoardNames.set(data);
  69. }
  70. });
  71. Meteor.subscribe('setting');
  72. if (Session.get('globalQuery')) {
  73. this.searchAllBoards(Session.get('globalQuery'));
  74. }
  75. },
  76. resetSearch() {
  77. this.searching.set(false);
  78. this.hasResults.set(false);
  79. this.hasQueryErrors.set(false);
  80. this.resultsHeading.set('');
  81. this.parsingErrors = [];
  82. this.resultsCount = 0;
  83. this.totalHits = 0;
  84. this.queryErrors = null;
  85. },
  86. results() {
  87. // eslint-disable-next-line no-console
  88. // console.log('getting results');
  89. if (this.queryParams) {
  90. const results = Cards.globalSearch(this.queryParams);
  91. this.queryErrors = results.errors;
  92. // eslint-disable-next-line no-console
  93. // console.log('errors:', this.queryErrors);
  94. if (this.errorMessages().length) {
  95. this.hasQueryErrors.set(true);
  96. return null;
  97. }
  98. if (results.cards) {
  99. const sessionData = SessionData.findOne({ userId: Meteor.userId() });
  100. this.totalHits = sessionData.totalHits;
  101. this.resultsCount = results.cards.count();
  102. this.resultsHeading.set(this.getResultsHeading());
  103. return results.cards;
  104. }
  105. }
  106. this.resultsCount = 0;
  107. return [];
  108. },
  109. errorMessages() {
  110. const messages = [];
  111. if (this.queryErrors) {
  112. this.queryErrors.notFound.boards.forEach(board => {
  113. messages.push({ tag: 'board-title-not-found', value: board });
  114. });
  115. this.queryErrors.notFound.swimlanes.forEach(swim => {
  116. messages.push({ tag: 'swimlane-title-not-found', value: swim });
  117. });
  118. this.queryErrors.notFound.lists.forEach(list => {
  119. messages.push({ tag: 'list-title-not-found', value: list });
  120. });
  121. this.queryErrors.notFound.labels.forEach(label => {
  122. const color = Object.entries(this.colorMap)
  123. .filter(value => value[1] === label)
  124. .map(value => value[0]);
  125. if (color.length) {
  126. messages.push({
  127. tag: 'label-color-not-found',
  128. value: color[0],
  129. });
  130. } else {
  131. messages.push({ tag: 'label-not-found', value: label });
  132. }
  133. });
  134. this.queryErrors.notFound.users.forEach(user => {
  135. messages.push({ tag: 'user-username-not-found', value: user });
  136. });
  137. this.queryErrors.notFound.members.forEach(user => {
  138. messages.push({ tag: 'user-username-not-found', value: user });
  139. });
  140. this.queryErrors.notFound.assignees.forEach(user => {
  141. messages.push({ tag: 'user-username-not-found', value: user });
  142. });
  143. }
  144. if (this.parsingErrors.length) {
  145. this.parsingErrors.forEach(err => {
  146. messages.push(err);
  147. });
  148. }
  149. return messages;
  150. },
  151. searchAllBoards(query) {
  152. query = query.trim();
  153. this.query.set(query);
  154. this.resetSearch();
  155. if (!query) {
  156. return;
  157. }
  158. // eslint-disable-next-line no-console
  159. // console.log('query:', query);
  160. this.searching.set(true);
  161. if (!this.colorMap) {
  162. this.colorMap = {};
  163. for (const color of Boards.simpleSchema()._schema['labels.$.color']
  164. .allowedValues) {
  165. this.colorMap[TAPi18n.__(`color-${color}`)] = color;
  166. }
  167. }
  168. const reOperator1 = /^((?<operator>\w+):|(?<abbrev>[#@]))(?<value>\w+)(\s+|$)/;
  169. const reOperator2 = /^((?<operator>\w+):|(?<abbrev>[#@]))(?<quote>["']*)(?<value>.*?)\k<quote>(\s+|$)/;
  170. const reText = /^(?<text>\S+)(\s+|$)/;
  171. const reQuotedText = /^(?<quote>["'])(?<text>\w+)\k<quote>(\s+|$)/;
  172. const operatorMap = {};
  173. operatorMap[TAPi18n.__('operator-board')] = 'boards';
  174. operatorMap[TAPi18n.__('operator-board-abbrev')] = 'boards';
  175. operatorMap[TAPi18n.__('operator-swimlane')] = 'swimlanes';
  176. operatorMap[TAPi18n.__('operator-swimlane-abbrev')] = 'swimlanes';
  177. operatorMap[TAPi18n.__('operator-list')] = 'lists';
  178. operatorMap[TAPi18n.__('operator-list-abbrev')] = 'lists';
  179. operatorMap[TAPi18n.__('operator-label')] = 'labels';
  180. operatorMap[TAPi18n.__('operator-label-abbrev')] = 'labels';
  181. operatorMap[TAPi18n.__('operator-user')] = 'users';
  182. operatorMap[TAPi18n.__('operator-user-abbrev')] = 'users';
  183. operatorMap[TAPi18n.__('operator-member')] = 'members';
  184. operatorMap[TAPi18n.__('operator-member-abbrev')] = 'members';
  185. operatorMap[TAPi18n.__('operator-assignee')] = 'assignees';
  186. operatorMap[TAPi18n.__('operator-assignee-abbrev')] = 'assignees';
  187. operatorMap[TAPi18n.__('operator-is')] = 'is';
  188. operatorMap[TAPi18n.__('operator-due')] = 'dueAt';
  189. operatorMap[TAPi18n.__('operator-created')] = 'createdAt';
  190. operatorMap[TAPi18n.__('operator-modified')] = 'modifiedAt';
  191. operatorMap[TAPi18n.__('operator-sort')] = 'sort';
  192. // eslint-disable-next-line no-console
  193. console.log('operatorMap:', operatorMap);
  194. const params = {
  195. boards: [],
  196. swimlanes: [],
  197. lists: [],
  198. users: [],
  199. members: [],
  200. assignees: [],
  201. labels: [],
  202. is: [],
  203. dueAt: null,
  204. createdAt: null,
  205. modifiedAt: null,
  206. };
  207. let text = '';
  208. while (query) {
  209. m = query.match(reOperator1);
  210. if (!m) {
  211. m = query.match(reOperator2);
  212. if (m) {
  213. query = query.replace(reOperator2, '');
  214. }
  215. } else {
  216. query = query.replace(reOperator1, '');
  217. }
  218. if (m) {
  219. let op;
  220. if (m.groups.operator) {
  221. op = m.groups.operator.toLowerCase();
  222. } else {
  223. op = m.groups.abbrev;
  224. }
  225. if (op in operatorMap) {
  226. let value = m.groups.value;
  227. if (operatorMap[op] === 'labels') {
  228. if (value in this.colorMap) {
  229. value = this.colorMap[value];
  230. }
  231. } else if (
  232. ['dueAt', 'createdAt', 'modifiedAt'].includes(operatorMap[op])
  233. ) {
  234. let days = parseInt(value, 10);
  235. let duration = null;
  236. if (isNaN(days)) {
  237. if (['day', 'week', 'month', 'quarter', 'year'].includes(value)) {
  238. duration = value;
  239. value = moment();
  240. } else if (value === 'overdue') {
  241. value = moment();
  242. duration = 'days';
  243. days = 0;
  244. } else {
  245. this.parsingErrors.push({
  246. tag: 'operator-number-expected',
  247. value: { operator: op, value },
  248. });
  249. value = null;
  250. }
  251. } else {
  252. value = moment();
  253. }
  254. if (value) {
  255. if (operatorMap[op] === 'dueAt') {
  256. value = value.add(days, duration ? duration : 'days').format();
  257. } else {
  258. value = value
  259. .subtract(days, duration ? duration : 'days')
  260. .format();
  261. }
  262. }
  263. } else if (operatorMap[op] === 'sort') {
  264. if (!['due', 'modified', 'created', 'system'].includes(value)) {
  265. this.parsingErrors.push({
  266. tag: 'operator-sort-invalid',
  267. value,
  268. });
  269. }
  270. }
  271. if (Array.isArray(params[operatorMap[op]])) {
  272. params[operatorMap[op]].push(value);
  273. } else {
  274. params[operatorMap[op]] = value;
  275. }
  276. } else {
  277. this.parsingErrors.push({
  278. tag: 'operator-unknown-error',
  279. value: op,
  280. });
  281. }
  282. continue;
  283. }
  284. m = query.match(reQuotedText);
  285. if (!m) {
  286. m = query.match(reText);
  287. if (m) {
  288. query = query.replace(reText, '');
  289. }
  290. } else {
  291. query = query.replace(reQuotedText, '');
  292. }
  293. if (m) {
  294. text += (text ? ' ' : '') + m.groups.text;
  295. }
  296. }
  297. // eslint-disable-next-line no-console
  298. // console.log('text:', text);
  299. params.text = text;
  300. // eslint-disable-next-line no-console
  301. // console.log('params:', params);
  302. this.queryParams = params;
  303. this.autorun(() => {
  304. const handle = subManager.subscribe('globalSearch', params);
  305. Tracker.nonreactive(() => {
  306. Tracker.autorun(() => {
  307. // eslint-disable-next-line no-console
  308. // console.log('ready:', handle.ready());
  309. if (handle.ready()) {
  310. this.searching.set(false);
  311. this.hasResults.set(true);
  312. }
  313. });
  314. });
  315. });
  316. },
  317. getResultsHeading() {
  318. if (this.resultsCount === 0) {
  319. return TAPi18n.__('no-cards-found');
  320. } else if (this.resultsCount === 1) {
  321. return TAPi18n.__('one-card-found');
  322. } else if (this.resultsCount === this.totalHits) {
  323. return TAPi18n.__('n-cards-found', this.resultsCount);
  324. }
  325. return TAPi18n.__('n-n-of-n-cards-found', {
  326. start: 1,
  327. end: this.resultsCount,
  328. total: this.totalHits,
  329. });
  330. },
  331. getSearchHref() {
  332. const baseUrl = window.location.href.replace(/([?#].*$|\s*$)/, '');
  333. return `${baseUrl}?q=${encodeURIComponent(this.query.get())}`;
  334. },
  335. searchInstructions() {
  336. tags = {
  337. operator_board: TAPi18n.__('operator-board'),
  338. operator_list: TAPi18n.__('operator-list'),
  339. operator_swimlane: TAPi18n.__('operator-swimlane'),
  340. operator_label: TAPi18n.__('operator-label'),
  341. operator_label_abbrev: TAPi18n.__('operator-label-abbrev'),
  342. operator_user: TAPi18n.__('operator-user'),
  343. operator_user_abbrev: TAPi18n.__('operator-user-abbrev'),
  344. operator_member: TAPi18n.__('operator-member'),
  345. operator_member_abbrev: TAPi18n.__('operator-member-abbrev'),
  346. operator_assignee: TAPi18n.__('operator-assignee'),
  347. operator_assignee_abbrev: TAPi18n.__('operator-assignee-abbrev'),
  348. };
  349. text = `# ${TAPi18n.__('globalSearch-instructions-heading')}`;
  350. text += `\n${TAPi18n.__('globalSearch-instructions-description', tags)}`;
  351. text += `\n${TAPi18n.__('globalSearch-instructions-operators', tags)}`;
  352. text += `\n* ${TAPi18n.__(
  353. 'globalSearch-instructions-operator-board',
  354. tags,
  355. )}`;
  356. text += `\n* ${TAPi18n.__(
  357. 'globalSearch-instructions-operator-list',
  358. tags,
  359. )}`;
  360. text += `\n* ${TAPi18n.__(
  361. 'globalSearch-instructions-operator-swimlane',
  362. tags,
  363. )}`;
  364. text += `\n* ${TAPi18n.__(
  365. 'globalSearch-instructions-operator-label',
  366. tags,
  367. )}`;
  368. text += `\n* ${TAPi18n.__(
  369. 'globalSearch-instructions-operator-hash',
  370. tags,
  371. )}`;
  372. text += `\n* ${TAPi18n.__(
  373. 'globalSearch-instructions-operator-user',
  374. tags,
  375. )}`;
  376. text += `\n* ${TAPi18n.__('globalSearch-instructions-operator-at', tags)}`;
  377. text += `\n* ${TAPi18n.__(
  378. 'globalSearch-instructions-operator-member',
  379. tags,
  380. )}`;
  381. text += `\n* ${TAPi18n.__(
  382. 'globalSearch-instructions-operator-assignee',
  383. tags,
  384. )}`;
  385. text += `\n## ${TAPi18n.__('heading-notes')}`;
  386. text += `\n* ${TAPi18n.__('globalSearch-instructions-notes-1', tags)}`;
  387. text += `\n* ${TAPi18n.__('globalSearch-instructions-notes-2', tags)}`;
  388. text += `\n* ${TAPi18n.__('globalSearch-instructions-notes-3', tags)}`;
  389. text += `\n* ${TAPi18n.__('globalSearch-instructions-notes-4', tags)}`;
  390. text += `\n* ${TAPi18n.__('globalSearch-instructions-notes-5', tags)}`;
  391. return text;
  392. },
  393. labelColors() {
  394. return Boards.simpleSchema()._schema['labels.$.color'].allowedValues.map(
  395. color => {
  396. return { color, name: TAPi18n.__(`color-${color}`) };
  397. },
  398. );
  399. },
  400. events() {
  401. return [
  402. {
  403. 'submit .js-search-query-form'(evt) {
  404. evt.preventDefault();
  405. this.searchAllBoards(evt.target.searchQuery.value);
  406. },
  407. 'click .js-label-color'(evt) {
  408. evt.preventDefault();
  409. this.query.set(
  410. `${this.query.get()} ${TAPi18n.__('operator-label')}:"${
  411. evt.currentTarget.textContent
  412. }"`,
  413. );
  414. document.getElementById('global-search-input').focus();
  415. },
  416. 'click .js-board-title'(evt) {
  417. evt.preventDefault();
  418. this.query.set(
  419. `${this.query.get()} ${TAPi18n.__('operator-board')}:"${
  420. evt.currentTarget.textContent
  421. }"`,
  422. );
  423. document.getElementById('global-search-input').focus();
  424. },
  425. 'click .js-list-title'(evt) {
  426. evt.preventDefault();
  427. this.query.set(
  428. `${this.query.get()} ${TAPi18n.__('operator-list')}:"${
  429. evt.currentTarget.textContent
  430. }"`,
  431. );
  432. document.getElementById('global-search-input').focus();
  433. },
  434. 'click .js-label-name'(evt) {
  435. evt.preventDefault();
  436. this.query.set(
  437. `${this.query.get()} ${TAPi18n.__('operator-label')}:"${
  438. evt.currentTarget.textContent
  439. }"`,
  440. );
  441. document.getElementById('global-search-input').focus();
  442. },
  443. },
  444. ];
  445. },
  446. }).register('globalSearch');