UNPKG

@dnb/eufemia

Version:

DNB Eufemia Design System UI Library

103 lines (102 loc) 3.22 kB
"use client"; import React, { useCallback, useContext, useRef, useState } from 'react'; import clsx from 'clsx'; import Popover from "../popover/Popover.js"; import useId from "../../shared/helpers/useId.js"; import useTranslation from "../../shared/useTranslation.js"; import { applySpacing, removeSpaceProps } from "../space/SpacingUtils.js"; import Context from "../../shared/Context.js"; import { extendPropsWithContext } from "../../shared/component-helper.js"; import { jsx as _jsx, Fragment as _Fragment, jsxs as _jsxs } from "react/jsx-runtime"; const defaultProps = { placement: 'bottom' }; export default function TermDefinition(localProps) { const context = useContext(Context); const allProps = extendPropsWithContext(localProps, defaultProps, { skeleton: context === null || context === void 0 ? void 0 : context.skeleton }, context === null || context === void 0 ? void 0 : context.TermDefinition); const { children, content, className, placement, ...rest } = allProps; const [active, setActive] = useState(false); const triggerRef = useRef(null); const id = useId(); const { TermDefinition: tr = {} } = useTranslation(); const title = active ? tr.closeTriggerTitle : tr.openTriggerTitle; const toggle = useCallback(next => { setActive(prev => { const value = typeof next === 'boolean' ? next : !prev; if (prev && !value) { var _triggerRef$current; (_triggerRef$current = triggerRef.current) === null || _triggerRef$current === void 0 || _triggerRef$current.focus({ preventScroll: true }); } return value; }); }, []); const onClick = useCallback(e => { e.preventDefault(); toggle(); }, [toggle]); const onKeyDown = useCallback(e => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); toggle(); } if (e.key === 'Escape') { e.preventDefault(); toggle(false); } }, [toggle]); const triggerProps = removeSpaceProps(rest); return _jsxs(_Fragment, { children: [_jsx("span", { ...applySpacing(rest, { role: 'button', tabIndex: 0, ref: triggerRef, className: clsx("dnb-term-definition__trigger dnb-anchor", className, active && 'dnb-anchor--hover'), 'aria-expanded': active, 'aria-controls': active ? id : undefined, 'aria-describedby': `${id}-description`, title, onClick, onKeyDown, ...triggerProps }), children: children }), _jsx("span", { className: "dnb-sr-only", "aria-hidden": true, id: `${id}-description`, children: title }), _jsx(Popover, { id: id, targetElement: triggerRef, open: active, onOpenChange: toggle, showDelay: 0, hideDelay: 0, triggerOffset: 4, placement: placement, arrowPosition: "left", alignOnTarget: "left", arrowEdgeOffset: 0, className: "dnb-term-definition", portalRootClass: "dnb-term-definition__portal", omitDescribedBy: true, hideArrow: true, title: children, children: content })] }); } //# sourceMappingURL=TermDefinition.js.map