Skip to content

Commit

Permalink
fix(lens): reactive match (#973)
Browse files Browse the repository at this point in the history
* test(lens): add reviewed reactive change test

* fix(lens): add reactive functionality in match

* test(lens): add reactive change test
  • Loading branch information
caio2983 authored Nov 14, 2024
1 parent 58bd42c commit 659b78d
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 4 deletions.
17 changes: 17 additions & 0 deletions packages/lens/src/match.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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()
9 changes: 5 additions & 4 deletions packages/lens/src/match.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ export function match<T>(
name = __count('match'),
): Match<T> {
type Case = {
clause: (ctx: Ctx, expression: T) => boolean
clause: (ctx: CtxSpy, expression: T) => boolean
statement: {} | Atom | ((ctx: Ctx, expression: T) => any)
}
const cases: Array<Case> = []
Expand All @@ -70,11 +70,12 @@ export function match<T>(
: 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'
Expand All @@ -89,7 +90,7 @@ export function match<T>(
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),
Expand Down

0 comments on commit 659b78d

Please sign in to comment.