|
1 | | -import { type FC, type PropsWithChildren } from 'react'; |
2 | | -import { DispatchSwitch, Context, useSwitch, useSwitchStore } from './switch.store'; |
3 | | - |
4 | | -export * from './case'; |
| 1 | +import type { FC, PropsWithChildren } from 'react'; |
5 | 2 |
|
| 3 | +type Child = typeof Case | typeof Default; |
6 | 4 | export const Switch: FC<PropsWithChildren<{}>> = ({ children }) => { |
7 | | - const [state, dispatch] = useSwitch(); |
8 | | - return ( |
9 | | - <Context.Provider value={state}> |
10 | | - <DispatchSwitch.Provider value={dispatch}>{children}</DispatchSwitch.Provider> |
11 | | - <Render /> |
12 | | - </Context.Provider> |
13 | | - ); |
14 | | -}; |
| 5 | + let matchChild: Child | null = null; |
| 6 | + let defaultCase: typeof Default | null = null; |
15 | 7 |
|
16 | | -const Render = () => { |
17 | | - const state = useSwitchStore(); |
18 | | - let activeKey; |
19 | | - for (var key in state.active) { |
20 | | - if (state.active[key] === true) { |
21 | | - activeKey = key; |
22 | | - break; |
| 8 | + const childs = Array.isArray(children) ? children : [children]; |
| 9 | + childs.some((child) => { |
| 10 | + if (!defaultCase && child && child.type === Default) { |
| 11 | + defaultCase = child; |
23 | 12 | } |
24 | | - } |
25 | | - return state[activeKey ?? 'default'] ?? null; |
| 13 | + if (child && child.type === Case) { |
| 14 | + const { condition } = child.props; |
| 15 | + const conditionIsTrue = Boolean(condition); |
| 16 | + if (conditionIsTrue) { |
| 17 | + matchChild = child; |
| 18 | + return true; |
| 19 | + } |
| 20 | + } |
| 21 | + return false; |
| 22 | + }); |
| 23 | + return <>{matchChild ?? defaultCase ?? null}</>; |
| 24 | +}; |
| 25 | + |
| 26 | +type TagType = React.ElementType | keyof JSX.IntrinsicElements; |
| 27 | +interface CaseElementProps<T extends TagType> { |
| 28 | + as?: T; |
| 29 | + readonly condition?: boolean; |
| 30 | +} |
| 31 | + |
| 32 | +export type CaseProps<T extends TagType> = CaseElementProps<T> & React.ComponentPropsWithoutRef<T>; |
| 33 | + |
| 34 | +export const Case = <T extends TagType>(props: CaseProps<T>) => { |
| 35 | + const { children, condition, as: Comp, ...reset } = props; |
| 36 | + const Elm = Comp as TagType; |
| 37 | + return Elm ? <Elm {...reset}>{children}</Elm> : children; |
26 | 38 | }; |
| 39 | + |
| 40 | +export const Default = <T extends TagType>(props: CaseProps<T>) => <Case {...props} />; |
0 commit comments