From 659b78dbe650a2e6747e8f1918210054cf369940 Mon Sep 17 00:00:00 2001 From: Caio de Luna <82726583+caio2983@users.noreply.github.com> Date: Thu, 14 Nov 2024 05:03:15 -0300 Subject: [PATCH] fix(lens): reactive match (#973) * test(lens): add reviewed reactive change test * fix(lens): add reactive functionality in match * test(lens): add reactive change test --- packages/lens/src/match.test.ts | 17 +++++++++++++++++ packages/lens/src/match.ts | 9 +++++---- 2 files changed, 22 insertions(+), 4 deletions(-) diff --git a/packages/lens/src/match.test.ts b/packages/lens/src/match.test.ts index f0ec49b34..70d8f17cf 100644 --- a/packages/lens/src/match.test.ts +++ b/packages/lens/src/match.test.ts @@ -87,4 +87,21 @@ test('default should checks in the end', () => { ;`👍` //? }) +test('reactive change', () => { + const ctx = createTestCtx() + + const boolAtom = atom(true) + const compAtom = match(true) + .is(boolAtom, () => 'a') + .default(() => 'b') + + const track = ctx.subscribeTrack(compAtom) + + assert.equal(track.inputs(), ['a']) + + boolAtom(ctx, false) + boolAtom(ctx, true) + assert.equal(track.inputs(), ['a', 'b', 'a']) +}) + test.run() diff --git a/packages/lens/src/match.ts b/packages/lens/src/match.ts index 61fff6a81..de525c7a8 100644 --- a/packages/lens/src/match.ts +++ b/packages/lens/src/match.ts @@ -56,7 +56,7 @@ export function match( name = __count('match'), ): Match { type Case = { - clause: (ctx: Ctx, expression: T) => boolean + clause: (ctx: CtxSpy, expression: T) => boolean statement: {} | Atom | ((ctx: Ctx, expression: T) => any) } const cases: Array = [] @@ -70,11 +70,12 @@ export function match( : typeof expression === 'function' ? (expression as Fn)(ctxSpy) : expression - const ctx = merge(ctxSpy, { spy: undefined }) + + const list = [...cases, _truthy, _falsy, _default].filter(Boolean) for (const { clause, statement } of list) { - if (clause(ctx, value)) { + if (clause(ctxSpy, value)) { return isAtom(statement) ? ctxSpy.spy(statement) : typeof statement === 'function' @@ -89,7 +90,7 @@ export function match( is(clause: any, statement: any) { cases.push({ clause: isAtom(clause) - ? (ctx, value) => Object.is(value, ctx.get(clause)) + ? (ctx, value) => Object.is(value, ctx.spy(clause)) : typeof clause === 'function' ? clause : (ctx, value) => Object.is(value, clause),