globalSearch.js 14 KB

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