filter.js 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800
  1. import { ReactiveCache } from '/imports/reactiveCache';
  2. import moment from 'moment/min/moment-with-locales';
  3. // Filtered view manager
  4. // We define local filter objects for each different type of field (SetFilter,
  5. // RangeFilter, dateFilter, etc.). We then define a global `Filter` object whose
  6. // goal is to filter complete documents by using the local filters for each
  7. // fields.
  8. function showFilterSidebar() {
  9. Sidebar.setView('filter');
  10. }
  11. class DateFilter {
  12. constructor() {
  13. this._dep = new Tracker.Dependency();
  14. this.subField = ''; // Prevent name mangling in Filter
  15. this._filter = null;
  16. this._filterState = null;
  17. }
  18. _updateState(state) {
  19. this._filterState = state;
  20. showFilterSidebar();
  21. this._dep.changed();
  22. }
  23. // past builds a filter for all dates before now
  24. past() {
  25. if (this._filterState == 'past') {
  26. this.reset();
  27. return;
  28. }
  29. this._filter = { $lte: moment().toDate() };
  30. this._updateState('past');
  31. }
  32. // today is a convenience method for calling relativeDay with 0
  33. today() {
  34. if (this._filterState == 'today') {
  35. this.reset();
  36. return;
  37. }
  38. this.relativeDay(0);
  39. this._updateState('today');
  40. }
  41. // tomorrow is a convenience method for calling relativeDay with 1
  42. tomorrow() {
  43. if (this._filterState == 'tomorrow') {
  44. this.reset();
  45. return;
  46. }
  47. this.relativeDay(1);
  48. this._updateState('tomorrow');
  49. }
  50. // thisWeek is a convenience method for calling relativeWeek with 1
  51. thisWeek() {
  52. this.relativeWeek(1, 'this')
  53. }
  54. // nextWeek is a convenience method for calling relativeWeek with 1
  55. nextWeek() {
  56. this.relativeWeek(1, 'next')
  57. }
  58. // relativeDay builds a filter starting from now and including all
  59. // days up to today +/- offset.
  60. relativeDay(offset) {
  61. if (this._filterState == 'day') {
  62. this.reset();
  63. return;
  64. }
  65. var startDay = moment()
  66. .startOf('day')
  67. .toDate(),
  68. endDay = moment()
  69. .endOf('day')
  70. .add(offset, 'day')
  71. .toDate();
  72. if (offset >= 0) {
  73. this._filter = { $gte: startDay, $lte: endDay };
  74. } else {
  75. this._filter = { $lte: startDay, $gte: endDay };
  76. }
  77. this._updateState('day');
  78. }
  79. // relativeWeek builds a filter starting from today (for this week)
  80. // or 7 days after (for next week) and including all
  81. // weeks up to today +/- offset. This considers the user's preferred
  82. // start of week day (as defined by Meteor).
  83. relativeWeek(offset, week) {
  84. if (this._filterState == 'thisweek') {
  85. this.reset();
  86. return;
  87. }
  88. if (this._filterState == 'nextweek') {
  89. this.reset();
  90. return;
  91. }
  92. // getStartDayOfWeek returns the offset from Sunday of the user's
  93. // preferred starting day of the week. This date should be added
  94. // to the moment start of week to get the real start of week date.
  95. // The default is 1, meaning Monday.
  96. const currentUser = ReactiveCache.getCurrentUser();
  97. const weekStartDay = currentUser ? currentUser.getStartDayOfWeek() : 1;
  98. if (week === 'this') {
  99. // Moments are mutable so they must be cloned before modification
  100. var WeekStart = moment()
  101. .startOf('day')
  102. .startOf('week')
  103. .add(weekStartDay, 'days');
  104. var WeekEnd = WeekStart
  105. .clone()
  106. .add(6, 'days')
  107. .endOf('day');
  108. this._updateState('thisweek');
  109. } else if (week === 'next') {
  110. // Moments are mutable so they must be cloned before modification
  111. var WeekStart = moment()
  112. .startOf('day')
  113. .startOf('week')
  114. .add(weekStartDay + 7, 'days');
  115. var WeekEnd = WeekStart
  116. .clone()
  117. .add(6, 'days')
  118. .endOf('day');
  119. this._updateState('nextweek');
  120. }
  121. var startDate = WeekStart.toDate();
  122. var endDate = WeekEnd.toDate();
  123. if (offset >= 0) {
  124. this._filter = { $gte: startDate, $lte: endDate };
  125. } else {
  126. this._filter = { $lte: startDate, $gte: endDate };
  127. }
  128. }
  129. // noDate builds a filter for items where date is not set
  130. noDate() {
  131. if (this._filterState == 'noDate') {
  132. this.reset();
  133. return;
  134. }
  135. this._filter = null;
  136. this._updateState('noDate');
  137. }
  138. reset() {
  139. this._filter = null;
  140. this._filterState = null;
  141. this._dep.changed();
  142. }
  143. isSelected(val) {
  144. this._dep.depend();
  145. return this._filterState == val;
  146. }
  147. _isActive() {
  148. this._dep.depend();
  149. return this._filterState !== null;
  150. }
  151. _getMongoSelector() {
  152. this._dep.depend();
  153. return this._filter;
  154. }
  155. _getEmptySelector() {
  156. this._dep.depend();
  157. return null;
  158. }
  159. }
  160. class StringFilter {
  161. constructor() {
  162. this._dep = new Tracker.Dependency();
  163. this.subField = ''; // Prevent name mangling in Filter
  164. this._filter = '';
  165. }
  166. set(str) {
  167. this._filter = str;
  168. this._dep.changed();
  169. }
  170. reset() {
  171. this._filter = '';
  172. this._dep.changed();
  173. }
  174. _isActive() {
  175. this._dep.depend();
  176. return this._filter !== '';
  177. }
  178. _getMongoSelector() {
  179. this._dep.depend();
  180. return {$regex : this._filter, $options: 'i'};
  181. }
  182. _getEmptySelector() {
  183. this._dep.depend();
  184. return {$regex : this._filter, $options: 'i'};
  185. }
  186. }
  187. // Use a "set" filter for a field that is a set of documents uniquely
  188. // identified. For instance `{ labels: ['labelA', 'labelC', 'labelD'] }`.
  189. // use "subField" for searching inside object Fields.
  190. // For instance '{ 'customFields._id': ['field1','field2']} (subField would be: _id)
  191. class SetFilter {
  192. constructor(subField = '') {
  193. this._dep = new Tracker.Dependency();
  194. this._selectedElements = [];
  195. this.subField = subField;
  196. }
  197. isSelected(val) {
  198. this._dep.depend();
  199. return this._selectedElements.indexOf(val) > -1;
  200. }
  201. add(val) {
  202. if (this._indexOfVal(val) === -1) {
  203. this._selectedElements.push(val);
  204. this._dep.changed();
  205. }
  206. }
  207. remove(val) {
  208. const indexOfVal = this._indexOfVal(val);
  209. if (this._indexOfVal(val) !== -1) {
  210. this._selectedElements.splice(indexOfVal, 1);
  211. this._dep.changed();
  212. }
  213. }
  214. toggle(val) {
  215. if (this._indexOfVal(val) === -1) {
  216. this.add(val);
  217. } else {
  218. this.remove(val);
  219. }
  220. }
  221. reset() {
  222. this._selectedElements = [];
  223. this._dep.changed();
  224. }
  225. _indexOfVal(val) {
  226. return this._selectedElements.indexOf(val);
  227. }
  228. _isActive() {
  229. this._dep.depend();
  230. return this._selectedElements.length !== 0;
  231. }
  232. _getMongoSelector() {
  233. this._dep.depend();
  234. return {
  235. $in: this._selectedElements,
  236. };
  237. }
  238. _getEmptySelector() {
  239. this._dep.depend();
  240. let includeEmpty = false;
  241. this._selectedElements.forEach(el => {
  242. if (el === undefined) {
  243. includeEmpty = true;
  244. }
  245. });
  246. return includeEmpty
  247. ? {
  248. $eq: [],
  249. }
  250. : null;
  251. }
  252. }
  253. // Advanced filter forms a MongoSelector from a users String.
  254. // Build by: Ignatz 19.05.2018 (github feuerball11)
  255. class AdvancedFilter {
  256. constructor() {
  257. this._dep = new Tracker.Dependency();
  258. this._filter = '';
  259. this._lastValide = {};
  260. }
  261. set(str) {
  262. this._filter = str;
  263. this._dep.changed();
  264. }
  265. reset() {
  266. this._filter = '';
  267. this._lastValide = {};
  268. this._dep.changed();
  269. }
  270. _isActive() {
  271. this._dep.depend();
  272. return this._filter !== '';
  273. }
  274. _filterToCommands() {
  275. const commands = [];
  276. let current = '';
  277. let string = false;
  278. let regex = false;
  279. let wasString = false;
  280. let ignore = false;
  281. for (let i = 0; i < this._filter.length; i++) {
  282. const char = this._filter.charAt(i);
  283. if (ignore) {
  284. ignore = false;
  285. current += char;
  286. continue;
  287. }
  288. if (char === '/') {
  289. string = !string;
  290. if (string) regex = true;
  291. current += char;
  292. continue;
  293. }
  294. // eslint-disable-next-line quotes
  295. if (char === "'") {
  296. string = !string;
  297. if (string) wasString = true;
  298. continue;
  299. }
  300. if (char === '\\' && !string) {
  301. ignore = true;
  302. continue;
  303. }
  304. if (char === ' ' && !string) {
  305. commands.push({
  306. cmd: current,
  307. string: wasString,
  308. regex,
  309. });
  310. wasString = false;
  311. current = '';
  312. continue;
  313. }
  314. current += char;
  315. }
  316. if (current !== '') {
  317. commands.push({
  318. cmd: current,
  319. string: wasString,
  320. regex,
  321. });
  322. }
  323. return commands;
  324. }
  325. _fieldNameToId(field) {
  326. const found = ReactiveCache.getCustomField({
  327. name: field,
  328. });
  329. return found._id;
  330. }
  331. _fieldValueToId(field, value) {
  332. const found = ReactiveCache.getCustomField({
  333. name: field,
  334. });
  335. if (
  336. found.settings.dropdownItems &&
  337. found.settings.dropdownItems.length > 0
  338. ) {
  339. for (let i = 0; i < found.settings.dropdownItems.length; i++) {
  340. if (found.settings.dropdownItems[i].name === value) {
  341. return found.settings.dropdownItems[i]._id;
  342. }
  343. }
  344. }
  345. return value;
  346. }
  347. _arrayToSelector(commands) {
  348. try {
  349. //let changed = false;
  350. this._processSubCommands(commands);
  351. } catch (e) {
  352. return this._lastValide;
  353. }
  354. this._lastValide = {
  355. $or: commands,
  356. };
  357. return {
  358. $or: commands,
  359. };
  360. }
  361. _processSubCommands(commands) {
  362. const subcommands = [];
  363. let level = 0;
  364. let start = -1;
  365. for (let i = 0; i < commands.length; i++) {
  366. if (commands[i].cmd) {
  367. switch (commands[i].cmd) {
  368. case '(': {
  369. level++;
  370. if (start === -1) start = i;
  371. continue;
  372. }
  373. case ')': {
  374. level--;
  375. commands.splice(i, 1);
  376. i--;
  377. continue;
  378. }
  379. default: {
  380. if (level > 0) {
  381. subcommands.push(commands[i]);
  382. commands.splice(i, 1);
  383. i--;
  384. continue;
  385. }
  386. }
  387. }
  388. }
  389. }
  390. if (start !== -1) {
  391. this._processSubCommands(subcommands);
  392. if (subcommands.length === 1) commands.splice(start, 0, subcommands[0]);
  393. else commands.splice(start, 0, subcommands);
  394. }
  395. this._processConditions(commands);
  396. this._processLogicalOperators(commands);
  397. }
  398. _processConditions(commands) {
  399. for (let i = 0; i < commands.length; i++) {
  400. if (!commands[i].string && commands[i].cmd) {
  401. switch (commands[i].cmd) {
  402. case '=':
  403. case '==':
  404. case '===': {
  405. const field = commands[i - 1].cmd;
  406. const str = commands[i + 1].cmd;
  407. if (commands[i + 1].regex) {
  408. const match = str.match(new RegExp('^/(.*?)/([gimy]*)$'));
  409. let regex = null;
  410. if (match.length > 2) regex = new RegExp(match[1], match[2]);
  411. else regex = new RegExp(match[1]);
  412. commands[i] = {
  413. 'customFields._id': this._fieldNameToId(field),
  414. 'customFields.value': regex,
  415. };
  416. } else {
  417. commands[i] = {
  418. 'customFields._id': this._fieldNameToId(field),
  419. 'customFields.value': {
  420. $in: [this._fieldValueToId(field, str), parseInt(str, 10)],
  421. },
  422. };
  423. }
  424. commands.splice(i - 1, 1);
  425. commands.splice(i, 1);
  426. //changed = true;
  427. i--;
  428. break;
  429. }
  430. case '!=':
  431. case '!==': {
  432. const field = commands[i - 1].cmd;
  433. const str = commands[i + 1].cmd;
  434. if (commands[i + 1].regex) {
  435. const match = str.match(new RegExp('^/(.*?)/([gimy]*)$'));
  436. let regex = null;
  437. if (match.length > 2) regex = new RegExp(match[1], match[2]);
  438. else regex = new RegExp(match[1]);
  439. commands[i] = {
  440. 'customFields._id': this._fieldNameToId(field),
  441. 'customFields.value': {
  442. $not: regex,
  443. },
  444. };
  445. } else {
  446. commands[i] = {
  447. 'customFields._id': this._fieldNameToId(field),
  448. 'customFields.value': {
  449. $not: {
  450. $in: [this._fieldValueToId(field, str), parseInt(str, 10)],
  451. },
  452. },
  453. };
  454. }
  455. commands.splice(i - 1, 1);
  456. commands.splice(i, 1);
  457. //changed = true;
  458. i--;
  459. break;
  460. }
  461. case '>':
  462. case 'gt':
  463. case 'Gt':
  464. case 'GT': {
  465. const field = commands[i - 1].cmd;
  466. const str = commands[i + 1].cmd;
  467. commands[i] = {
  468. 'customFields._id': this._fieldNameToId(field),
  469. 'customFields.value': {
  470. $gt: parseInt(str, 10),
  471. },
  472. };
  473. commands.splice(i - 1, 1);
  474. commands.splice(i, 1);
  475. //changed = true;
  476. i--;
  477. break;
  478. }
  479. case '>=':
  480. case '>==':
  481. case 'gte':
  482. case 'Gte':
  483. case 'GTE': {
  484. const field = commands[i - 1].cmd;
  485. const str = commands[i + 1].cmd;
  486. commands[i] = {
  487. 'customFields._id': this._fieldNameToId(field),
  488. 'customFields.value': {
  489. $gte: parseInt(str, 10),
  490. },
  491. };
  492. commands.splice(i - 1, 1);
  493. commands.splice(i, 1);
  494. //changed = true;
  495. i--;
  496. break;
  497. }
  498. case '<':
  499. case 'lt':
  500. case 'Lt':
  501. case 'LT': {
  502. const field = commands[i - 1].cmd;
  503. const str = commands[i + 1].cmd;
  504. commands[i] = {
  505. 'customFields._id': this._fieldNameToId(field),
  506. 'customFields.value': {
  507. $lt: parseInt(str, 10),
  508. },
  509. };
  510. commands.splice(i - 1, 1);
  511. commands.splice(i, 1);
  512. //changed = true;
  513. i--;
  514. break;
  515. }
  516. case '<=':
  517. case '<==':
  518. case 'lte':
  519. case 'Lte':
  520. case 'LTE': {
  521. const field = commands[i - 1].cmd;
  522. const str = commands[i + 1].cmd;
  523. commands[i] = {
  524. 'customFields._id': this._fieldNameToId(field),
  525. 'customFields.value': {
  526. $lte: parseInt(str, 10),
  527. },
  528. };
  529. commands.splice(i - 1, 1);
  530. commands.splice(i, 1);
  531. //changed = true;
  532. i--;
  533. break;
  534. }
  535. }
  536. }
  537. }
  538. }
  539. _processLogicalOperators(commands) {
  540. for (let i = 0; i < commands.length; i++) {
  541. if (!commands[i].string && commands[i].cmd) {
  542. switch (commands[i].cmd) {
  543. case 'or':
  544. case 'Or':
  545. case 'OR':
  546. case '|':
  547. case '||': {
  548. const op1 = commands[i - 1];
  549. const op2 = commands[i + 1];
  550. commands[i] = {
  551. $or: [op1, op2],
  552. };
  553. commands.splice(i - 1, 1);
  554. commands.splice(i, 1);
  555. //changed = true;
  556. i--;
  557. break;
  558. }
  559. case 'and':
  560. case 'And':
  561. case 'AND':
  562. case '&':
  563. case '&&': {
  564. const op1 = commands[i - 1];
  565. const op2 = commands[i + 1];
  566. commands[i] = {
  567. $and: [op1, op2],
  568. };
  569. commands.splice(i - 1, 1);
  570. commands.splice(i, 1);
  571. //changed = true;
  572. i--;
  573. break;
  574. }
  575. case 'not':
  576. case 'Not':
  577. case 'NOT':
  578. case '!': {
  579. const op1 = commands[i + 1];
  580. commands[i] = {
  581. $not: op1,
  582. };
  583. commands.splice(i + 1, 1);
  584. //changed = true;
  585. i--;
  586. break;
  587. }
  588. }
  589. }
  590. }
  591. }
  592. _getMongoSelector() {
  593. this._dep.depend();
  594. const commands = this._filterToCommands();
  595. return this._arrayToSelector(commands);
  596. }
  597. getRegexSelector() {
  598. // generate a regex for filter list
  599. this._dep.depend();
  600. return new RegExp(
  601. `^.*${this._filter.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}.*$`,
  602. 'i',
  603. );
  604. }
  605. }
  606. // The global Filter object.
  607. // XXX It would be possible to re-write this object more elegantly, and removing
  608. // the need to provide a list of `_fields`. We also should move methods into the
  609. // object prototype.
  610. Filter = {
  611. // XXX I would like to rename this field into `labels` to be consistent with
  612. // the rest of the schema, but we need to set some migrations architecture
  613. // before changing the schema.
  614. labelIds: new SetFilter(),
  615. members: new SetFilter(),
  616. assignees: new SetFilter(),
  617. archive: new SetFilter(),
  618. hideEmpty: new SetFilter(),
  619. dueAt: new DateFilter(),
  620. title: new StringFilter(),
  621. customFields: new SetFilter('_id'),
  622. advanced: new AdvancedFilter(),
  623. lists: new AdvancedFilter(), // we need the ability to filter list by name as well
  624. _fields: [
  625. 'labelIds',
  626. 'members',
  627. 'assignees',
  628. 'archive',
  629. 'hideEmpty',
  630. 'dueAt',
  631. 'title',
  632. 'customFields',
  633. ],
  634. // We don't filter cards that have been added after the last filter change. To
  635. // implement this we keep the id of these cards in this `_exceptions` fields
  636. // and use a `$or` condition in the mongo selector we return.
  637. _exceptions: [],
  638. _exceptionsDep: new Tracker.Dependency(),
  639. isActive() {
  640. return (
  641. _.any(this._fields, fieldName => {
  642. return this[fieldName]._isActive();
  643. }) ||
  644. this.advanced._isActive() ||
  645. this.lists._isActive()
  646. );
  647. },
  648. _getMongoSelector() {
  649. if (!this.isActive()) return {};
  650. const filterSelector = {};
  651. const emptySelector = {};
  652. let includeEmptySelectors = false;
  653. let isFilterActive = false; // we don't want there is only Filter.lists
  654. this._fields.forEach(fieldName => {
  655. const filter = this[fieldName];
  656. if (filter._isActive()) {
  657. isFilterActive = true;
  658. if (filter.subField !== '') {
  659. filterSelector[
  660. `${fieldName}.${filter.subField}`
  661. ] = filter._getMongoSelector();
  662. } else {
  663. filterSelector[fieldName] = filter._getMongoSelector();
  664. }
  665. emptySelector[fieldName] = filter._getEmptySelector();
  666. if (emptySelector[fieldName] !== null) {
  667. includeEmptySelectors = true;
  668. }
  669. }
  670. });
  671. const exceptionsSelector = {
  672. _id: {
  673. $in: this._exceptions,
  674. },
  675. };
  676. this._exceptionsDep.depend();
  677. const selectors = [exceptionsSelector];
  678. if (
  679. _.any(this._fields, fieldName => {
  680. return this[fieldName]._isActive();
  681. })
  682. )
  683. selectors.push(filterSelector);
  684. if (includeEmptySelectors) selectors.push(emptySelector);
  685. if (this.advanced._isActive()) {
  686. isFilterActive = true;
  687. selectors.push(this.advanced._getMongoSelector());
  688. }
  689. if(isFilterActive) {
  690. return {
  691. $or: selectors,
  692. };
  693. }
  694. else {
  695. // we don't want there is only Filter.lists
  696. // otherwise no card will be displayed ...
  697. // selectors = [exceptionsSelector];
  698. // will return [{"_id":{"$in":[]}}]
  699. return {};
  700. }
  701. },
  702. mongoSelector(additionalSelector) {
  703. const filterSelector = this._getMongoSelector();
  704. if (_.isUndefined(additionalSelector)) return filterSelector;
  705. else
  706. return {
  707. $and: [filterSelector, additionalSelector],
  708. };
  709. },
  710. reset() {
  711. this._fields.forEach(fieldName => {
  712. const filter = this[fieldName];
  713. filter.reset();
  714. });
  715. this.lists.reset();
  716. this.advanced.reset();
  717. this.resetExceptions();
  718. },
  719. addException(_id) {
  720. if (this.isActive()) {
  721. this._exceptions.push(_id);
  722. this._exceptionsDep.changed();
  723. Tracker.flush();
  724. }
  725. },
  726. resetExceptions() {
  727. this._exceptions = [];
  728. this._exceptionsDep.changed();
  729. },
  730. };
  731. Blaze.registerHelper('Filter', Filter);