@mantine/core
Version:
React components library focused on usability, accessibility and developer experience
86 lines (83 loc) • 2.51 kB
JavaScript
import { useUncontrolled, useDidUpdate } from '@mantine/hooks';
import { useFloating, size, offset, shift, limitShift, flip, inline, arrow } from '@floating-ui/react';
import { useFloatingAutoUpdate } from '../Floating/use-floating-auto-update.js';
function getPopoverMiddlewares(options) {
const middlewares = [offset(options.offset)];
if (options.middlewares.shift) {
middlewares.push(shift({ limiter: limitShift() }));
}
if (options.middlewares.flip) {
middlewares.push(flip());
}
if (options.middlewares.inline) {
middlewares.push(inline());
}
middlewares.push(arrow({ element: options.arrowRef, padding: options.arrowOffset }));
return middlewares;
}
function usePopover(options) {
const [_opened, setOpened] = useUncontrolled({
value: options.opened,
defaultValue: options.defaultOpened,
finalValue: false,
onChange: options.onChange
});
const onClose = () => {
var _a;
(_a = options.onClose) == null ? void 0 : _a.call(options);
setOpened(false);
};
const onToggle = () => {
var _a, _b;
if (_opened) {
(_a = options.onClose) == null ? void 0 : _a.call(options);
setOpened(false);
} else {
(_b = options.onOpen) == null ? void 0 : _b.call(options);
setOpened(true);
}
};
const floating = useFloating({
placement: options.position,
middleware: [
...getPopoverMiddlewares(options),
...options.width === "target" ? [
size({
apply({ rects }) {
var _a, _b;
Object.assign((_b = (_a = floating.refs.floating.current) == null ? void 0 : _a.style) != null ? _b : {}, {
width: `${rects.reference.width}px`
});
}
})
] : []
]
});
useFloatingAutoUpdate({
opened: options.opened,
position: options.position,
positionDependencies: options.positionDependencies,
floating
});
useDidUpdate(() => {
var _a;
(_a = options.onPositionChange) == null ? void 0 : _a.call(options, floating.placement);
}, [floating.placement]);
useDidUpdate(() => {
var _a, _b;
if (!options.opened) {
(_a = options.onClose) == null ? void 0 : _a.call(options);
} else {
(_b = options.onOpen) == null ? void 0 : _b.call(options);
}
}, [options.opened]);
return {
floating,
controlled: typeof options.opened === "boolean",
opened: _opened,
onClose,
onToggle
};
}
export { usePopover };
//# sourceMappingURL=use-popover.js.map