Loggest thine Stuff
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.

73 lines
2.0 KiB

  1. <script lang="ts" context="module">
  2. const contextKey = {ctx: "itemMultiListContext"};
  3. interface ItemMultiListContextData {
  4. lists: Readable<Record<string, Item[]>>,
  5. reloadItemLists(): void,
  6. };
  7. const fallback: ItemMultiListContextData = {
  8. lists: readable({}),
  9. reloadItemLists() {},
  10. }
  11. export function getItemMultiListContext() {
  12. return getContext(contextKey) as ItemMultiListContextData || fallback
  13. }
  14. </script>
  15. <script lang="ts">
  16. import { readable, writable, type Readable } from "svelte/store";
  17. import { getContext, setContext } from "svelte";
  18. import type Item from "$lib/models/item";
  19. import type { ItemFilter } from "$lib/models/item";
  20. import { getScopeContext } from "./ScopeContext.svelte";
  21. import deepEqual from "$lib/utils/object";
  22. import { sl3 } from "$lib/clients/sl3";
  23. import { getStores } from "$app/stores";
  24. const {scope} = getScopeContext();
  25. const {page} = getStores();
  26. export let lists: Record<string, Item[]>
  27. export let filters: Record<string, ItemFilter>
  28. export let global: boolean = false;
  29. let loaded: Record<string, ItemFilter> = {...filters};
  30. let loading: Record<string, boolean> = {};
  31. const listsWritable = writable<Record<string, Item[]>>({...lists});
  32. function reloadItemLists() {
  33. loaded = {};
  34. }
  35. async function runLoad(key: string, filter: ItemFilter) {
  36. loading = {...loading, [key]: true};
  37. try {
  38. const items = await sl3(fetch, $page.stuff.idToken).listItems(global ? "ALL" : $scope.id, filter)
  39. listsWritable.update(l => ({...l, [key.replace("Filter", "Items")]: items}));
  40. } catch(_err) {
  41. // TODO: Use err
  42. }
  43. loading = {...loading, [key]: false};
  44. loaded = {...loaded, [key]: filter};
  45. }
  46. setContext<ItemMultiListContextData>(contextKey, {
  47. lists: {subscribe: listsWritable.subscribe},
  48. reloadItemLists,
  49. });
  50. $: for (const key in filters) {
  51. if (loading[key]) {
  52. continue;
  53. }
  54. if (loaded[key] == null || !deepEqual(filters[key], loaded[key])) {
  55. runLoad(key, {...filters[key]})
  56. }
  57. }
  58. </script>
  59. <slot></slot>