watchable.js 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. // simple version, only toggle watch / unwatch
  2. const simpleWatchable = collection => {
  3. collection.attachSchema({
  4. watchers: {
  5. type: [String],
  6. optional: true,
  7. },
  8. });
  9. collection.helpers({
  10. getWatchLevels() {
  11. return [true, false];
  12. },
  13. watcherIndex(userId) {
  14. return this.watchers.indexOf(userId);
  15. },
  16. findWatcher(userId) {
  17. return _.contains(this.watchers, userId);
  18. },
  19. });
  20. collection.mutations({
  21. setWatcher(userId, level) {
  22. // if level undefined or null or false, then remove
  23. if (!level) return { $pull: { watchers: userId } };
  24. return { $addToSet: { watchers: userId } };
  25. },
  26. });
  27. };
  28. // more complex version of same interface, with 3 watching levels
  29. const complexWatchOptions = ['watching', 'tracking', 'muted'];
  30. const complexWatchDefault = 'muted';
  31. const complexWatchable = collection => {
  32. collection.attachSchema({
  33. 'watchers.$.userId': {
  34. type: String,
  35. },
  36. 'watchers.$.level': {
  37. type: String,
  38. allowedValues: complexWatchOptions,
  39. },
  40. });
  41. collection.helpers({
  42. getWatchOptions() {
  43. return complexWatchOptions;
  44. },
  45. getWatchDefault() {
  46. return complexWatchDefault;
  47. },
  48. watcherIndex(userId) {
  49. return _.pluck(this.watchers, 'userId').indexOf(userId);
  50. },
  51. findWatcher(userId) {
  52. return _.findWhere(this.watchers, { userId });
  53. },
  54. getWatchLevel(userId) {
  55. const watcher = this.findWatcher(userId);
  56. return watcher ? watcher.level : complexWatchDefault;
  57. },
  58. });
  59. collection.mutations({
  60. setWatcher(userId, level) {
  61. // if level undefined or null or false, then remove
  62. if (level === complexWatchDefault) level = null;
  63. if (!level) return { $pull: { watchers: { userId } } };
  64. const index = this.watcherIndex(userId);
  65. if (index < 0) return { $push: { watchers: { userId, level } } };
  66. return {
  67. $set: {
  68. [`watchers.${index}.level`]: level,
  69. },
  70. };
  71. },
  72. });
  73. };
  74. complexWatchable(Boards);
  75. simpleWatchable(Lists);
  76. simpleWatchable(Cards);