UNPKG

@lobehub/ui

Version:

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

560 lines (524 loc) 24.5 kB
'use client'; var _excluded = ["body", "className", "classNames", "defaultExpand", "defaultWidth", "expand", "expandable", "footer", "header", "maxWidth", "minWidth", "onExpandChange", "onWidthChange", "onWidthDragging", "placement", "resizable", "showBorder", "showHandle", "showHandleWhenCollapsed", "showHandleHighlight", "backgroundColor", "styles", "width"]; 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 _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; } function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; } 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 { ChevronLeft, ChevronRight } from 'lucide-react'; import { Resizable } from 're-resizable'; import { memo, useCallback, useEffect, useMemo, useReducer, useRef } from 'react'; import { Center, Flexbox } from 'react-layout-kit'; import useControlledState from 'use-merge-value'; import Icon from "../Icon"; import { useStyles } from "./style"; import { jsx as _jsx } from "react/jsx-runtime"; import { jsxs as _jsxs } from "react/jsx-runtime"; var DEFAULT_MIN_WIDTH = 64; // 最小宽度即折叠宽度 var DEFAULT_EXPAND = true; var DEFAULT_EXPANDED_WIDTH = 280; var ANIMATION_DURATION = 300; var COLLAPSE_ANIMATION_DELAY = 200; // Pre-define static objects to avoid recreating var RESIZE_DISABLED = { bottom: false, bottomLeft: false, bottomRight: false, left: false, right: false, top: false, topLeft: false, topRight: false }; // State reducer for better state management function sideNavReducer(state, action) { switch (action.type) { case 'START_RESIZE': { return _objectSpread(_objectSpread({}, state), {}, { isResizing: true }); } case 'STOP_RESIZE': { return _objectSpread(_objectSpread({}, state), {}, { isResizing: false }); } case 'START_ANIMATION': { return _objectSpread(_objectSpread({}, state), {}, { isAnimating: true }); } case 'STOP_ANIMATION': { return _objectSpread(_objectSpread({}, state), {}, { isAnimating: false }); } case 'SET_WIDTH': { return _objectSpread(_objectSpread({}, state), {}, { internalWidth: action.payload }); } case 'SET_EXPANDED_WIDTH': { return _objectSpread(_objectSpread({}, state), {}, { expandedWidth: action.payload }); } case 'SET_RENDER_EXPAND': { return _objectSpread(_objectSpread({}, state), {}, { renderExpand: action.payload }); } case 'ANIMATE_EXPAND': { return _objectSpread(_objectSpread({}, state), {}, { internalWidth: action.payload, renderExpand: true }); } case 'ANIMATE_COLLAPSE': { return _objectSpread(_objectSpread({}, state), {}, { internalWidth: action.payload }); } default: { return state; } } } var DraggableSideNav = /*#__PURE__*/memo(function (_ref) { var body = _ref.body, className = _ref.className, classNames = _ref.classNames, _ref$defaultExpand = _ref.defaultExpand, defaultExpand = _ref$defaultExpand === void 0 ? DEFAULT_EXPAND : _ref$defaultExpand, defaultWidth = _ref.defaultWidth, expand = _ref.expand, _ref$expandable = _ref.expandable, expandable = _ref$expandable === void 0 ? true : _ref$expandable, footer = _ref.footer, header = _ref.header, maxWidth = _ref.maxWidth, _ref$minWidth = _ref.minWidth, minWidth = _ref$minWidth === void 0 ? DEFAULT_MIN_WIDTH : _ref$minWidth, onExpandChange = _ref.onExpandChange, onWidthChange = _ref.onWidthChange, onWidthDragging = _ref.onWidthDragging, _ref$placement = _ref.placement, placement = _ref$placement === void 0 ? 'left' : _ref$placement, _ref$resizable = _ref.resizable, resizable = _ref$resizable === void 0 ? true : _ref$resizable, _ref$showBorder = _ref.showBorder, showBorder = _ref$showBorder === void 0 ? true : _ref$showBorder, _ref$showHandle = _ref.showHandle, showHandle = _ref$showHandle === void 0 ? true : _ref$showHandle, _ref$showHandleWhenCo = _ref.showHandleWhenCollapsed, showHandleWhenCollapsed = _ref$showHandleWhenCo === void 0 ? false : _ref$showHandleWhenCo, _ref$showHandleHighli = _ref.showHandleHighlight, showHandleHighlight = _ref$showHandleHighli === void 0 ? false : _ref$showHandleHighli, backgroundColor = _ref.backgroundColor, customStyles = _ref.styles, width = _ref.width, rest = _objectWithoutProperties(_ref, _excluded); var _useStyles = useStyles({ backgroundColor: backgroundColor, showBorder: showBorder }), styles = _useStyles.styles, cx = _useStyles.cx; var ref = useRef(null); var isHovering = useHover(ref); // Expand state management var _useControlledState = useControlledState(defaultExpand, { onChange: onExpandChange, value: expand }), _useControlledState2 = _slicedToArray(_useControlledState, 2), isExpand = _useControlledState2[0], setIsExpand = _useControlledState2[1]; // Use refs for animation timeouts to avoid memory leaks var animationTimeoutRef = useRef(undefined); var collapseTimeoutRef = useRef(undefined); // Compute default expanded width - memoize to avoid recalculation var computedDefaultExpandedWidth = useMemo(function () { return defaultWidth || DEFAULT_EXPANDED_WIDTH; }, [defaultWidth]); // Initialize state with useReducer for better performance var initialState = { expandedWidth: width !== null && width !== void 0 ? width : computedDefaultExpandedWidth, internalWidth: isExpand ? width !== null && width !== void 0 ? width : computedDefaultExpandedWidth : minWidth, isAnimating: false, isResizing: false, renderExpand: isExpand }; var _useReducer = useReducer(sideNavReducer, initialState), _useReducer2 = _slicedToArray(_useReducer, 2), state = _useReducer2[0], dispatch = _useReducer2[1]; // 计算折叠阈值:展开最小宽度和折叠宽度的中间值 var collapseThreshold = useMemo(function () { return minWidth + (state.expandedWidth - minWidth) / 3; }, [minWidth, state.expandedWidth]); // Toggle expand state with smooth animation var toggleExpand = useCallback(function () { if (!expandable) return; // 在动画或拖拽期间阻止新的切换操作,避免状态混乱 if (state.isAnimating || state.isResizing) return; // 清除之前的动画 if (animationTimeoutRef.current) { clearTimeout(animationTimeoutRef.current); } // 立即设置动画状态,避免其他 useEffect 干扰 dispatch({ type: 'START_ANIMATION' }); setIsExpand(!isExpand); // 动画完成后重置状态 - 与宽度动画时长一致 animationTimeoutRef.current = setTimeout(function () { dispatch({ type: 'STOP_ANIMATION' }); }, ANIMATION_DURATION); }, [expandable, isExpand, setIsExpand, state.isAnimating, state.isResizing]); // 用于跟踪上一次的 expand 状态,以检测外部变化 var prevExpandRef = useRef(isExpand); // 监听外部 expand prop 变化,触发动画 useEffect(function () { // 检测到 expand 状态变化,且不在拖拽和动画中 if (prevExpandRef.current !== isExpand && !state.isResizing && !state.isAnimating) { if (animationTimeoutRef.current) { clearTimeout(animationTimeoutRef.current); } // 立即设置动画状态,避免其他 useEffect 干扰 dispatch({ type: 'START_ANIMATION' }); animationTimeoutRef.current = setTimeout(function () { dispatch({ type: 'STOP_ANIMATION' }); }, ANIMATION_DURATION); prevExpandRef.current = isExpand; } }, [isExpand, state.isResizing, state.isAnimating]); // 处理展开/折叠状态变化时的宽度动画和内容切换时机 useEffect(function () { if (state.isAnimating) { // 使用 requestAnimationFrame 确保动画平滑 var rafId = requestAnimationFrame(function () { if (isExpand) { // 展开动画:立即切换内容(先切换内容,再开始宽度动画) dispatch({ payload: state.expandedWidth, type: 'ANIMATE_EXPAND' }); } else { // 折叠动画:延迟切换内容,在动画接近结束时才切换(300ms,略早于动画结束) dispatch({ payload: minWidth, type: 'ANIMATE_COLLAPSE' }); if (collapseTimeoutRef.current) { clearTimeout(collapseTimeoutRef.current); } collapseTimeoutRef.current = setTimeout(function () { dispatch({ payload: false, type: 'SET_RENDER_EXPAND' }); }, COLLAPSE_ANIMATION_DELAY); } }); return function () { cancelAnimationFrame(rafId); }; } }, [isExpand, state.isAnimating, minWidth, state.expandedWidth]); // 同步非动画期间的 renderExpand 状态(如拖拽) // 使用 ref 追踪上一次的 isResizing 状态,只在拖拽结束时同步 var prevIsResizingRef = useRef(state.isResizing); useEffect(function () { var wasResizing = prevIsResizingRef.current; prevIsResizingRef.current = state.isResizing; // 只在拖拽刚结束时同步 renderExpand,避免干扰正常的展开/折叠动画 if (wasResizing && !state.isResizing && !state.isAnimating) { dispatch({ payload: isExpand, type: 'SET_RENDER_EXPAND' }); } }, [isExpand, state.isAnimating, state.isResizing]); // 处理外部 width prop 变化 // width 表示展开时的宽度,实际显示宽度根据 isExpand 状态决定 useEffect(function () { if (width !== undefined && !state.isResizing && !state.isAnimating) { // 更新展开宽度记录 dispatch({ payload: width, type: 'SET_EXPANDED_WIDTH' }); // 根据当前状态设置实际宽度 if (isExpand) { dispatch({ payload: width, type: 'SET_WIDTH' }); } // 如果是折叠状态,保持 minWidth,不改变 internalWidth } }, [width, state.isResizing, state.isAnimating, isExpand]); // 计算当前的 body 内容 - 使用 renderExpand var currentBody = useMemo(function () { return body(state.renderExpand); }, [body, state.renderExpand]); // 计算当前的 header(支持函数和静态值)- 使用 renderExpand var currentHeader = useMemo(function () { return typeof header === 'function' ? header(state.renderExpand) : header; }, [header, state.renderExpand]); // 计算当前的 footer(支持函数和静态值)- 使用 renderExpand var currentFooter = useMemo(function () { return typeof footer === 'function' ? footer(state.renderExpand) : footer; }, [footer, state.renderExpand]); // Handle resize - memoize to prevent recreating on every render var handleResize = useCallback(function (_, __, ref, delta) { var currentWidth = ref.offsetWidth; dispatch({ payload: currentWidth, type: 'SET_WIDTH' }); onWidthDragging === null || onWidthDragging === void 0 || onWidthDragging(delta, currentWidth); }, [onWidthDragging]); var handleResizeStart = useCallback(function () { dispatch({ type: 'START_RESIZE' }); }, []); var handleResizeStop = useCallback(function (_, __, ref, delta) { dispatch({ type: 'STOP_RESIZE' }); var currentWidth = ref.offsetWidth; // 清除之前的动画 if (animationTimeoutRef.current) { clearTimeout(animationTimeoutRef.current); } // 根据拖拽后的宽度决定是折叠还是展开 if (expandable) { var shouldCollapse = currentWidth <= minWidth || currentWidth < collapseThreshold; var shouldExpand = !isExpand && currentWidth > minWidth && currentWidth >= collapseThreshold; if (shouldCollapse || shouldExpand) { // 立即设置动画状态 dispatch({ type: 'START_ANIMATION' }); if (shouldCollapse) { setIsExpand(false); dispatch({ payload: minWidth, type: 'SET_WIDTH' }); } else { setIsExpand(true); dispatch({ payload: currentWidth, type: 'SET_EXPANDED_WIDTH' }); dispatch({ payload: currentWidth, type: 'SET_WIDTH' }); } animationTimeoutRef.current = setTimeout(function () { dispatch({ type: 'STOP_ANIMATION' }); }, ANIMATION_DURATION); } else if (isExpand) { // 展开状态下正常拖拽,记住宽度 dispatch({ payload: currentWidth, type: 'SET_EXPANDED_WIDTH' }); dispatch({ payload: currentWidth, type: 'SET_WIDTH' }); } } else { // 如果不可折叠,仅更新宽度 dispatch({ payload: currentWidth, type: 'SET_EXPANDED_WIDTH' }); dispatch({ payload: currentWidth, type: 'SET_WIDTH' }); } onWidthChange === null || onWidthChange === void 0 || onWidthChange(delta, currentWidth); }, [expandable, minWidth, collapseThreshold, isExpand, onWidthChange, setIsExpand]); // Arrow icon based on placement and expand state var ArrowIcon = useMemo(function () { if (placement === 'left') { // 左侧:展开时箭头向左(折叠方向),折叠时箭头向右(展开方向) return ChevronLeft; } // 右侧:展开时箭头向右(折叠方向),折叠时箭头向左(展开方向) return ChevronRight; }, [placement]); // Memoize handle styles to prevent recreation var handleRootStyle = useMemo(function () { return { display: 'flex', opacity: !isExpand && showHandleWhenCollapsed ? 1 : isHovering ? 1 : 0, transition: 'opacity 0.25s ease' }; }, [isExpand, showHandleWhenCollapsed, isHovering]); var handleCenterStyle = useMemo(function () { return _objectSpread(_objectSpread({}, customStyles === null || customStyles === void 0 ? void 0 : customStyles.handle), {}, { cursor: 'pointer' }); }, [customStyles === null || customStyles === void 0 ? void 0 : customStyles.handle]); var handleIconWrapperStyle = useMemo(function () { return { marginLeft: placement === 'right' ? 4 : 0, marginRight: placement === 'left' ? 4 : 0, transform: isExpand ? 'rotate(0deg)' : 'rotate(180deg)', transition: "transform ".concat(COLLAPSE_ANIMATION_DELAY, " ease") }; }, [placement, isExpand]); // Toggle handle with smooth transitions var handle = useMemo(function () { return showHandle && expandable && /*#__PURE__*/_jsx("div", { className: cx(styles.toggleRoot, placement === 'left' ? styles.toggleLeft : styles.toggleRight), style: handleRootStyle, children: /*#__PURE__*/_jsx(Center, { className: classNames === null || classNames === void 0 ? void 0 : classNames.handle, onClick: toggleExpand, style: handleCenterStyle, children: /*#__PURE__*/_jsx("div", { style: handleIconWrapperStyle, children: /*#__PURE__*/_jsx(Icon, { className: styles.handlerIcon, icon: ArrowIcon, size: 16 }) }) }) }); }, [showHandle, expandable, styles.toggleRoot, styles.toggleLeft, styles.toggleRight, styles.handlerIcon, placement, handleRootStyle, classNames === null || classNames === void 0 ? void 0 : classNames.handle, toggleExpand, handleCenterStyle, handleIconWrapperStyle, ArrowIcon, cx]); // Size configuration - 使用内部宽度状态 var sizeConfig = useMemo(function () { return { maxWidth: maxWidth, minWidth: minWidth, size: { height: '100%', width: state.internalWidth } }; }, [state.internalWidth, minWidth, maxWidth]); // Resize enable configuration - 始终允许拖拽 var resizeEnable = useMemo(function () { if (!resizable) { return RESIZE_DISABLED; } return { bottom: false, bottomLeft: false, bottomRight: false, left: placement === 'right', right: placement === 'left', top: false, topLeft: false, topRight: false }; }, [resizable, placement]); // Memoize handle classes to prevent recreation var handleClasses = useMemo(function () { return _defineProperty({}, placement === 'left' ? 'right' : 'left', cx(styles.resizeHandle, showHandleHighlight && styles.resizeHandleHighlight, placement === 'left' ? styles.resizeHandleLeft : styles.resizeHandleRight)); }, [placement, styles, showHandleHighlight, cx]); // Memoize container style to prevent recreation var containerStyle = useMemo(function () { return _objectSpread(_objectSpread(_objectSpread({}, customStyles === null || customStyles === void 0 ? void 0 : customStyles.container), rest.style), {}, { // 拖拽时不要动画,点击 handle 时有流畅的弹性动画 transition: state.isResizing ? 'none' : state.isAnimating ? "width ".concat(ANIMATION_DURATION, "ms cubic-bezier(0.22, 1, 0.36, 1)") : 'none' }); }, [customStyles === null || customStyles === void 0 ? void 0 : customStyles.container, rest.style, state.isResizing, state.isAnimating]); // Memoize class names var containerClassName = useMemo(function () { return cx(styles.container, classNames === null || classNames === void 0 ? void 0 : classNames.container, className); }, [cx, styles.container, classNames === null || classNames === void 0 ? void 0 : classNames.container, className]); var contentClassName = useMemo(function () { return cx(styles.contentContainer, styles.menuOverride, classNames === null || classNames === void 0 ? void 0 : classNames.content); }, [cx, styles.contentContainer, styles.menuOverride, classNames === null || classNames === void 0 ? void 0 : classNames.content]); var headerClassName = useMemo(function () { return cx(styles.header, classNames === null || classNames === void 0 ? void 0 : classNames.header); }, [cx, styles.header, classNames === null || classNames === void 0 ? void 0 : classNames.header]); var bodyClassName = useMemo(function () { return cx(styles.body, classNames === null || classNames === void 0 ? void 0 : classNames.body); }, [cx, styles.body, classNames === null || classNames === void 0 ? void 0 : classNames.body]); var footerClassName = useMemo(function () { return cx(styles.footer, classNames === null || classNames === void 0 ? void 0 : classNames.footer); }, [cx, styles.footer, classNames === null || classNames === void 0 ? void 0 : classNames.footer]); // Cleanup timeouts on unmount useEffect(function () { return function () { if (animationTimeoutRef.current) { clearTimeout(animationTimeoutRef.current); } if (collapseTimeoutRef.current) { clearTimeout(collapseTimeoutRef.current); } }; }, []); return /*#__PURE__*/_jsx("aside", { ref: ref, children: /*#__PURE__*/_jsxs(Resizable, _objectSpread(_objectSpread({}, sizeConfig), {}, { className: containerClassName, enable: resizeEnable, handleClasses: handleClasses, onResize: handleResize, onResizeStart: handleResizeStart, onResizeStop: handleResizeStop, style: containerStyle, children: [handle, /*#__PURE__*/_jsxs(Flexbox, { className: contentClassName, style: customStyles === null || customStyles === void 0 ? void 0 : customStyles.content, children: [currentHeader && /*#__PURE__*/_jsx("div", { className: headerClassName, style: customStyles === null || customStyles === void 0 ? void 0 : customStyles.header, children: currentHeader }), /*#__PURE__*/_jsx("div", { className: bodyClassName, style: customStyles === null || customStyles === void 0 ? void 0 : customStyles.body, children: currentBody }), currentFooter && /*#__PURE__*/_jsx("div", { className: footerClassName, style: customStyles === null || customStyles === void 0 ? void 0 : customStyles.footer, children: currentFooter })] })] })) }); }); DraggableSideNav.displayName = 'DraggableSideNav'; export default DraggableSideNav;