UNPKG

components-switch

Version:

A lightweight React utility component library featuring Switch and Match for conditional rendering, inspired by SolidJS. Simplifies readable and declarative conditional logic in JSX.

1 lines 2.91 kB
{"version":3,"file":"components-switch.esm.mjs","sources":["../src/Match.tsx","../src/utils.ts","../src/Switch.tsx"],"sourcesContent":["import { ReactNode } from \"react\";\nimport { BoolOrFn } from \"./types\";\n\nexport type MatchProps = {\n children: ReactNode;\n when: BoolOrFn;\n}\n\nexport function Match({ children }: MatchProps) {\n return children\n}\n","import { isValidElement, ReactElement, ReactNode } from \"react\";\n\nimport { BoolOrFn } from \"./types\";\nimport { Match, MatchProps } from \"./Match\";\n\nexport function isMatchElement(element: ReactNode): element is ReactElement<MatchProps, typeof Match> {\n return (\n isValidElement(element) &&\n element.type === Match &&\n \"when\" in (element.props as MatchProps)\n );\n}\n\nexport function isMatchValidCondition(condition: BoolOrFn) {\n try {\n if (condition === undefined || condition === null) {\n return false;\n }\n\n if (typeof condition === \"function\") {\n return condition();\n }\n\n return !!condition;\n } catch {\n return false;\n }\n}\n","import { isValidElement, ReactNode } from \"react\"\n\nimport { Match } from \"./Match\";\nimport { OneOrMore } from \"./types\";\nimport { isMatchElement, isMatchValidCondition } from \"./utils\";\n\nexport type SwitchProps = {\n children: OneOrMore<typeof Match>\n fallback?: ReactNode;\n}\n\nexport function Switch({children, fallback}: SwitchProps) {\n try {\n if (!Array.isArray(children)) children = [children];\n\n const childrenToShow = [];\n\n for (let i = 0; i < children.length; ++i) {\n const child = children[i];\n\n if (!isValidElement(child)) {\n continue;\n }\n \n if (isMatchElement(child) && !isMatchValidCondition(child.props.when)) {\n continue;\n }\n\n childrenToShow.push(child);\n }\n\n\n if (childrenToShow.length === 0) {\n return fallback;\n }\n\n return childrenToShow;\n } catch {\n return fallback;\n }\n}"],"names":["Match","_ref","children","isMatchValidCondition","condition","_unused","Switch","element","fallback","Array","isArray","childrenToShow","i","length","child","isValidElement","type","props","when","push"],"mappings":"gDAQgBA,EAAKC,GACjB,OAD4BA,EAARC,QAExB,CCGM,SAAUC,EAAsBC,GAClC,IACI,OAAIA,UAIqB,mBAAdA,EACAA,MAGFA,EACb,CAAE,MAAAC,GACE,QACJ,CACJ,UChBgBC,EAAML,GAAE,IDNOM,ECMPL,EAAQD,EAARC,SAAUM,EAAQP,EAARO,SAC9B,IACSC,MAAMC,QAAQR,KAAWA,EAAW,CAACA,IAI1C,IAFA,IAAMS,EAAiB,GAEdC,EAAI,EAAGA,EAAIV,EAASW,SAAUD,EAAG,CACtC,IAAME,EAAQZ,EAASU,GAElBG,EAAeD,KDbxBC,EAFuBR,ECmBAO,IDhBvBP,EAAQS,OAAShB,GACjB,SAAWO,EAAQU,QCeed,EAAsBW,EAAMG,MAAMC,OAIhEP,EAAeQ,KAAKL,GACxB,CAGA,OAA8B,IAA1BH,EAAeE,OACRL,EAGJG,CACX,CAAE,MAAAN,GACE,OAAOG,CACX,CACJ"}