view-store.ts 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. "use client";
  2. import { useSyncExternalStore } from "react";
  3. export const VIEWS = ["all", "about", "work", "projects"] as const;
  4. export type View = (typeof VIEWS)[number];
  5. type Listener = () => void;
  6. let current: View = "all";
  7. const listeners = new Set<Listener>();
  8. const beforeChange = new Set<Listener>();
  9. export const isView = (value: string): value is View =>
  10. (VIEWS as readonly string[]).includes(value);
  11. export function getView() {
  12. return current;
  13. }
  14. /** Switch the home grid's view. `beforeChange` listeners run first so the grid can measure for FLIP. */
  15. export function setView(next: View, { updateUrl = true } = {}) {
  16. if (next === current) return;
  17. beforeChange.forEach((fn) => fn());
  18. current = next;
  19. if (updateUrl && typeof window !== "undefined") {
  20. const url = next === "all" ? window.location.pathname : `#${next}`;
  21. window.history.replaceState(window.history.state, "", url);
  22. }
  23. listeners.forEach((fn) => fn());
  24. }
  25. export function onBeforeViewChange(fn: Listener) {
  26. beforeChange.add(fn);
  27. return () => {
  28. beforeChange.delete(fn);
  29. };
  30. }
  31. function subscribe(fn: Listener) {
  32. listeners.add(fn);
  33. return () => {
  34. listeners.delete(fn);
  35. };
  36. }
  37. export function useView() {
  38. return useSyncExternalStore(subscribe, getView, () => "all" as View);
  39. }