UNPKG

@lobehub/ui

Version:

Lobe UI is an open-source UI component library for building AIGC web apps

431 lines (408 loc) 18.5 kB
'use client'; function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); } function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; } function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } } function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : String(i); } function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } import { useHover } from 'ahooks'; import { ConfigProvider } from 'antd'; import { cva } from 'class-variance-authority'; import { ChevronDown, ChevronLeft, ChevronRight, ChevronUp } from 'lucide-react'; import { Resizable } from 're-resizable'; import { memo, use, useCallback, useEffect, useMemo, useReducer, useRef, useTransition } from 'react'; import { Center } from 'react-layout-kit'; import useControlledState from 'use-merge-value'; import Icon from "../Icon"; import { useStyles } from "./style"; import { reversePlacement } from "./utils"; // Constants import { jsx as _jsx } from "react/jsx-runtime"; import { jsxs as _jsxs } from "react/jsx-runtime"; var DEFAULT_HEIGHT = 180; var DEFAULT_WIDTH = 280; var DEFAULT_HEADER_HEIGHT = 0; var DEFAULT_PIN = true; var DEFAULT_MODE = 'fixed'; var DEFAULT_EXPANDABLE = true; var DEFAULT_EXPAND = true; var DEFAULT_SHOW_HANDLE_WIDE_AREA = true; // State reducer for better state management function draggablePanelReducer(state, action) { switch (action.type) { case 'START_RESIZE': { return _objectSpread(_objectSpread({}, state), {}, { isResizing: true, showExpand: false }); } case 'STOP_RESIZE': { return _objectSpread(_objectSpread({}, state), {}, { isResizing: false, showExpand: true }); } case 'SET_SHOW_EXPAND': { return _objectSpread(_objectSpread({}, state), {}, { showExpand: action.payload }); } default: { return state; } } } var DraggablePanel = /*#__PURE__*/memo(function (_ref) { var _ref$headerHeight = _ref.headerHeight, headerHeight = _ref$headerHeight === void 0 ? DEFAULT_HEADER_HEIGHT : _ref$headerHeight, fullscreen = _ref.fullscreen, maxHeight = _ref.maxHeight, _ref$pin = _ref.pin, pin = _ref$pin === void 0 ? DEFAULT_PIN : _ref$pin, _ref$mode = _ref.mode, mode = _ref$mode === void 0 ? DEFAULT_MODE : _ref$mode, children = _ref.children, _ref$placement = _ref.placement, placement = _ref$placement === void 0 ? 'right' : _ref$placement, resize = _ref.resize, style = _ref.style, _ref$showBorder = _ref.showBorder, showBorder = _ref$showBorder === void 0 ? true : _ref$showBorder, _ref$showHandleHighli = _ref.showHandleHighlight, showHandleHighlight = _ref$showHandleHighli === void 0 ? false : _ref$showHandleHighli, _ref$showHandleWideAr = _ref.showHandleWideArea, showHandleWideArea = _ref$showHandleWideAr === void 0 ? DEFAULT_SHOW_HANDLE_WIDE_AREA : _ref$showHandleWideAr, backgroundColor = _ref.backgroundColor, size = _ref.size, customizeDefaultSize = _ref.defaultSize, minWidth = _ref.minWidth, minHeight = _ref.minHeight, maxWidth = _ref.maxWidth, onSizeChange = _ref.onSizeChange, onSizeDragging = _ref.onSizeDragging, _ref$expandable = _ref.expandable, expandable = _ref$expandable === void 0 ? DEFAULT_EXPANDABLE : _ref$expandable, expand = _ref.expand, _ref$defaultExpand = _ref.defaultExpand, defaultExpand = _ref$defaultExpand === void 0 ? DEFAULT_EXPAND : _ref$defaultExpand, onExpandChange = _ref.onExpandChange, className = _ref.className, showHandleWhenCollapsed = _ref.showHandleWhenCollapsed, destroyOnClose = _ref.destroyOnClose, customStyles = _ref.styles, classNames = _ref.classNames, dir = _ref.dir; var ref = useRef(null); var isHovering = useHover(ref); var isVertical = placement === 'top' || placement === 'bottom'; var _useTransition = useTransition(), _useTransition2 = _slicedToArray(_useTransition, 2), isPending = _useTransition2[0], startTransition = _useTransition2[1]; // Use ref for hover timeout to avoid memory leaks var hoverTimeoutRef = useRef(undefined); // inherit direction from Ant Design ConfigProvider var _use = use(ConfigProvider.ConfigContext), antdDirection = _use.direction; var direction = dir !== null && dir !== void 0 ? dir : antdDirection; // Handle RTL direction var internalPlacement = useMemo(function () { return direction === 'rtl' && ['left', 'right'].includes(placement) ? placement === 'left' ? 'right' : 'left' : placement; }, [direction, placement]); var _useStyles = useStyles({ backgroundColor: backgroundColor, headerHeight: headerHeight, showBorder: showBorder, showHandleWideArea: showHandleWideArea }), styles = _useStyles.styles, cx = _useStyles.cx; var _useControlledState = useControlledState(defaultExpand, { onChange: onExpandChange, value: expand }), _useControlledState2 = _slicedToArray(_useControlledState, 2), isExpand = _useControlledState2[0], setIsExpand = _useControlledState2[1]; // Initialize state with useReducer for better performance var initialState = { isResizing: false, showExpand: true }; var _useReducer = useReducer(draggablePanelReducer, initialState), _useReducer2 = _slicedToArray(_useReducer, 2), state = _useReducer2[0], dispatch = _useReducer2[1]; // Auto-expand on hover if not pinned with optimized transition useEffect(function () { if (pin) return; // Clear previous timeout if (hoverTimeoutRef.current) { clearTimeout(hoverTimeoutRef.current); } if (isHovering && !isExpand) { startTransition(function () { setIsExpand(true); }); } else if (!isHovering && isExpand) { // Add a small delay before collapsing to prevent flickering hoverTimeoutRef.current = setTimeout(function () { startTransition(function () { setIsExpand(false); }); }, 150); } }, [pin, isHovering, isExpand, setIsExpand]); // Cleanup timeout on unmount useEffect(function () { return function () { if (hoverTimeoutRef.current) { clearTimeout(hoverTimeoutRef.current); } }; }, []); var canResizing = resize !== false && isExpand; // Style variants for the panel var variants = useMemo(function () { return cva(styles.root, { compoundVariants: [{ class: styles.bottomFloat, mode: 'float', placement: 'bottom' }, { class: styles.topFloat, mode: 'float', placement: 'top' }, { class: styles.leftFloat, mode: 'float', placement: 'left' }, { class: styles.rightFloat, mode: 'float', placement: 'right' }], /* eslint-disable sort-keys-fix/sort-keys-fix */ variants: { placement: { top: isExpand && styles.borderBottom, right: isExpand && styles.borderLeft, bottom: isExpand && styles.borderTop, left: isExpand && styles.borderRight }, mode: { fixed: styles.fixed, float: null } } /* eslint-enable sort-keys-fix/sort-keys-fix */ }); }, [styles, isExpand]); // Style variants for the handle var handleVariants = useMemo(function () { return cva(styles.handleRoot, { variants: { placement: { bottom: styles.handleBottom, left: styles.handleLeft, right: styles.handleRight, top: styles.handleTop } } }); }, [styles]); // Style variants for the toggle button var toggleVariants = useMemo(function () { return cva(styles.toggleRoot, { variants: { placement: { bottom: styles.toggleTop, left: styles.toggleRight, right: styles.toggleLeft, top: styles.toggleBottom } } }); }, [styles]); // Configure resizing handles var resizing = useMemo(function () { return _objectSpread(_defineProperty({ bottom: false, bottomLeft: false, bottomRight: false, left: false, right: false, top: false, topLeft: false, topRight: false }, reversePlacement(internalPlacement), true), resize); }, [internalPlacement, resize]); // Calculate default size based on orientation var defaultSize = useMemo(function () { if (isVertical) return _objectSpread({ height: DEFAULT_HEIGHT, width: '100%' }, customizeDefaultSize); return _objectSpread({ height: '100%', width: DEFAULT_WIDTH }, customizeDefaultSize); }, [isVertical, customizeDefaultSize]); // Determine appropriate size props based on expand state var sizeProps = useMemo(function () { if (!isExpand) { return isVertical ? { minHeight: 0, size: { height: 0 } } : { minWidth: 0, size: { width: 0 } }; } return { defaultSize: defaultSize, maxHeight: typeof maxHeight === 'number' ? Math.max(maxHeight, 0) : maxHeight, maxWidth: typeof maxWidth === 'number' ? Math.max(maxWidth, 0) : maxWidth, minHeight: typeof minHeight === 'number' ? Math.max(minHeight, 0) : minHeight, minWidth: typeof minWidth === 'number' ? Math.max(minWidth, 0) : minWidth, size: size }; }, [isExpand, isVertical, defaultSize, maxHeight, maxWidth, minHeight, minWidth, size]); // Determine the appropriate arrow icon based on placement var Arrow = useMemo(function () { switch (internalPlacement) { case 'top': { return ChevronDown; } case 'bottom': { return ChevronUp; } case 'right': { return ChevronLeft; } case 'left': { return ChevronRight; } default: { return ChevronLeft; } } }, [internalPlacement]); // Toggle expand state with transition for better performance var toggleExpand = useCallback(function () { if (!expandable) return; startTransition(function () { setIsExpand(!isExpand); }); }, [expandable, isExpand, setIsExpand]); // Toggle handle component var handle = useMemo(function () { return /*#__PURE__*/_jsx(Center, { className: toggleVariants({ placement: internalPlacement }), style: { opacity: isExpand ? pin ? undefined : 0 : showHandleWhenCollapsed ? 1 : 0 }, children: /*#__PURE__*/_jsx(Center, { className: classNames === null || classNames === void 0 ? void 0 : classNames.handle, onClick: toggleExpand, style: customStyles === null || customStyles === void 0 ? void 0 : customStyles.handle, children: /*#__PURE__*/_jsx(Icon, { className: styles.handlerIcon, icon: Arrow, size: 16, style: { marginBottom: internalPlacement === 'top' ? 4 : 0, marginLeft: internalPlacement === 'right' ? 4 : 0, marginRight: internalPlacement === 'left' ? 4 : 0, marginTop: internalPlacement === 'bottom' ? 4 : 0, transform: "rotate(".concat(isExpand ? 180 : 0, "deg)"), transition: 'transform 0.3s ease' } }) }) }); }, [toggleVariants, internalPlacement, isExpand, pin, showHandleWhenCollapsed, classNames === null || classNames === void 0 ? void 0 : classNames.handle, toggleExpand, customStyles === null || customStyles === void 0 ? void 0 : customStyles.handle, styles.handlerIcon, Arrow]); // Handle resize events with memoization var handleResize = useCallback(function (_, _direction, reference_, delta) { onSizeDragging === null || onSizeDragging === void 0 || onSizeDragging(delta, { height: reference_.style.height, width: reference_.style.width }); }, [onSizeDragging]); var handleResizeStart = useCallback(function () { dispatch({ type: 'START_RESIZE' }); }, []); var handleResizeStop = useCallback(function (e, direction, reference_, delta) { dispatch({ type: 'STOP_RESIZE' }); onSizeChange === null || onSizeChange === void 0 || onSizeChange(delta, { height: reference_.style.height, width: reference_.style.width }); }, [onSizeChange]); // Main panel content var inner = useMemo(function () { return /*#__PURE__*/_jsx(Resizable, _objectSpread(_objectSpread({}, sizeProps), {}, { className: cx(styles.panel, classNames === null || classNames === void 0 ? void 0 : classNames.content), enable: canResizing ? resizing : undefined, handleClasses: canResizing ? _defineProperty({}, reversePlacement(internalPlacement), cx(handleVariants({ placement: reversePlacement(internalPlacement) }), showHandleHighlight && styles.handleHighlight)) : {}, onResize: handleResize, onResizeStart: handleResizeStart, onResizeStop: handleResizeStop, style: _objectSpread({ opacity: isPending ? 0.95 : 1, transition: state.isResizing ? 'unset' : undefined }, style), children: children })); }, [sizeProps, styles.panel, classNames === null || classNames === void 0 ? void 0 : classNames.content, canResizing, resizing, internalPlacement, handleVariants, showHandleHighlight, styles.handleHighlight, handleResize, handleResizeStart, handleResizeStop, state.isResizing, isPending, style, children, cx]); // For fullscreen mode, return a simpler layout if (fullscreen) { return /*#__PURE__*/_jsx("div", { className: cx(styles.fullscreen, className), children: children }); } return /*#__PURE__*/_jsxs("aside", { className: cx(variants({ mode: mode, placement: internalPlacement }), className), dir: dir, ref: ref, children: [expandable && state.showExpand && handle, destroyOnClose ? isExpand && inner : inner] }); }, // Custom comparison function to avoid unnecessary re-renders function (prevProps, nextProps) { // Only re-render if critical props change return prevProps.placement === nextProps.placement && prevProps.mode === nextProps.mode && prevProps.expand === nextProps.expand && prevProps.pin === nextProps.pin && prevProps.fullscreen === nextProps.fullscreen && prevProps.size === nextProps.size && prevProps.defaultSize === nextProps.defaultSize && prevProps.minWidth === nextProps.minWidth && prevProps.minHeight === nextProps.minHeight && prevProps.maxWidth === nextProps.maxWidth && prevProps.maxHeight === nextProps.maxHeight && prevProps.expandable === nextProps.expandable && prevProps.resize === nextProps.resize && prevProps.showHandleWhenCollapsed === nextProps.showHandleWhenCollapsed && prevProps.destroyOnClose === nextProps.destroyOnClose && prevProps.showBorder === nextProps.showBorder && prevProps.showHandleHighlight === nextProps.showHandleHighlight && prevProps.showHandleWideArea === nextProps.showHandleWideArea && prevProps.backgroundColor === nextProps.backgroundColor && prevProps.className === nextProps.className && prevProps.dir === nextProps.dir && prevProps.headerHeight === nextProps.headerHeight && prevProps.onSizeChange === nextProps.onSizeChange && prevProps.onSizeDragging === nextProps.onSizeDragging && prevProps.onExpandChange === nextProps.onExpandChange && prevProps.children === nextProps.children; }); DraggablePanel.displayName = 'DraggablePanel'; export default DraggablePanel;