Files
yaak/src-web/hooks/useRecentWorkspaces.ts
Gregory Schier b4a1c418bb Run oxfmt across repo, add format script and docs
Add .oxfmtignore to skip generated bindings and wasm-pack output.
Add npm format script, update DEVELOPMENT.md for Vite+ toolchain,
and format all non-generated files with oxfmt.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-13 10:15:49 -07:00

49 lines
1.6 KiB
TypeScript

import { workspacesAtom } from "@yaakapp-internal/models";
import { useAtomValue } from "jotai";
import { useEffect, useMemo } from "react";
import { jotaiStore } from "../lib/jotai";
import { getKeyValue, setKeyValue } from "../lib/keyValueStore";
import { activeWorkspaceIdAtom } from "./useActiveWorkspace";
import { useKeyValue } from "./useKeyValue";
const kvKey = () => "recent_workspaces";
const namespace = "global";
const fallback: string[] = [];
export function useRecentWorkspaces() {
const workspaces = useAtomValue(workspacesAtom);
const { value, isLoading } = useKeyValue<string[]>({ key: kvKey(), namespace, fallback });
const onlyValidIds = useMemo(
() => value?.filter((id) => workspaces.some((w) => w.id === id)) ?? [],
[value, workspaces],
);
if (isLoading) return null;
return onlyValidIds;
}
export function useSubscribeRecentWorkspaces() {
useEffect(() => {
const unsub = jotaiStore.sub(activeWorkspaceIdAtom, updateRecentWorkspaces);
updateRecentWorkspaces().catch(console.error); // Update when opened in a new window
return unsub;
}, []);
}
async function updateRecentWorkspaces() {
const activeWorkspaceId = jotaiStore.get(activeWorkspaceIdAtom);
if (activeWorkspaceId == null) return;
const key = kvKey();
const recentIds = getKeyValue<string[]>({ namespace, key, fallback });
if (recentIds[0] === activeWorkspaceId) return; // Short-circuit
const withoutActiveId = recentIds.filter((id) => id !== activeWorkspaceId);
const value = [activeWorkspaceId, ...withoutActiveId];
console.log("Recent workspaces update", activeWorkspaceId);
await setKeyValue({ namespace, key, value });
}