|
| 1 | +import type { Interpolation, Theme } from "@emotion/react"; |
| 2 | +import { forwardRef, type HTMLProps, type ReactNode } from "react"; |
| 3 | + |
| 4 | +type BarColor = "default" | "green"; |
| 5 | + |
| 6 | +type BarProps = Omit<HTMLProps<HTMLDivElement>, "size"> & { |
| 7 | + width: number; |
| 8 | + children?: ReactNode; |
| 9 | + color?: BarColor; |
| 10 | + /** |
| 11 | + * Label to be displayed adjacent to the bar component. |
| 12 | + */ |
| 13 | + afterLabel?: ReactNode; |
| 14 | + /** |
| 15 | + * The X position of the bar component. |
| 16 | + */ |
| 17 | + x?: number; |
| 18 | +}; |
| 19 | + |
| 20 | +export const Bar = forwardRef<HTMLDivElement, BarProps>( |
| 21 | + ( |
| 22 | + { color = "default", width, afterLabel, children, x, ...htmlProps }, |
| 23 | + ref, |
| 24 | + ) => { |
| 25 | + return ( |
| 26 | + <div |
| 27 | + ref={ref} |
| 28 | + css={[styles.root, { transform: `translateX(${x}px)` }]} |
| 29 | + {...htmlProps} |
| 30 | + > |
| 31 | + <div css={[styles.bar, colorStyles[color], { width }]}>{children}</div> |
| 32 | + {afterLabel} |
| 33 | + </div> |
| 34 | + ); |
| 35 | + }, |
| 36 | +); |
| 37 | + |
| 38 | +const styles = { |
| 39 | + root: { |
| 40 | + // Stack children horizontally for adjacent labels |
| 41 | + display: "flex", |
| 42 | + alignItems: "center", |
| 43 | + width: "fit-content", |
| 44 | + gap: 8, |
| 45 | + }, |
| 46 | + bar: { |
| 47 | + border: "1px solid transparent", |
| 48 | + borderRadius: 8, |
| 49 | + height: 32, |
| 50 | + }, |
| 51 | +} satisfies Record<string, Interpolation<Theme>>; |
| 52 | + |
| 53 | +const colorStyles = { |
| 54 | + default: (theme) => ({ |
| 55 | + backgroundColor: theme.palette.background.default, |
| 56 | + borderColor: theme.palette.divider, |
| 57 | + }), |
| 58 | + green: (theme) => ({ |
| 59 | + backgroundColor: theme.roles.success.background, |
| 60 | + borderColor: theme.roles.success.outline, |
| 61 | + color: theme.roles.success.text, |
| 62 | + }), |
| 63 | +} satisfies Record<BarColor, Interpolation<Theme>>; |
0 commit comments