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.
TypeScript boardcollaborationdocdocxexceloffce365officepdfpptpptxpresentationsdksheetslidesspreadsheetuniverwordwordprocessorworkspacexlsx
fix(sheet): sheet bar scroll button's state (#454)
Dushusire4fb92e84f1b
diff --git a/packages/ui-plugin-sheets/src/locale/en-US.ts b/packages/ui-plugin-sheets/src/locale/en-US.tsindex b872f45428..fc4bc513ad 100644--- a/packages/ui-plugin-sheets/src/locale/en-US.ts+++ b/packages/ui-plugin-sheets/src/locale/en-US.ts@@ -414,7 +414,7 @@ export default {noHide: "Can't hide, at least keep one sheet tag",chartEditNoOpt: 'This operation is not allowed in chart editing mode!',sheetNameSpecCharError: 'The name cannot contain:[ ] : ? * / \' "',- sheetNameCannotIsEmptyError: 'Sheet name cannot be empty',+ sheetNameCannotIsEmptyError: 'The sheet name cannot be empty',},rightClick: {copy: 'Copy',diff --git a/packages/ui-plugin-sheets/src/locale/zh-CN.ts b/packages/ui-plugin-sheets/src/locale/zh-CN.tsindex 722dd6a7d8..a84557606d 100644--- a/packages/ui-plugin-sheets/src/locale/zh-CN.ts+++ b/packages/ui-plugin-sheets/src/locale/zh-CN.ts@@ -278,7 +278,7 @@ export default {noHide: '不能隐藏, 至少保留一个sheet标签',chartEditNoOpt: '图表编辑模式下不允许该操作!',sheetNameSpecCharError: "名称不能超过31个字符,首尾不能是' 且名称不能包含:\r\n[ ] : \\ ? * /",- sheetNameCannotIsEmptyError: '名称不能为空!',+ sheetNameCannotIsEmptyError: '名称不能为空',},rightClick: {copy: '复制',diff --git a/packages/ui-plugin-sheets/src/views/sheet-bar/SheetBar.tsx b/packages/ui-plugin-sheets/src/views/sheet-bar/SheetBar.tsxindex ae5a1715db..2da08def96 100644--- a/packages/ui-plugin-sheets/src/views/sheet-bar/SheetBar.tsx+++ b/packages/ui-plugin-sheets/src/views/sheet-bar/SheetBar.tsx@@ -14,8 +14,8 @@ import { IScrollState } from './sheet-bar-tabs/utils/slide-tab-bar';const SCROLL_WIDTH = 100;export const SheetBar = () => {- const [leftScrollState, setLeftScrollState] = useState(false);- const [rightScrollState, setRightScrollState] = useState(false);+ const [leftScrollState, setLeftScrollState] = useState(true);+ const [rightScrollState, setRightScrollState] = useState(true);const commandService = useDependency(ICommandService);const sheetbarService = useDependency(ISheetBarService);@@ -67,14 +67,16 @@ export const SheetBar = () => {<SheetBarTabs />{/* Scroll arrows */}- <div className={styles.sheetBarOptions}>- <SheetBarButton disabled={leftScrollState} onClick={handleScrollLeft}>- <MoreSingle style={{ transform: 'rotateZ(180deg)' }} />- </SheetBarButton>- <SheetBarButton disabled={rightScrollState} onClick={handleScrollRight}>- <MoreSingle />- </SheetBarButton>- </div>+ {(!leftScrollState || !rightScrollState) && (+ <div className={styles.sheetBarOptions}>+ <SheetBarButton disabled={leftScrollState} onClick={handleScrollLeft}>+ <MoreSingle style={{ transform: 'rotateZ(180deg)' }} />+ </SheetBarButton>+ <SheetBarButton disabled={rightScrollState} onClick={handleScrollRight}>+ <MoreSingle />+ </SheetBarButton>+ </div>+ )}</div>);};diff --git a/packages/ui-plugin-sheets/src/views/sheet-bar/index.module.less b/packages/ui-plugin-sheets/src/views/sheet-bar/index.module.lessindex 791feea533..abc4f68167 100644--- a/packages/ui-plugin-sheets/src/views/sheet-bar/index.module.less+++ b/packages/ui-plugin-sheets/src/views/sheet-bar/index.module.less@@ -21,5 +21,8 @@display: flex;flex-direction: row;align-items: center;+margin: var(--margin-xxs);++ transition: display .2s;}diff --git a/packages/ui-plugin-sheets/src/views/sheet-bar/sheet-bar-tabs/SheetBarTabs.tsx b/packages/ui-plugin-sheets/src/views/sheet-bar/sheet-bar-tabs/SheetBarTabs.tsxindex cb85dd511c..35f71f5770 100644--- a/packages/ui-plugin-sheets/src/views/sheet-bar/sheet-bar-tabs/SheetBarTabs.tsx+++ b/packages/ui-plugin-sheets/src/views/sheet-bar/sheet-bar-tabs/SheetBarTabs.tsx@@ -10,9 +10,10 @@ import {SetWorksheetOrderCommand,SetWorksheetOrderMutation,} from '@univerjs/base-sheets';-import { BooleanNumber, ICommandInfo, ICommandService, IUniverInstanceService } from '@univerjs/core';+import { IConfirmService } from '@univerjs/base-ui';+import { BooleanNumber, ICommandInfo, ICommandService, IUniverInstanceService, LocaleService } from '@univerjs/core';import { useDependency } from '@wendellhu/redi/react-bindings';-import React, { useEffect, useState } from 'react';+import React, { useEffect, useRef, useState } from 'react';import { ISheetBarService } from '../../../services/sheetbar/sheetbar.service';import sheetBarStyles from '../index.module.less';@@ -24,25 +25,33 @@ export interface ISheetBarTabsProps {}export function SheetBarTabs() {const [sheetList, setSheetList] = useState<IBaseSheetBarProps[]>([]);- const [activeKey, setActiveKey] = useState<string>('');- const [subscribe, setSubscribe] = useState(false);+ const [activeKey, setActiveKey] = useState('');const [boxShadow, setBoxShadow] = useState('');+ const slideTabBarRef = useRef<{ slideTabBar: SlideTabBar | null }>({ slideTabBar: null });const univerInstanceService = useDependency(IUniverInstanceService);const commandService = useDependency(ICommandService);const sheetbarService = useDependency(ISheetBarService);- const workbook = univerInstanceService.getCurrentUniverSheetInstance();+ const localeService = useDependency(LocaleService);+ const confirmService = useDependency(IConfirmService);- let slideTabBar: SlideTabBar;+ const workbook = univerInstanceService.getCurrentUniverSheetInstance();useEffect(() => {statusInit();+ const slideTabBar = setupSlideTabBarInit();const disposable = setupStatusUpdate();- const subscription = setupSubscribeScroll();+ const subscribeList = [+ setupSubscribeScroll(),+ setupSubscribeScrollX(),+ setupSubscribeRenameId(),+ setupSubscribeAddSheet(),+ ];return () => {disposable.dispose();- subscription.unsubscribe();+ slideTabBar.destroy();+ subscribeList.forEach((subscribe) => subscribe.unsubscribe());};}, []);@@ -52,18 +61,15 @@ export function SheetBarTabs() {}}, [sheetList]);- const setupSlideTabBarUpdate = () => {- const currentIndex = sheetList.findIndex((item) => item.selected);-- // TODO@Dushusir: There may not be initialization each time- slideTabBar = new SlideTabBar({+ const setupSlideTabBarInit = () => {+ const slideTabBar = new SlideTabBar({slideTabBarClassName: styles.slideTabBar,slideTabBarItemActiveClassName: styles.slideTabActive,slideTabBarItemClassName: styles.slideTabItem,slideTabBarSpanEditClassName: styles.slideTabSpanEdit,slideTabBarItemAutoSort: true,slideTabRootClassName: sheetBarStyles.sheetBar,- currentIndex,+ currentIndex: 0,onChangeName: (worksheetId: string, worksheetName: string) => {commandService.executeCommand(SetWorksheetNameCommand.id, {worksheetId,@@ -79,26 +85,34 @@ export function SheetBarTabs() {onScroll: (state: IScrollState) => {sheetbarService.setScroll(state);},+ onEmptyAlert: () => {+ const id = 'slideTabBarAlert';+ confirmService.open({+ id,+ children: { title: localeService.t('sheetConfig.sheetNameCannotIsEmptyError') },+ // TODO@Dushusir: i18n+ title: { title: 'There was a problem' },+ onClose() {+ confirmService.close(id);+ },+ onConfirm() {+ confirmService.close(id);+ },+ });+ },});- // TODO@Dushusir: Can you initialize it once without using the `subscribe` label?- if (!subscribe) {- sheetbarService.scrollX$.subscribe((x: number) => {- // update scrollX- slideTabBar.setScroll(x);- });+ slideTabBarRef.current.slideTabBar = slideTabBar;- sheetbarService.renameId$.subscribe((renameId: string) => {- const index = sheetList.findIndex((item) => item.sheetId === renameId);- slideTabBar.getSlideTabItems()[index].editor();- });+ // FIXME@Dushusir: First time asynchronous rendering will cause flickering problems+ resizeInit(slideTabBar);- sheetbarService.addSheet$.subscribe((addSheet: number) => {- slideTabBar.getScrollbar().scrollRight();- });+ return slideTabBar;+ };- setSubscribe(true);- }+ const setupSlideTabBarUpdate = () => {+ const currentIndex = sheetList.findIndex((item) => item.selected);+ slideTabBarRef.current.slideTabBar?.update(currentIndex);};const setupStatusUpdate = () =>@@ -140,6 +154,21 @@ export function SheetBarTabs() {updateScrollButtonState(state);});+ const setupSubscribeScrollX = () =>+ sheetbarService.scrollX$.subscribe((x: number) => {+ slideTabBarRef.current.slideTabBar?.setScroll(x);+ });++ const setupSubscribeRenameId = () =>+ sheetbarService.renameId$.subscribe(() => {+ slideTabBarRef.current.slideTabBar?.getActiveItem()?.editor();+ });++ const setupSubscribeAddSheet = () =>+ sheetbarService.addSheet$.subscribe(() => {+ slideTabBarRef.current.slideTabBar?.getScrollbar().scrollRight();+ });+const updateScrollButtonState = (state: IScrollState) => {const { leftEnd, rightEnd } = state;// box-shadow: inset 10px 0px 10px -10px rgba(0, 0, 0, 0.2), inset -10px 0px 10px -10px rgba(0, 0, 0, 0.2);@@ -157,6 +186,27 @@ export function SheetBarTabs() {setBoxShadow(boxShadow);};+ const buttonScroll = (slideTabBar: SlideTabBar) => {+ sheetbarService.setScroll({+ leftEnd: slideTabBar.isLeftEnd(),+ rightEnd: slideTabBar.isRightEnd(),+ });+ };++ const resizeInit = (slideTabBar: SlideTabBar) => {+ // Target element+ const slideTabBarContainer = document.querySelector(`.${styles.slideTabBar}`);+ if (!slideTabBarContainer) return;++ // Create a Resizeobserver+ const observer = new ResizeObserver(() => {+ buttonScroll(slideTabBar);+ });++ // Start the observer+ observer.observe(slideTabBarContainer);+ };+return (<div className={styles.slideTabBarContainer}><div className={styles.slideTabBar} style={{ boxShadow }}>diff --git a/packages/ui-plugin-sheets/src/views/sheet-bar/sheet-bar-tabs/utils/slide-tab-bar.ts b/packages/ui-plugin-sheets/src/views/sheet-bar/sheet-bar-tabs/utils/slide-tab-bar.tsindex 64e0d8c995..2f2c902f21 100644--- a/packages/ui-plugin-sheets/src/views/sheet-bar/sheet-bar-tabs/utils/slide-tab-bar.ts+++ b/packages/ui-plugin-sheets/src/views/sheet-bar/sheet-bar-tabs/utils/slide-tab-bar.ts@@ -10,13 +10,13 @@ export interface SlideTabBarConfig {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;+ onEmptyAlert: () => void;}export interface SlideTabItemAnimate {@@ -113,7 +113,7 @@ export class SlideTabItem {}// Event must be removed before updateItems- this._slideTabBar.destroy();+ this._slideTabBar.removeListener();this._slideTabBar.updateItems();if (this._slideTabBar.getConfig().onChangeName) {const text = input?.innerText || '';@@ -177,8 +177,7 @@ export class SlideTabItem {if (!input) return false;const text = input.innerText;if (text.trim() === '') {- // TODO@Dushusir: i18n and dialog service- alert('The sheet name cannot be empty.');+ this._slideTabBar.getConfig().onEmptyAlert();return true;}return false;@@ -324,8 +323,6 @@ export class SlideTabItem {}}-// TODO@Dushusir: resize container trigger scroll box-shadow-// init container, no box-shadow, no scroll buttonexport class SlideScrollbar {protected _slideTabBar: SlideTabBar;@@ -361,21 +358,21 @@ export class SlideTabBar {/** Time in milliseconds with two consecutive clicks will be considered as a double click */static DoubleClickDelay = 300; // in milliseconds- protected _activeTabItemIndex: number | null;+ protected _activeTabItemIndex: number = 0;protected _slideTabBar: HTMLElement;- protected _slideTabItems: SlideTabItem[];+ protected _slideTabItems: SlideTabItem[] = [];protected _config: SlideTabBarConfig;- protected _downActionX: number;+ protected _downActionX: number = 0;- protected _moveActionX: number;+ protected _moveActionX: number = 0;- protected _compareIndex: number | null;+ protected _compareIndex: number = 0;- protected _activeTabItem: SlideTabItem | null;+ protected _activeTabItem: SlideTabItem | null = null;protected _moveAction: (e: MouseEvent) => void;@@ -423,25 +420,15 @@ export class SlideTabBar {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];+ this._config = config as SlideTabBarConfig;++ this._initConfig();let lastPageX = 0;let lastPageY = 0;@@ -458,7 +445,7 @@ export class SlideTabBar {if (this._activeTabItemIndex !== slideItemIndex) {this._activeTabItem?.removeEventListener('pointermove', this._moveAction);this._activeTabItem?.removeEventListener('pointerup', this._upAction);- this.destroy();+ this.removeListener();this._config.onChangeTab(downEvent, slideItemId);return;}@@ -497,10 +484,8 @@ export class SlideTabBar {// double clickif (diffTime && diffPageX && diffPageY) {- if (this._activeTabItem) {- // user editor- this._activeTabItem.editor();- }+ // user editor+ this._activeTabItem.editor();}lastPageX = pageX;@@ -509,21 +494,12 @@ export class SlideTabBar {// Set a timer to delay dragging for 300 millisecondsthis._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 dragactiveSlideItemElement.setPointerCapture((downEvent as PointerEvent).pointerId);activeSlideItemElement.style.cursor = 'move';-this._activeTabItem?.addEventListener('pointermove', this._moveAction);}, SlideTabBar.LongPressDelay);};@@ -552,8 +528,7 @@ export class SlideTabBar {this._activeTabItem?.removeEventListener('pointermove', this._moveAction);this._activeTabItem?.removeEventListener('pointerup', this._upAction);if (this._config.onSlideEnd && this._activeTabItemIndex !== this._compareIndex) {- this.destroy();-+ this.removeListener();this._config.onSlideEnd(upEvent, this._compareIndex || 0);}@@ -581,7 +556,7 @@ export class SlideTabBar {this.setScroll(wheelEvent.deltaY);};- this._initialize();+ this.addListener();}static checkedSkipSlide(event: MouseEvent): boolean {@@ -618,6 +593,17 @@ export class SlideTabBar {});}+ /**+ * The current instance is persistent, but some parameters need to be updated after refreshing+ * @param currentIndex+ */+ update(currentIndex: number) {+ this._config.currentIndex = currentIndex;+ this._initConfig();+ this.removeListener();+ this.addListener();+ }+primeval(): HTMLElement {return this._slideTabBar;}@@ -646,6 +632,10 @@ export class SlideTabBar {return this._slideTabItems;}+ getActiveItem() {+ return this._activeTabItem;+ }+isLeftEnd(): boolean {return this._slideTabBar.scrollLeft === 0;}@@ -656,7 +646,14 @@ export class SlideTabBar {return this._slideTabBar.scrollWidth - parent.clientWidth === this._slideTabBar.scrollLeft;}- destroy(): void {+ addListener() {+ this._slideTabBar.addEventListener('wheel', this._wheelAction);+ this._slideTabItems.forEach((item) => {+ item.addEventListener('pointerdown', this._downAction);+ });+ }++ removeListener(): void {this._slideTabBar.removeEventListener('wheel', this._wheelAction);this._slideTabItems.forEach((item) => {item.removeEventListener('pointerdown', this._downAction);@@ -672,6 +669,25 @@ export class SlideTabBar {});}+ destroy() {+ this._downActionX = 0;+ this._moveActionX = 0;+ this._compareDirection = 0;+ this._compareIndex = 0;+ this._slideTabItems = [];+ this._activeTabItem = null;+ this.removeListener();++ // TODO@Dushusir: If set to null, the types in other places need to be judged+ // this._slideTabBar = null;+ // this._slideScrollbar = null;+ // this._config = null;+ // this._downAction = null;+ // this._upAction = null;+ // this._moveAction = null;+ // this._wheelAction = null;+ }+protected _hasEditItem(): boolean {for (let index = 0; index < this._slideTabItems.length; index++) {const element = this._slideTabItems[index];@@ -829,10 +845,18 @@ export class SlideTabBar {}}- protected _initialize(): void {- this._slideTabBar.addEventListener('wheel', this._wheelAction);- this._slideTabItems.forEach((item) => {- item.addEventListener('pointerdown', this._downAction);- });+ protected _initConfig(): void {+ const slideTabItems = this._slideTabBar.querySelectorAll(+ `.${this._config.slideTabBarItemClassName ?? 'slide-tab-item'}`+ );++ this._downActionX = 0;+ this._moveActionX = 0;+ this._compareDirection = 0;+ this._compareIndex = 0;++ this._slideTabItems = SlideTabItem.make(slideTabItems, this);+ this._activeTabItemIndex = this._config.currentIndex;+ this._activeTabItem = this._slideTabItems[this._activeTabItemIndex];}}