From ac954b6b9554da74bec217b61508b6bb58215225 Mon Sep 17 00:00:00 2001 From: Francisco Veracoechea Date: Thu, 18 Apr 2024 15:58:42 -0400 Subject: [PATCH 1/7] chore: backup original implementation --- packages/cva/src/old-index.ts | 240 ++++++++++++++++++++++++++++++++++ 1 file changed, 240 insertions(+) create mode 100644 packages/cva/src/old-index.ts diff --git a/packages/cva/src/old-index.ts b/packages/cva/src/old-index.ts new file mode 100644 index 0000000..0815a99 --- /dev/null +++ b/packages/cva/src/old-index.ts @@ -0,0 +1,240 @@ +import { clsx } from "clsx"; + +/* Types + ============================================ */ + +/* clsx + ---------------------------------- */ + +// When compiling with `declaration: true`, many projects experience the dreaded +// TS2742 error. To combat this, we copy clsx's types manually. +// Should this project move to JSDoc, this workaround would no longer be needed. + +type ClassValue = + | ClassArray + | ClassDictionary + | string + | number + | null + | boolean + | undefined; +type ClassDictionary = Record; +type ClassArray = ClassValue[]; + +/* Utils + ---------------------------------- */ + +type OmitUndefined = T extends undefined ? never : T; +type StringToBoolean = T extends "true" | "false" ? boolean : T; +type UnionToIntersection = (U extends any ? (k: U) => void : never) extends ( + k: infer I, +) => void + ? I + : never; + +export type VariantProps any> = Omit< + OmitUndefined[0]>, + "class" | "className" +>; + +/* compose + ---------------------------------- */ + +export interface Compose { + []>( + ...components: [...T] + ): ( + props?: ( + | UnionToIntersection< + { + [K in keyof T]: VariantProps; + }[number] + > + | undefined + ) & + CVAClassProp, + ) => string; +} + +/* cx + ---------------------------------- */ + +export interface CX { + (...inputs: ClassValue[]): string; +} + +export type CXOptions = Parameters; +export type CXReturn = ReturnType; + +/* cva + ============================================ */ + +type CVAConfigBase = { base?: ClassValue }; +type CVAVariantShape = Record>; +type CVAVariantSchema = { + [Variant in keyof V]?: StringToBoolean | undefined; +}; +type CVAClassProp = + | { + class?: ClassValue; + className?: never; + } + | { + class?: never; + className?: ClassValue; + }; + +export interface CVA { + < + _ extends "cva's generic parameters are restricted to internal use only.", + V, + >( + config: V extends CVAVariantShape + ? CVAConfigBase & { + variants?: V; + compoundVariants?: (V extends CVAVariantShape + ? ( + | CVAVariantSchema + | { + [Variant in keyof V]?: + | StringToBoolean + | StringToBoolean[] + | undefined; + } + ) & + CVAClassProp + : CVAClassProp)[]; + defaultVariants?: CVAVariantSchema; + } + : CVAConfigBase & { + variants?: never; + compoundVariants?: never; + defaultVariants?: never; + }, + ): ( + props?: V extends CVAVariantShape + ? CVAVariantSchema & CVAClassProp + : CVAClassProp, + ) => string; +} + +/* defineConfig + ---------------------------------- */ + +export interface DefineConfigOptions { + hooks?: { + /** + * @deprecated please use `onComplete` + */ + "cx:done"?: (className: string) => string; + /** + * Returns the completed string of concatenated classes/classNames. + */ + onComplete?: (className: string) => string; + }; +} + +export interface DefineConfig { + (options?: DefineConfigOptions): { + compose: Compose; + cx: CX; + cva: CVA; + }; +} + +/* Exports + ============================================ */ + +const falsyToString = (value: T) => + typeof value === "boolean" ? `${value}` : value === 0 ? "0" : value; + +export const defineConfig: DefineConfig = (options) => { + const cx: CX = (...inputs) => { + if (typeof options?.hooks?.["cx:done"] !== "undefined") + return options?.hooks["cx:done"](clsx(inputs)); + + if (typeof options?.hooks?.onComplete !== "undefined") + return options?.hooks.onComplete(clsx(inputs)); + + return clsx(inputs); + }; + + const cva: CVA = (config) => (props) => { + if (config?.variants == null) + return cx(config?.base, props?.class, props?.className); + + const { variants, defaultVariants } = config; + + const getVariantClassNames = Object.keys(variants).map( + (variant: keyof typeof variants) => { + const variantProp = props?.[variant as keyof typeof props]; + const defaultVariantProp = defaultVariants?.[variant]; + + const variantKey = (falsyToString(variantProp) || + falsyToString( + defaultVariantProp, + )) as keyof (typeof variants)[typeof variant]; + + return variants[variant][variantKey]; + }, + ); + + const defaultsAndProps = { + ...defaultVariants, + // remove `undefined` props + ...(props && + Object.entries(props).reduce( + (acc, [key, value]) => + typeof value === "undefined" ? acc : { ...acc, [key]: value }, + {} as typeof props, + )), + }; + + const getCompoundVariantClassNames = config?.compoundVariants?.reduce( + (acc, { class: cvClass, className: cvClassName, ...cvConfig }) => + Object.entries(cvConfig).every(([cvKey, cvSelector]) => { + const selector = + defaultsAndProps[cvKey as keyof typeof defaultsAndProps]; + + return Array.isArray(cvSelector) + ? cvSelector.includes(selector) + : selector === cvSelector; + }) + ? [...acc, cvClass, cvClassName] + : acc, + [] as ClassValue[], + ); + + return cx( + config?.base, + getVariantClassNames, + getCompoundVariantClassNames, + props?.class, + props?.className, + ); + }; + + const compose: Compose = + (...components) => + (props) => { + const propsWithoutClass = Object.fromEntries( + Object.entries(props || {}).filter( + ([key]) => !["class", "className"].includes(key), + ), + ); + + return cx( + components.map((component) => component(propsWithoutClass)), + props?.class, + props?.className, + ); + }; + + return { + compose, + cva, + cx, + }; +}; + +export const { compose, cva, cx } = defineConfig(); From a80aa7c54a77ad135dd24b698471a7a4dca03e1b Mon Sep 17 00:00:00 2001 From: Francisco Veracoechea Date: Thu, 18 Apr 2024 15:59:58 -0400 Subject: [PATCH 2/7] feat: add compound variants type --- packages/cva/src/index.ts | 25 +++++++++++++------------ 1 file changed, 13 insertions(+), 12 deletions(-) diff --git a/packages/cva/src/index.ts b/packages/cva/src/index.ts index 0815a99..c9f77f4 100644 --- a/packages/cva/src/index.ts +++ b/packages/cva/src/index.ts @@ -84,6 +84,18 @@ type CVAClassProp = className?: ClassValue; }; +type CVACompoundVariants = (V extends CVAVariantShape + ? ( + | CVAVariantSchema + | { + [Variant in keyof V]?: + | StringToBoolean + | StringToBoolean[] + | undefined; + } + ) & + CVAClassProp + : CVAClassProp)[]; export interface CVA { < _ extends "cva's generic parameters are restricted to internal use only.", @@ -92,18 +104,7 @@ export interface CVA { config: V extends CVAVariantShape ? CVAConfigBase & { variants?: V; - compoundVariants?: (V extends CVAVariantShape - ? ( - | CVAVariantSchema - | { - [Variant in keyof V]?: - | StringToBoolean - | StringToBoolean[] - | undefined; - } - ) & - CVAClassProp - : CVAClassProp)[]; + compoundVariants?: CVACompoundVariants; defaultVariants?: CVAVariantSchema; } : CVAConfigBase & { From ffb8b1145975360569943b2395e5cddbcefff5a5 Mon Sep 17 00:00:00 2001 From: Francisco Veracoechea Date: Thu, 18 Apr 2024 16:01:05 -0400 Subject: [PATCH 3/7] feat: implement performance enhancements --- packages/cva/src/index.ts | 196 ++++++++++++++++++++++++++------------ 1 file changed, 136 insertions(+), 60 deletions(-) diff --git a/packages/cva/src/index.ts b/packages/cva/src/index.ts index c9f77f4..316bac6 100644 --- a/packages/cva/src/index.ts +++ b/packages/cva/src/index.ts @@ -96,6 +96,7 @@ type CVACompoundVariants = (V extends CVAVariantShape ) & CVAClassProp : CVAClassProp)[]; + export interface CVA { < _ extends "cva's generic parameters are restricted to internal use only.", @@ -142,87 +143,162 @@ export interface DefineConfig { cva: CVA; }; } - -/* Exports +/* Internal helper functions ============================================ */ +/** + * Type guard. + * Determines whether an object has a property with the specified name. + * */ +function isKeyOf, V = keyof R>( + record: R, + key: unknown, +): key is V { + return ( + (typeof key === "string" || + typeof key === "number" || + typeof key === "symbol") && + Object.prototype.hasOwnProperty.call(record, key) + ); +} + +/** + * Merges two given objects, Props take precedence over Defaults + * */ +function mergeDefaultsAndProps< + V extends CVAVariantShape, + P extends Record, + D extends CVAVariantSchema, +>(props: P = {} as P, defaults: D = {} as D) { + const result: Record = { ...defaults }; + + for (const key in props) { + if (!isKeyOf(props, key)) continue; + const value = props[key]; + if (typeof value !== "undefined") result[key] = value; + } + + return result as Record>; +} + +/** + * Returns a list of class variants based on the given Props and Defaults + * */ +function getVariantClassNames< + V extends CVAVariantShape, + P extends Record & CVAClassProp, + D extends CVAVariantSchema, +>(variants: V, props: P = {} as P, defaults: D = {} as D) { + const variantClassNames: ClassArray = []; + + for (const variant in variants) { + if (!isKeyOf(variants, variant)) continue; + const variantProp = props[variant]; + const defaultVariantProp = defaults[variant]; + + const variantKey = + falsyToString(variantProp) || falsyToString(defaultVariantProp); + + if (isKeyOf(variants[variant], variantKey)) + variantClassNames.push(variants[variant][variantKey]); + } + + return variantClassNames; +} + +/** + * Returns selected compound className variants based on Props and Defaults + * */ +function getCompoundVariantClassNames( + compoundVariants: CVACompoundVariants, + defaultsAndProps: ClassDictionary, +) { + const compoundClassNames: ClassArray = []; + + for (const compoundConfig of compoundVariants) { + let selectorMatches = true; + + for (const cvKey in compoundConfig) { + if ( + !isKeyOf(compoundConfig, cvKey) || + cvKey === "class" || + cvKey === "className" + ) + continue; + + const cvSelector = compoundConfig[cvKey]; + const selector = defaultsAndProps[cvKey]; + + const matches = Array.isArray(cvSelector) + ? cvSelector.includes(selector) + : selector === cvSelector; + + if (!matches) { + selectorMatches = false; + break; + } + } + + if (selectorMatches) + compoundClassNames.push(compoundConfig.class ?? compoundConfig.className); + } + + return compoundClassNames; +} + const falsyToString = (value: T) => typeof value === "boolean" ? `${value}` : value === 0 ? "0" : value; +/* Exports + ============================================ */ + export const defineConfig: DefineConfig = (options) => { const cx: CX = (...inputs) => { if (typeof options?.hooks?.["cx:done"] !== "undefined") return options?.hooks["cx:done"](clsx(inputs)); - if (typeof options?.hooks?.onComplete !== "undefined") return options?.hooks.onComplete(clsx(inputs)); return clsx(inputs); }; - const cva: CVA = (config) => (props) => { - if (config?.variants == null) - return cx(config?.base, props?.class, props?.className); - - const { variants, defaultVariants } = config; - - const getVariantClassNames = Object.keys(variants).map( - (variant: keyof typeof variants) => { - const variantProp = props?.[variant as keyof typeof props]; - const defaultVariantProp = defaultVariants?.[variant]; - - const variantKey = (falsyToString(variantProp) || - falsyToString( - defaultVariantProp, - )) as keyof (typeof variants)[typeof variant]; - - return variants[variant][variantKey]; - }, - ); - - const defaultsAndProps = { - ...defaultVariants, - // remove `undefined` props - ...(props && - Object.entries(props).reduce( - (acc, [key, value]) => - typeof value === "undefined" ? acc : { ...acc, [key]: value }, - {} as typeof props, - )), - }; + const cva: CVA = (config) => { + const { + variants, + defaultVariants = {}, + base, + compoundVariants = [], + } = config ?? {}; + + return (props) => { + if (config?.variants == null) + return cx(config?.base, props?.class, props?.className); + + const variantClassNames = getVariantClassNames( + config.variants, + props, + defaultVariants, + ); + + const compoundVariantClassNames = getCompoundVariantClassNames( + compoundVariants, + mergeDefaultsAndProps(props, defaultVariants), + ); - const getCompoundVariantClassNames = config?.compoundVariants?.reduce( - (acc, { class: cvClass, className: cvClassName, ...cvConfig }) => - Object.entries(cvConfig).every(([cvKey, cvSelector]) => { - const selector = - defaultsAndProps[cvKey as keyof typeof defaultsAndProps]; - - return Array.isArray(cvSelector) - ? cvSelector.includes(selector) - : selector === cvSelector; - }) - ? [...acc, cvClass, cvClassName] - : acc, - [] as ClassValue[], - ); - - return cx( - config?.base, - getVariantClassNames, - getCompoundVariantClassNames, - props?.class, - props?.className, - ); + return cx( + config?.base, + variantClassNames, + compoundVariantClassNames, + props?.class, + props?.className, + ); + }; }; const compose: Compose = (...components) => (props) => { - const propsWithoutClass = Object.fromEntries( - Object.entries(props || {}).filter( - ([key]) => !["class", "className"].includes(key), - ), - ); + const { class: _class, className, ...propsWithoutClass } = props ?? {}; return cx( components.map((component) => component(propsWithoutClass)), From c920bbfd355151898c1325d7eee76e3da3c9be3c Mon Sep 17 00:00:00 2001 From: Francisco Veracoechea Date: Thu, 18 Apr 2024 16:13:59 -0400 Subject: [PATCH 4/7] cleanup --- packages/cva/src/index.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/cva/src/index.ts b/packages/cva/src/index.ts index 316bac6..a7da264 100644 --- a/packages/cva/src/index.ts +++ b/packages/cva/src/index.ts @@ -271,11 +271,11 @@ export const defineConfig: DefineConfig = (options) => { } = config ?? {}; return (props) => { - if (config?.variants == null) + if (variants == null) return cx(config?.base, props?.class, props?.className); const variantClassNames = getVariantClassNames( - config.variants, + variants, props, defaultVariants, ); From 7a3d8a4d65bb4463674edebc00e7ecd389a302c7 Mon Sep 17 00:00:00 2001 From: Francisco Veracoechea Date: Fri, 19 Apr 2024 09:30:29 -0400 Subject: [PATCH 5/7] feat: update benchmarks --- packages/cva/package.json | 1 + packages/cva/src/benchmark.ts | 162 ++++++++++++++++++++++++++++++++++ pnpm-lock.yaml | 9 +- 3 files changed, 169 insertions(+), 3 deletions(-) create mode 100644 packages/cva/src/benchmark.ts diff --git a/packages/cva/package.json b/packages/cva/package.json index 1ae6ee8..bb52b83 100644 --- a/packages/cva/package.json +++ b/packages/cva/package.json @@ -53,6 +53,7 @@ "npm-run-all": "4.1.5", "react": "18.2.0", "react-dom": "18.2.0", + "tinybench": "^2.7.0", "ts-node": "10.8.1", "typescript": "5.1.3" }, diff --git a/packages/cva/src/benchmark.ts b/packages/cva/src/benchmark.ts new file mode 100644 index 0000000..d3028c6 --- /dev/null +++ b/packages/cva/src/benchmark.ts @@ -0,0 +1,162 @@ +import { Bench } from "tinybench"; + +import { defineConfig as originalDefineConfig } from "./old-index"; +import { defineConfig as enhancedDefineConfig } from "./index"; + +function logResultsTable(bench: Bench) { + const table: any[] = []; + + for (const task of bench.tasks) { + if (!task.result) continue; + table.push({ + name: task.name, + "ops/sec": task.result.error ? 0 : task.result.hz, + "average (ms)": task.result.error ? "NaN" : task.result.mean.toFixed(3), + samples: task.result.error ? "NaN" : task.result.samples.length, + }); + } + + const results = table + .map((x) => ({ + ...x, + "ops/sec": parseFloat(parseInt(x["ops/sec"].toString(), 10).toString()), + })) + .sort( + (a: Record, b: Record) => + b["ops/sec"] - a["ops/sec"], + ); + + const maxOps = Math.max(...results.map((x) => x["ops/sec"])); + + console.table( + results.map((x, i) => ({ + ...x, + [`relative to ${results[0]["name"]}`]: + i === 0 + ? "" + : `${(maxOps / parseInt(x["ops/sec"])).toFixed(2)} x slower`, + })), + ); +} + +const originalCVA = originalDefineConfig().cva; +const enhancedCVA = enhancedDefineConfig().cva; + +const buttonWithoutBaseWithDefaultsWithClassNameString = { + base: "button font-semibold border rounded", + variants: { + intent: { + unset: null, + primary: + "button--primary bg-blue-500 text-white border-transparent hover:bg-blue-600", + secondary: + "button--secondary bg-white text-gray-800 border-gray-400 hover:bg-gray-100", + warning: + "button--warning bg-yellow-500 border-transparent hover:bg-yellow-600", + danger: [ + "button--danger", + [ + 1 && "bg-red-500", + { baz: false, bat: null }, + ["text-white", ["border-transparent"]], + ], + "hover:bg-red-600", + ], + }, + disabled: { + unset: null, + true: "button--disabled opacity-050 cursor-not-allowed", + false: "button--enabled cursor-pointer", + }, + size: { + unset: null, + small: "button--small text-sm py-1 px-2", + medium: "button--medium text-base py-2 px-4", + large: "button--large text-lg py-2.5 px-4", + }, + m: { + unset: null, + 0: "m-0", + 1: "m-1", + }, + }, + compoundVariants: [ + { + intent: "primary", + size: "medium", + className: "button--primary-medium uppercase", + }, + { + intent: "warning", + disabled: false, + className: "button--warning-enabled text-gray-800", + }, + { + intent: "warning", + disabled: true, + className: [ + "button--warning-disabled", + [1 && "text-black", { baz: false, bat: null }], + ], + }, + { + intent: ["warning", "danger"], + className: "button--warning-danger !border-red-500", + }, + { + intent: ["warning", "danger"], + size: "medium", + className: "button--warning-danger-medium", + }, + ], + defaultVariants: { + m: 0, + disabled: false, + intent: "primary", + size: "medium", + }, +} as any; + +async function run() { + const benchmark = new Bench({ time: 5000 }); + + benchmark.add("cva/main", () => { + const buttonVariants = originalCVA( + buttonWithoutBaseWithDefaultsWithClassNameString, + ); + buttonVariants({}); + buttonVariants({ intent: "primary", disabled: true } as any); + buttonVariants({ intent: "primary", size: "medium" } as any); + buttonVariants({ + intent: "warning", + size: "medium", + disabled: true, + } as any); + buttonVariants({ size: "small" } as any); + buttonVariants({ size: "large", intent: "unset" } as any); + }); + + benchmark.add("feat/performance-enhancement", () => { + const buttonVariants = enhancedCVA( + buttonWithoutBaseWithDefaultsWithClassNameString, + ); + buttonVariants({}); + buttonVariants({ intent: "primary", disabled: true } as any); + buttonVariants({ intent: "primary", size: "medium" } as any); + buttonVariants({ + intent: "warning", + size: "medium", + disabled: true, + } as any); + buttonVariants({ size: "small" } as any); + buttonVariants({ size: "large", intent: "unset" } as any); + }); + + await benchmark.warmup(); + await benchmark.run(); + logResultsTable(benchmark); + + process.exit(); +} + +run(); diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 8ab25b2..299cb00 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -330,6 +330,9 @@ importers: react-dom: specifier: 18.2.0 version: 18.2.0(react@18.2.0) + tinybench: + specifier: ^2.7.0 + version: 2.7.0 ts-node: specifier: 10.8.1 version: 10.8.1(@swc/core@1.2.198)(@types/node@18.11.18)(typescript@5.1.3) @@ -8642,8 +8645,8 @@ packages: resolution: {integrity: sha512-AD5ih2NlSssTCwsMznbvwMZpJ1cbhkGd2uueNxzv2jDlEeZdU04JQfRnggJQ8DrcVBGjAsCKwFBbDlVNtEMlzw==} dev: false - /tinybench@2.5.0: - resolution: {integrity: sha512-kRwSG8Zx4tjF9ZiyH4bhaebu+EDz1BOx9hOigYHlUW4xxI/wKIUQUqo018UlU4ar6ATPBsaMrdbKZ+tmPdohFA==} + /tinybench@2.7.0: + resolution: {integrity: sha512-Qgayeb106x2o4hNzNjsZEfFziw8IbKqtbXBjVh7VIZfBxfD5M4gWtpyx5+YTae2gJ6Y6Dz/KLepiv16RFeQWNA==} dev: true /tinypool@0.7.0: @@ -9252,7 +9255,7 @@ packages: picocolors: 1.0.0 std-env: 3.4.0 strip-literal: 1.3.0 - tinybench: 2.5.0 + tinybench: 2.7.0 tinypool: 0.7.0 vite: 4.2.1(@types/node@18.11.18) vite-node: 0.34.2(@types/node@18.11.18) From ad7e196a95a5568dcefdc8bfb66b7785cd4c3d21 Mon Sep 17 00:00:00 2001 From: Francisco Veracoechea Date: Thu, 25 Apr 2024 10:26:05 -0400 Subject: [PATCH 6/7] Add tinybench dev dependency --- packages/cva/package.json | 1 + pnpm-lock.yaml | 4 ++-- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/packages/cva/package.json b/packages/cva/package.json index ea57a48..df41a17 100644 --- a/packages/cva/package.json +++ b/packages/cva/package.json @@ -53,6 +53,7 @@ "npm-run-all": "4.1.5", "react": "18.2.0", "react-dom": "18.2.0", + "tinybench": "^2.8.0", "ts-node": "10.9.2", "typescript": "5.4.5" }, diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index fa59065..fa83e15 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -334,8 +334,8 @@ importers: specifier: 18.2.0 version: 18.2.0(react@18.2.0) tinybench: - specifier: ^2.7.0 - version: 2.7.0 + specifier: ^2.8.0 + version: 2.8.0 ts-node: specifier: 10.9.2 version: 10.9.2(@swc/core@1.4.16(@swc/helpers@0.5.2))(@types/node@20.12.7)(typescript@5.4.5) From 2a7e7084688e366235adbdd2ed0dc70b7b2120de Mon Sep 17 00:00:00 2001 From: Francisco Veracoechea Date: Thu, 25 Apr 2024 10:30:35 -0400 Subject: [PATCH 7/7] Add early return when no variants are provided --- packages/cva/src/index.ts | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/packages/cva/src/index.ts b/packages/cva/src/index.ts index 91f9f1c..6614032 100644 --- a/packages/cva/src/index.ts +++ b/packages/cva/src/index.ts @@ -285,10 +285,10 @@ export const defineConfig: DefineConfig = (options) => { compoundVariants = [], } = config ?? {}; - return (props) => { - if (variants == null) - return cx(config?.base, props?.class, props?.className); + if (variants == null) + return (props) => cx(base, props?.class, props?.className); + return (props) => { const variantClassNames = getVariantClassNames( variants, props, @@ -301,7 +301,7 @@ export const defineConfig: DefineConfig = (options) => { ); return cx( - config?.base, + base, variantClassNames, compoundVariantClassNames, props?.class,