UNPKG

@stratakit/structures

Version:

Medium-sized component structures for the Strata design system

98 lines (97 loc) 3 kB
import { jsx, jsxs } from "react/jsx-runtime"; import * as React from "react"; import { Role } from "@ariakit/react/role"; import { IconButton } from "@stratakit/bricks"; import { forwardRef, useSafeContext } from "@stratakit/foundations/secret-internals"; import cx from "classnames"; import { createStore, useStore } from "zustand"; import { combine } from "zustand/middleware"; import { Dismiss } from "./~utils.icons.js"; function createChipStore(initialState) { return createStore( combine(initialState, (set, _, store) => ({ setLabelId: (labelId) => { set({ labelId: labelId || store.getInitialState().labelId }); } })) ); } const ChipContext = React.createContext(void 0); function ChipProvider(props) { const defaultLabelId = React.useId(); const [store] = React.useState( () => createChipStore({ labelId: defaultLabelId }) ); return /* @__PURE__ */ jsx(ChipContext.Provider, { value: store, children: props.children }); } function useChipState(selectorFn) { const store = useSafeContext(ChipContext); return useStore(store, selectorFn); } const ChipRoot = forwardRef((props, forwardedRef) => { const { variant = "solid", ...rest } = props; return /* @__PURE__ */ jsx(ChipProvider, { children: /* @__PURE__ */ jsx( Role.div, { "data-kiwi-variant": variant, ...rest, className: cx("\u{1F95D}-chip", props.className), ref: forwardedRef } ) }); }); const ChipLabel = forwardRef((props, forwardedRef) => { const labelId = useChipState((state) => state.labelId); const setLabelId = useChipState((state) => state.setLabelId); React.useEffect(() => { setLabelId(props.id); }, [setLabelId, props.id]); return /* @__PURE__ */ jsx( Role.span, { id: labelId, ...props, className: cx("\u{1F95D}-chip-label", props.className), ref: forwardedRef } ); }); const ChipDismissButton = forwardRef( (props, forwardedRef) => { const { label = "Dismiss", ...rest } = props; const labelId = useChipState((state) => state.labelId); const defaultId = React.useId(); const id = props.id ?? defaultId; return /* @__PURE__ */ jsx( IconButton, { id, "aria-labelledby": `${id} ${labelId}`, ...rest, label, className: cx("\u{1F95D}-chip-dismiss-button", props.className), variant: "ghost", labelVariant: "visually-hidden", icon: /* @__PURE__ */ jsx(Dismiss, {}), ref: forwardedRef } ); } ); const Chip = forwardRef((props, forwardedRef) => { const { onDismiss, label, ...rest } = props; return /* @__PURE__ */ jsxs(ChipRoot, { ...rest, ref: forwardedRef, children: [ /* @__PURE__ */ jsx(ChipLabel, { children: label }), onDismiss && /* @__PURE__ */ jsx(ChipDismissButton, { onClick: onDismiss }) ] }); }); var Chip_default = Chip; export { ChipDismissButton as DismissButton, ChipLabel as Label, ChipRoot as Root, Chip_default as default };