Better recent work/env/req logic

This commit is contained in:
Gregory Schier
2024-02-13 17:21:54 -08:00
parent 4e1700f8a4
commit f45c898be0
12 changed files with 138 additions and 102 deletions

View File

@@ -1,34 +1,45 @@
import { useEffect, useMemo } from 'react';
import { createGlobalState, useEffectOnce, useLocalStorage } from 'react-use';
import { createGlobalState, useEffectOnce } from 'react-use';
import { getKeyValue, NAMESPACE_GLOBAL } from '../lib/keyValueStore';
import { useActiveWorkspaceId } from './useActiveWorkspaceId';
import { useKeyValue } from './useKeyValue';
import { useWorkspaces } from './useWorkspaces';
const useHistoryState = createGlobalState<string[]>([]);
const kvKey = () => 'recent_workspaces';
const namespace = NAMESPACE_GLOBAL;
const defaultValue: string[] = [];
export function useRecentWorkspaces() {
const workspaces = useWorkspaces();
const activeWorkspaceId = useActiveWorkspaceId();
const [history, setHistory] = useHistoryState();
const [lsState, setLSState] = useLocalStorage<string[]>('recent_workspaces', []);
const kv = useKeyValue<string[]>({
key: kvKey(),
namespace,
defaultValue,
});
// Load local storage state on initial render
useEffectOnce(() => {
if (lsState) {
setHistory(lsState);
if (kv.value) {
setHistory(kv.value);
}
});
// Update local storage state when history changes
useEffect(() => {
setLSState(history);
}, [history, setLSState]);
kv.set(history);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [history]);
// Set history when active request changes
useEffect(() => {
setHistory((currentHistory: string[]) => {
if (activeWorkspaceId === null) return currentHistory;
const withoutCurrentWorkspace = currentHistory.filter((id) => id !== activeWorkspaceId);
return [activeWorkspaceId, ...withoutCurrentWorkspace];
const withoutCurrent = currentHistory.filter((id) => id !== activeWorkspaceId);
return [activeWorkspaceId, ...withoutCurrent];
});
}, [activeWorkspaceId, setHistory]);
@@ -39,3 +50,11 @@ export function useRecentWorkspaces() {
return onlyValidIds;
}
export async function getRecentWorkspaces() {
return getKeyValue<string[]>({
namespace,
key: kvKey(),
fallback: defaultValue,
});
}