Skip to content

Commit e071d57

Browse files
committed
Add fallback prop
1 parent 0a7969b commit e071d57

File tree

2 files changed

+40
-1
lines changed

2 files changed

+40
-1
lines changed

packages/match/src/index.ts

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,13 +28,15 @@ export function Match<
2828
on: T | null | undefined,
2929
tag: Tag,
3030
case: {[K in T[Tag]]: (v: Accessor<T & {[k in Tag]: K}>) => JSX.Element},
31+
fallback?: JSX.Element,
3132
partial?: false,
3233
}): JSX.Element
3334
export function Match<
3435
T extends {kind: PropertyKey},
3536
>(props: {
3637
on: T | null | undefined,
3738
case: {[K in T['kind']]: (v: Accessor<T & {[k in 'kind']: K}>) => JSX.Element},
39+
fallback?: JSX.Element,
3840
partial?: false,
3941
}): JSX.Element
4042
export function Match<
@@ -44,16 +46,18 @@ export function Match<
4446
on: T | null | undefined,
4547
tag: Tag,
4648
case: {[K in T[Tag]]?: (v: Accessor<T & {[k in Tag]: K}>) => JSX.Element},
49+
fallback?: JSX.Element,
4750
partial: true,
4851
}): JSX.Element
4952
export function Match<
5053
T extends {kind: PropertyKey},
5154
>(props: {
5255
on: T | null | undefined,
5356
case: {[K in T['kind']]?: (v: Accessor<T & {[k in 'kind']: K}>) => JSX.Element},
57+
fallback?: JSX.Element,
5458
partial: true,
5559
}): JSX.Element
5660
export function Match(props: any): any {
5761
const kind = createMemo(() => props.on?.[props.tag ?? 'kind'])
58-
return createMemo(() => props.case[kind()]?.(() => props.on))
62+
return createMemo(() => props.case[kind()]?.(() => props.on) ?? props.fallback)
5963
}

packages/match/test/index.test.tsx

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -106,4 +106,39 @@ v.describe("Match", () => {
106106

107107
data.dispose();
108108
});
109+
110+
v.test("fallback", () => {
111+
112+
type MyUnion = {
113+
kind: 'foo',
114+
foo: 'foo-value',
115+
} | {
116+
kind: 'bar',
117+
bar: 'bar-value',
118+
}
119+
120+
const [value, setValue] = s.createSignal<MyUnion>()
121+
122+
const data = s.createRoot(dispose => {
123+
return {
124+
dispose,
125+
result: s.children(() => <>
126+
<Match on={value()} case={{
127+
foo: v => <>{v().foo}</>,
128+
bar: v => <>{v().bar}</>,
129+
}} fallback={<>fallback</>} />
130+
</>)
131+
}
132+
})
133+
134+
v.expect(data.result()).toEqual(<>fallback</>);
135+
136+
setValue({kind: 'foo', foo: 'foo-value'});
137+
v.expect(data.result()).toEqual(<>foo-value</>);
138+
139+
setValue(undefined);
140+
v.expect(data.result()).toEqual(<>fallback</>);
141+
142+
data.dispose();
143+
});
109144
});

0 commit comments

Comments
 (0)