Skip to content

Build your own AI office with Univer Office SDK. Bring editing, calculation, collaboration, and file processing into your product for people and AI agents. Built on an extensible open-source core.

refactor(base-ui): tabs component (#165)

tonytonychopper123b50181374a61
diff --git a/packages/base-sheets/src/Commands/Commands/insert-range-move-down.command.ts b/packages/base-sheets/src/Commands/Commands/insert-range-move-down.command.ts
index f6c4f0be9c..45fd4c9243 100644
--- a/packages/base-sheets/src/Commands/Commands/insert-range-move-down.command.ts
+++ b/packages/base-sheets/src/Commands/Commands/insert-range-move-down.command.ts
@@ -1,4 +1,13 @@
-import { CommandType, Dimension, ICellData, ICommand, ICommandService, ICurrentUniverService, IUndoRedoService, ObjectMatrix } from '@univerjs/core';
+import {
+ CommandType,
+ Dimension,
+ ICellData,
+ ICommand,
+ ICommandService,
+ ICurrentUniverService,
+ IUndoRedoService,
+ ObjectMatrix,
+} from '@univerjs/core';
import { IAccessor } from '@wendellhu/redi';
import { IDeleteRangeMutationParams, IInsertRangeMutationParams } from '../../Basics/Interfaces/MutationInterface';
@@ -20,7 +29,11 @@ export const InsertRangeMoveDownCommand: ICommand = {
const selectionManagerService = accessor.get(SelectionManagerService);
const workbookId = currentUniverService.getCurrentUniverSheetInstance().getUnitId();
- const worksheetId = currentUniverService.getCurrentUniverSheetInstance().getWorkBook().getActiveSheet().getSheetId();
+ const worksheetId = currentUniverService
+ .getCurrentUniverSheetInstance()
+ .getWorkBook()
+ .getActiveSheet()
+ .getSheetId();
const range = selectionManagerService.getRangeDatas();
if (!range?.length) return false;
@@ -48,7 +61,10 @@ export const InsertRangeMoveDownCommand: ICommand = {
cellValue: cellValue.getData(),
};
- const deleteRangeMutationParams: IDeleteRangeMutationParams = InsertRangeUndoMutationFactory(accessor, insertRangeMutationParams);
+ const deleteRangeMutationParams: IDeleteRangeMutationParams = InsertRangeUndoMutationFactory(
+ accessor,
+ insertRangeMutationParams
+ );
// execute do mutations and add undo mutations to undo stack if completed
const result = commandService.executeCommand(InsertRangeMutation.id, insertRangeMutationParams);
diff --git a/packages/base-sheets/src/Commands/Commands/move-range-to.command.ts b/packages/base-sheets/src/Commands/Commands/move-range-to.command.ts
index d04beb0dc8..6b77eee6bd 100644
--- a/packages/base-sheets/src/Commands/Commands/move-range-to.command.ts
+++ b/packages/base-sheets/src/Commands/Commands/move-range-to.command.ts
@@ -1,8 +1,21 @@
-import { CommandType, ICellData, ICommand, ICommandService, ICurrentUniverService, ISelectionRange, IUndoRedoService, ObjectMatrix } from '@univerjs/core';
+import {
+ CommandType,
+ ICellData,
+ ICommand,
+ ICommandService,
+ ICurrentUniverService,
+ ISelectionRange,
+ IUndoRedoService,
+ ObjectMatrix,
+} from '@univerjs/core';
import { IAccessor } from '@wendellhu/redi';
import { SelectionManagerService } from '../../Services/selection-manager.service';
-import { ISetRangeValuesMutationParams, SetRangeValuesMutation, SetRangeValuesUndoMutationFactory } from '../Mutations/set-range-values.mutation';
+import {
+ ISetRangeValuesMutationParams,
+ SetRangeValuesMutation,
+ SetRangeValuesUndoMutationFactory,
+} from '../Mutations/set-range-values.mutation';
export interface IMoveRangeToCommandParams {
destinationRange: ISelectionRange;
@@ -23,7 +36,11 @@ export const MoveRangeToCommand: ICommand = {
}
const workbookId = currentUniverService.getCurrentUniverSheetInstance().getUnitId();
- const worksheetId = currentUniverService.getCurrentUniverSheetInstance().getWorkBook().getActiveSheet().getSheetId();
+ const worksheetId = currentUniverService
+ .getCurrentUniverSheetInstance()
+ .getWorkBook()
+ .getActiveSheet()
+ .getSheetId();
const workbook = currentUniverService.getUniverSheetInstance(workbookId)?.getWorkBook();
if (!workbook) return false;
const worksheet = workbook.getSheetBySheetId(worksheetId);
@@ -33,7 +50,10 @@ export const MoveRangeToCommand: ICommand = {
rangeData: [originRange],
worksheetId,
};
- const undoClearMutationParams: ISetRangeValuesMutationParams = SetRangeValuesUndoMutationFactory(accessor, clearMutationParams);
+ const undoClearMutationParams: ISetRangeValuesMutationParams = SetRangeValuesUndoMutationFactory(
+ accessor,
+ clearMutationParams
+ );
const clearResult = commandService.executeCommand(SetRangeValuesMutation.id, clearMutationParams);
@@ -45,7 +65,11 @@ export const MoveRangeToCommand: ICommand = {
for (let r = startRow; r <= endRow; r++) {
for (let c = startColumn; c <= endColumn; c++) {
- targetMatrix.setValue(targetStartRow + (r - startRow), targetStartColumn + (c - startColumn), sheetMatrix.getValue(r, c) || {});
+ targetMatrix.setValue(
+ targetStartRow + (r - startRow),
+ targetStartColumn + (c - startColumn),
+ sheetMatrix.getValue(r, c) || {}
+ );
}
}
@@ -56,7 +80,10 @@ export const MoveRangeToCommand: ICommand = {
cellValue: targetMatrix.getData(),
};
- const undoMutationParams: ISetRangeValuesMutationParams = SetRangeValuesUndoMutationFactory(accessor, setRangeValuesMutationParams);
+ const undoMutationParams: ISetRangeValuesMutationParams = SetRangeValuesUndoMutationFactory(
+ accessor,
+ setRangeValuesMutationParams
+ );
const result = commandService.executeCommand(SetRangeValuesMutation.id, setRangeValuesMutationParams);
@@ -66,14 +93,28 @@ export const MoveRangeToCommand: ICommand = {
// 通过勾子可以 hook 外部 controller 的代码来增加新的 action
URI: workbookId,
undo() {
- return (commandService.executeCommand(SetRangeValuesMutation.id, undoClearMutationParams) as Promise<boolean>).then((res) => {
+ return (
+ commandService.executeCommand(
+ SetRangeValuesMutation.id,
+ undoClearMutationParams
+ ) as Promise<boolean>
+ ).then((res) => {
if (res) return commandService.executeCommand(SetRangeValuesMutation.id, undoMutationParams);
return false;
});
},
redo() {
- return (commandService.executeCommand(SetRangeValuesMutation.id, clearMutationParams) as Promise<boolean>).then((res) => {
- if (res) return commandService.executeCommand(SetRangeValuesMutation.id, setRangeValuesMutationParams);
+ return (
+ commandService.executeCommand(
+ SetRangeValuesMutation.id,
+ clearMutationParams
+ ) as Promise<boolean>
+ ).then((res) => {
+ if (res)
+ return commandService.executeCommand(
+ SetRangeValuesMutation.id,
+ setRangeValuesMutationParams
+ );
return false;
});
},
diff --git a/packages/base-ui/src/Components/ColorPicker/ColorPicker.tsx b/packages/base-ui/src/Components/ColorPicker/ColorPicker.tsx
index cbcca44129..fc1f718b6c 100644
--- a/packages/base-ui/src/Components/ColorPicker/ColorPicker.tsx
+++ b/packages/base-ui/src/Components/ColorPicker/ColorPicker.tsx
@@ -360,7 +360,13 @@ export function ColorPicker(props: BaseColorPickerProps) {
e.nativeEvent.stopImmediatePropagation();
}}
>
- <Button onClick={onSwitch}>{setting ? <CustomLabel label="colorPicker.collapse" /> : <CustomLabel label="colorPicker.customColor" />}</Button>
+ <Button onClick={onSwitch}>
+ {setting ? (
+ <CustomLabel label="colorPicker.collapse" />
+ ) : (
+ <CustomLabel label="colorPicker.customColor" />
+ )}
+ </Button>
</div>
</div>
diff --git a/packages/base-ui/src/Components/Slider/Slider.tsx b/packages/base-ui/src/Components/Slider/Slider.tsx
index e179ecda85..38bb47f292 100644
--- a/packages/base-ui/src/Components/Slider/Slider.tsx
+++ b/packages/base-ui/src/Components/Slider/Slider.tsx
@@ -57,7 +57,7 @@ export function Slider(props: BaseSliderProps) {
const idNextRef = useRef<string>(randomId('slider'));
const sliderRef = useRef<HTMLDivElement | null>(null);
- const { min = 0, max = 100, step = 1, range = false, value } = props;
+ const { min = 0, max = 100, step = 1, range = false, value, className = '' } = props;
useEffect(() => {
const diff = max - min;
@@ -129,10 +129,9 @@ export function Slider(props: BaseSliderProps) {
index = 1;
}
}
+ props.onChange?.(e.nativeEvent);
changeInputValue(index, value);
-
- props.onChange?.(e.nativeEvent);
};
const onClick = (e: React.MouseEvent<HTMLDivElement>) => {
@@ -152,9 +151,8 @@ export function Slider(props: BaseSliderProps) {
index = 1;
}
}
-
- changeInputValue(index, value);
props.onClick?.(e.nativeEvent, value);
+ changeInputValue(index, value);
};
const changeInputValue = (index: number, value: number) => {
@@ -174,7 +172,7 @@ export function Slider(props: BaseSliderProps) {
return (
<div
- className={styles.slider}
+ className={`${styles.slider} ${className}`}
role="slider-group"
aria-labelledby="multi-lbl"
style={{ '--min': min, '--max': max } as CSSProperties}
@@ -182,11 +180,27 @@ export function Slider(props: BaseSliderProps) {
onClick={(e) => onClick(e)}
>
<label className="sr-only" htmlFor={idPrevRef.current}></label>
- <input id={idPrevRef.current} type="range" min={min} value={valuePrev} max={max} step={step} onInput={(e) => onInput(e)} />
+ <input
+ id={idPrevRef.current}
+ type="range"
+ min={min}
+ value={valuePrev}
+ max={max}
+ step={step}
+ onInput={(e) => onInput(e)}
+ />
{range && (
<>
<label className="sr-only" htmlFor={idNextRef.current}></label>
- <input id={idNextRef.current} type="range" min={min} value={valueNext} max={max} step={step} onInput={(e) => onInput(e)} />
+ <input
+ id={idNextRef.current}
+ type="range"
+ min={min}
+ value={valueNext}
+ max={max}
+ step={step}
+ onInput={(e) => onInput(e)}
+ />
</>
)}
</div>
diff --git a/packages/base-ui/src/Components/Slider/test/index.test.tsx b/packages/base-ui/src/Components/Slider/test/index.test.tsx
index 89e8b395dc..cc3f5ad5c8 100644
--- a/packages/base-ui/src/Components/Slider/test/index.test.tsx
+++ b/packages/base-ui/src/Components/Slider/test/index.test.tsx
@@ -24,4 +24,13 @@ describe('Slider', () => {
expect(a).toEqual(2);
});
+
+ test('test change event', () => {
+ let a = 1;
+ const { container } = render(<Slider onChange={() => a++} />);
+ const slider = screen.getByRole('slider-group');
+ const input = slider.querySelector('input');
+ fireEvent.input(input!);
+ expect(a).toEqual(2);
+ });
});
diff --git a/packages/base-ui/src/Components/Tabs/Tabs.stories.tsx b/packages/base-ui/src/Components/Tabs/Tabs.stories.tsx
index b538245bce..78b9f5ee1a 100644
--- a/packages/base-ui/src/Components/Tabs/Tabs.stories.tsx
+++ b/packages/base-ui/src/Components/Tabs/Tabs.stories.tsx
@@ -1,10 +1,10 @@
import type { Meta } from '@storybook/react';
-import { Tab, TabPane } from './Tabs';
+import { TabPane, Tabs } from './Tabs';
-const meta: Meta<typeof Tab> = {
+const meta: Meta<typeof Tabs> = {
title: 'Components / Tabs',
- component: Tab,
+ component: Tabs,
parameters: {
layout: 'centered',
},
diff --git a/packages/base-ui/src/Components/Tabs/Tabs.tsx b/packages/base-ui/src/Components/Tabs/Tabs.tsx
index f265d8827b..4d22a96eae 100644
--- a/packages/base-ui/src/Components/Tabs/Tabs.tsx
+++ b/packages/base-ui/src/Components/Tabs/Tabs.tsx
@@ -1,27 +1,16 @@
-import React, { ReactNode, useEffect, useState } from 'react';
+import React, { createRef, ReactNode, useEffect, useState } from 'react';
-import { BaseComponentProps } from '../../BaseComponent';
import { joinClassNames, randomId } from '../../Utils';
import styles from './index.module.less';
// Components interface
// Props of tab pane
-export interface BaseTabPaneProps {
+export interface IBaseTabPaneProps {
/**
* TabPane's head display content
*/
- label: ReactNode;
-
- /**
- * Active status of tab pane
- */
- active?: boolean;
-
- /**
- * TabPane's key
- */
- keys?: string;
+ children?: ReactNode;
/**
* TabPane's id
@@ -41,11 +30,21 @@ export interface BaseTabPaneProps {
/**
* TabPane's head display content
*/
- children?: ReactNode;
+ label: ReactNode;
+
+ /**
+ * Active status of tab pane
+ */
+ active?: boolean;
+
+ /**
+ * TabPane's key
+ */
+ keys?: string;
}
// Props of tabs
-export interface BaseTabProps extends BaseComponentProps {
+export interface IBaseTabsProps {
/**
* Basic style of tabs
*/
@@ -74,74 +73,336 @@ export interface BaseTabProps extends BaseComponentProps {
/**
* Content of tab
*/
- children: Array<React.ReactElement<BaseTabPaneProps, string>>;
+ children: Array<React.ReactElement<IBaseTabPaneProps, string>>;
+
+ /**
+ * Tab pane is draggable
+ * @default false
+ */
+ draggable?: boolean;
+}
+
+interface ITabInfo {
+ min: number;
+ max: number;
}
-// Todo: rename component name
/**
* Tabs Component
*/
-export function Tab(props: BaseTabProps) {
- const { type = 'line', className = '' } = props;
- const [active, setActive] = useState<string>(props.activeKey || ''); // Initialize active with the provided activeKey
- const [tabChildren, setTabChildren] = useState<Array<React.ReactElement<BaseTabPaneProps, string>>>(props.children);
-
- useEffect(() => {
- props.activeKey && setActive(props.activeKey); // Update active state when props.activeKey changes
- }, [props.activeKey]);
-
- useEffect(() => {
- setTabChildren(props.children); // Update children state when props.children changes
- }, [props.children]);
-
- const parseNavList = () =>
- tabChildren.map((child) => {
- const { label, keys } = child.props;
- const id = `${randomId('tab')}-${keys}`;
- const tabClassName = active === keys ? `${styles.tabsTab} ${styles.tabsTabActive}` : styles.tabsTab;
-
- return (
- <div key={id} id={id} onClick={handleClick} className={tabClassName}>
- {label}
- </div>
- );
- });
+export const Tabs = React.memo(
+ (props: IBaseTabsProps) => {
+ const { type = 'line', className = '', draggable = false } = props;
+ const [active, setActive] = useState<string>(props.activeKey ?? ''); // Initialize active with the provided activeKey
- const handleClick = (e: React.MouseEvent<HTMLDivElement>) => {
- const id = e.currentTarget.id;
- const index = id.lastIndexOf('-');
- const value = id.slice(index + 1);
+ useEffect(() => {
+ props.activeKey && setActive(props.activeKey); // Update active state when props.activeKey changes
+ }, [props.activeKey]);
- setActive(value);
+ useEffect(() => {
+ if (!parent.current) return;
+ parent.current.removeEventListener('wheel', wheel);
+ parent.current.addEventListener('wheel', wheel);
- if (props.onTabClick) {
- props.onTabClick(value, e.nativeEvent);
- }
- };
+ return () => {
+ parent.current?.removeEventListener('wheel', wheel);
+ };
+ }, [props.children]);
- return (
- <div className={`${styles.tabs} ${type === 'card' ? `${styles.tabs}-card` : ''} ${className}`}>
- <div className={styles.tabsNav}>
- <div className={styles.tabsNavWrap}>
- <div className={styles.tabsNavList}>{parseNavList()}</div>
+ const parseNavList = () =>
+ props.children.map((child) => {
+ const { label, keys, className = '' } = child.props;
+ const id = `${randomId('tab')}-${keys}`;
+ const tabClassName =
+ active === keys
+ ? `${styles.tabsTab} ${className} ${styles.tabsTabActive}`
+ : `${styles.tabsTab} ${className}`;
+
+ return (
+ <div
+ key={id}
+ id={id}
+ onClick={handleClick}
+ className={tabClassName}
+ onMouseDown={draggable ? (e: any) => dragStart(e) : undefined}
+ >
+ {label}
+ </div>
+ );
+ });
+
+ const handleClick = (e: React.MouseEvent<HTMLDivElement, MouseEvent>) => {
+ const id = e.currentTarget.id;
+ const index = id.lastIndexOf('-');
+ const value = id.slice(index + 1);
+
+ setActive(value);
+
+ if (props.onTabClick) {
+ props.onTabClick(value, e.nativeEvent);
+ }
+ };
+
+ // 拖拽逻辑
+ let target: HTMLDivElement | null;
+ let startX: number;
+ let left: number;
+ const parent = createRef<HTMLDivElement>();
+ let parentOffsetLeft: number;
+ let parentOffsetTop: number;
+ let list: ITabInfo[] = [];
+ let nextIndex = 0;
+ let previousIndex = 0;
+ // 滚轮滚动距离
+ let wheelDistance = 0;
+ // 超出右边界再回来
+ let overRight = false;
+ // 超出左边界再回来
+ let overLeft = false;
+ let startTime: number;
+ // requestAnimationFrameId
+ let scrollToRightId: number;
+
+ const getDistance = (element: HTMLDivElement, direction: 'Left' | 'Top' = 'Left') => {
+ let distance = 0;
+
+ while (element) {
+ distance += element[`offset${direction}`];
+ element = element.offsetParent as HTMLDivElement;
+ }
+ return distance;
+ };
+
+ const getList = (parent: HTMLDivElement) => {
+ const list: ITabInfo[] = [];
+ Array.from(parent.children).forEach((item) => {
+ const divItem = item as HTMLDivElement;
+ list.push({
+ min: divItem.offsetLeft,
+ max: divItem.offsetLeft + divItem.offsetWidth,
+ });
+ });
+ return list;
+ };
+
+ const wheel = (e: WheelEvent) => {
+ e.preventDefault();
+ if (!parent.current) return;
+ const children = parent.current.children;
+ if (e.deltaY > 0) {
+ const lastChild = children[children.length - 1] as HTMLDivElement;
+ const width = lastChild.offsetLeft + lastChild.offsetWidth - parent.current.offsetWidth;
+ wheelDistance = wheelDistance + 100 <= width ? wheelDistance + 100 : width;
+ parent.current.scrollTo(wheelDistance, 0);
+ } else {
+ wheelDistance = wheelDistance - 100 < 0 ? 0 : wheelDistance - 100;
+ parent.current.scrollTo(wheelDistance, 0);
+ }
+ };
+
+ // 动画函数
+ const scrollToAnimation = (current: HTMLDivElement, direction: 'left' | 'right') => () => {
+ let scrollLeft;
+ if (direction === 'left') {
+ scrollLeft = current.scrollLeft - 2;
+ } else {
+ scrollLeft = current.scrollLeft + 2;
+ }
+ current.scrollTo(scrollLeft, 0);
+ scrollToRightId = requestAnimationFrame(scrollToAnimation(current, direction));
+ };
+
+ const drag = (e: MouseEvent) => {
+ const time = new Date().getTime();
+ if (time - startTime < 300) return;
+ cancelAnimationFrame(scrollToRightId);
+
+ const current = parent.current;
+ if (!current || !target) return;
+ const diff = e.pageX - startX;
+ const distance = left + diff;
+ if (e.pageX > parentOffsetLeft + current.offsetWidth) {
+ target.style.left = `${parentOffsetLeft + current.offsetWidth}px`;
+ scrollToAnimation(current, 'right')();
+ overRight = true;
+ } else if (e.pageX < parentOffsetLeft) {
+ target.style.left = `${parentOffsetLeft - target.offsetWidth}px`;
+ scrollToAnimation(current, 'left')();
+ overLeft = true;
+ } else {
+ target.style.left = `${distance}px`;
+ // 相对父元素的offsetLeft
+ const offsetLeft = e.pageX + current.scrollLeft - parentOffsetLeft;
+
+ // 超出边界再回来时,把相应的tab挤掉
+ requestAnimationFrame(() => {
+ if (!target) return;
+ if (overRight || overLeft) {
+ if (nextIndex < current.children.length) {
+ const item = current.children[nextIndex] as HTMLDivElement;
+ item.style.marginRight = '0';
+ item.style.marginLeft = '0';
+ }
+ if (previousIndex > -1) {
+ const item = current.children[previousIndex] as HTMLDivElement;
+ item.style.marginLeft = '0';
+ item.style.marginRight = '0';
+ }
+
+ let index = list.findIndex((item) => offsetLeft >= item.min && offsetLeft <= item.max);
+ if (offsetLeft > list[list.length - 1].max) index = current.children.length - 1;
+
+ if (index < 1) {
+ const item = current.children[0] as HTMLDivElement;
+ item.style.marginLeft = `${target.offsetWidth}px`;
+ previousIndex = -1;
+ nextIndex = 0;
+ } else if (index === current.children.length - 1) {
+ const item = current.children[index] as HTMLDivElement;
+ item.style.marginRight = `${target.offsetWidth}px`;
+ previousIndex = index;
+ nextIndex = current.children.length;
+ } else {
+ const item = current.children[index - 1] as HTMLDivElement;
+ item.style.marginRight = `${target.offsetWidth}px`;
+ previousIndex = index - 1;
+ nextIndex = index;
+ }
+ }
+ });
+
+ if (nextIndex < current.children.length && offsetLeft > list[nextIndex].min) {
+ const nextElement = current.children[nextIndex] as HTMLDivElement;
+ const previousElement = current.children[previousIndex] as HTMLDivElement;
+ nextElement.style.marginRight = `${target.offsetWidth}px`;
+ nextElement.style.marginLeft = '0';
+ if (previousIndex > -1) {
+ previousElement.style.marginRight = '0';
+ previousElement.style.marginLeft = '0';
+ }
+ previousIndex = nextIndex;
+ nextIndex += 1;
+ } else if (previousIndex > -1 && offsetLeft < list[previousIndex].max) {
+ const nextElement = current.children[nextIndex] as HTMLDivElement;
+ const previousElement = current.children[previousIndex] as HTMLDivElement;
+ previousElement.style.marginLeft = `${target.offsetWidth}px`;
+ previousElement.style.marginRight = '0';
+ if (nextIndex < current.children.length) {
+ nextElement.style.marginLeft = '0';
+ nextElement.style.marginRight = '0';
+ }
+ nextIndex = previousIndex;
+ previousIndex -= 1;
+ }
+ list = getList(current);
+ overLeft = false;
+ overRight = false;
+ }
+ };
+
+ const dragEnd = () => {
+ cancelAnimationFrame(scrollToRightId);
+
+ overLeft = false;
+ overRight = false;
+ window.removeEventListener('mousemove', drag);
+ window.removeEventListener('mouseup', dragEnd);
+
+ const current = parent.current;
+ if (!current || !target) return;
+
+ const previousElement = current.children[previousIndex > -1 ? previousIndex : 0] as HTMLDivElement;
+ previousElement.style.marginLeft = '0';
+ previousElement.style.marginRight = '0';
+ const nextElement = current.children[
+ nextIndex < current.children.length ? nextIndex : current.children.length - 1
+ ] as HTMLDivElement;
+ nextElement.style.marginLeft = '0';
+ nextElement.style.marginRight = '0';
+ target.style.position = 'relative';
+ target.style.left = '0';
+ target.style.top = '0';
+ current.insertBefore(target, current.children[nextIndex]) as HTMLDivElement;
+ };
+
+ const dragStart = (e: MouseEvent) => {
+ requestAnimationFrame(() => {
+ startTime = new Date().getTime();
+ startX = e.pageX;
+ window.addEventListener('mousemove', drag);
+ window.addEventListener('mouseup', dragEnd);
+ target = (e.target as HTMLElement).closest(`.${styles.tabsTab}`);
+ if (!target) return;
+ const width = target.offsetWidth;
+ const nextElement = target.nextElementSibling as HTMLDivElement;
+ const previousElement = target.previousElementSibling as HTMLDivElement;
+ const targetOffsetLeft = target.offsetLeft;
+ const targetOffsetTop = target.offsetTop;
+ const current = parent.current;
+ if (!current) return;
+ parentOffsetLeft = getDistance(parent.current, 'Left');
+ parentOffsetTop = getDistance(parent.current, 'Top');
+ // 点击时距离左边的距离
+ left = targetOffsetLeft + parentOffsetLeft - current.scrollLeft;
+ target.style.left = `${targetOffsetLeft + parentOffsetLeft - current.scrollLeft}px`;
+ target.style.top = `${targetOffsetTop + parentOffsetTop - current.scrollTop}px`;
+ // current.removeChild(target);
+ if (previousElement) {
+ previousElement.style.marginRight = `${width}px`;
+ } else {
+ nextElement.style.marginLeft = `${width}px`;
+ }
+ document.body.appendChild(target);
+ target.style.position = 'absolute';
+ // TODO: CSS变量挂在container上,container外层取不到
+ target.style.fontSize = '14px';
+ list = getList(current);
+ nextIndex = nextElement
+ ? list.findIndex((item) => item.min === nextElement.offsetLeft)
+ : current.children.length;
+ previousIndex = previousElement
+ ? list.findIndex((item) => item.min === previousElement.offsetLeft)
+ : -1;
+ });
+ };
+
+ return (
+ <div className={`${styles.tabs} ${type === 'card' ? `${styles.tabs}-card` : ''} ${className}`}>
+ <div className={styles.tabsNav}>
+ <div className={styles.tabsNavWrap}>
+ <div className={styles.tabsNavList} ref={parent}>
+ {parseNavList()}
+ </div>
+ </div>
+ </div>
+ <div className={styles.tabsContent}>
+ {props.children.map((child, index) => (
+ <TabPane
+ label={child.props.label}
+ key={index}
+ keys={child.props.keys}
+ active={child.props.keys === active}
+ >
+ {child.props.children}
+ </TabPane>
+ ))}
</div>
</div>
- <div className={styles.tabsContent}>
- {tabChildren.map((child, index) => (
- <TabPane label={child.props.label} key={index} keys={child.props.keys} active={child.props.keys === active}>
- {child.props.children}
- </TabPane>
- ))}
- </div>
- </div>
- );
-}
+ );
+ },
+ (prev, next) => prev.children.length === next.children.length && prev.activeKey === next.activeKey
+);
// tab content
-export function TabPane(props: BaseTabPaneProps) {
+export function TabPane(props: IBaseTabPaneProps) {
const { id, keys, style, children, active } = props;
return (
- <div id={id && `${id}-panel-${keys}`} role="tabpanel" style={{ ...style }} className={joinClassNames(styles.tabsPanel, active && styles.tabsPanelActive)}>
+ <div
+ id={id && `${id}-panel-${keys}`}
+ role="tabpanel"
+ className={joinClassNames(styles.tabsPanel, active && styles.tabsPanelActive)}
+ style={{ ...style }}
+ >
{active && children}
</div>
);
diff --git a/packages/base-ui/src/Components/Tabs/index.module.less b/packages/base-ui/src/Components/Tabs/index.module.less
index c0f4457a2d..42415bda2b 100644
--- a/packages/base-ui/src/Components/Tabs/index.module.less
+++ b/packages/base-ui/src/Components/Tabs/index.module.less
@@ -1,16 +1,17 @@
@import '../../Basics/CSS/Skin/base.module.less';
.tabs {
- // display: flex;
overflow: hidden;
+ ::-webkit-scrollbar {
+ display: none;
+ }
+
.tabs-nav {
- position: relative;
- display: flex;
- flex: none;
- align-items: center;
+ width: 100%;
.tabs-nav-wrap {
+ width: 100%;
position: relative;
display: flex;
flex: auto;
@@ -19,25 +20,11 @@
white-space: nowrap;
.tabs-nav-list {
+ display: inline-block;
+ overflow-y: hidden;
+ overflow-x: auto;
position: relative;
- display: flex;
-
- .tabs-tab {
- position: relative;
- display: inline-flex;
- align-items: center;
- padding: 0.5rem 1em;
- font-size: var(--font-size);
- background: transparent;
- border: 0;
- outline: none;
- cursor: pointer;
-
- &:hover,
- &-active {
- color: var(--primary-color);
- }
- }
+ white-space: nowrap;
}
}
}
@@ -58,9 +45,28 @@
}
}
+.tabs-tab {
+ display: inline-block;
+ position: relative;
+ user-select: none;
+ padding: 0.5rem 1em;
+ font-size: var(--font-size);
+ background: transparent;
+ border: 0;
+ outline: none;
+ cursor: pointer;
+
+ &:hover,
+ &-active {
+ color: var(--primary-color);
+ }
+}
+
.tabs.tabs-card {
.tabs-nav {
+ width: 100%;
.tabs-nav-wrap {
+ width: 100%;
.tabs-nav-list {
.tabs-tab {
margin: 0;
@@ -77,3 +83,4 @@
}
}
}
+
diff --git a/packages/base-ui/src/Components/Tabs/test/index.test.tsx b/packages/base-ui/src/Components/Tabs/test/index.test.tsx
index 19abd67e53..04c6c99c88 100644
--- a/packages/base-ui/src/Components/Tabs/test/index.test.tsx
+++ b/packages/base-ui/src/Components/Tabs/test/index.test.tsx
@@ -1,18 +1,18 @@
import { fireEvent, render, screen } from '@testing-library/react';
-import { Tab, TabPane } from '..';
+import { TabPane, Tabs } from '..';
describe('tab', () => {
test('tab render', () => {
const { container } = render(
- <Tab activeKey="tab" type="card">
+ <Tabs activeKey="tab" type="card">
<TabPane label="tab1" keys="tab">
test tab
</TabPane>
<TabPane label="tab2" keys="tabs">
test tabs
</TabPane>
- </Tab>
+ </Tabs>
);
expect(container);
@@ -22,14 +22,14 @@ describe('tab', () => {
let a = 1;
render(
- <Tab activeKey="tab" type="card" onTabClick={() => a++}>
+ <Tabs activeKey="tab" type="card" onTabClick={() => a++}>
<TabPane label="tab1" keys="tab">
test tab
</TabPane>
<TabPane label="tab2" keys="tabs">
test tabs
</TabPane>
- </Tab>
+ </Tabs>
);
fireEvent.click(screen.getByText('tab1'));
diff --git a/packages/ui-plugin-sheets/src/View/SheetBar/SheetBar.tsx b/packages/ui-plugin-sheets/src/View/SheetBar/SheetBar.tsx
index 405be9110d..1b75d54481 100644
--- a/packages/ui-plugin-sheets/src/View/SheetBar/SheetBar.tsx
+++ b/packages/ui-plugin-sheets/src/View/SheetBar/SheetBar.tsx
@@ -9,7 +9,19 @@ import {
SetWorksheetOrderMutation,
SetWorksheetShowCommand,
} from '@univerjs/base-sheets';
-import { AppContext, BaseComponentProps, BaseMenuItem, BaseSelectProps, Button, CustomLabel, Icon, IDisplayMenuItem, IMenuItem, Menu, MenuPosition } from '@univerjs/base-ui';
+import {
+ AppContext,
+ BaseComponentProps,
+ BaseMenuItem,
+ BaseSelectProps,
+ Button,
+ CustomLabel,
+ Icon,
+ IDisplayMenuItem,
+ IMenuItem,
+ Menu,
+ MenuPosition,
+} from '@univerjs/base-ui';
import { BooleanNumber, ICommandService, ICurrentUniverService, IKeyValue } from '@univerjs/core';
import { IDisposable } from '@wendellhu/redi';
import { Component, createRef } from 'react';
@@ -39,6 +51,7 @@ type SheetState = {
menuItems: Array<IDisplayMenuItem<IMenuItem>>;
showMenu: boolean;
menuStyle: React.CSSProperties;
+ activeKey: string;
};
export class SheetBar extends Component<BaseSheetBarProps, SheetState> {
@@ -80,6 +93,7 @@ export class SheetBar extends Component<BaseSheetBarProps, SheetState> {
menuItems: [],
showMenu: false,
menuStyle: {},
+ activeKey: '',
};
}
@@ -188,6 +202,44 @@ export class SheetBar extends Component<BaseSheetBarProps, SheetState> {
return currentSheet?.sheetId;
}
+ // getSheetBarItem(item: BaseSheetBarProps) {
+ // return (
+ // <div
+ // onMouseDown={item.onMouseDown}
+ // onContextMenu={this.contextMenu}
+ // key={item.sheetId}
+ // data-id={item.sheetId}
+ // className={`${styles.slideTabItem} ${item.selected ? styles.slideTabActive : ''}`}
+ // >
+ // <div className={`${styles.slideTabContent}`}>
+ // <div className={`${styles.slideTabDivider}`}></div>
+ // <div className={`${styles.slideTabTitle}`}>
+ // <span className={`${styles.slideTabSpan}`} style={{ padding: '2px 5px 2px 5px' }}>
+ // <CustomLabel label={item.label} />
+ // </span>
+ // </div>
+ // <div
+ // className={`${styles.slideTabIcon}`}
+ // data-slide-skip="true"
+ // style={{ lineHeight: 1 }}
+ // data-id={item.sheetId}
+ // onMouseDown={(e) => {
+ // this.onContextMenuClick(e);
+ // }}
+ // >
+ // <Icon.NextIcon />
+ // </div>
+ // </div>
+ // <div className={`${styles.slideTabFooter}`}>
+ // <div
+ // className={`${styles.slideTabActiveBar}`}
+ // style={item.color ? { background: item.color } : {}}
+ // ></div>
+ // </div>
+ // </div>
+ // );
+ // }
+
/**
* Update worksheet info.
*
@@ -225,6 +277,10 @@ export class SheetBar extends Component<BaseSheetBarProps, SheetState> {
color: (sheet.getTabColor() as string) ?? undefined,
onMouseDown: (e: MouseEvent) => {
const worksheetId = sheet.getSheetId();
+ // this.setState({
+ // activeKey: worksheetId,
+ // });
+
commandService.executeCommand(SetWorksheetActivateCommand.id, {
workbookId: workbook.getUnitId(),
worksheetId,
@@ -264,7 +320,7 @@ export class SheetBar extends Component<BaseSheetBarProps, SheetState> {
}
override render() {
- const { sheetList, menuList, sheetUl, showMenu, menuStyle } = this.state;
+ const { sheetList, menuList, sheetUl, showMenu, menuStyle, activeKey } = this.state;
const { addSheet } = this.props;
@@ -276,13 +332,26 @@ export class SheetBar extends Component<BaseSheetBarProps, SheetState> {
<Icon.Math.AddIcon style={{ fontSize: '20px' }} />
</Button>
{/* all sheets button */}
- <Button className={styles.sheetBarOptionsButton} onClick={(e: MouseEvent) => this.ref.current?.showMenu(true)}>
+ <Button
+ className={styles.sheetBarOptionsButton}
+ onClick={(e: MouseEvent) => this.ref.current?.showMenu(true)}
+ >
<Icon.MenuIcon style={{ fontSize: '20px' }} />
<SheetBarMenu menu={menuList as ISheetBarMenuItem[]}></SheetBarMenu>
</Button>
</div>
{/* user s button */}
+ {/* <Tabs draggable className={styles.slideTabBar} activeKey={activeKey}>
+ {sheetList.map((item) => (
+ <TabPane
+ key={item.sheetId}
+ keys={item.sheetId}
+ label={this.getSheetBarItem(item)}
+ className={styles.sheetBarTabPane}
+ ></TabPane>
+ ))}
+ </Tabs> */}
<div className={styles.slideTabBar}>
{sheetList.map((item) => (
<div
@@ -310,7 +379,10 @@ export class SheetBar extends Component<BaseSheetBarProps, SheetState> {
</div>
</div>
<div className={`${styles.slideTabFooter}`}>
- <div className={`${styles.slideTabActiveBar}`} style={item.color ? { background: item.color } : {}}></div>
+ <div
+ className={`${styles.slideTabActiveBar}`}
+ style={item.color ? { background: item.color } : {}}
+ ></div>
</div>
</div>
))}
@@ -325,7 +397,9 @@ export class SheetBar extends Component<BaseSheetBarProps, SheetState> {
style={menuStyle}
onOptionSelect={(params) => {
const { label: commandId } = params;
- const commandService: ICommandService = (this.context as IKeyValue).injector.get(ICommandService);
+ const commandService: ICommandService = (this.context as IKeyValue).injector.get(
+ ICommandService
+ );
commandService.executeCommand(commandId as string);
}}
/>
diff --git a/packages/ui-plugin-sheets/src/View/SheetBar/index.module.less b/packages/ui-plugin-sheets/src/View/SheetBar/index.module.less
index f30433802a..22a4769726 100644
--- a/packages/ui-plugin-sheets/src/View/SheetBar/index.module.less
+++ b/packages/ui-plugin-sheets/src/View/SheetBar/index.module.less
@@ -4,6 +4,7 @@
display: flex;
flex-direction: row;
background-color: var(--bg);
+ width: 70%;
}
.sheet-bar-options {
@@ -41,6 +42,22 @@
scrollbar-width: none;
}
+.sheet-bar-tab-pane {
+ padding: 0;
+
+ &.tabs-tab-active {
+ .slide-tab-content {
+ background: #efefef;
+ color: #222;
+ }
+
+ .slide-tab-active-bar {
+ background: #d0d0d0;
+ }
+
+ }
+}
+
.slide-tab-bar::-webkit-scrollbar {
display: none;
}
@@ -89,6 +106,7 @@
flex-direction: row;
align-items: center;
flex-grow: 1;
+ padding: 0.3rem;
}
.slide-tab-title {
@@ -229,4 +247,4 @@
color: #eee;
}
}
-}
+}
\ No newline at end of file