globalSearch.js 14 KB

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