From 2b2897ffe967973fbe0194accf88e304db771238 Mon Sep 17 00:00:00 2001 From: Wonsuk Choi Date: Fri, 19 Jul 2024 15:12:42 +0900 Subject: [PATCH] =?UTF-8?q?feat(ui/react/styles):=20extractDynamicProps=20?= =?UTF-8?q?=ED=95=A8=EC=88=98=20=EC=B6=94=EA=B0=80=20(#248)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../react/src/styles/extract-dynamic-props.ts | 49 +++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 packages/ui/react/src/styles/extract-dynamic-props.ts diff --git a/packages/ui/react/src/styles/extract-dynamic-props.ts b/packages/ui/react/src/styles/extract-dynamic-props.ts new file mode 100644 index 0000000..4b3ec7e --- /dev/null +++ b/packages/ui/react/src/styles/extract-dynamic-props.ts @@ -0,0 +1,49 @@ +import { cx, mergeStyles, toPx } from '@favolink-ui/utils'; +import { assignInlineVars } from '@vanilla-extract/dynamic'; +import { type CSSProperties } from 'react'; + +export function extractDynamicProps< + P extends { + style?: CSSProperties; + className?: string; + [key: string]: any; + }, + S extends Record, +>(props: P, dynamicVars: Record, dynamicStyles: S) { + const { className, style, ...restProps } = props; + + let composedClassName: string = ''; + let willAssignInlineVars: Record = {}; + + for (const prop in restProps) { + if (prop in dynamicStyles) { + composedClassName = cx( + composedClassName, + restProps[prop] && dynamicStyles[prop], + ); + + const regex = new RegExp(`${prop}Var`, 'g'); + + for (const dynamicVar in dynamicVars) { + if (regex.test(dynamicVar)) { + willAssignInlineVars = { + ...willAssignInlineVars, + [dynamicVars[dynamicVar] as string]: toPx(restProps[prop]), + }; + + break; + } + } + + delete restProps[prop]; + } + } + + const resultProps = { + ...restProps, + className: cx(composedClassName, className), + style: mergeStyles(assignInlineVars(willAssignInlineVars), style), + } as Omit; + + return resultProps; +}