mirror of
https://github.com/mountain-loop/yaak.git
synced 2026-03-24 18:31:16 +01:00
Refactor desktop app into separate client and proxy apps
This commit is contained in:
48
apps/yaak-client/hooks/useRecentWorkspaces.ts
Normal file
48
apps/yaak-client/hooks/useRecentWorkspaces.ts
Normal file
@@ -0,0 +1,48 @@
|
||||
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 });
|
||||
}
|
||||
Reference in New Issue
Block a user