Skip to content

Commit

Permalink
support implicit parent edge case
Browse files Browse the repository at this point in the history
  • Loading branch information
David Maskasky committed May 21, 2024
1 parent f6cf990 commit fb17e03
Show file tree
Hide file tree
Showing 2 changed files with 172 additions and 11 deletions.
120 changes: 120 additions & 0 deletions __tests__/ScopeProvider/06_implicit_parent.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@
import { FC } from 'react';
import { render } from '@testing-library/react';
import { atom, useAtom, useAtomValue } from 'jotai';
import { atomWithReducer } from 'jotai/vanilla/utils';
import { clickButton, getTextContents } from '../utils';
import { ScopeProvider } from '../../src/index';

function renderWithOrder(level1: 'BD' | 'DB', level2: 'BD' | 'DB') {
const baseAtom = atomWithReducer(0, (v) => v + 1);
baseAtom.debugLabel = 'baseAtom';
baseAtom.toString = function toString() {
return this.debugLabel ?? 'Unknown Atom';
};

const derivedAtom = atom((get) => get(baseAtom));
derivedAtom.debugLabel = 'derivedAtom';
derivedAtom.toString = function toString() {
return this.debugLabel ?? 'Unknown Atom';
};

type Counter = FC<{ level: string }>;
const BaseThenDerived: Counter = ({ level }) => {
const [base, increaseBase] = useAtom(baseAtom);
const derived = useAtomValue(derivedAtom);
return (
<>
<div>
base: <span className={`${level} base`}>{base}</span>
<button
type="button"
className={`${level} setBase`}
onClick={increaseBase}
>
+
</button>
</div>
<div>
derived:<span className={`${level} derived`}>{derived}</span>
</div>
</>
);
};

const DerivedThenBase: Counter = ({ level }) => {
const derived = useAtomValue(derivedAtom);
const [base, increaseBase] = useAtom(baseAtom);
return (
<>
<div>
base:<span className={`${level} base`}>{base}</span>
<button
type="button"
className={`${level} setBase`}
onClick={increaseBase}
>
+
</button>
</div>
<div>
derived:<span className={`${level} derived`}>{derived}</span>
</div>
</>
);
};
const App = (props: { Level1Counter: Counter; Level2Counter: Counter }) => {
const { Level1Counter, Level2Counter } = props;
return (
<div>
<h1>Layer 1: Scope derived</h1>
<p>base should be globally shared</p>
<ScopeProvider atoms={[derivedAtom]} debugName="layer1">
<Level1Counter level="layer1" />
<h1>Layer 2: Scope base</h1>
<p>base should be globally shared</p>
<ScopeProvider atoms={[]} debugName="layer2">
<Level2Counter level="layer2" />
</ScopeProvider>
</ScopeProvider>
</div>
);
};
function getCounter(order: 'BD' | 'DB') {
return order === 'BD' ? BaseThenDerived : DerivedThenBase;
}
return render(
<App
Level1Counter={getCounter(level1)}
Level2Counter={getCounter(level2)}
/>,
);
}

/*
b, D(b)
S1[D]: b0, D1(b1)
S2[ ]: b0, D1(b1)
*/
describe('Implicit parent does not affect unscoped', () => {
const cases = [
['BD', 'BD'],
['BD', 'DB'],
['DB', 'BD'],
['DB', 'DB'],
] as const;
test.each(cases)('level 1: %p and level 2: %p', (level1, level2) => {
const { container } = renderWithOrder(level1, level2);
const increaseLayer2Base = '.layer2.setBase';
const selectors = [
'.layer1.base',
'.layer1.derived',
'.layer2.base',
'.layer2.derived',
];

expect(getTextContents(container, selectors).join('')).toEqual('0000');

clickButton(container, increaseLayer2Base);
expect(getTextContents(container, selectors).join('')).toEqual('1010');
});
});
63 changes: 52 additions & 11 deletions src/ScopeProvider/scope.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,16 +23,30 @@ export type Scope = {
* @debug
*/
name?: string;

/**
* @debug
*/
toString?: () => string;
};

const globalScopeKey: { name?: string } = {};
if (process.env.NODE_ENV !== 'production') {
globalScopeKey.name = 'unscoped';
globalScopeKey.toString = toString;
}

type GlobalScopeKey = typeof globalScopeKey;

export function createScope(
atoms: Iterable<AnyAtom>,
parentScope: Scope | undefined,
scopeName?: string | undefined,
): Scope {
const explicit = new WeakMap<AnyAtom, [AnyAtom, Scope?]>();
const implicit = new WeakMap<AnyAtom, [AnyAtom, Scope?]>();
const inherited = new WeakMap<AnyAtom, [AnyAtom, Scope?]>();
type ScopeMap = WeakMap<AnyAtom, [AnyAtom, Scope?]>;
const inherited = new WeakMap<Scope | GlobalScopeKey, ScopeMap>();

const currentScope: Scope = {
getAtom,
Expand Down Expand Up @@ -64,6 +78,7 @@ export function createScope(

if (scopeName && process.env.NODE_ENV !== 'production') {
currentScope.name = scopeName;
currentScope.toString = toString;
}
// populate explicitly scoped atoms
for (const anAtom of atoms) {
Expand Down Expand Up @@ -91,29 +106,51 @@ export function createScope(
}
return implicit.get(anAtom) as [T, Scope];
}
const scopeKey = implicitScope ?? globalScopeKey;
if (parentScope) {
// inherited atoms are copied so they can access scoped atoms
// but they are not explicitly scoped
// dependencies of inherited atoms first check if they are explicitly scoped
// otherwise they use their original scope's atom
if (!inherited.has(anAtom)) {
const [ancestorAtom, ...ancestorScope] = parentScope.getAtom(
if (!inherited.get(scopeKey)?.has(anAtom)) {
const [ancestorAtom, explicitScope] = parentScope.getAtom(
anAtom,
implicitScope,
);
setInheritedAtom(
inheritAtom(ancestorAtom, anAtom, explicitScope),
anAtom,
implicitScope,
explicitScope,
);
inherited.set(anAtom, [
inheritAtom(ancestorAtom, anAtom, ...ancestorScope),
...ancestorScope,
]);
}
return inherited.get(anAtom) as [T, Scope];
return inherited.get(scopeKey)?.get(anAtom) as [T, Scope];
}
if (!inherited.has(anAtom)) {
if (!inherited.get(scopeKey)?.has(anAtom)) {
// non-primitive atoms may need to access scoped atoms
// so we need to create a copy of the atom
inherited.set(anAtom, [inheritAtom(anAtom, anAtom)]);
setInheritedAtom(inheritAtom(anAtom, anAtom), anAtom);
}
return inherited.get(anAtom) as [T];
return inherited.get(scopeKey)?.get(anAtom) as [T, Scope?];
}

function setInheritedAtom<T extends AnyAtom>(
scopedAtom: T,
originalAtom: T,
implicitScope?: Scope,
explicitScope?: Scope,
) {
const scopeKey = implicitScope ?? globalScopeKey;
if (!inherited.has(scopeKey)) {
inherited.set(scopeKey, new Map());
}
inherited.get(scopeKey)!.set(
originalAtom,
[
scopedAtom, //
explicitScope,
].filter(Boolean) as [T, Scope?],
);
}

/**
Expand Down Expand Up @@ -211,3 +248,7 @@ function isWritableAtom(anAtom: AnyAtom): anAtom is AnyWritableAtom {
}

const { read: defaultRead, write: defaultWrite } = atom<unknown>(null);

function toString(this: { name: string }) {
return this.name;
}

0 comments on commit fb17e03

Please sign in to comment.