Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Add support for Setter, Getter, AffineFold and Fold optics #18

Open
wants to merge 7 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
127 changes: 105 additions & 22 deletions src/focusAtom.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
/* eslint-disable @typescript-eslint/no-explicit-any */

import { atom } from 'jotai/vanilla';
import type { SetStateAction, WritableAtom } from 'jotai/vanilla';
import type { Atom, SetStateAction, WritableAtom } from 'jotai/vanilla';
import * as O from 'optics-ts';

const getCached = <T>(c: () => T, m: WeakMap<object, T>, k: object): T =>
Expand All @@ -17,6 +17,21 @@ const isFunction = <T>(x: T): x is T & ((...args: any[]) => any) =>

type NonFunction<T> = [T] extends [(...args: any[]) => any] ? never : T;

type ModifiableLensLike<S, A> =
| O.Lens<S, any, A>
| O.Equivalence<S, any, A>
| O.Iso<S, any, A>
| O.Prism<S, any, A>
| O.Traversal<S, any, A>;

type SettableLensLike<S, A> = ModifiableLensLike<S, A> | O.Setter<S, any, A>;

type LensLike<S, A> =
| SettableLensLike<S, A>
| O.Getter<S, A>
| O.AffineFold<S, A>
| O.Fold<S, A>;

// Pattern 1: Promise

export function focusAtom<S, A, R>(
Expand All @@ -36,6 +51,26 @@ export function focusAtom<S, A, R>(
) => O.Lens<S, any, A> | O.Equivalence<S, any, A> | O.Iso<S, any, A>,
): WritableAtom<Promise<A>, [SetStateAction<A>], R>;

export function focusAtom<S, A, R>(
baseAtom: WritableAtom<Promise<S>, [Promise<S>], R>,
callback: (optic: O.OpticFor_<S>) => O.Setter<S, any, A>,
): WritableAtom<Promise<void>, [NonFunction<A>], R>;

export function focusAtom<S, A, R>(
baseAtom: WritableAtom<Promise<S>, [Promise<S>], R>,
callback: (optic: O.OpticFor_<S>) => O.Getter<S, A>,
): Atom<Promise<A>>;

export function focusAtom<S, A, R>(
baseAtom: WritableAtom<Promise<S>, [Promise<S>], R>,
callback: (optic: O.OpticFor_<S>) => O.AffineFold<S, A>,
): Atom<Promise<A | undefined>>;

export function focusAtom<S, A, R>(
baseAtom: WritableAtom<Promise<S>, [Promise<S>], R>,
callback: (optic: O.OpticFor_<S>) => O.Fold<S, A>,
): Atom<Promise<A[]>>;

// Pattern 2: Promise with undefined type

export function focusAtom<S, A, R>(
Expand All @@ -55,6 +90,26 @@ export function focusAtom<S, A, R>(
) => O.Lens<S, any, A> | O.Equivalence<S, any, A> | O.Iso<S, any, A>,
): WritableAtom<Promise<A>, [SetStateAction<A>], R>;

export function focusAtom<S, A, R>(
baseAtom: WritableAtom<Promise<S | undefined>, [Promise<S>], R>,
callback: (optic: O.OpticFor_<S | undefined>) => O.Setter<S, any, A>,
): WritableAtom<Promise<void>, [NonFunction<A>], R>;

export function focusAtom<S, A, R>(
baseAtom: WritableAtom<Promise<S | undefined>, [Promise<S>], R>,
callback: (optic: O.OpticFor_<S | undefined>) => O.Getter<S, A>,
): Atom<Promise<A>>;

export function focusAtom<S, A, R>(
baseAtom: WritableAtom<Promise<S | undefined>, [Promise<S>], R>,
callback: (optic: O.OpticFor_<S | undefined>) => O.AffineFold<S, A>,
): Atom<Promise<A | undefined>>;

export function focusAtom<S, A, R>(
baseAtom: WritableAtom<Promise<S | undefined>, [Promise<S>], R>,
callback: (optic: O.OpticFor_<S | undefined>) => O.Fold<S, A>,
): Atom<Promise<A[]>>;

// Pattern 3: Default

export function focusAtom<S, A, R>(
Expand All @@ -74,6 +129,26 @@ export function focusAtom<S, A, R>(
) => O.Lens<S, any, A> | O.Equivalence<S, any, A> | O.Iso<S, any, A>,
): WritableAtom<A, [SetStateAction<A>], R>;

export function focusAtom<S, A, R>(
baseAtom: WritableAtom<S, [NonFunction<S>], R>,
callback: (optic: O.OpticFor_<S>) => O.Setter<S, any, A>,
): WritableAtom<void, [NonFunction<A>], R>;

export function focusAtom<S, A, R>(
baseAtom: WritableAtom<S, [NonFunction<S>], R>,
callback: (optic: O.OpticFor_<S>) => O.Getter<S, A>,
): Atom<A>;

export function focusAtom<S, A, R>(
baseAtom: WritableAtom<S, [NonFunction<S>], R>,
callback: (optic: O.OpticFor_<S>) => O.AffineFold<S, A>,
): Atom<A | undefined>;

export function focusAtom<S, A, R>(
baseAtom: WritableAtom<S, [NonFunction<S>], R>,
callback: (optic: O.OpticFor_<S>) => O.Fold<S, A>,
): Atom<A[]>;

// Pattern 4: Default with undefined type

export function focusAtom<S, A, R>(
Expand All @@ -93,18 +168,31 @@ export function focusAtom<S, A, R>(
) => O.Lens<S, any, A> | O.Equivalence<S, any, A> | O.Iso<S, any, A>,
): WritableAtom<A, [SetStateAction<A>], R>;

export function focusAtom<S, A, R>(
baseAtom: WritableAtom<S | undefined, [NonFunction<S>], R>,
callback: (optic: O.OpticFor_<S | undefined>) => O.Setter<S, any, A>,
): WritableAtom<void, [NonFunction<A>], R>;

export function focusAtom<S, A, R>(
baseAtom: WritableAtom<S | undefined, [NonFunction<S>], R>,
callback: (optic: O.OpticFor_<S | undefined>) => O.Getter<S, A>,
): Atom<A>;

export function focusAtom<S, A, R>(
baseAtom: WritableAtom<S | undefined, [NonFunction<S>], R>,
callback: (optic: O.OpticFor_<S | undefined>) => O.AffineFold<S, A>,
): Atom<A | undefined>;

export function focusAtom<S, A, R>(
baseAtom: WritableAtom<S | undefined, [NonFunction<S>], R>,
callback: (optic: O.OpticFor_<S | undefined>) => O.Fold<S, A>,
): Atom<A[]>;

// Implementation

export function focusAtom<S, A, R>(
baseAtom: WritableAtom<S, [NonFunction<S>], R>,
callback: (
optic: O.OpticFor_<S>,
) =>
| O.Lens<S, any, A>
| O.Equivalence<S, any, A>
| O.Iso<S, any, A>
| O.Prism<S, any, A>
| O.Traversal<S, any, A>,
callback: (optic: O.OpticFor_<S>) => LensLike<S, A>,
) {
return memo2(
() => {
Expand All @@ -118,8 +206,8 @@ export function focusAtom<S, A, R>(
},
(get, set, update: SetStateAction<A>) => {
const newValueProducer = isFunction(update)
? O.modify(focus)(update)
: O.set(focus)(update);
? O.modify(focus as ModifiableLensLike<S, A>)(update)
: O.set(focus as SettableLensLike<S, A>)(update);
const base = get(baseAtom);
return set(
baseAtom,
Expand All @@ -136,23 +224,18 @@ export function focusAtom<S, A, R>(
);
}

const getValueUsingOptic = <S, A>(
focus:
| O.Lens<S, any, A>
| O.Equivalence<S, any, A>
| O.Iso<S, any, A>
| O.Prism<S, any, A>
| O.Traversal<S, any, A>,
bigValue: S,
) => {
if (focus._tag === 'Traversal') {
const getValueUsingOptic = <S, A>(focus: LensLike<S, A>, bigValue: S) => {
if (focus._tag === 'Traversal' || focus._tag === 'Fold') {
const values = O.collect(focus)(bigValue);
return values;
}
if (focus._tag === 'Prism') {
if (focus._tag === 'Prism' || focus._tag === 'AffineFold') {
const value = O.preview(focus)(bigValue);
return value;
}
if (focus._tag === 'Setter') {
return undefined;
}
const value = O.get(focus)(bigValue);
return value;
};
144 changes: 144 additions & 0 deletions tests/focus-setter.spec.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,144 @@
import { afterEach, test } from 'vitest';
import { StrictMode, Suspense } from 'react';
import { cleanup, fireEvent, render } from '@testing-library/react';
import { useAtom, useSetAtom } from 'jotai/react';
import { atom } from 'jotai/vanilla';
import type { SetStateAction } from 'jotai/vanilla';
import * as O from 'optics-ts';
import { focusAtom } from 'jotai-optics';

afterEach(cleanup);

test('basic derivation using focus works', async () => {
const bigAtom = atom([{ a: 0 }]);
const focusFunction = (optic: O.OpticFor_<{ a: number }[]>) =>
optic.appendTo();

const Counter = () => {
const appendNumber = useSetAtom(focusAtom(bigAtom, focusFunction));
const [bigAtomValue] = useAtom(bigAtom);
return (
<>
<div>bigAtom: {JSON.stringify(bigAtomValue)}</div>
<button onClick={() => appendNumber({ a: bigAtomValue.length })}>
Append to bigAtom
</button>
</>
);
};

const { getByText, findByText } = render(
<StrictMode>
<Counter />
</StrictMode>,
);

await findByText('bigAtom: [{"a":0}]');

fireEvent.click(getByText('Append to bigAtom'));
await findByText('bigAtom: [{"a":0},{"a":1}]');

fireEvent.click(getByText('Append to bigAtom'));
await findByText('bigAtom: [{"a":0},{"a":1},{"a":2}]');
});

test('double-focus on an atom works', async () => {
const bigAtom = atom({ a: [0] });
const atomA = focusAtom(bigAtom, (optic) => optic.prop('a'));
const atomAppend = focusAtom(atomA, (optic) => optic.appendTo());

const Counter = () => {
const [bigAtomValue, setBigAtom] = useAtom(bigAtom);
const [atomAValue, setAtomA] = useAtom(atomA);
const append = useSetAtom(atomAppend);
return (
<>
<div>bigAtom: {JSON.stringify(bigAtomValue)}</div>
<div>atomA: {JSON.stringify(atomAValue)}</div>
<button onClick={() => setBigAtom((v) => ({ a: [...v.a, 1] }))}>
inc bigAtom
</button>
<button onClick={() => setAtomA((v) => [...v, 2])}>inc atomA</button>
<button onClick={() => append(3)}>append</button>
</>
);
};

const { getByText, findByText } = render(
<StrictMode>
<Counter />
</StrictMode>,
);

await findByText('bigAtom: {"a":[0]}');
await findByText('atomA: [0]');

fireEvent.click(getByText('inc bigAtom'));
await findByText('bigAtom: {"a":[0,1]}');
await findByText('atomA: [0,1]');

fireEvent.click(getByText('inc atomA'));
await findByText('bigAtom: {"a":[0,1,2]}');
await findByText('atomA: [0,1,2]');

fireEvent.click(getByText('append'));
await findByText('bigAtom: {"a":[0,1,2,3]}');
await findByText('atomA: [0,1,2,3]');
});

test('focus on async atom works', async () => {
const baseAtom = atom([0]);
const asyncAtom = atom(
(get) => Promise.resolve(get(baseAtom)),
async (get, set, param: SetStateAction<Promise<number[]>>) => {
const prev = Promise.resolve(get(baseAtom));
const next = await (typeof param === 'function' ? param(prev) : param);
set(baseAtom, next);
},
);
const focusFunction = (optic: O.OpticFor_<number[]>) => optic.appendTo();

const Counter = () => {
const append = useSetAtom(focusAtom(asyncAtom, focusFunction));
const [asyncValue, setAsync] = useAtom(asyncAtom);
const [baseValue, setBase] = useAtom(baseAtom);
return (
<>
<div>baseAtom: {JSON.stringify(baseValue)}</div>
<div>asyncAtom: {JSON.stringify(asyncValue)}</div>
<button onClick={() => append(baseValue.length)}>append</button>
<button
onClick={() => setAsync((p) => p.then((v) => [...v, v.length]))}
>
incr async
</button>
<button onClick={() => setBase((v) => [...v, v.length])}>
incr base
</button>
</>
);
};

const { getByText, findByText } = render(
<StrictMode>
<Suspense fallback={<div>Loading...</div>}>
<Counter />
</Suspense>
</StrictMode>,
);

await findByText('baseAtom: [0]');
await findByText('asyncAtom: [0]');

fireEvent.click(getByText('append'));
await findByText('baseAtom: [0,1]');
await findByText('asyncAtom: [0,1]');

fireEvent.click(getByText('incr async'));
await findByText('baseAtom: [0,1,2]');
await findByText('asyncAtom: [0,1,2]');

fireEvent.click(getByText('incr base'));
await findByText('baseAtom: [0,1,2,3]');
await findByText('asyncAtom: [0,1,2,3]');
});
Loading