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.

feat(sheet): sheet bar refactor (#331)

Dushusir90c0da6652d0
diff --git a/packages/base-sheets/src/index.ts b/packages/base-sheets/src/index.ts
index 629dfcf435..953ceb44a6 100644
--- a/packages/base-sheets/src/index.ts
+++ b/packages/base-sheets/src/index.ts
@@ -20,6 +20,8 @@ export {
type IAddWorksheetMergeMutationParams,
type IRemoveWorksheetMergeMutationParams,
} from './Basics/Interfaces/MutationInterface';
+export { type IRemoveSheetMutationParams } from './Basics/Interfaces/MutationInterface';
+export { type IInsertSheetMutationParams } from './Basics/Interfaces/MutationInterface';
export { transformCellDataToSelectionData } from './Basics/selection';
export {
AddWorksheetMergeAllCommand,
@@ -133,7 +135,9 @@ export { SetRangeValuesMutation } from './commands/mutations/set-range-values.mu
export { SetRangeValuesUndoMutationFactory } from './commands/mutations/set-range-values.mutation';
export { SetRowHiddenMutation, SetRowVisibleMutation } from './commands/mutations/set-row-visible.mutation';
export { SetTabColorMutation } from './commands/mutations/set-tab-color.mutation';
+export { type ISetTabColorMutationParams } from './commands/mutations/set-tab-color.mutation';
export { SetWorksheetActivateMutation } from './commands/mutations/set-worksheet-activate.mutation';
+export { type ISetWorksheetActivateMutationParams } from './commands/mutations/set-worksheet-activate.mutation';
export {
type ISetWorksheetColWidthMutationParams,
SetWorksheetColWidthMutation,
@@ -144,7 +148,9 @@ export {
SetWorksheetHideMutation,
} from './commands/mutations/set-worksheet-hide.mutation';
export { SetWorksheetNameMutation } from './commands/mutations/set-worksheet-name.mutation';
+export { type ISetWorksheetNameMutationParams } from './commands/mutations/set-worksheet-name.mutation';
export { SetWorksheetOrderMutation } from './commands/mutations/set-worksheet-order.mutation';
+export { type ISetWorksheetOrderMutationParams } from './commands/mutations/set-worksheet-order.mutation';
export {
type ISetWorksheetRowHeightMutationParams,
SetWorksheetRowAutoHeightMutation,
diff --git a/packages/base-ui/src/Components/Dropdown/Dropdown2.tsx b/packages/base-ui/src/Components/Dropdown/Dropdown2.tsx
index 754e1f77d4..fc3c4cb610 100644
--- a/packages/base-ui/src/Components/Dropdown/Dropdown2.tsx
+++ b/packages/base-ui/src/Components/Dropdown/Dropdown2.tsx
@@ -4,6 +4,7 @@ import Placements from 'rc-dropdown/lib/placements';
import styles from './index.module.less';
+// TODO@jikkai Need to limit width
export interface IDropdown2Props {
visible?: boolean;
trigger?: ActionType | ActionType[];
diff --git a/packages/base-ui/src/Components/Notification/test/index.test.tsx b/packages/base-ui/src/Components/Notification/test/index.test.tsx
deleted file mode 100644
index 3b4fab4e4b..0000000000
--- a/packages/base-ui/src/Components/Notification/test/index.test.tsx
+++ /dev/null
@@ -1,27 +0,0 @@
-import { fireEvent, render, screen } from '@testing-library/react';
-import { Button } from '@univerjs/design';
-import { describe, expect, test } from 'vitest';
-
-import { notification } from '../Notification';
-
-describe('Notification', () => {
- test('renders correctly', () => {
- const { container } = render(
- <Button
- onClick={() => {
- notification.show({
- type: 'success',
- title: 'success title',
- content: 'success content',
- });
- }}
- >
- btn2
- </Button>
- );
-
- fireEvent.click(container.querySelector('button')!);
-
- expect(screen.getByText('success content')).toBeTruthy();
- });
-});
diff --git a/packages/ui-plugin-sheets/package.json b/packages/ui-plugin-sheets/package.json
index 7ff5f345f6..9551b57f19 100644
--- a/packages/ui-plugin-sheets/package.json
+++ b/packages/ui-plugin-sheets/package.json
@@ -45,12 +45,14 @@
"esbuild": "node ./esbuild.config.mjs"
},
"dependencies": {
+ "@ctrl/tinycolor": "^4.0.2",
"@univerjs/base-docs": "workspace:*",
"@univerjs/base-render": "workspace:*",
"@univerjs/base-sheets": "workspace:*",
"@univerjs/base-ui": "workspace:*",
"@univerjs/core": "workspace:*",
"@univerjs/design": "workspace:*",
+ "@univerjs/icons": "^0.1.3",
"@wendellhu/redi": "^0.12.10",
"react": "^18.2.0",
"react-dom": "^18.2.0",
diff --git a/packages/ui-plugin-sheets/src/View/SheetBar/SheetBar.tsx b/packages/ui-plugin-sheets/src/View/SheetBar/SheetBar.tsx
index a1a9389eb1..a6a68d1c57 100644
--- a/packages/ui-plugin-sheets/src/View/SheetBar/SheetBar.tsx
+++ b/packages/ui-plugin-sheets/src/View/SheetBar/SheetBar.tsx
@@ -1,460 +1,80 @@
-import {
- InsertSheetCommand,
- InsertSheetMutation,
- RemoveSheetMutation,
- SetTabColorMutation,
- SetWorksheetActivateCommand,
- SetWorksheetActivateMutation,
- SetWorksheetHideMutation,
- SetWorksheetNameMutation,
- SetWorksheetOrderMutation,
- SetWorksheetShowCommand,
-} from '@univerjs/base-sheets';
-import {
- AppContext,
- BaseComponentProps,
- BaseMenuItem,
- BaseSelectProps,
- IDisplayMenuItem,
- IMenuItem,
- ITabRef,
- Menu,
- TabPane,
- Tabs,
-} from '@univerjs/base-ui';
-import { BooleanNumber, ICommandService, IKeyValue, IUniverInstanceService } from '@univerjs/core';
+import { InsertSheetCommand } from '@univerjs/base-sheets';
+import { ICommandService } from '@univerjs/core';
import { Button } from '@univerjs/design';
-import { IDisposable } from '@wendellhu/redi';
-import { Component, createRef } from 'react';
+import { IncreaseSingle, LeftTriangleSingle, RightTriangleSingle } from '@univerjs/icons';
+import { useDependency } from '@wendellhu/redi/react-bindings';
+import { useEffect, useState } from 'react';
-import { SheetMenuPosition } from '../../controller/menu/menu';
+import { ISheetBarService } from '../../services/sheetbar/sheetbar.service';
import styles from './index.module.less';
-import { InputEdit } from './input-edit';
-import { ISheetBarMenuItem, SheetBarMenu } from './SheetBarMenu';
-
-export interface BaseSheetBarProps extends BaseComponentProps, Omit<BaseSelectProps, 'children'> {
- children?: any[];
- index?: string;
- color?: string;
- sheetId?: string;
- style?: React.CSSProperties;
- hidden?: BooleanNumber;
- addSheet?: () => void;
- onMouseDown?: (e: React.MouseEvent) => void;
- selectSheet?: (slideItemIndex: number) => void;
- changeSheetName?: (sheetId: string, name: string) => void;
- dragEnd?: (elements: HTMLElement[]) => void;
- selected?: boolean;
-}
-
-type SheetState = {
- sheetList: BaseSheetBarProps[];
- menuList: BaseSheetBarProps[];
- sheetUl: BaseMenuItem[];
- menuItems: Array<IDisplayMenuItem<IMenuItem>>;
- showMenu: boolean;
- showManageMenu: boolean;
- menuStyle: React.CSSProperties;
- activeKey: string;
-};
+import { SheetBarMenu } from './SheetBarMenu/SheetBarMenu';
+import { SheetBarTabs } from './SheetBarTabs/SheetBarTabs';
+import { IScrollState } from './SheetBarTabs/utils/slide-tab-bar';
const SCROLL_WIDTH = 100;
-export class SheetBar extends Component<BaseSheetBarProps, SheetState> {
- static override contextType = AppContext;
-
- declare context: React.ContextType<typeof AppContext>;
-
- ref = createRef<SheetBarMenu>();
-
- sheetContainerRef = createRef<HTMLDivElement>();
-
- sheetContentRef = createRef();
- sheetBarContentRef = createRef<ITabRef>();
+export const SheetBar = () => {
+ const [leftScrollState, setLeftScrollState] = useState(false);
+ const [rightScrollState, setRightScrollState] = useState(false);
- // 先生成移动对象的副本,移动对象固定定位,达到边界的时候将副本移位
- time = 0;
+ const commandService = useDependency(ICommandService);
+ const sheetbarService = useDependency(ISheetBarService);
- target: any = null;
-
- cloneTarget: any = null;
-
- startLeft: number = 0;
-
- startClientX: number = 0;
-
- private _renderKey: number = 1;
-
- constructor(props: BaseSheetBarProps) {
- super(props);
- this.initialize(props);
- }
+ useEffect(() => {
+ const subscription = sheetbarService.scroll$.subscribe((state: IScrollState) => {
+ updateScrollButtonState(state);
+ });
- initialize(props: BaseSheetBarProps) {
- this.state = {
- sheetList: [],
- sheetUl: [],
- menuList: [],
- menuItems: [],
- showMenu: false,
- showManageMenu: false,
- menuStyle: {},
- activeKey: '',
+ return () => {
+ subscription?.unsubscribe();
};
- }
+ }, []);
- // setstate
- setValue = (value: any, fn?: () => void) => {
- this.setState((prevState) => ({ ...value }), fn);
+ const updateScrollButtonState = (state: IScrollState) => {
+ const { leftEnd, rightEnd } = state;
+ setLeftScrollState(leftEnd);
+ setRightScrollState(rightEnd);
};
- overGrid = () => {};
-
- // Right click to display menu
- contextMenu = (e: React.MouseEvent<HTMLDivElement, MouseEvent>) => {
- e.preventDefault();
- const target = e.currentTarget as HTMLDivElement;
- const worksheetId = target.dataset.id as string;
-
- // activate command
- // FIXME this.context type error
- const commandService: ICommandService = (this.context as IKeyValue).injector.get(ICommandService);
- commandService.executeCommand(SetWorksheetActivateCommand.id, { worksheetId });
+ // Complete the _addSheet, handleScrollLeft, and handleScrollRight functions
+ const addSheet = () => {
+ commandService.executeCommand(InsertSheetCommand.id);
+ setTimeout(() => {
+ sheetbarService.setAddSheet(0);
+ }, 0);
};
- // Click the button to display the menu, if it is not in the current sheet, only switch the sheet after clicking
- onContextMenuClick = (e: React.MouseEvent<HTMLDivElement, MouseEvent>) => {
- e.preventDefault();
-
- const target = e.currentTarget as HTMLDivElement;
- const worksheetId = target.dataset.id as string;
-
- const currentSheetId = this.getCurrentSheetId();
-
- if (worksheetId === currentSheetId) {
- this.showUlList(e);
- } else {
- // FIXME this.context type error
- const commandService: ICommandService = (this.context as IKeyValue).injector.get(ICommandService);
- commandService.executeCommand(SetWorksheetActivateCommand.id, { worksheetId });
- }
+ const handleScrollLeft = () => {
+ sheetbarService.setScrollX(-SCROLL_WIDTH);
};
- // 显示下拉
- showSelect = (e: React.MouseEvent<HTMLDivElement, MouseEvent>) => {
- e.stopPropagation();
- e.preventDefault();
- this.setState({
- showMenu: true,
- });
- // 点击外部隐藏子组件
- window.addEventListener('click', this.hideSelect);
+ const handleScrollRight = () => {
+ sheetbarService.setScrollX(SCROLL_WIDTH);
};
- // 隐藏下拉
- hideSelect = () => {
- this.setState({
- showMenu: false,
- });
- window.removeEventListener('click', this.hideSelect);
- };
-
- // 点击不同sheet页显示ullist
- showUlList = (e: React.MouseEvent<HTMLDivElement, MouseEvent>, cb?: () => void) => {
- new Promise<void>((resolve) => {
- const target = e.currentTarget as HTMLDivElement;
- resolve();
- }).then(() => {
- const currentTarget = (e.target as HTMLElement).closest(`.${styles.slideTabItem}`);
- if (currentTarget) {
- const currentRect = currentTarget.getBoundingClientRect();
- const left = `${currentRect.left}px`;
- const bottom = `${currentRect.height}px`;
- const top = 'auto';
- const right = 'auto';
- this.setState({
- menuStyle: {
- left,
- bottom,
- top,
- right,
- },
- });
-
- this.showSelect(e);
-
- cb && cb();
- }
- });
- };
-
- override componentDidUpdate() {}
-
- override componentDidMount() {
- this.props.getComponent?.(this);
-
- this._updateSheetBarStatus();
- this._setupStatusUpdate();
- }
-
- // Convenient for controller to control sheetBarMenu
- showMenuList(show: boolean) {
- this.ref.current?.showMenu(show);
- }
-
- getCurrentSheetId() {
- const sheetList = this.state.sheetList;
- const currentSheet = sheetList.find((sheet) => sheet.selected);
- return currentSheet?.sheetId;
- }
-
- getSheetBarItem(item: BaseSheetBarProps) {
- return (
- <div
- onMouseDown={item.onMouseDown}
- onContextMenu={this.onContextMenuClick}
- key={item.sheetId}
- data-id={item.sheetId}
- className={`${styles.slideTabItem}`}
- >
- <div className={`${styles.slideTabContent}`}>
- <div className={`${styles.slideTabDivider}`}></div>
- <div className={`${styles.slideTabTitle}`}>
- <span className={`${styles.slideTabSpan}`} style={{ padding: '2px 5px 2px 5px' }}>
- <InputEdit sheetId={item.sheetId} sheetName={item.label as string} />
- </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>
+ return (
+ <div className={styles.sheetBar}>
+ <div className={styles.sheetBarOptions}>
+ {/* Add sheet button */}
+ <Button type="text" size="small" onClick={addSheet}>
+ <IncreaseSingle />
+ </Button>
+ {/* All sheets button */}
+ <SheetBarMenu />
</div>
- );
- }
-
- /**
- * Update worksheet info.
- *
- * This method could be triggered when
- */
- private _updateSheetBarStatus(): void {
- const injector = this.context.injector!;
- const univerInstanceService = injector.get(IUniverInstanceService);
- const commandService = injector.get(ICommandService);
- const workbook = univerInstanceService.getCurrentUniverSheetInstance();
- const sheets = workbook.getSheets();
-
- const worksheetMenuItems = sheets.map((sheet, index) => ({
- label: sheet.getName(),
- index: `${index}`,
- sheetId: sheet.getSheetId(),
- hide: sheet.isSheetHidden() === BooleanNumber.TRUE,
- selected: sheet.getStatus() === BooleanNumber.TRUE,
- onClick: (e?: MouseEvent) => {
- const worksheetId = sheet.getSheetId();
- commandService.executeCommand(SetWorksheetShowCommand.id, {
- workbookId: workbook.getUnitId(),
- worksheetId,
- });
- },
- }));
-
- const sheetListItems = sheets
- .filter((sheet) => !sheet.isSheetHidden())
- .map((sheet, index) => ({
- sheetId: sheet.getSheetId(),
- label: sheet.getName(),
- index: `${index}`,
- selected: sheet.getStatus() === BooleanNumber.TRUE,
- color: (sheet.getTabColor() as string) ?? undefined,
- onMouseDown: () => {
- const worksheetId = sheet.getSheetId();
- this.setState({
- activeKey: worksheetId,
- });
-
- commandService.executeCommand(SetWorksheetActivateCommand.id, {
- workbookId: workbook.getUnitId(),
- worksheetId,
- });
- },
- }));
- const activeKey = sheetListItems.find((item) => item.selected)?.sheetId || '';
-
- // TODO: update state to the component, including active sheet index
-
- this.setState({
- menuList: worksheetMenuItems,
- sheetList: sheetListItems,
- activeKey,
- });
- }
- /**
- * When specific command executed, update the status of sheet bar.
- * @returns disposable
- */
- private _setupStatusUpdate(): IDisposable {
- const commandService = this.context.injector.get(ICommandService);
- return commandService.onCommandExecuted((commandInfo) => {
- switch (commandInfo.id) {
- case SetTabColorMutation.id:
- case SetWorksheetHideMutation.id:
- case RemoveSheetMutation.id:
- case SetWorksheetNameMutation.id:
- case InsertSheetMutation.id:
- case SetWorksheetOrderMutation.id:
- case SetWorksheetActivateMutation.id:
- this._updateSheetBarStatus();
- break;
- default:
- break;
- }
- });
- }
-
- private _addSheet() {
- const commandService = this.context.injector.get(ICommandService);
- commandService.executeCommand(InsertSheetCommand.id, {});
- }
-
- private handleScrollLeft = () => {
- if (this.sheetBarContentRef.current) {
- this.sheetBarContentRef.current.scrollContent(-SCROLL_WIDTH);
- }
- };
- private handleScrollRight = () => {
- if (this.sheetBarContentRef.current) {
- this.sheetBarContentRef.current.scrollContent(SCROLL_WIDTH);
- }
- };
-
- override render() {
- const { sheetList, menuList, sheetUl, showMenu, showManageMenu, menuStyle, activeKey } = this.state;
-
- const reRenderString = sheetList
- .map((item) => `${item?.color?.toString()}${item?.label?.toString()}`)
- .join('-');
-
- return (
- <div className={styles.sheetBar}>
- <div className={styles.sheetBarOptions}>
- {/* add sheet button */}
- <Button
- className={styles.sheetBarOptionsButton}
- onClick={() => {
- this._addSheet();
- }}
- >
- {/* <Icon.Math.AddIcon style={{ fontSize: '20px' }} /> */}
- </Button>
- {/* all sheets button */}
- <Button className={styles.sheetBarOptionsButton} onClick={() => 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}
- reRenderString={reRenderString}
- ref={this.sheetBarContentRef}
- >
- {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
- 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}
- onClick={(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>
- ))}
- </div> */}
-
- {/* context menu */}
- <Menu
- className={styles.sheetUl}
- menu={sheetUl}
- menuId={SheetMenuPosition.SHEET_BAR}
- show={showMenu}
- style={menuStyle}
- onOptionSelect={(params) => {
- const { label: commandId, value } = params;
- const commandService: ICommandService = (this.context as IKeyValue).injector.get(
- ICommandService
- );
- commandService.executeCommand(commandId as string, { value, worksheetId: activeKey });
- }}
- />
- <Menu
- menuId={SheetMenuPosition.WORKSHEET_MANAGE_MENU}
- show={showManageMenu}
- onOptionSelect={(params) => {
- // TODO: handle menu item click
- }}
- />
-
- {/* prev next scroll button */}
- <div className={`${styles.sheetBarOptions} ${styles.sheetBarScrollButton}`}>
- <Button className={styles.sheetBarOptionsButton} onClick={this.handleScrollLeft.bind(this)}>
- {/* <Icon.NextIcon rotate={90} style={{ padding: '5px' }} /> */}
- </Button>
- <Button className={styles.sheetBarOptionsButton} onClick={this.handleScrollRight.bind(this)}>
- {/* <Icon.NextIcon rotate={-90} style={{ padding: '5px' }} /> */}
- </Button>
- </div>
+ {/* All sheets tabs */}
+ <SheetBarTabs />
+
+ {/* Scroll arrows */}
+ <div className={`${styles.sheetBarOptions} ${styles.sheetBarScrollButton}`}>
+ <Button type="text" size="small" disabled={leftScrollState} onClick={handleScrollLeft}>
+ <LeftTriangleSingle />
+ </Button>
+ <Button type="text" size="small" disabled={rightScrollState} onClick={handleScrollRight}>
+ <RightTriangleSingle />
+ </Button>
</div>
- );
- }
-}
+ </div>
+ );
+};
diff --git a/packages/ui-plugin-sheets/src/View/SheetBar/SheetBarMenu.tsx b/packages/ui-plugin-sheets/src/View/SheetBar/SheetBarMenu.tsx
deleted file mode 100644
index f94f82a8b2..0000000000
--- a/packages/ui-plugin-sheets/src/View/SheetBar/SheetBarMenu.tsx
+++ /dev/null
@@ -1,95 +0,0 @@
-import { CustomLabel, joinClassNames } from '@univerjs/base-ui';
-import { Component } from 'react';
-
-import styles from './index.module.less';
-
-export interface ISheetBarMenuItem {
- label?: string;
- hide?: boolean;
- selected?: boolean;
- index?: string;
- sheetId?: string;
- onClick?: (e?: React.MouseEvent) => void;
-}
-
-export interface ISheetBarMenuProps {
- menu: ISheetBarMenuItem[];
- style?: React.CSSProperties;
- onClick?: (e?: MouseEvent) => void;
-}
-
-interface IState {
- show: boolean;
-}
-
-// TODO@wzhudev: this component could be directly placed in SheetBar component.
-
-export class SheetBarMenu extends Component<ISheetBarMenuProps, IState> {
- constructor(props: ISheetBarMenuProps) {
- super(props);
- this.initialize();
- }
-
- initialize() {
- this.state = {
- show: false,
- };
- }
-
- handleClick(e: React.MouseEvent<HTMLLIElement, MouseEvent>, item: ISheetBarMenuItem) {
- e.stopPropagation();
- const { onClick } = this.props;
- if (item.onClick) {
- item.onClick(e);
- }
- // onClick?.(e);
- this.showMenu(false);
- window.removeEventListener('click', this.hideMenu, true);
- }
-
- hideMenu = () => {
- this.showMenu(false);
- };
-
- showMenu(show: boolean) {
- this.setState({ show }, () => {
- if (this.state.show) {
- window.addEventListener('click', this.hideMenu, true);
- }
- });
- }
-
- override render() {
- const { style, menu } = this.props;
- const { show } = this.state;
-
- return (
- <ul className={styles.sheetBarMenu} style={{ ...style, display: show ? 'block' : ' none' }}>
- {menu.map((item) => (
- <li
- key={item.index}
- onClick={(e) => this.handleClick(e, item)}
- className={joinClassNames(styles.sheetBarMenuItem)}
- >
- <span className={styles.sheetBarMenuIcon}>
- <EffIcon item={item}></EffIcon>
- </span>
- <span className={styles.sheetBarMenuTitle}>
- <CustomLabel label={item.label ?? ''} />
- </span>
- </li>
- ))}
- </ul>
- );
- }
-}
-
-function EffIcon(props: { item: ISheetBarMenuItem }) {
- if (props.item.hide) {
- // return <Icon.HideIcon />;
- }
- if (props.item.selected) {
- // return <Icon.Format.CorrectIcon className={styles.sheetBarMenuSvg} />;
- }
- return <></>;
-}
diff --git a/packages/ui-plugin-sheets/src/View/SheetBar/SheetBarMenu/SheetBarMenu.tsx b/packages/ui-plugin-sheets/src/View/SheetBar/SheetBarMenu/SheetBarMenu.tsx
new file mode 100644
index 0000000000..a889940095
--- /dev/null
+++ b/packages/ui-plugin-sheets/src/View/SheetBar/SheetBarMenu/SheetBarMenu.tsx
@@ -0,0 +1,159 @@
+import {
+ InsertSheetMutation,
+ RemoveSheetMutation,
+ SetWorksheetActivateCommand,
+ SetWorksheetActivateMutation,
+ SetWorksheetHideMutation,
+ SetWorksheetNameMutation,
+ SetWorksheetOrderMutation,
+ SetWorksheetShowCommand,
+} from '@univerjs/base-sheets';
+import { Dropdown2, joinClassNames } from '@univerjs/base-ui';
+import {
+ BooleanNumber,
+ DisposableCollection,
+ ICommandInfo,
+ ICommandService,
+ IUniverInstanceService,
+} from '@univerjs/core';
+import { Button } from '@univerjs/design';
+import { CheckMarkSingle, ConvertSingle } from '@univerjs/icons';
+import { useDependency } from '@wendellhu/redi/react-bindings';
+import React, { useEffect, useState } from 'react';
+
+import { ISheetBarService } from '../../../services/sheetbar/sheetbar.service';
+import styles from './index.module.less';
+
+export interface ISheetBarMenuItem {
+ label?: string;
+ hidden?: boolean;
+ selected?: boolean;
+ index?: string;
+ sheetId?: string;
+}
+
+export interface ISheetBarMenuProps {
+ style?: React.CSSProperties;
+ onClick?: (e?: MouseEvent) => void;
+}
+
+export function SheetBarMenu(props: ISheetBarMenuProps) {
+ const { style } = props;
+ const [menu, setMenu] = useState<ISheetBarMenuItem[]>([]);
+ const [visible, setVisible] = useState(false);
+
+ const univerInstanceService = useDependency(IUniverInstanceService);
+ const commandService = useDependency(ICommandService);
+ const sheetBarService = useDependency(ISheetBarService);
+ const workbook = univerInstanceService.getCurrentUniverSheetInstance();
+
+ const handleClick = (item: ISheetBarMenuItem) => {
+ const { sheetId } = item;
+ if (!sheetId) return;
+
+ if (item.hidden) {
+ commandService.executeCommand(SetWorksheetShowCommand.id, {
+ value: sheetId,
+ });
+ } else if (!item.selected) {
+ commandService.executeCommand(SetWorksheetActivateCommand.id, {
+ workbookId: workbook.getUnitId(),
+ worksheetId: sheetId,
+ });
+ }
+
+ setVisible(false);
+ };
+
+ useEffect(() => {
+ statusInit();
+
+ const _disposables = new DisposableCollection();
+
+ _disposables.add(setupStatusUpdate());
+ _disposables.add(
+ sheetBarService.registerSheetBarMenuHandler({
+ handleSheetBarMenu,
+ })
+ );
+
+ return () => {
+ // Clean up disposable when the component unmounts
+ _disposables.dispose();
+ };
+ }, []);
+
+ const setupStatusUpdate = () =>
+ commandService.onCommandExecuted((commandInfo: ICommandInfo<object>) => {
+ switch (commandInfo.id) {
+ case SetWorksheetHideMutation.id:
+ case RemoveSheetMutation.id:
+ case SetWorksheetNameMutation.id:
+ case InsertSheetMutation.id:
+ case SetWorksheetOrderMutation.id:
+ case SetWorksheetActivateMutation.id:
+ statusInit();
+ break;
+ default:
+ break;
+ }
+ });
+
+ const statusInit = () => {
+ const sheets = workbook.getSheets();
+ const worksheetMenuItems = sheets.map((sheet, index) => ({
+ label: sheet.getName(),
+ index: `${index}`,
+ sheetId: sheet.getSheetId(),
+ hidden: sheet.isSheetHidden() === BooleanNumber.TRUE,
+ selected: sheet.getStatus() === BooleanNumber.TRUE,
+ }));
+
+ setMenu(worksheetMenuItems);
+ };
+
+ function handleSheetBarMenu() {
+ setVisible(true);
+ }
+
+ const onVisibleChange = (visible: boolean) => {
+ setVisible(visible);
+ };
+
+ return (
+ <Dropdown2
+ placement="topLeft"
+ trigger={['click']}
+ overlay={
+ <ul className={styles.sheetBarMenu} style={{ ...style }}>
+ {menu.map((item) => (
+ <li
+ key={item.index}
+ onClick={() => handleClick(item)}
+ className={joinClassNames(styles.sheetBarMenuItem)}
+ >
+ <span className={styles.sheetBarMenuItemIcon}>
+ {item.selected ? <CheckMarkSingle /> : ''}
+ </span>
+ <span
+ className={
+ item.hidden
+ ? `${styles.sheetBarMenuItemTitle} ${styles.sheetBarMenuItemHide}`
+ : styles.sheetBarMenuItemTitle
+ }
+ >
+ {item.label}
+ </span>
+ </li>
+ ))}
+ </ul>
+ }
+ visible={visible}
+ onVisibleChange={onVisibleChange}
+ >
+ <Button type="text" size="small">
+ <ConvertSingle />
+ </Button>
+ </Dropdown2>
+ );
+}
diff --git a/packages/ui-plugin-sheets/src/View/SheetBar/SheetBarMenu/index.module.less b/packages/ui-plugin-sheets/src/View/SheetBar/SheetBarMenu/index.module.less
new file mode 100644
index 0000000000..e0d2344f0d
--- /dev/null
+++ b/packages/ui-plugin-sheets/src/View/SheetBar/SheetBarMenu/index.module.less
@@ -0,0 +1,54 @@
+@item-padding-left:36px;
+@sheet-bar-menu-min-width:128px;
+
+.sheet-bar-menu {
+ min-width: @sheet-bar-menu-min-width;
+ padding: var(--padding-sm);
+ font-size: var(--font-size-base);
+ background-color: rgb(var(--bg-color-secondary));
+ border: 1px solid rgb(var(--border-color));
+ border-radius: var(--border-radius-lg);
+ box-shadow: var(--box-shadow-lg);
+ box-sizing: border-box;
+ display: grid;
+ align-items: center;
+ gap: var(--margin-xxs);
+
+ li {
+ list-style: none;
+ }
+
+ &-item {
+ position: relative;
+ text-align: left;
+
+ position: relative;
+ padding: var(--padding-xs) 0 var(--padding-xs) @item-padding-left;
+ color: rgb(var(--text-color));
+ border-radius: var(--border-radius-base);
+ box-sizing: border-box;
+ cursor: pointer;
+ transition: background .2s;
+
+ &:hover {
+ background-color: rgb(var(--bg-color-hover));
+ }
+
+
+ &-icon {
+ position: absolute;
+ left: var(--padding-xs);
+ top: 50%;
+ transform: translateY(-50%);
+ }
+
+ &-title {
+ vertical-align: middle;
+ padding: var(--padding-xs) var(--padding-xs) var(--padding-xs) 0;
+ }
+
+ &-hide {
+ color: rgb(var(--text-color-secondary));
+ }
+ }
+}
\ No newline at end of file
diff --git a/packages/ui-plugin-sheets/src/View/SheetBar/SheetBarTabs/SheetBarItem.tsx b/packages/ui-plugin-sheets/src/View/SheetBar/SheetBarTabs/SheetBarItem.tsx
new file mode 100644
index 0000000000..7f9a3443ab
--- /dev/null
+++ b/packages/ui-plugin-sheets/src/View/SheetBar/SheetBarTabs/SheetBarItem.tsx
@@ -0,0 +1,83 @@
+import { TinyColor } from '@ctrl/tinycolor';
+import { Dropdown2, Menu2 } from '@univerjs/base-ui';
+import { BooleanNumber, ICommandService, ThemeService } from '@univerjs/core';
+import { useDependency } from '@wendellhu/redi/react-bindings';
+import React, { useEffect, useState } from 'react';
+
+import { SheetMenuPosition } from '../../../controller/menu/menu';
+import styles from './index.module.less';
+
+export interface IBaseSheetBarProps {
+ label?: string;
+ children?: any[];
+ index?: number;
+ color?: string;
+ sheetId?: string;
+ style?: React.CSSProperties;
+ hidden?: BooleanNumber;
+ selected?: boolean;
+}
+
+export function SheetBarItem(props: IBaseSheetBarProps) {
+ const { sheetId, label, color, selected } = props;
+
+ const [visible, setVisible] = useState(false);
+ const [currentSelected, setCurrentSelected] = useState(selected);
+
+ const commandService = useDependency(ICommandService);
+ const themeService = useDependency(ThemeService);
+
+ useEffect(() => {
+ // TODO: update too many times?
+ setCurrentSelected(selected);
+ }, [selected]);
+
+ const onVisibleChange = (visible: boolean) => {
+ setVisible(visible);
+ };
+
+ const getTextColor = (color: string) => {
+ const theme = themeService.getCurrentTheme();
+ const darkTextColor = theme.textColor;
+ const lightTextColor = theme.colorWhite;
+ return new TinyColor(color).isDark() ? lightTextColor : darkTextColor;
+ };
+
+ return (
+ <Dropdown2
+ visible={visible}
+ trigger={['contextMenu']}
+ overlay={
+ <Menu2
+ menuType={SheetMenuPosition.SHEET_BAR}
+ onOptionSelect={(params) => {
+ const { label: commandId, value } = params;
+ commandService.executeCommand(commandId as string, { value, worksheetId: sheetId });
+ setVisible(false);
+ }}
+ />
+ }
+ onVisibleChange={onVisibleChange}
+ >
+ <div
+ key={sheetId}
+ data-id={sheetId}
+ className={currentSelected ? `${styles.slideTabActive} ${styles.slideTabItem}` : styles.slideTabItem}
+ >
+ <div
+ className={styles.slideTabContent}
+ style={{
+ backgroundColor: !currentSelected && color ? color : '',
+ color: !currentSelected && color ? getTextColor(color) : '',
+ boxShadow: currentSelected && color ? `inset 0px -2px 0px 0px ${color}` : '',
+ }}
+ >
+ <span className={styles.slideTabSpan}>{label}</span>
+ </div>
+ <div className={styles.slideTabFooter}>
+ <div className={styles.slideTabActiveBar} style={color ? { background: color } : {}}></div>
+ </div>
+ </div>
+ </Dropdown2>
+ );
+}
diff --git a/packages/ui-plugin-sheets/src/View/SheetBar/SheetBarTabs/SheetBarTabs.tsx b/packages/ui-plugin-sheets/src/View/SheetBar/SheetBarTabs/SheetBarTabs.tsx
new file mode 100644
index 0000000000..5d694cb8a4
--- /dev/null
+++ b/packages/ui-plugin-sheets/src/View/SheetBar/SheetBarTabs/SheetBarTabs.tsx
@@ -0,0 +1,144 @@
+import {
+ InsertSheetMutation,
+ RemoveSheetMutation,
+ SetTabColorMutation,
+ SetWorksheetActivateCommand,
+ SetWorksheetActivateMutation,
+ SetWorksheetHideMutation,
+ SetWorksheetNameCommand,
+ SetWorksheetNameMutation,
+ SetWorksheetOrderCommand,
+ SetWorksheetOrderMutation,
+} from '@univerjs/base-sheets';
+import { BooleanNumber, ICommandInfo, ICommandService, IUniverInstanceService } from '@univerjs/core';
+import { useDependency } from '@wendellhu/redi/react-bindings';
+import React, { useEffect, useState } from 'react';
+
+import { ISheetBarService } from '../../../services/sheetbar/sheetbar.service';
+import sheetBarStyles from '../index.module.less';
+import styles from './index.module.less';
+import { IBaseSheetBarProps, SheetBarItem } from './SheetBarItem';
+import { IScrollState, SlideTabBar } from './utils/slide-tab-bar';
+
+export interface ISheetBarTabsProps {}
+
+export function SheetBarTabs() {
+ const [sheetList, setSheetList] = useState<IBaseSheetBarProps[]>([]);
+ const [activeKey, setActiveKey] = useState<string>('');
+ const [subscribe, setSubscribe] = useState(false);
+ const univerInstanceService = useDependency(IUniverInstanceService);
+ const commandService = useDependency(ICommandService);
+ const sheetbarService = useDependency(ISheetBarService);
+ const workbook = univerInstanceService.getCurrentUniverSheetInstance();
+
+ let slideTabBar: SlideTabBar;
+
+ useEffect(() => {
+ statusInit();
+
+ const disposable = setupStatusUpdate();
+
+ return () => {
+ disposable.dispose();
+ };
+ }, []);
+
+ useEffect(() => {
+ if (sheetList.length > 0) {
+ setupSlideTabBarUpdate();
+ }
+ }, [sheetList]);
+
+ const setupSlideTabBarUpdate = () => {
+ const currentIndex = sheetList.findIndex((item) => item.selected);
+
+ // TODO@Dushusir: There may not be initialization each time
+ slideTabBar = new SlideTabBar({
+ slideTabBarClassName: styles.slideTabBar,
+ slideTabBarItemActiveClassName: styles.slideTabActive,
+ slideTabBarItemClassName: styles.slideTabItem,
+ slideTabBarSpanEditClassName: styles.slideTabSpanEdit,
+ slideTabBarItemAutoSort: true,
+ slideTabRootClassName: sheetBarStyles.sheetBar,
+ currentIndex,
+ onChangeName: (worksheetId: string, worksheetName: string) => {
+ commandService.executeCommand(SetWorksheetNameCommand.id, {
+ worksheetId,
+ name: worksheetName,
+ });
+ },
+ onSlideEnd: (event: Event, order: number) => {
+ commandService.executeCommand(SetWorksheetOrderCommand.id, { order });
+ },
+ onChangeTab: (event: Event, worksheetId: string) => {
+ commandService.executeCommand(SetWorksheetActivateCommand.id, { worksheetId });
+ },
+ onScroll: (state: IScrollState) => {
+ sheetbarService.setScroll(state);
+ },
+ });
+
+ // TODO@Dushusir: Can you initialize it once without using the `subscribe` label?
+ if (!subscribe) {
+ sheetbarService.scrollX$.subscribe((x: number) => {
+ // update scrollX
+ slideTabBar.setScroll(x);
+ });
+
+ sheetbarService.renameId$.subscribe((renameId: string) => {
+ const index = sheetList.findIndex((item) => item.sheetId === renameId);
+ slideTabBar.getSlideTabItems()[index].editor();
+ });
+
+ sheetbarService.addSheet$.subscribe((addSheet: number) => {
+ slideTabBar.getScrollbar().scrollRight();
+ });
+
+ setSubscribe(true);
+ }
+ };
+
+ const setupStatusUpdate = () =>
+ commandService.onCommandExecuted((commandInfo: ICommandInfo<object>) => {
+ switch (commandInfo.id) {
+ case SetTabColorMutation.id:
+ case SetWorksheetHideMutation.id:
+ case RemoveSheetMutation.id:
+ case SetWorksheetNameMutation.id:
+ case InsertSheetMutation.id:
+ case SetWorksheetOrderMutation.id:
+ case SetWorksheetActivateMutation.id:
+ statusInit();
+ break;
+ default:
+ break;
+ }
+ });
+
+ const statusInit = () => {
+ const currentWorksheetId = workbook.getActiveSheet().getSheetId();
+ setActiveKey(currentWorksheetId);
+
+ const sheets = workbook.getSheets();
+ const sheetListItems = sheets
+ .filter((sheet) => !sheet.isSheetHidden())
+ .map((sheet, index) => ({
+ sheetId: sheet.getSheetId(),
+ label: sheet.getName(),
+ index,
+ selected: sheet.getStatus() === BooleanNumber.TRUE,
+ color: sheet.getTabColor() ?? undefined,
+ }));
+ setSheetList(sheetListItems);
+ };
+
+ return (
+ <div className={styles.slideTabBarContainer}>
+ <div className={styles.slideTabBar}>
+ {sheetList.map((item) => (
+ <SheetBarItem {...item} key={item.sheetId} selected={activeKey === item.sheetId} />
+ ))}
+ </div>
+ </div>
+ );
+}
diff --git a/packages/ui-plugin-sheets/src/View/SheetBar/SheetBarTabs/index.module.less b/packages/ui-plugin-sheets/src/View/SheetBar/SheetBarTabs/index.module.less
new file mode 100644
index 0000000000..e7d3fff04c
--- /dev/null
+++ b/packages/ui-plugin-sheets/src/View/SheetBar/SheetBarTabs/index.module.less
@@ -0,0 +1,87 @@
+@right-bar-width: 700px;
+
+.slide-tab-bar-container {
+ overflow: hidden;
+ max-width: calc(100% - @right-bar-width);
+
+ .slide-tab-bar {
+ user-select: none;
+ width: 100%;
+ display: flex;
+ flex-direction: row;
+ align-items: center;
+ overflow: hidden;
+ }
+}
+
+/**
+Tab Item, Put outside to be compatible with drag styles
+*/
+.slide-tab-item {
+ user-select: none;
+ display: flex;
+ flex-direction: column;
+ justify-content: center;
+ cursor: pointer;
+ margin: 0 var(--margin-xxs);
+
+ /**
+ Content area
+ */
+ .slide-tab-content {
+ display: flex;
+ flex-direction: row;
+ align-items: center;
+ flex-grow: 1;
+ box-sizing: border-box;
+ border-radius: var(--border-radius-base);
+ font-size: var(--font-size-sm);
+ // box-shadow: inset 0px -2px 0px 0px red;
+
+ .slide-tab-span {
+ white-space: nowrap;
+ box-sizing: border-box;
+ padding: var(--padding-xs) var(--padding-base);
+ border: 2px solid transparent;
+ border-radius: var(--border-radius-base);
+
+
+ &-edit {
+ outline: none;
+ cursor: text;
+ border-color: rgb(var(--primary-color));
+
+ &::selection{
+ background-color: rgb(var(--primary-color));
+ color: rgb(var(--color-white));
+ }
+ }
+
+ }
+
+
+ }
+
+ /**
+ Bottom area
+ */
+ // .slide-tab-footer {
+ // height: auto;
+ // width: 100%;
+ // flex-grow: 0;
+
+ // .slide-tab-active-bar {
+ // height: 2px;
+ // width: 100%;
+ // }
+ // }
+
+}
+
+.slide-tab-active {
+ .slide-tab-content {
+ color: rgb(var(--primary-color));
+ background-color: rgb(var(--bg-color-secondary));
+ font-weight: 700;
+ }
+}
\ No newline at end of file
diff --git a/packages/ui-plugin-sheets/src/View/SheetBar/SheetBarTabs/utils/animate.ts b/packages/ui-plugin-sheets/src/View/SheetBar/SheetBarTabs/utils/animate.ts
new file mode 100644
index 0000000000..4e8528b1dd
--- /dev/null
+++ b/packages/ui-plugin-sheets/src/View/SheetBar/SheetBarTabs/utils/animate.ts
@@ -0,0 +1,154 @@
+const Tween: Record<string, Function> = {
+ easeOutStrong(t: number, b: number, c: number, d: number): number {
+ return -c * ((t = t / d - 1) * t * t * t - 1) + b;
+ },
+ backOut(t: number, b: number, c: number, d: number, s: number): number {
+ if (typeof s === 'undefined') {
+ s = 0.7;
+ }
+ return c * ((t = t / d - 1) * t * ((s + 1) * t + s) + 1) + b;
+ },
+};
+
+export interface AnimateConfig {
+ loop: boolean;
+ begin: number;
+ end: number;
+ duration: number;
+ delay: number;
+ type: string;
+ receive: (v: number) => void;
+ success: (v: number) => void;
+ cancel: (v: number) => void;
+ complete: (v: number) => void;
+}
+
+const CONFIG: AnimateConfig = {
+ loop: false,
+ begin: 0,
+ end: 0,
+ duration: 300,
+ delay: 0,
+ type: 'easeOutStrong',
+ receive(v) {
+ /*noop*/
+ },
+ success(v) {
+ /*noop*/
+ },
+ cancel(v) {
+ /*noop*/
+ },
+ complete(v) {
+ /*noop*/
+ },
+};
+
+export enum AnimateStatus {
+ Request,
+ Cancel,
+}
+
+export class Animate {
+ protected _config: AnimateConfig;
+
+ protected _status: AnimateStatus = AnimateStatus.Request;
+
+ protected _start: number = 0;
+
+ protected _handle: number = 0;
+
+ protected _delayHandle: number | null = null;
+
+ constructor(config: Partial<AnimateConfig>) {
+ this._config = {
+ ...CONFIG,
+ ...config,
+ };
+ if (this._config.loop) {
+ this._config.complete = () => {
+ /*noop*/
+ };
+ this._config.success = () => {
+ this.request();
+ };
+ }
+ }
+
+ static success(...animates: Animate[]): Promise<void> {
+ let successNumber = 0;
+ return new Promise<void>((resolve) => {
+ for (let i = 0; i < animates.length; i++) {
+ const animate = animates[i];
+ const config = animate._config;
+ const success = config.success;
+ const loop = config.loop;
+ if (loop) {
+ continue;
+ }
+ config.success = (v) => {
+ successNumber++;
+ if (success) {
+ success.call(animate, v);
+ }
+ if (successNumber === animates.length) {
+ resolve();
+ }
+ };
+ }
+ });
+ }
+
+ request(): void {
+ if (this._config.delay === 0) {
+ this._status = AnimateStatus.Request;
+ this._start = Date.now();
+ this._fakeHandle();
+ } else {
+ this._delayHandle && window.clearTimeout(this._delayHandle);
+ this._delayHandle = window.setTimeout(() => {
+ this._status = AnimateStatus.Request;
+ this._start = Date.now();
+ this._fakeHandle();
+ }, this._config.delay);
+ }
+ }
+
+ cancel(): void {
+ this._status = AnimateStatus.Cancel;
+ this._delayHandle && window.clearTimeout(this._delayHandle);
+ cancelAnimationFrame(this._handle);
+ }
+
+ protected _fakeHandle(): void {
+ let times = Date.now() - this._start;
+ times = times >= this._config.duration ? this._config.duration : times;
+
+ const val = Tween[this._config.type](
+ times,
+ this._config.begin,
+ this._config.end - this._config.begin,
+ this._config.duration,
+ 0.7
+ );
+ const fix = val.toFixed(2);
+
+ this._config.receive(fix);
+
+ if (this._status === AnimateStatus.Cancel) {
+ this._config.cancel(fix);
+ this._config.complete(fix);
+ return;
+ }
+
+ if (times === this._config.duration) {
+ this._config.success(fix);
+ this._config.complete(fix);
+ return;
+ }
+
+ this._handle = requestAnimationFrame(() => {
+ this._fakeHandle();
+ });
+ }
+}
diff --git a/packages/ui-plugin-sheets/src/View/SheetBar/SheetBarTabs/utils/slide-tab-bar.ts b/packages/ui-plugin-sheets/src/View/SheetBar/SheetBarTabs/utils/slide-tab-bar.ts
new file mode 100644
index 0000000000..80b06f82f6
--- /dev/null
+++ b/packages/ui-plugin-sheets/src/View/SheetBar/SheetBarTabs/utils/slide-tab-bar.ts
@@ -0,0 +1,824 @@
+import { Animate } from './animate';
+
+export interface IScrollState {
+ leftEnd: boolean;
+ rightEnd: boolean;
+}
+export interface SlideTabBarConfig {
+ slideTabBarClassName: string;
+ slideTabBarItemActiveClassName: string;
+ slideTabBarItemClassName: string;
+ slideTabBarSpanEditClassName: string;
+ slideTabRootClassName: string;
+ activeClassNameAutoController: boolean;
+ slideTabBarItemAutoSort: boolean;
+ currentIndex: number;
+ onSlideEnd: (event: MouseEvent, compareIndex: number) => void;
+ onChangeName: (id: string, name: string) => void;
+ onChangeTab: (event: FocusEvent, id: string) => void;
+ onScroll: (state: IScrollState) => void;
+}
+
+export interface SlideTabItemAnimate {
+ translateX: (x: number) => void;
+ cancel: () => void;
+}
+
+export class SlideTabItem {
+ _slideTabItem: HTMLElement;
+
+ _animate: Animate | null;
+
+ _midline: number = 0;
+
+ _translateX: number;
+
+ _scrollbar: SlideScrollbar;
+
+ _slideTabBar: SlideTabBar;
+
+ _editMode: boolean;
+
+ _placeholder: HTMLElement | null;
+
+ constructor(slideTabItem: HTMLElement, slideTabBar: SlideTabBar) {
+ this._slideTabItem = slideTabItem;
+ this._animate = null;
+ this._translateX = 0;
+ this._editMode = false;
+ this._slideTabBar = slideTabBar;
+ this._placeholder = null;
+ this._scrollbar = slideTabBar.getScrollbar();
+ this.update();
+ }
+
+ static midline(item: SlideTabItem) {
+ return item.getBoundingRect().x + item.getBoundingRect().width / 2;
+ }
+
+ static make(nodeList: NodeList, slideTabBar: SlideTabBar): SlideTabItem[] {
+ const result: SlideTabItem[] = [];
+ nodeList.forEach((item) => result.push(new SlideTabItem(item as HTMLElement, slideTabBar)));
+ return result;
+ }
+
+ getSlideTabItem(): HTMLElement {
+ return this._slideTabItem;
+ }
+
+ isEditMode(): boolean {
+ return this._editMode;
+ }
+
+ classList(): DOMTokenList {
+ return this._slideTabItem.classList;
+ }
+
+ primeval(): HTMLElement {
+ return this._slideTabItem;
+ }
+
+ translateX(x: number) {
+ this._translateX = x;
+ this._slideTabItem.style.transform = `translateX(${x}px)`;
+ return this.getTranslateXDirection();
+ }
+
+ editor(callback?: (event: FocusEvent) => void): void {
+ let compositionFlag = true;
+ if (this._editMode === false) {
+ const input = this.primeval().querySelector('span');
+
+ const blurAction = (focusEvent: FocusEvent) => {
+ if (this.emptyCheck()) return;
+
+ this._editMode = false;
+
+ if (input) {
+ input.removeAttribute('contentEditable');
+ input.removeEventListener('blur', blurAction);
+ input.removeEventListener('compositionstart', compositionstartAction);
+ input.removeEventListener('compositionend', compositionendAction);
+ input.removeEventListener('input', inputAction);
+ input.removeEventListener('keydown', keydownAction);
+ input.classList.remove(this._slideTabBar.getConfig().slideTabBarSpanEditClassName);
+ }
+
+ this._slideTabBar.updateItems();
+ if (this._slideTabBar.getConfig().onChangeName) {
+ const text = input?.innerText || '';
+ const id = this.getId();
+ this._slideTabBar.getConfig().onChangeName(id, text);
+ }
+
+ if (callback) {
+ callback(focusEvent);
+ }
+ };
+
+ let keydownAction = (e: KeyboardEvent) => {
+ if (!input) return;
+ e.stopPropagation();
+
+ if (e.key === 'Enter') {
+ input.blur();
+ }
+ };
+
+ const compositionstartAction = (e: CompositionEvent) => {
+ compositionFlag = false;
+ };
+
+ const compositionendAction = (e: CompositionEvent) => {
+ compositionFlag = true;
+ };
+
+ const inputAction = (e: Event) => {
+ if (!input) return;
+ const maxLength = 50;
+
+ setTimeout(() => {
+ if (compositionFlag) {
+ const text = input.innerText;
+ if (text.length > maxLength) {
+ input.innerText = text.substring(0, maxLength);
+ SlideTabBar.keepLastIndex(input);
+ }
+ }
+ }, 0);
+ };
+
+ if (input) {
+ input.setAttribute('contentEditable', 'true');
+ input.addEventListener('blur', blurAction);
+ input.addEventListener('compositionstart', compositionstartAction);
+ input.addEventListener('compositionend', compositionendAction);
+ input.addEventListener('input', inputAction);
+ input.addEventListener('keydown', keydownAction);
+ input.classList.add(this._slideTabBar.getConfig().slideTabBarSpanEditClassName);
+ this._editMode = true;
+ SlideTabBar.keepSelectAll(input);
+ }
+ }
+ }
+
+ emptyCheck() {
+ const input = this.primeval().querySelector('span');
+ if (!input) return false;
+ const text = input.innerText;
+ if (text.trim() === '') {
+ // TODO@Dushusir: i18n and dialog service
+ alert('The sheet name cannot be empty.');
+ return true;
+ }
+ return false;
+ }
+
+ animate(): SlideTabItemAnimate {
+ return {
+ translateX: (x: number) => {
+ if (this._translateX !== x) {
+ if (this._animate) {
+ this._animate.cancel();
+ this._animate = null;
+ }
+ this._animate = new Animate({
+ begin: this._translateX,
+ end: x,
+ receive: (val: number) => {
+ this._slideTabItem.style.transform = `translateX(${val}px)`;
+ },
+ });
+ this._translateX = x;
+ this._animate.request();
+ }
+ },
+ cancel: () => {
+ if (this._animate) {
+ this._animate.cancel();
+ this._animate = null;
+ }
+ },
+ };
+ }
+
+ after(other: SlideTabItem) {
+ this._slideTabItem.after(other._slideTabItem || other);
+ }
+
+ update() {
+ this._midline = SlideTabItem.midline(this);
+ }
+
+ disableFixed() {
+ if (this._placeholder) {
+ const primeval = this._slideTabBar.primeval();
+
+ this._slideTabItem.style.removeProperty('position');
+ this._slideTabItem.style.removeProperty('left');
+ this._slideTabItem.style.removeProperty('top');
+ this._slideTabItem.style.removeProperty('width');
+ this._slideTabItem.style.removeProperty('height');
+ this._slideTabItem.style.removeProperty('box-shadow');
+ this._slideTabItem.style.removeProperty('background');
+
+ this._placeholder.after(this._slideTabItem);
+ primeval.removeChild(this._placeholder);
+ this._placeholder = null;
+ }
+ }
+
+ enableFixed() {
+ const placeholder = document.createElement('div');
+ const boundingRect = this.getBoundingRect();
+
+ this._placeholder = placeholder;
+ this._placeholder.style.width = `${boundingRect.width}px`;
+ this._placeholder.style.height = `${boundingRect.height}px`;
+ this._placeholder.style.flexShrink = '0';
+
+ this._slideTabItem.style.left = `${boundingRect.x - this.getScrollbar().getScrollX()}px`;
+ this._slideTabItem.style.top = `${boundingRect.y}px`;
+ this._slideTabItem.style.width = `${boundingRect.width}px`;
+ this._slideTabItem.style.height = `${boundingRect.height}px`;
+ this._slideTabItem.style.background = getComputedStyle(this._slideTabItem).background;
+ this._slideTabItem.style.boxShadow = '0px 0px 1px 1px rgba(82,82,82,0.1)';
+ this._slideTabItem.style.position = 'fixed';
+
+ this._slideTabItem.after(placeholder);
+ document.body.appendChild(this._slideTabItem);
+ }
+
+ addEventListener<K extends keyof HTMLElementEventMap>(
+ type: K,
+ action: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any,
+ options?: boolean | AddEventListenerOptions
+ ) {
+ this._slideTabItem.addEventListener(type, action, options);
+ }
+
+ removeEventListener<K extends keyof HTMLElementEventMap>(
+ type: K,
+ action: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any,
+ options?: boolean | AddEventListenerOptions
+ ) {
+ this._slideTabItem.removeEventListener(type, action, options);
+ }
+
+ getScrollbar() {
+ return this._scrollbar;
+ }
+
+ getMidLine() {
+ return this._midline;
+ }
+
+ getBoundingRect() {
+ const boundingClientRect = this._slideTabItem.getBoundingClientRect();
+ boundingClientRect.x += this._scrollbar.getScrollX();
+ return boundingClientRect;
+ }
+
+ getWidth() {
+ return this.getBoundingRect().width;
+ }
+
+ getTranslateXDirection() {
+ const midline = SlideTabItem.midline(this);
+ return midline > this._midline ? 1 : midline < this._midline ? -1 : 0;
+ }
+
+ equals(other: SlideTabItem | null) {
+ return other && other._slideTabItem === this._slideTabItem;
+ }
+
+ getId(): string {
+ return this._slideTabItem.dataset.id || '';
+ }
+}
+
+export class SlideScrollbar {
+ protected _slideTabBar: SlideTabBar;
+
+ protected _scrollX: number;
+
+ constructor(slideTabBar: SlideTabBar) {
+ const primeval = slideTabBar.primeval();
+ this._scrollX = primeval.scrollLeft;
+ this._slideTabBar = slideTabBar;
+ }
+
+ scrollX(x: number): boolean {
+ const preX = this._scrollX;
+ const primeval = this._slideTabBar.primeval();
+ primeval.scrollLeft = x;
+ this._scrollX = primeval.scrollLeft;
+
+ return preX === this._scrollX;
+ }
+
+ scrollRight(): boolean {
+ const preX = this._scrollX;
+ const primeval = this._slideTabBar.primeval();
+ primeval.scrollLeft = primeval.scrollWidth;
+ this._scrollX = primeval.scrollLeft;
+
+ return preX === this._scrollX;
+ }
+
+ getScrollX(): number {
+ return this._scrollX;
+ }
+}
+
+export class SlideTabBar {
+ /** Time in milliseconds to wait to raise long press events if button is still pressed */
+ static LongPressDelay = 500; // in milliseconds
+
+ /** Time in milliseconds with two consecutive clicks will be considered as a double click */
+ static DoubleClickDelay = 300; // in milliseconds
+
+ protected _activeTabItemIndex: number | null;
+
+ protected _slideTabBar: HTMLElement;
+
+ protected _slideTabItems: SlideTabItem[];
+
+ protected _config: SlideTabBarConfig;
+
+ protected _downActionX: number;
+
+ protected _moveActionX: number;
+
+ protected _compareIndex: number | null;
+
+ protected _activeTabItem: SlideTabItem | null;
+
+ protected _moveAction: (e: MouseEvent) => void;
+
+ protected _upAction: (e: MouseEvent) => void;
+
+ protected _downAction: (e: MouseEvent) => void;
+
+ protected _wheelAction: (e: WheelEvent) => void;
+
+ protected _scrollIncremental: number = 0;
+
+ protected _compareDirection: number = 0;
+
+ protected _autoScrollTime: number | null = null;
+
+ protected _slideScrollbar: SlideScrollbar;
+
+ protected _longPressTimer: number | null = null;
+
+ /**
+ * Whether to reach the left boundary
+ */
+ protected _isLeftEnd: boolean = false;
+
+ /**
+ * Whether to reach the right boundary
+ */
+ protected _isRightEnd: boolean = false;
+
+ /**
+ * left border line
+ */
+ protected _leftBoundingLine: number = 0;
+
+ /**
+ * right border line
+ */
+ protected _rightBoundingLine: number = 0;
+
+ /**
+ * The distance required to move to the left border
+ */
+ protected _leftMoveX: number = 0;
+
+ /**
+ * The distance required to move to the right border
+ */
+ protected _rightMoveX: number = 0;
+
+ constructor(config: Partial<SlideTabBarConfig>) {
+ if (config.slideTabRootClassName == null) {
+ throw new Error('not found slide-tab-bar root element');
+ }
+
+ const slideTabBar = document.querySelector(
+ `.${config.slideTabRootClassName} .${config.slideTabBarClassName ?? 'slide-tab-bar'}`
+ );
+ const slideTabItems = document.querySelectorAll(
+ `.${config.slideTabRootClassName} .${config.slideTabBarItemClassName ?? 'slide-tab-item'}`
+ );
+
+ if (slideTabBar == null) {
+ throw new Error('not found slide-tab-bar');
+ }
+
+ this._config = config as SlideTabBarConfig;
+ this._downActionX = 0;
+ this._moveActionX = 0;
+ this._compareDirection = 0;
+ this._compareIndex = 0;
+ this._slideTabBar = slideTabBar as HTMLElement;
+ this._slideScrollbar = new SlideScrollbar(this);
+ this._slideTabItems = SlideTabItem.make(slideTabItems, this);
+ this._activeTabItemIndex = this._config.currentIndex;
+ this._activeTabItem = this._slideTabItems[this._activeTabItemIndex];
+
+ let lastPageX = 0;
+ let lastPageY = 0;
+ let lastTime = 0;
+ this._downAction = (downEvent: MouseEvent) => {
+ const slideItemId = (downEvent.target as HTMLElement)
+ ?.closest(`.${config.slideTabBarItemClassName}`)
+ ?.getAttribute('data-id');
+ const slideItemIndex = this._slideTabItems.findIndex((item) => item.getId() === slideItemId);
+
+ if (slideItemId == null || slideItemIndex === -1) return;
+
+ // switch tab
+ if (this._activeTabItemIndex !== slideItemIndex) {
+ this._activeTabItem?.removeEventListener('pointermove', this._moveAction);
+ this._activeTabItem?.removeEventListener('pointerup', this._upAction);
+ this.destroy();
+ this._config.onChangeTab(downEvent, slideItemId);
+ return;
+ }
+
+ this._compareIndex = slideItemIndex;
+ this._downActionX = downEvent.pageX;
+ this._moveActionX = 0;
+ this._scrollIncremental = 0;
+ this._activeTabItem = this._slideTabItems[slideItemIndex];
+ if (!this._activeTabItem) {
+ console.error('Not found active slide-tab-item in sheet bar');
+ return;
+ }
+
+ const activeSlideItemElement = this._activeTabItem.getSlideTabItem();
+ activeSlideItemElement?.setPointerCapture((downEvent as PointerEvent).pointerId);
+ this._activeTabItem?.addEventListener('pointerup', this._upAction);
+
+ const { x, width } = this._activeTabItem.getBoundingRect();
+ const { x: containerX, width: containerWidth } = this.getBoundingRect();
+ const scrollX = this._slideScrollbar.getScrollX();
+ this._leftBoundingLine = this._downActionX - (x - scrollX);
+ const adjustment = 24;
+ this._rightBoundingLine = x - scrollX + width - this._downActionX - adjustment;
+ this._leftMoveX = x - containerX - scrollX;
+ this._rightMoveX = containerX + containerWidth - (x + width) + scrollX + adjustment;
+
+ if (downEvent.button === 2 || this._hasEditItem()) {
+ return;
+ }
+
+ const { pageX, pageY } = downEvent;
+ const current = Date.now();
+ const diffTime = current - lastTime <= SlideTabBar.DoubleClickDelay;
+ const diffPageX = Math.abs(pageX - lastPageX) < 10;
+ const diffPageY = Math.abs(pageY - lastPageY) < 10;
+
+ // double click
+ if (diffTime && diffPageX && diffPageY) {
+ if (this._activeTabItem) {
+ // user editor
+ this._activeTabItem.editor();
+ }
+ }
+
+ lastPageX = pageX;
+ lastPageY = pageY;
+ lastTime = current;
+
+ // Set a timer to delay dragging for 300 milliseconds
+ this._longPressTimer = window.setTimeout(() => {
+ if (this._config.activeClassNameAutoController) {
+ this._slideTabItems.forEach((item) => {
+ item.classList().remove(this._config.slideTabBarItemActiveClassName);
+ });
+ this._activeTabItem?.classList().add(this._config.slideTabBarItemActiveClassName);
+ }
+ this._activeTabItem?.enableFixed();
+
+ //
+ this._startAutoScroll();
+ if (!activeSlideItemElement) return;
+ // Set the mouse cursor to drag
+ activeSlideItemElement.setPointerCapture((downEvent as PointerEvent).pointerId);
+ activeSlideItemElement.style.cursor = 'move';
+
+ this._activeTabItem?.addEventListener('pointermove', this._moveAction);
+ }, SlideTabBar.LongPressDelay);
+ };
+
+ this._upAction = (upEvent: MouseEvent) => {
+ // Clear timer
+ if (this._longPressTimer) {
+ clearTimeout(this._longPressTimer);
+ this._longPressTimer = null;
+ }
+
+ if (!this._activeTabItem) return;
+
+ this._closeAutoScroll();
+ this._activeTabItem.disableFixed();
+ // this._sortedItems();
+ this.updateItems();
+
+ // Restore the mouse cursor
+ const activeSlideItemElement = this._activeTabItem?.getSlideTabItem();
+ if (!activeSlideItemElement) return;
+
+ activeSlideItemElement.style.cursor = '';
+ activeSlideItemElement.releasePointerCapture((upEvent as PointerEvent).pointerId);
+
+ this._activeTabItem?.removeEventListener('pointermove', this._moveAction);
+ this._activeTabItem?.removeEventListener('pointerup', this._upAction);
+ if (this._config.onSlideEnd && this._activeTabItemIndex !== this._compareIndex) {
+ this.destroy();
+
+ this._config.onSlideEnd(upEvent, this._compareIndex || 0);
+ }
+
+ this._scrollIncremental = 0;
+ this._downActionX = 0;
+ this._moveActionX = 0;
+ this._compareIndex = 0;
+ };
+
+ this._moveAction = (moveEvent) => {
+ if (this._activeTabItem) {
+ this._moveActionX = moveEvent.pageX - this._downActionX;
+ if (this._moveActionX <= -this._leftMoveX) {
+ this._moveActionX = -this._leftMoveX;
+ } else if (this._moveActionX >= this._rightMoveX) {
+ this._moveActionX = this._rightMoveX;
+ }
+ this._scrollIncremental = 0;
+ this._scrollLeft(moveEvent);
+ this._scrollRight(moveEvent);
+ }
+ };
+
+ this._wheelAction = (wheelEvent: WheelEvent) => {
+ this.setScroll(wheelEvent.deltaY);
+ };
+
+ this._initialize();
+ }
+
+ static checkedSkipSlide(event: MouseEvent): boolean {
+ let parent: HTMLElement | null = event.target as HTMLElement;
+ while (parent != null && parent !== document.body) {
+ if (parent.getAttribute('data-slide-skip')) {
+ return true;
+ }
+ parent = parent.parentElement;
+ }
+ return false;
+ }
+
+ static keepLastIndex(inputHtml: HTMLElement) {
+ setTimeout(() => {
+ const range = window.getSelection();
+ if (range) {
+ range.selectAllChildren(inputHtml);
+ range.collapseToEnd();
+ }
+ });
+ }
+ static keepSelectAll(inputHtml: HTMLElement) {
+ setTimeout(() => {
+ const selection = window.getSelection();
+ if (!selection) return;
+
+ const range = document.createRange();
+ range.selectNodeContents(inputHtml);
+
+ selection.removeAllRanges();
+ selection.addRange(range);
+ });
+ }
+
+ primeval(): HTMLElement {
+ return this._slideTabBar;
+ }
+
+ updateItems(): void {
+ for (let i = 0; i < this._slideTabItems.length; i++) {
+ this._slideTabItems[i].animate().cancel();
+ this._slideTabItems[i].translateX(0);
+ this._slideTabItems[i].update();
+ }
+ }
+
+ getScrollbar(): SlideScrollbar {
+ return this._slideScrollbar;
+ }
+
+ getConfig(): SlideTabBarConfig {
+ return this._config;
+ }
+
+ getBoundingRect(): DOMRect {
+ return this._slideTabBar.getBoundingClientRect();
+ }
+
+ getSlideTabItems(): SlideTabItem[] {
+ return this._slideTabItems;
+ }
+
+ isLeftEnd(): boolean {
+ return this._isLeftEnd;
+ }
+
+ isRightEnd(): boolean {
+ return this._isRightEnd;
+ }
+
+ destroy(): void {
+ this._slideTabBar.removeEventListener('wheel', this._wheelAction);
+ this._slideTabItems.forEach((item) => {
+ item.removeEventListener('pointerdown', this._downAction);
+ });
+ }
+ setScroll(x: number) {
+ const isEnd = this._slideScrollbar.scrollX(this._slideScrollbar.getScrollX() + x);
+ this._isRightEnd = x > 0 ? isEnd : false;
+ this._isLeftEnd = x < 0 ? isEnd : false;
+
+ this._config.onScroll({
+ leftEnd: this._isLeftEnd,
+ rightEnd: this._isRightEnd,
+ });
+ }
+
+ protected _hasEditItem(): boolean {
+ for (let index = 0; index < this._slideTabItems.length; index++) {
+ const element = this._slideTabItems[index];
+ if (element.isEditMode()) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ protected _autoScrollFrame(): void {
+ if (this._activeTabItem) {
+ this._compareDirection = this._activeTabItem.translateX(this._moveActionX);
+ switch (this._compareDirection) {
+ case 1: {
+ this._slideScrollbar.scrollX(this._slideScrollbar.getScrollX() + this._scrollIncremental);
+ this._compareRight();
+ break;
+ }
+ case 0: {
+ this._slideScrollbar.scrollX(this._slideScrollbar.getScrollX() + this._scrollIncremental);
+ this._compareIndex = this._activeTabItemIndex;
+ break;
+ }
+ case -1: {
+ this._slideScrollbar.scrollX(this._slideScrollbar.getScrollX() + this._scrollIncremental);
+ this._compareLeft();
+ break;
+ }
+ }
+ }
+ this._autoScrollTime = requestAnimationFrame(() => {
+ this._autoScrollFrame();
+ });
+ }
+
+ protected _startAutoScroll(): void {
+ if (this._autoScrollTime == null) {
+ this._autoScrollFrame();
+ }
+ }
+
+ protected _closeAutoScroll(): void {
+ if (this._autoScrollTime) {
+ cancelAnimationFrame(this._autoScrollTime);
+ }
+ this._autoScrollTime = null;
+ }
+
+ protected _scrollLeft(event: MouseEvent): void {
+ const boundingRect = this.getBoundingRect();
+ const x = event.pageX - boundingRect.x;
+ if (x < this._leftBoundingLine) {
+ this._scrollIncremental = -Math.min(Math.abs(x - this._leftBoundingLine) * 0.1, 50);
+ }
+ }
+
+ protected _scrollRight(event: MouseEvent): void {
+ const boundingRect = this.getBoundingRect();
+ const x = event.pageX - boundingRect.x;
+ if (x > boundingRect.width - this._rightBoundingLine) {
+ this._scrollIncremental = Math.min(Math.abs(x - (boundingRect.width - this._rightBoundingLine)) * 0.1, 50);
+ }
+ }
+
+ protected _sortedItems(): void {
+ if (this._activeTabItem != null && this._activeTabItemIndex != null && this._compareIndex != null) {
+ // data array list sort
+ this._slideTabItems.splice(this._activeTabItemIndex, 1);
+ this._slideTabItems.splice(this._compareIndex, 0, this._activeTabItem);
+
+ // dom list sort
+ if (this._config.slideTabBarItemAutoSort) {
+ for (let i = 0; i < this._slideTabItems.length; i++) {
+ const item = this._slideTabItems[i];
+ const next = this._slideTabItems[i + 1];
+ if (next) {
+ item.after(next);
+ }
+ }
+ }
+ }
+ }
+
+ protected _compareLeft(): void {
+ if (this._activeTabItem && this._activeTabItemIndex) {
+ const splice = this._slideTabItems.findIndex((item) => item.equals(this._activeTabItem));
+ const length = this._slideTabItems.length;
+ const collect = [];
+
+ // collect compare item
+ for (let i = 0; i < splice; i++) {
+ if (i >= splice) {
+ break;
+ }
+ collect.push(this._slideTabItems[i]);
+ }
+
+ // reset right
+ for (let i = splice + 1; i < length; i++) {
+ this._slideTabItems[i].animate().translateX(0);
+ }
+
+ // diff item midline
+ let notFound = true;
+ for (let i = collect.length - 1; i >= 0; i--) {
+ const item = collect[i];
+ if (SlideTabItem.midline(this._activeTabItem) < item.getMidLine()) {
+ item.animate().translateX(this._activeTabItem.getWidth());
+ this._compareIndex = i;
+ notFound = false;
+ } else {
+ item.animate().translateX(0);
+ if (notFound) {
+ this._compareIndex = this._activeTabItemIndex;
+ }
+ }
+ }
+ }
+ }
+
+ protected _compareRight(): void {
+ if (this._activeTabItem) {
+ const splice = this._slideTabItems.findIndex((item) => item.equals(this._activeTabItem));
+ const length = this._slideTabItems.length;
+ const collect = [];
+
+ // collect compare item
+ for (let i = splice + 1; i < length; i++) {
+ collect.push(this._slideTabItems[i]);
+ }
+
+ // reset left
+ for (let i = 0; i < splice; i++) {
+ this._slideTabItems[i].animate().translateX(0);
+ }
+
+ // diff item midline
+ let notFound = true;
+ for (let i = 0; i < collect.length; i++) {
+ const item = collect[i];
+ if (SlideTabItem.midline(this._activeTabItem) > item.getMidLine()) {
+ item.animate().translateX(-this._activeTabItem.getWidth());
+ this._compareIndex = splice + i + 1;
+ notFound = false;
+ } else {
+ item.animate().translateX(0);
+ if (notFound) {
+ this._compareIndex = this._activeTabItemIndex;
+ }
+ }
+ }
+ }
+ }
+
+ protected _initialize(): void {
+ // TODO@Dushusir: Listener cannot be removed, resulting in repeated monitoring after renaming or setting tab color.
+ this.destroy();
+
+ this._slideTabBar.addEventListener('wheel', this._wheelAction);
+ this._slideTabItems.forEach((item) => {
+ item.addEventListener('pointerdown', this._downAction);
+ });
+ }
+}
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 66e7e32286..733a2933f0 100644
--- a/packages/ui-plugin-sheets/src/View/SheetBar/index.module.less
+++ b/packages/ui-plugin-sheets/src/View/SheetBar/index.module.less
@@ -1,9 +1,12 @@
+
+@sheet-bar-height: 31px;
+
.sheet-bar {
position: relative;
- height: 31px;
+ height: @sheet-bar-height;
display: flex;
flex-direction: row;
- background-color: var(--bg);
+ background-color: rgb(var(--bg-color));
flex: 1;
width: calc(100% - 350px);
}
@@ -13,238 +16,5 @@
display: flex;
flex-direction: row;
align-items: center;
- padding-right: 5px;
-}
-
-.sheet-bar-options-button {
- padding: 0;
- margin: 0;
- border: none;
- height: initial;
- line-height: initial;
- padding-right: 2px;
-}
-
-.sheet_bar_scroll_button {
- border: none;
- border-left: 1px solid var(--border-color);
- padding-left: 5px;
-}
-
-.slide-tab-bar {
- user-select: none;
- max-width: 100%;
- height: 100%;
- display: flex;
- flex-direction: row;
- align-items: center;
- overflow: auto;
- overflow-y: hidden;
- scrollbar-width: none;
-}
-
-.sheet-bar-tab-pane {
- padding: 0;
-
- &.tabs-tab-active {
- .slide-tab-content {
- color: rgb(var(--color-white));
- background: rgb(var(--primary-color));
- }
-
- .slide-tab-active-bar {
- background: #d0d0d0;
- }
-
- }
-}
-
-.slide-tab-bar::-webkit-scrollbar {
- display: none;
-}
-
-/**
- 高亮标记
- */
-.slide-tab-active {
- position: relative;
-}
-
-/**
- Tab Item
-*/
-.slide-tab-item {
- user-select: none;
- display: flex;
- flex-direction: column;
- justify-content: center;
- cursor: pointer;
- height: 100%;
- background-color: var(--bg);
-}
-
-.slide-tab-item:first-child .slide-tab-divider {
- opacity: 0;
-}
-
-.slide-tab-item:hover {
- background: #efefef;
-}
-
-.slide-tab-item:hover .slide-tab-divider {
- opacity: 0;
-}
-
-.slide-tab-item:hover+.slide-tab-item .slide-tab-divider {
- opacity: 0;
-}
-
-/**
- 内容区域
-*/
-.slide-tab-content {
- display: flex;
- flex-direction: row;
- align-items: center;
- flex-grow: 1;
- padding: 0.3rem;
-}
-
-.slide-tab-title {
- font-size: 14px;
- margin-right: 3px;
- margin-left: 6px;
-}
-
-.slide-tab-span {
- outline-color: rgb(0, 162, 255);
- white-space: nowrap;
-}
-
-.slide-tab-icon {
- width: 16px;
- height: 16px;
- font-size: 15px;
- color: #a1a1a1;
- margin-right: 6px;
-}
-
-.slide-tab-divider {
- width: 1px;
- height: 16px;
- background: var(--border-color);
-}
-
-.slide-tab-active .slide-tab-content {
- background: #efefef;
- color: #222;
-}
-
-.slide-tab-active .slide-tab-divider {
- opacity: 0;
-}
-
-.slide-tab-active+.slide-tab-item .slide-tab-divider {
- opacity: 0;
-}
-
-/**
- 底部区域
- */
-.slide-tab-footer {
- height: auto;
- width: 100%;
- flex-grow: 0;
-}
-
-.slide-tab-active-bar {
- height: 2px;
- width: 100%;
-}
-
-.slide-tab-active .slide-tab-active-bar {
- background: #d0d0d0;
-}
-
-.sheet-ul {
- .cols-menuitem {
- text-align: left;
- padding: 5px 5px 5px 25px;
- }
-
- .select-color-picker-parent {
- .select-item-content {
- width: 100%;
- }
-
- ul {
- padding: 0;
- }
-
- .select-color-picker {
- padding: 0;
-
- .select-item {
- padding: 0;
- }
- }
- }
-}
-
-.sheet-bar-menu {
- position: absolute;
- bottom: 120%;
- left: 0;
- padding: 0;
- border: 1px solid rgba(0, 0, 0, 0.2);
- border-radius: 0;
- transition: opacity 218ms;
- padding: 5px;
- background: var(--bg);
- margin: 0;
- outline: 0;
- z-index: 2;
- box-sizing: border-box;
- user-select: none;
- box-shadow: rgb(0 0 0 / 20%) 0px 2px 4px;
-
- li {
- list-style: none;
- }
-
- .sheet-bar-menu-item {
- position: relative;
- padding: 5px 10px 5px 5px;
- text-align: left;
-
- .sheet-bar-menu-icon {
- display: inline-block;
- vertical-align: middle;
- position: relative;
- width: 20px;
- height: 20px;
- }
-
- .sheet-bar-menu-svg {
- position: absolute;
- left: 50%;
- top: 50%;
- width: 100%;
- height: 100%;
- font-size: 20px;
- margin-left: -10px;
- margin-top: -10px;
- }
-
- .sheet-bar-menu-title {
- font-size: 14px;
- vertical-align: middle;
- padding: 5px 5px 5px 0px;
- }
-
- &-hide {
- pointer-events: none;
- color: #eee;
- }
- }
+ padding-right: var(--padding-xs);
}
\ No newline at end of file
diff --git a/packages/ui-plugin-sheets/src/View/SheetBar/index.ts b/packages/ui-plugin-sheets/src/View/SheetBar/index.ts
deleted file mode 100644
index 327b3d528e..0000000000
--- a/packages/ui-plugin-sheets/src/View/SheetBar/index.ts
+++ /dev/null
@@ -1 +0,0 @@
-export * from './SheetBar';
diff --git a/packages/ui-plugin-sheets/src/View/SheetBar/input-edit.tsx b/packages/ui-plugin-sheets/src/View/SheetBar/input-edit.tsx
deleted file mode 100644
index e4297301e7..0000000000
--- a/packages/ui-plugin-sheets/src/View/SheetBar/input-edit.tsx
+++ /dev/null
@@ -1,69 +0,0 @@
-import { SetWorksheetNameCommand } from '@univerjs/base-sheets';
-import { useObservable } from '@univerjs/base-ui/Components/hooks/observable.js';
-import { ICommandService, IUniverInstanceService } from '@univerjs/core';
-import { useDependency } from '@wendellhu/redi/react-bindings';
-import { useState } from 'react';
-
-import { ISheetBarService } from '../../services/sheetbar/sheetbar.service';
-
-interface IBaseInputProps {
- sheetId: string | undefined;
- sheetName: string;
-}
-export const InputEdit: React.FC<IBaseInputProps> = (props) => {
- const sheetbarService = useDependency(ISheetBarService);
- const commandService = useDependency(ICommandService);
- const univerInstanceService = useDependency(IUniverInstanceService);
- const renameId = useObservable(sheetbarService.renameId$, '');
- const oldValue = props.sheetName;
- const [val, setVal] = useState(props.sheetName || '');
- const changeValue = (e: React.ChangeEvent<HTMLInputElement>) => {
- setVal(e.target.value);
- };
- const blur = () => {
- submit();
- };
-
- const submit = () => {
- if (val !== oldValue) {
- const workbookId = univerInstanceService.getCurrentUniverSheetInstance()?.getUnitId();
- commandService.executeCommand(SetWorksheetNameCommand.id, {
- worksheetId: props.sheetId,
- workbookId,
- name: val,
- });
- }
-
- sheetbarService.setRenameId('');
- };
-
- const keydown = (ev: React.KeyboardEvent<HTMLInputElement>) => {
- if (ev.key !== undefined && ev.key === 'Enter') {
- return submit();
- }
- if (ev.keyCode !== undefined && ev.keyCode === 13) {
- return submit();
- }
- };
-
- const isRenaming = renameId === props.sheetId;
- return isRenaming ? (
- <input
- type="text"
- draggable={false}
- value={val}
- onMouseDown={(e) => {
- e.stopPropagation();
- }}
- autoFocus
- onChange={changeValue}
- onBlur={blur}
- onKeyDown={keydown}
- onClick={(e) => {
- e.stopPropagation();
- }}
- />
- ) : (
- <span>{props.sheetName}</span>
- );
-};
diff --git a/packages/ui-plugin-sheets/src/View/SheetContainer/SheetContainer.tsx b/packages/ui-plugin-sheets/src/View/SheetContainer/SheetContainer.tsx
index 7b511026e7..6c5ba443fc 100644
--- a/packages/ui-plugin-sheets/src/View/SheetContainer/SheetContainer.tsx
+++ b/packages/ui-plugin-sheets/src/View/SheetContainer/SheetContainer.tsx
@@ -2,7 +2,7 @@ import { ISheetUIPluginConfig } from '../../Basics';
import { CountBar } from '../CountBar';
import { EditorContainer } from '../EditorContainer/EditorContainer';
import { FormulaBar } from '../FormulaBar/FormulaBar';
-import { SheetBar } from '../SheetBar';
+import { SheetBar } from '../SheetBar/SheetBar';
import styles from './index.module.less';
export interface BaseSheetContainerProps {
diff --git a/packages/ui-plugin-sheets/src/commands/commands/unhide.command.ts b/packages/ui-plugin-sheets/src/commands/commands/unhide.command.ts
index 4883af5b31..2796ceb584 100644
--- a/packages/ui-plugin-sheets/src/commands/commands/unhide.command.ts
+++ b/packages/ui-plugin-sheets/src/commands/commands/unhide.command.ts
@@ -1,10 +1,15 @@
import { CommandType, ICommand } from '@univerjs/core';
import { IAccessor } from '@wendellhu/redi';
+import { ISheetBarService } from '../../services/sheetbar/sheetbar.service';
+
export const ShowMenuListCommand: ICommand = {
id: 'ui-sheet.command.show-menu-list',
type: CommandType.OPERATION,
- handler: async (accessor: IAccessor) =>
- // TODO: directly change sheet bar visibility
- true,
+ handler: async (accessor: IAccessor) => {
+ const sheetBarService = accessor.get(ISheetBarService);
+ sheetBarService.triggerSheetBarMenu();
+
+ return true;
+ },
};
diff --git a/packages/ui-plugin-sheets/src/controller/clipboard/clipboard.controller.ts b/packages/ui-plugin-sheets/src/controller/clipboard/clipboard.controller.ts
index db0add5467..ab134578fb 100644
--- a/packages/ui-plugin-sheets/src/controller/clipboard/clipboard.controller.ts
+++ b/packages/ui-plugin-sheets/src/controller/clipboard/clipboard.controller.ts
@@ -368,6 +368,7 @@ export class SheetClipboardController extends Disposable {
const undoMutationsInfo: ICommandInfo[] = [];
let hasMerge = false;
+ // TODO@Dushusir: undo selection
matrix.forValue((row, col, value) => {
// TODO@Dushusir Temporarily use handleStringToStyle. After all replication and paste function is completed, fix the handleStringToStyle method
const style = handleStringToStyle(undefined, value.properties.style);
diff --git a/packages/ui-plugin-sheets/src/controller/menu/menu.ts b/packages/ui-plugin-sheets/src/controller/menu/menu.ts
index a1d18d0a0e..5bf02d3df0 100644
--- a/packages/ui-plugin-sheets/src/controller/menu/menu.ts
+++ b/packages/ui-plugin-sheets/src/controller/menu/menu.ts
@@ -79,6 +79,7 @@ import {
SetInfiniteFormatPainterCommand,
SetOnceFormatPainterCommand,
} from '../../commands/commands/set-format-painter.command';
+import { ShowMenuListCommand } from '../../commands/commands/unhide.command';
import { FormatPainterStatus, IFormatPainterService } from '../../services/format-painter/format-painter.service';
export const CONTEXT_MENU_INPUT_LABEL = 'CONTEXT_MENU_INPUT';
@@ -86,11 +87,9 @@ export const CONTEXT_MENU_INPUT_LABEL = 'CONTEXT_MENU_INPUT';
export { SetBorderColorMenuItemFactory, SetBorderStyleMenuItemFactory } from './border.menu';
export enum SheetMenuPosition {
- TAB_CONTEXT_MENU = 'tabContextMenu',
ROW_HEADER_CONTEXT_MENU = 'rowHeaderContextMenu',
COL_HEADER_CONTEXT_MENU = 'colHeaderContextMenu',
SHEET_BAR = 'sheetBar',
- WORKSHEET_MANAGE_MENU = 'worksheetManageMenu',
}
export function FormatPainterMenuItemFactory(accessor: IAccessor): IMenuButtonItem {
@@ -1475,3 +1474,12 @@ export function UnHideSheetMenuItemFactory(accessor: IAccessor): IMenuSelectorIt
}),
};
}
+
+export function ShowMenuItemFactory(): IMenuButtonItem {
+ return {
+ id: ShowMenuListCommand.id,
+ type: MenuItemType.BUTTON,
+ positions: [SheetMenuPosition.SHEET_BAR],
+ title: 'sheetConfig.unhide',
+ };
+}
diff --git a/packages/ui-plugin-sheets/src/controller/sheet-ui.controller.ts b/packages/ui-plugin-sheets/src/controller/sheet-ui.controller.ts
index 287e50398c..13eb81e094 100644
--- a/packages/ui-plugin-sheets/src/controller/sheet-ui.controller.ts
+++ b/packages/ui-plugin-sheets/src/controller/sheet-ui.controller.ts
@@ -98,12 +98,12 @@ import {
SetColWidthMenuItemFactory,
SetRowHeightMenuItemFactory,
ShowColMenuItemFactory,
+ ShowMenuItemFactory,
ShowRowMenuItemFactory,
StrikeThroughMenuItemFactory,
TextColorSelectorMenuItemFactory,
TextRotateMenuItemFactory,
UnderlineMenuItemFactory,
- UnHideSheetMenuItemFactory,
VerticalAlignMenuItemFactory,
WrapTextMenuItemFactory,
} from './menu/menu';
@@ -288,7 +288,7 @@ export class SheetUIController extends Disposable {
RenameSheetMenuItemFactory,
ChangeColorSheetMenuItemFactory,
HideSheetMenuItemFactory,
- UnHideSheetMenuItemFactory,
+ ShowMenuItemFactory,
] as IMenuItemFactory[]
).forEach((factory) => {
this.disposeWithMe(this._menuService.addMenuItem(this._injector.invoke(factory)));
diff --git a/packages/ui-plugin-sheets/src/services/sheetbar/sheetbar.service.ts b/packages/ui-plugin-sheets/src/services/sheetbar/sheetbar.service.ts
index e20758598e..c6a7777808 100644
--- a/packages/ui-plugin-sheets/src/services/sheetbar/sheetbar.service.ts
+++ b/packages/ui-plugin-sheets/src/services/sheetbar/sheetbar.service.ts
@@ -1,27 +1,86 @@
-import { Disposable } from '@univerjs/core/Shared/lifecycle.js';
-import { createIdentifier } from '@wendellhu/redi';
-import { BehaviorSubject, Observable } from 'rxjs';
+import { Disposable, toDisposable } from '@univerjs/core';
+import { createIdentifier, IDisposable } from '@wendellhu/redi';
+import { Observable, Subject } from 'rxjs';
+
+import { IScrollState } from '../../View/SheetBar/SheetBarTabs/utils/slide-tab-bar';
+
+export interface ISheetBarMenuHandler {
+ handleSheetBarMenu(): void;
+}
export interface ISheetBarService {
renameId$: Observable<string>;
+ scroll$: Observable<IScrollState>;
+ scrollX$: Observable<number>;
+ addSheet$: Observable<number>;
setRenameId(id: string): void;
+ setScroll(state: IScrollState): void;
+ setScrollX(x: number): void;
+ setAddSheet(index: number): void;
+ triggerSheetBarMenu(): void;
+ registerSheetBarMenuHandler(handler: ISheetBarMenuHandler): IDisposable;
}
export const ISheetBarService = createIdentifier<ISheetBarService>('univer.sheetbar-service');
export class SheetBarService extends Disposable implements ISheetBarService {
readonly renameId$: Observable<string>;
+ readonly scroll$: Observable<IScrollState>;
+ readonly scrollX$: Observable<number>;
+ readonly addSheet$: Observable<number>;
- private readonly _renameId$: BehaviorSubject<string>;
+ private readonly _renameId$: Subject<string>;
+ private readonly _scroll$: Subject<IScrollState>;
+ private readonly _scrollX$: Subject<number>;
+ private readonly _addSheet$: Subject<number>;
+
+ private _currentHandler: ISheetBarMenuHandler | null = null;
constructor() {
super();
- this._renameId$ = new BehaviorSubject('');
+ this._renameId$ = new Subject();
this.renameId$ = this._renameId$.asObservable();
+
+ this._scroll$ = new Subject();
+ this.scroll$ = this._scroll$.asObservable();
+
+ this._scrollX$ = new Subject();
+ this.scrollX$ = this._scrollX$.asObservable();
+
+ this._addSheet$ = new Subject();
+ this.addSheet$ = this._addSheet$.asObservable();
}
setRenameId(renameId: string): void {
this._renameId$.next(renameId);
}
+
+ setScroll(state: IScrollState): void {
+ this._scroll$.next(state);
+ }
+
+ setScrollX(x: number): void {
+ this._scrollX$.next(x);
+ }
+
+ setAddSheet(index: number): void {
+ this._addSheet$.next(index);
+ }
+
+ triggerSheetBarMenu(): void {
+ this._currentHandler?.handleSheetBarMenu();
+ }
+
+ registerSheetBarMenuHandler(handler: ISheetBarMenuHandler): IDisposable {
+ if (this._currentHandler) {
+ throw new Error('There is already a context menu handler!');
+ }
+
+ this._currentHandler = handler;
+
+ return toDisposable(() => {
+ this._currentHandler = null;
+ });
+ }
}
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 20f5be9ef8..b562ee5712 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -1122,6 +1122,9 @@ importers:
packages/ui-plugin-sheets:
dependencies:
+ '@ctrl/tinycolor':
+ specifier: ^4.0.2
+ version: 4.0.2
'@univerjs/base-docs':
specifier: workspace:*
version: link:../base-docs
@@ -1140,6 +1143,9 @@ importers:
'@univerjs/design':
specifier: workspace:*
version: link:../design
+ '@univerjs/icons':
+ specifier: ^0.1.3
'@wendellhu/redi':
specifier: ^0.12.10
version: 0.12.10
@@ -1517,7 +1523,7 @@ packages:
resolution: {integrity: sha512-C/BaXcnnvBCmHTpz/VGZ8jgtE2aYlW4hxDhseJAWZb7gqGM/qtCK6iZUb0TyKFf7BOUsBH7Q7fkRsDRhg1XklQ==}
engines: {node: '>=6.9.0'}
dependencies:
- '@babel/helper-validator-identifier': 7.22.20
+ '@babel/helper-validator-identifier': 7.22.15
chalk: 2.4.2
js-tokens: 4.0.0
dev: true