|
| 1 | +import { Table } from '@digdir/designsystemet-react'; |
| 2 | +import cl from 'clsx'; |
| 3 | +import { forwardRef } from 'react'; |
| 4 | + |
| 5 | +type CssVariablesProps = { |
| 6 | + vars: { |
| 7 | + [key: string]: string; |
| 8 | + }; |
| 9 | +} & React.HTMLAttributes<HTMLTableElement>; |
| 10 | + |
| 11 | +export const CssVariables = forwardRef<HTMLTableElement, CssVariablesProps>( |
| 12 | + function CssVariables({ vars, className, ...rest }, ref) { |
| 13 | + return ( |
| 14 | + <Table |
| 15 | + zebra |
| 16 | + className={cl('component-table', className)} |
| 17 | + data-color='accent' |
| 18 | + border |
| 19 | + style={{ |
| 20 | + tableLayout: 'fixed', |
| 21 | + }} |
| 22 | + {...rest} |
| 23 | + ref={ref} |
| 24 | + > |
| 25 | + <Table.Head> |
| 26 | + <Table.Row> |
| 27 | + <Table.HeaderCell>Name</Table.HeaderCell> |
| 28 | + <Table.HeaderCell>Value</Table.HeaderCell> |
| 29 | + </Table.Row> |
| 30 | + </Table.Head> |
| 31 | + <Table.Body> |
| 32 | + {Object.entries(vars).map(([name, value]) => ( |
| 33 | + <Table.Row key={name}> |
| 34 | + <Table.Cell>{name}</Table.Cell> |
| 35 | + <Table.Cell>{value}</Table.Cell> |
| 36 | + </Table.Row> |
| 37 | + ))} |
| 38 | + </Table.Body> |
| 39 | + </Table> |
| 40 | + ); |
| 41 | + }, |
| 42 | +); |
| 43 | + |
| 44 | +/* get variables and its value from css file */ |
| 45 | +export function getCssVariables(css: string) { |
| 46 | + const res: { [key: string]: string } = {}; |
| 47 | + |
| 48 | + // temporarily remove inline strings, as they may contain ; and } characters |
| 49 | + // and thus ruin the matching for property declarations |
| 50 | + const stringsRemovedFromCss = Array.from(css.matchAll(/"[^"]*"/g)).map( |
| 51 | + (x) => x[0], |
| 52 | + ); |
| 53 | + const cssWithRemovedStrings = stringsRemovedFromCss.reduce( |
| 54 | + (prev, curr, idx) => prev.replace(curr, `<placeholder-${idx}>`), |
| 55 | + css, |
| 56 | + ); |
| 57 | + // get all --dsc-* property declarations |
| 58 | + const cssVars = Array.from( |
| 59 | + cssWithRemovedStrings.matchAll(/(?<!var\()(--dsc-[^;}]+)[;}]/g), |
| 60 | + ).map((matches) => matches[1]); |
| 61 | + |
| 62 | + /* Iterate over the CSS properties */ |
| 63 | + for (const declaration of cssVars) { |
| 64 | + const [name, value] = declaration.split(':'); |
| 65 | + // Choose the earliest declaration of the property. |
| 66 | + // We assume later declarations are part of a sub-selector. |
| 67 | + if (!res[name]) { |
| 68 | + // Return the original inline string from the value, if it was removed earlier |
| 69 | + const valueWithOriginalString = value.replace( |
| 70 | + /<placeholder-(\d+)>/, |
| 71 | + (_, p1: string) => stringsRemovedFromCss[parseInt(p1, 10)], |
| 72 | + ); |
| 73 | + res[name] = valueWithOriginalString; |
| 74 | + } |
| 75 | + } |
| 76 | + |
| 77 | + return res; |
| 78 | +} |
0 commit comments