mirror of
https://github.com/mountain-loop/yaak.git
synced 2026-03-18 23:43:55 +01:00
Better recent work/env/req logic
This commit is contained in:
@@ -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,
|
||||
});
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user