|
- import * as React from 'react';
- import { tailwind } from '@tesseract-design/web-base';
-
- const { tw } = tailwind;
-
- const KeyValueTableDerivedElementComponent = 'dl' as const;
-
- /**
- * Derived HTML element of the {@link KeyValueTable} component.
- */
- export type KeyValueTableDerivedElement = HTMLElementTagNameMap[
- typeof KeyValueTableDerivedElementComponent
- ];
-
- const KeyValueTablePropertyElementComponent = 'div' as const;
-
- const KeyValueTableKeyElementComponent = 'dt' as const;
-
- const KeyValueTableValueElementComponent = 'dd' as const;
-
- /**
- * Individual property of the {@link KeyValueTable} component.
- */
- export interface KeyValueTableProperty {
- /**
- * Key of the property.
- */
- key: string;
- /**
- * Class name of the property.
- */
- className?: string;
- /**
- * Value of the property.
- */
- valueProps?: React.HTMLProps<HTMLElement>;
- }
-
- /**
- * Props of the {@link KeyValueTable} component.
- */
- export interface KeyValueTableProps extends Omit<React.HTMLProps<KeyValueTableDerivedElement>, 'children'> {
- /**
- * Should the keys be hidden?
- */
- hiddenKeys?: boolean;
- /**
- * Properties displayed on the component.
- */
- properties?: (KeyValueTableProperty | boolean | null | undefined)[];
- }
-
- /**
- * Component for displaying key-value pairs.
- */
- export const KeyValueTable = React.forwardRef<KeyValueTableDerivedElement, KeyValueTableProps>((
- {
- hiddenKeys = false,
- properties = [],
- className,
- style,
- ...etcProps
- },
- forwardedRef,
- ) => (
- <KeyValueTableDerivedElementComponent
- {...etcProps}
- className={tw(
- 'grid gap-y-1 grid-cols-3',
- className,
- )}
- ref={forwardedRef}
- style={style}
- >
- {properties.map((property) => typeof property === 'object' && property && (
- <KeyValueTablePropertyElementComponent
- key={property.key}
- className={tw('contents', property.className)}
- >
- <KeyValueTableKeyElementComponent
- className={tw(hiddenKeys && 'sr-only', 'pr-4')}
- >
- {property.key}
- </KeyValueTableKeyElementComponent>
- <KeyValueTableValueElementComponent
- {...(property.valueProps ?? {})}
- className={tw(
- 'm-0 text-ellipsis overflow-hidden',
- !hiddenKeys && 'col-span-2',
- hiddenKeys && 'col-span-3',
- property.valueProps?.className,
- )}
- >
- {property.valueProps?.children}
- </KeyValueTableValueElementComponent>
- </KeyValueTablePropertyElementComponent>
- ))}
- </KeyValueTableDerivedElementComponent>
- ));
-
- KeyValueTable.displayName = 'KeyValueTable';
-
- KeyValueTable.defaultProps = {
- hiddenKeys: false,
- properties: [],
- };
|