view-store.ts 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. "use client";
  2. import { useSyncExternalStore } from "react";
  3. export const VIEWS = ["all", "about", "work"] 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. /** The view a URL hash asks for. Work and projects were once two views; old #projects links land on Work. */
  12. export const viewFromHash = (hash: string): View =>
  13. hash === "projects" ? "work" : isView(hash) ? hash : "all";
  14. export function getView() {
  15. return current;
  16. }
  17. /** Switch the home grid's view. `beforeChange` listeners run first so the grid can measure for FLIP. */
  18. export function setView(next: View, { updateUrl = true } = {}) {
  19. if (next === current) return;
  20. beforeChange.forEach((fn) => fn());
  21. current = next;
  22. if (updateUrl && typeof window !== "undefined") {
  23. const url = next === "all" ? window.location.pathname : `#${next}`;
  24. window.history.replaceState(window.history.state, "", url);
  25. }
  26. listeners.forEach((fn) => fn());
  27. }
  28. export function onBeforeViewChange(fn: Listener) {
  29. beforeChange.add(fn);
  30. return () => {
  31. beforeChange.delete(fn);
  32. };
  33. }
  34. function subscribe(fn: Listener) {
  35. listeners.add(fn);
  36. return () => {
  37. listeners.delete(fn);
  38. };
  39. }
  40. export function useView() {
  41. return useSyncExternalStore(subscribe, getView, () => "all" as View);
  42. }