Skip to content

Instantly share code, notes, and snippets.

@yarinsa
Created October 24, 2023 22:45
Show Gist options
  • Save yarinsa/d7ab076626723bcac94b59d3e128edde to your computer and use it in GitHub Desktop.
Save yarinsa/d7ab076626723bcac94b59d3e128edde to your computer and use it in GitHub Desktop.
create-cx.ts
import {prefix} from '@acme/design-tokens';
import {ArgumentArray} from 'classnames';
import classNames from 'classnames';
type CXOptions = {
customPrefix?: string;
};
export const createCX = ({customPrefix}: CXOptions = {}) => {
const prefixToUse = `${customPrefix ? `${prefix}__${customPrefix}` : `${prefix}`}__`;
const addPrefix = (className: string) => {
if (!className) return `${prefix}_${customPrefix}`;
return `${prefixToUse}${className}`;
};
const cx = (...args: ArgumentArray): string => {
const processedArgs = args.map(arg => {
if (typeof arg === `string`) {
return addPrefix(arg);
}
if (Array.isArray(arg)) {
return cx(...arg);
}
if (typeof arg === `object`) {
const newObj: Record<string, any> = {};
for (const key in arg) {
newObj[addPrefix(key)] = arg[key];
}
return newObj;
}
return arg;
});
return classNames(...processedArgs);
};
return {cx, prefix: prefixToUse};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment