mirror of
https://github.com/mountain-loop/yaak.git
synced 2026-11-29 03:32:43 +01:00
Proxy viewer extraction: response viewers into packages/ui (#754)
This commit is contained in:
1 parent
b5508e6bb1
commit
b6c1f700f1
137 files changed
+3498
-2890
No files matched your search
@@ -0,0 +1,42 @@
|
||||
import { atom, useAtom } from "jotai";
|
||||
import { atomFamily } from "jotai-family";
|
||||
import { useCallback, useState } from "react";
|
||||
|
||||
export type StoredValue = object | boolean | number | string | null;
|
||||
|
||||
export type SetStoredValue<T> = (value: T | ((prev: T) => T)) => void | Promise<unknown>;
|
||||
|
||||
/**
|
||||
* Reads and writes a value kept under `key`, falling back to `fallback` until one is written. A
|
||||
* `null` key keeps the value for the component's lifetime only. Components that remember things
|
||||
* take one of these, so each host decides where the memory lives.
|
||||
*/
|
||||
export type UseStoredValue = <T extends StoredValue>(
|
||||
key: string | string[] | null,
|
||||
fallback: T,
|
||||
) => readonly [T, SetStoredValue<T>];
|
||||
|
||||
const memoryAtoms = atomFamily((_key: string) => atom<{ value: unknown } | null>(null));
|
||||
|
||||
/** The default {@link UseStoredValue}: kept in memory for the session */
|
||||
export function useInMemoryStoredValue<T extends StoredValue>(
|
||||
key: string | string[] | null,
|
||||
fallback: T,
|
||||
): readonly [T, SetStoredValue<T>] {
|
||||
const memoryKey = key == null ? null : Array.isArray(key) ? key.join("::") : key;
|
||||
const [local, setLocal] = useState<T>(fallback);
|
||||
const [stored, setStored] = useAtom(memoryAtoms(memoryKey ?? ""));
|
||||
|
||||
const storedValue = stored == null ? fallback : (stored.value as T);
|
||||
const setStoredValue = useCallback<SetStoredValue<T>>(
|
||||
(update) =>
|
||||
setStored((prev) => {
|
||||
const prevValue = prev == null ? fallback : (prev.value as T);
|
||||
const value = typeof update === "function" ? (update as (p: T) => T)(prevValue) : update;
|
||||
return { value };
|
||||
}),
|
||||
[fallback, setStored],
|
||||
);
|
||||
|
||||
return memoryKey == null ? [local, setLocal] : [storedValue, setStoredValue];
|
||||
}
|
||||
Reference in new issue
Block a user