|
| 1 | +import { component$, h, useComputed$ } from '@builder.io/qwik'; |
| 2 | + |
| 3 | +export function $$styled( |
| 4 | + Comp: any, |
| 5 | + styles: ((options?: any) => string) & { |
| 6 | + macaronMeta: { |
| 7 | + variants: string[]; |
| 8 | + defaultClassName: string; |
| 9 | + variantConcat(options: any): string; |
| 10 | + }; |
| 11 | + } |
| 12 | +) { |
| 13 | + const StyledComponent: any = component$(({ as, ...props }: any) => { |
| 14 | + let CompToRender = as ?? Comp; |
| 15 | + const propsSignal = useComputed$(() => { |
| 16 | + const [classes, others]: any[] = [{}, {}]; |
| 17 | + |
| 18 | + for (const [key, value] of Object.entries(props)) { |
| 19 | + if (StyledComponent.variants.includes(key)) { |
| 20 | + classes[key] = value; |
| 21 | + } else { |
| 22 | + others[key] = value; |
| 23 | + } |
| 24 | + } |
| 25 | + |
| 26 | + return { variants: classes, others }; |
| 27 | + }); |
| 28 | + const className = useComputed$(() => { |
| 29 | + const classes = StyledComponent.classes( |
| 30 | + propsSignal.value.variants, |
| 31 | + props.className |
| 32 | + ); |
| 33 | + return classes.join(' '); |
| 34 | + }); |
| 35 | + |
| 36 | + if (typeof CompToRender === 'string') { |
| 37 | + return h(CompToRender, { ...propsSignal.value.others, className }); |
| 38 | + } |
| 39 | + |
| 40 | + return h(CompToRender, { ...props, className }); |
| 41 | + }); |
| 42 | + |
| 43 | + StyledComponent.toString = () => StyledComponent.selector(null); |
| 44 | + StyledComponent.variants = [ |
| 45 | + ...(styles.macaronMeta.variants ?? []), |
| 46 | + ...(Comp.variants ?? []), |
| 47 | + ]; |
| 48 | + StyledComponent.variantConcat = styles.macaronMeta.variantConcat; |
| 49 | + StyledComponent.classes = ( |
| 50 | + variants: any, |
| 51 | + merge?: string, |
| 52 | + fn: any = styles |
| 53 | + ) => { |
| 54 | + const classes = new Set( |
| 55 | + classNames(fn(variants) + (merge ? ` ${merge}` : '')) |
| 56 | + ); |
| 57 | + |
| 58 | + if (Comp.classes) { |
| 59 | + for (const c of Comp.classes( |
| 60 | + variants, |
| 61 | + merge, |
| 62 | + Comp.variantConcat |
| 63 | + ) as string[]) { |
| 64 | + classes.add(c); |
| 65 | + } |
| 66 | + } |
| 67 | + |
| 68 | + return Array.from(classes); |
| 69 | + }; |
| 70 | + StyledComponent.selector = (variants: any) => { |
| 71 | + const classes = StyledComponent.classes( |
| 72 | + variants, |
| 73 | + undefined, |
| 74 | + styles.macaronMeta.variantConcat |
| 75 | + ); |
| 76 | + // first element isn't empty |
| 77 | + if (classes.length > 0 && classes[0].length > 0) { |
| 78 | + return '.' + classes.join('.'); |
| 79 | + } |
| 80 | + return classes.join('.'); |
| 81 | + }; |
| 82 | + |
| 83 | + return StyledComponent; |
| 84 | +} |
| 85 | + |
| 86 | +function classNames(className: string) { |
| 87 | + return className.split(' '); |
| 88 | +} |
0 commit comments