import { produce, nothing } from 'immer'; import type { Draft } from 'immer'; import { atom } from 'jotai/vanilla'; import type { PrimitiveAtom, WritableAtom } from 'jotai/vanilla'; const cache1 = new WeakMap(); const memo1 = (create: () => T, dep1: object): T => (cache1.has(dep1) ? cache1 : cache1.set(dep1, create())).get(dep1); export function withImmer( anAtom: WritableAtom, ): WritableAtom< Value, Args extends [Value | infer OtherValue] ? [ | Value | ((draft: Draft) => void) | Exclude unknown>, ] : unknown[], Result >; export function withImmer( anAtom: PrimitiveAtom, ): WritableAtom) => void)], void>; export function withImmer( anAtom: WritableAtom, ) { return memo1(() => { const derivedAtom = atom( (get) => get(anAtom), (get, set, fn: Value | ((draft: Draft) => void)) => set( anAtom, produce( get(anAtom), typeof fn === 'function' ? (fn as (draft: Draft) => void) : () => (fn === undefined ? nothing : fn), ), ), ); return derivedAtom; }, anAtom); }