You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

72 lines
1.7 KiB

4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
  1. import { writable } from "svelte/store";
  2. import stuffLogClient from "../clients/stufflog";
  3. import type { GoalFilter, GoalResult } from "../models/goal";
  4. interface GoalStoreData {
  5. loading: boolean
  6. stale: boolean
  7. goals: GoalResult[]
  8. filter: GoalFilter
  9. }
  10. function createGoalStore() {
  11. const {update, subscribe} = writable<GoalStoreData>({
  12. loading: false,
  13. stale: true,
  14. goals: [],
  15. filter: {},
  16. });
  17. let lastLoad = 0;
  18. let spamPoints = 3;
  19. return {
  20. subscribe,
  21. markStale() {
  22. update(v => ({...v, stale: true}));
  23. },
  24. async load(filter: GoalFilter) {
  25. update(v => ({...v, loading: true, filter}));
  26. // Prevent too much spammery when tweaking the date.
  27. const timeSince = Date.now() - lastLoad;
  28. if (timeSince < 3000) {
  29. if (timeSince < 1000) {
  30. spamPoints -= 1;
  31. }
  32. if (spamPoints <= 0) {
  33. await new Promise(resolve => setTimeout(resolve, 3000 - timeSince));
  34. spamPoints = 3;
  35. }
  36. } else {
  37. spamPoints = 3;
  38. }
  39. lastLoad = Date.now();
  40. const goals = await stuffLogClient.listGoals(filter);
  41. const expireds = [];
  42. const upcomings = [];
  43. const actives = [];
  44. const now = Date.now();
  45. for (const goal of goals) {
  46. if (Date.parse(goal.endTime) < now) {
  47. expireds.push(goal);
  48. } else if (Date.parse(goal.startTime) > now) {
  49. upcomings.push(goal);
  50. } else {
  51. actives.push(goal);
  52. }
  53. }
  54. update(v => ({...v, loading: false, stale: false, goals: [...upcomings, ...actives, ...expireds] }));
  55. },
  56. }
  57. }
  58. const goalStore = createGoalStore();
  59. export default goalStore;
  60. export const fpGoalStore = createGoalStore();