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.

fix(sheets-ui): prevent switching tabs during invalid sheet renames (#8089)

白熱20df3a6455be
diff --git a/packages/sheets-ui/src/views/sheet-bar/sheet-bar-tabs/SheetBarTabs.tsx b/packages/sheets-ui/src/views/sheet-bar/sheet-bar-tabs/SheetBarTabs.tsx
index 23cdc85c29..a1e5d07f7a 100644
--- a/packages/sheets-ui/src/views/sheet-bar/sheet-bar-tabs/SheetBarTabs.tsx
+++ b/packages/sheets-ui/src/views/sheet-bar/sheet-bar-tabs/SheetBarTabs.tsx
@@ -14,7 +14,6 @@
* limitations under the License.
*/
-import type { ICommandInfo } from '@univerjs/core';
import type { IUniverUIConfig } from '@univerjs/ui';
import type { KeyboardEvent as ReactKeyboardEvent, MouseEvent as ReactMouseEvent } from 'react';
import {
@@ -27,7 +26,6 @@ import {
Quantity,
UniverInstanceType,
} from '@univerjs/core';
-import { IRenderManagerService } from '@univerjs/engine-render';
import {
BasesMultiIcon,
BoardsMultiIcon,
@@ -61,7 +59,6 @@ import { getEmbedSheetsTabCustomData } from '../../../embed-tab-anchor';
import { IEditorBridgeService } from '../../../services/editor-bridge.service';
import { ISheetBarService } from '../../../services/sheet-bar/sheet-bar.service';
import { ISheetEmbedRuntimeService } from '../../../services/sheet-embed-runtime.service';
-import { SheetSkeletonManagerService } from '../../../services/sheet-skeleton-manager.service';
import { useActiveWorkbook } from '../../hook';
import { SheetBarItem } from './SheetBarItem';
import { SheetBarTabsContextMenu } from './SheetBarTabsContextMenu';
@@ -102,39 +99,6 @@ function EmbedSheetTabProductIcon({ childType }: IEmbedSheetTabProductIconProps)
}
}
-function getScrollShadow(state: IScrollState) {
- const { leftEnd, rightEnd } = state;
-
- if (leftEnd && rightEnd) {
- return SCROLL_SHADOW_NONE;
- }
-
- if (leftEnd) {
- return SCROLL_SHADOW_RIGHT;
- }
-
- if (rightEnd) {
- return SCROLL_SHADOW_LEFT;
- }
-
- return SCROLL_SHADOW_BOTH;
-}
-
-function shouldRefreshSheetTabs(commandInfo: ICommandInfo) {
- switch (commandInfo.id) {
- case SetTabColorMutation.id:
- case SetWorksheetHideMutation.id:
- case RemoveSheetMutation.id:
- case SetWorksheetNameMutation.id:
- case InsertSheetMutation.id:
- case SetWorksheetOrderMutation.id:
- case SetWorksheetActiveOperation.id:
- return true;
- default:
- return false;
- }
-}
-
export function SheetBarTabs() {
const injector = useDependency(Injector);
const [sheetList, setSheetList] = useState<IBaseSheetBarProps[]>([]);
@@ -145,11 +109,9 @@ export function SheetBarTabs() {
const slideTabBarRef = useRef<SlideTabBar | null>(null);
const slideTabBarContainerRef = useRef<HTMLDivElement>(null);
- const activeSheetIdRef = useRef(activeSheetId);
const commandService = useDependency(ICommandService);
const layoutService = useDependency(ILayoutService);
- const renderManagerService = useDependency(IRenderManagerService);
const sheetBarService = useDependency(ISheetBarService);
const localeService = useDependency(LocaleService);
const confirmService = useDependency(IConfirmService);
@@ -159,7 +121,6 @@ export function SheetBarTabs() {
const permissionService = useDependency(IPermissionService);
const workbook = useActiveWorkbook()!;
- const workbookRef = useRef(workbook);
const resetOrder = useObservable(worksheetProtectionRuleModel.resetOrder$);
const config = useConfigValue<IUniverUIConfig>(UI_PLUGIN_CONFIG_KEY);
const showContextMenu = config?.contextMenu ?? true;
@@ -316,9 +277,7 @@ export function SheetBarTabs() {
} satisfies IBaseSheetBarProps;
});
- // eslint-disable-next-line react/set-state-in-effect
setSheetList(sheetListItems);
- // eslint-disable-next-line react/set-state-in-effect
setActiveSheetId(currentSubUnitId);
}, [injector, rangeProtectionRuleModel, workbook, worksheetProtectionRuleModel]);
@@ -326,8 +285,16 @@ export function SheetBarTabs() {
slideTabBarRef.current?.getActiveItem()?.setEditor();
}, []);
- const syncScrollState = useCallback((state: IScrollState) => {
- setScrollShadow(getScrollShadow(state));
+ const syncScrollState = useCallback(({ leftEnd, rightEnd }: IScrollState) => {
+ if (leftEnd && rightEnd) {
+ setScrollShadow(SCROLL_SHADOW_NONE);
+ } else if (leftEnd) {
+ setScrollShadow(SCROLL_SHADOW_RIGHT);
+ } else if (rightEnd) {
+ setScrollShadow(SCROLL_SHADOW_LEFT);
+ } else {
+ setScrollShadow(SCROLL_SHADOW_BOTH);
+ }
}, []);
const syncScrollButtonState = useCallback((slideTabBar: SlideTabBar) => {
@@ -343,46 +310,20 @@ export function SheetBarTabs() {
});
}, [sheetBarService]);
- useEffect(() => {
- activeSheetIdRef.current = activeSheetId;
- }, [activeSheetId]);
-
- useEffect(() => {
- workbookRef.current = workbook;
- }, [workbook]);
-
- const syncActiveSheetRender = useCallback((subUnitId: string) => {
- const render = renderManagerService.getRenderUnitById(workbookRef.current.getUnitId());
- try {
- render?.with(SheetSkeletonManagerService).setCurrent({ sheetId: subUnitId });
- render?.scene.makeDirty(true);
- render?.scene.render();
- } catch {
- // The normal command path owns render updates. This fallback only runs when that path was skipped.
- }
- }, [renderManagerService]);
-
const activateSheetTab = useCallback((subUnitId?: string) => {
- if (!subUnitId || subUnitId === activeSheetIdRef.current) {
+ if (!subUnitId || subUnitId === activeSheetId || slideTabBarRef.current?.getActiveItem()?.isEditMode()) {
return;
}
commandService.executeCommand(SetWorksheetActiveOperation.id, {
subUnitId,
- unitId: workbookRef.current.getUnitId(),
+ unitId: workbook.getUnitId(),
}).then((result) => {
- requestAnimationFrame(() => layoutService.focus(workbookRef.current.getUnitId()));
if (result !== false) {
- return;
- }
-
- const worksheet = workbookRef.current.getSheetBySheetId(subUnitId);
- if (worksheet) {
- workbookRef.current.setActiveSheet(worksheet);
- syncActiveSheetRender(subUnitId);
+ requestAnimationFrame(() => layoutService.focus(workbook.getUnitId()));
}
});
- }, [commandService, layoutService, syncActiveSheetRender]);
+ }, [activeSheetId, commandService, layoutService, workbook]);
const observeResize = useCallback((slideTabBar: SlideTabBar) => {
const slideTabBarContainer = slideTabBarContainerRef.current?.querySelector('[data-u-comp=slide-tab-bar]');
@@ -456,6 +397,10 @@ export function SheetBarTabs() {
const onTabListContextMenu = useCallback((event: ReactMouseEvent<HTMLDivElement>) => {
event.preventDefault();
+ if (slideTabBarRef.current?.getActiveItem()?.isEditMode()) {
+ return;
+ }
+
const triggerItem = (event.target as HTMLElement).closest<HTMLElement>('[data-u-comp=slide-tab-item]');
const targetSheetId = triggerItem?.dataset.id;
@@ -499,10 +444,7 @@ export function SheetBarTabs() {
if (event.key === 'Enter' || event.key === ' ') {
event.preventDefault();
- commandService.executeCommand(SetWorksheetActiveOperation.id, {
- unitId: workbook.getUnitId(),
- subUnitId: currentSheetId,
- });
+ activateSheetTab(currentSheetId);
return;
}
@@ -530,11 +472,8 @@ export function SheetBarTabs() {
}
nextTab.focus();
- commandService.executeCommand(SetWorksheetActiveOperation.id, {
- unitId: workbook.getUnitId(),
- subUnitId: nextSheetId,
- });
- }, [commandService, workbook]);
+ activateSheetTab(nextSheetId);
+ }, [activateSheetTab]);
const initializeSlideTabBar = useCallback(() => {
const slideTabBar = new SlideTabBar({
@@ -598,12 +537,18 @@ export function SheetBarTabs() {
]);
useEffect(() => {
- updateSheetItems();
-
const { slideTabBar, disconnectResizeObserver } = initializeSlideTabBar();
const commandDisposable = commandService.onCommandExecuted((commandInfo) => {
- if (shouldRefreshSheetTabs(commandInfo)) {
- updateSheetItems();
+ switch (commandInfo.id) {
+ case SetTabColorMutation.id:
+ case SetWorksheetHideMutation.id:
+ case RemoveSheetMutation.id:
+ case SetWorksheetNameMutation.id:
+ case InsertSheetMutation.id:
+ case SetWorksheetOrderMutation.id:
+ case SetWorksheetActiveOperation.id:
+ updateSheetItems();
+ break;
}
});
@@ -672,12 +617,9 @@ export function SheetBarTabs() {
};
}, [rangeProtectionRuleModel, updateSheetItems, worksheetProtectionRuleModel]);
- useEffect(() => {
- if (!showContextMenu && contextMenuVisible) {
- // eslint-disable-next-line react/set-state-in-effect
- setContextMenuVisible(false);
- }
- }, [contextMenuVisible, showContextMenu]);
+ if (!showContextMenu && contextMenuVisible) {
+ setContextMenuVisible(false);
+ }
return (
<SheetBarTabsContextMenu
diff --git a/packages/sheets-ui/src/views/sheet-bar/sheet-bar-tabs/__tests__/SheetBarTabs.spec.tsx b/packages/sheets-ui/src/views/sheet-bar/sheet-bar-tabs/__tests__/SheetBarTabs.spec.tsx
new file mode 100644
index 0000000000..eddffd66c3
--- /dev/null
+++ b/packages/sheets-ui/src/views/sheet-bar/sheet-bar-tabs/__tests__/SheetBarTabs.spec.tsx
@@ -0,0 +1,115 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { IWorkbookData, Workbook } from '@univerjs/core';
+import { getSheetsEmptySnapshot, ICommandService, IConfigService, IConfirmService, IPermissionService, LocaleService, LocaleType, Univer, UniverInstanceType } from '@univerjs/core';
+import { RangeProtectionRuleModel, SetWorksheetActiveOperation, SetWorksheetNameCommand, SetWorksheetNameMutation, SheetInterceptorService, WorkbookRenameSheetPermission, WorksheetProtectionRuleModel } from '@univerjs/sheets';
+import { DesktopConfirmService, DesktopLayoutService, ILayoutService, IUIPartsService, RediContext, UI_PLUGIN_CONFIG_KEY, UIPartsService } from '@univerjs/ui';
+import { act } from 'react';
+import { createRoot } from 'react-dom/client';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import enUS from '../../../../locale/en-US';
+import { ISheetBarService, SheetBarService } from '../../../../services/sheet-bar/sheet-bar.service';
+import { SheetBarTabs } from '../SheetBarTabs';
+
+(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+const disposals: Array<() => void> = [];
+
+function renderSheetTabs() {
+ const univer = new Univer();
+ const injector = univer.__getInjector();
+ injector.add([ISheetBarService, { useClass: SheetBarService }]);
+ injector.add([ILayoutService, { useClass: DesktopLayoutService }]);
+ injector.add([IUIPartsService, { useClass: UIPartsService }]);
+ injector.add([IConfirmService, { useClass: DesktopConfirmService as never }]);
+ injector.add([RangeProtectionRuleModel]);
+ injector.add([WorksheetProtectionRuleModel]);
+ injector.add([SheetInterceptorService]);
+ injector.get(IConfigService).setConfig(UI_PLUGIN_CONFIG_KEY, { contextMenu: false });
+ const localeService = injector.get(LocaleService);
+ localeService.load({ [LocaleType.EN_US]: enUS });
+ localeService.setLocale(LocaleType.EN_US);
+ localeService.setDirection('ltr');
+ const workbook = univer.createUnit<IWorkbookData, Workbook>(UniverInstanceType.UNIVER_SHEET, {
+ ...getSheetsEmptySnapshot('rename-tabs'),
+ sheetOrder: ['first', 'second'],
+ sheets: {
+ first: { id: 'first', name: 'Sheet1' },
+ second: { id: 'second', name: 'Sheet2' },
+ },
+ });
+ injector.get(IPermissionService).addPermissionPoint(new WorkbookRenameSheetPermission(workbook.getUnitId()));
+ const commandService = injector.get(ICommandService);
+ [SetWorksheetActiveOperation, SetWorksheetNameCommand, SetWorksheetNameMutation]
+ .forEach((command) => commandService.registerCommand(command));
+ const container = document.createElement('div');
+ document.body.appendChild(container);
+ const root = createRoot(container);
+ disposals.push(() => {
+ act(() => root.unmount());
+ container.remove();
+ univer.dispose();
+ });
+ act(() => root.render(<RediContext.Provider value={{ injector }}><SheetBarTabs /></RediContext.Provider>));
+ return { container, workbook, injector };
+}
+
+afterEach(() => {
+ disposals.splice(0).forEach((dispose) => dispose());
+ window.getSelection()?.removeAllRanges();
+ vi.useRealTimers();
+});
+
+describe('SheetBarTabs name validation', () => {
+ it.each(['', ' ', 'Sheet2', 'invalid/name'])(
+ 'keeps the original sheet active until the invalid name %j is corrected',
+ async (name) => {
+ vi.useFakeTimers();
+ const { container, workbook, injector } = renderSheetTabs();
+ const sheetBarService = injector.get(ISheetBarService);
+ const confirmService = injector.get(IConfirmService) as DesktopConfirmService;
+ const firstTab = container.querySelector<HTMLElement>('[data-id="first"]')!;
+ const secondTab = container.querySelector<HTMLElement>('[data-id="second"]')!;
+ const editor = firstTab.querySelector('span')!;
+ act(() => sheetBarService.setRenameId('first'));
+ act(() => vi.runOnlyPendingTimers());
+ editor.textContent = name;
+
+ await act(async () => {
+ secondTab.dispatchEvent(new PointerEvent('pointerdown', { bubbles: true }));
+ editor.dispatchEvent(new FocusEvent('focusout', { bubbles: true, relatedTarget: secondTab }));
+ secondTab.dispatchEvent(new MouseEvent('contextmenu', { bubbles: true }));
+ secondTab.dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter', bubbles: true }));
+ });
+ expect(workbook.getActiveSheet()?.getSheetId()).toBe('first');
+ expect(workbook.getSheetBySheetId('first')?.getName()).toBe('Sheet1');
+ const dialog = confirmService.confirmOptions$.getValue().find((option) => option.visible)!;
+ expect(dialog).toBeDefined();
+ await act(async () => dialog.onConfirm?.());
+ act(() => vi.runOnlyPendingTimers());
+ expect(editor.contains(window.getSelection()?.anchorNode ?? null)).toBe(true);
+ expect(editor.getAttribute('contenteditable')).toBe('true');
+
+ editor.textContent = 'Renamed';
+ await act(async () => editor.dispatchEvent(new FocusEvent('focusout', { bubbles: true })));
+ await act(async () => secondTab.dispatchEvent(new PointerEvent('pointerdown', { bubbles: true })));
+ expect(workbook.getActiveSheet()?.getSheetId()).toBe('second');
+ expect(workbook.getSheetBySheetId('first')?.getName()).toBe('Renamed');
+ expect(firstTab.textContent).toBe('Renamed');
+ }
+ );
+});
diff --git a/packages/sheets-ui/src/views/sheet-bar/sheet-bar-tabs/utils/slide-tab-bar.ts b/packages/sheets-ui/src/views/sheet-bar/sheet-bar-tabs/utils/slide-tab-bar.ts
index a8d85ffa29..6d1270a833 100644
--- a/packages/sheets-ui/src/views/sheet-bar/sheet-bar-tabs/utils/slide-tab-bar.ts
+++ b/packages/sheets-ui/src/views/sheet-bar/sheet-bar-tabs/utils/slide-tab-bar.ts
@@ -343,13 +343,95 @@ export class SlideTabBar {
protected _activeTabItem: SlideTabItem | null = null;
- protected _moveAction: (e: MouseEvent) => void;
+ protected _moveAction = (moveEvent: MouseEvent) => {
+ 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);
+ }
+ };
+
+ protected _upAction = (upEvent: MouseEvent) => {
+ // Clear timer
+ if (this._longPressTimer) {
+ clearTimeout(this._longPressTimer);
+ this._longPressTimer = null;
+ }
+
+ if (!this._activeTabItem) return;
+
+ if (this._activeTabItem.isEditMode()) {
+ const activeSlideItemElement = this._activeTabItem.getSlideTabItem();
+ const pointerId = (upEvent as PointerEvent).pointerId;
+ if (pointerId != null && activeSlideItemElement.hasPointerCapture(pointerId)) {
+ activeSlideItemElement.releasePointerCapture(pointerId);
+ }
+ this._activeTabItem.removeEventListener('pointerup', this._upAction);
+ return;
+ }
- protected _upAction: (e: MouseEvent) => void;
+ // When blurring after editing the table name, _activeTabItemIndex and _compareIndex may not be equal, causing slideEnd to be triggered
+ const isFromScroll = this._autoScrollTime !== null;
+
+ this._closeAutoScroll();
+ this._activeTabItem.disableFixed();
+ 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 &&
+ isFromScroll
+ ) {
+ this.removeListener();
+ this._config.onSlideEnd(upEvent, this._compareIndex || 0);
+ }
+
+ this._scrollIncremental = 0;
+ this._downActionX = 0;
+ this._moveActionX = 0;
+ this._dragStartScrollX = this._slideScrollbar.getScrollX();
+ this._compareIndex = 0;
+ };
protected _downAction: (e: MouseEvent) => void;
- protected _wheelAction: (e: WheelEvent) => void;
+ protected _wheelAction = (wheelEvent: WheelEvent) => {
+ const viewportWidth = this._slideTabBar.parentElement?.clientWidth ?? this._slideTabBar.clientWidth;
+ if (this._slideTabBar.scrollWidth <= viewportWidth) {
+ return;
+ }
+
+ const dominantDelta = Math.abs(wheelEvent.deltaX) > Math.abs(wheelEvent.deltaY)
+ ? wheelEvent.deltaX
+ : wheelEvent.deltaY;
+ if (dominantDelta === 0) {
+ return;
+ }
+
+ const deltaModeMultiplier = wheelEvent.deltaMode === WheelEvent.DOM_DELTA_LINE
+ ? 16
+ : wheelEvent.deltaMode === WheelEvent.DOM_DELTA_PAGE
+ ? viewportWidth
+ : 1;
+
+ wheelEvent.preventDefault();
+ this.setScroll(dominantDelta * deltaModeMultiplier);
+ };
protected _scrollIncremental: number = 0;
@@ -383,7 +465,6 @@ export class SlideTabBar {
*/
protected _rightMoveX: number = 0;
- // eslint-disable-next-line max-lines-per-function
constructor(config: Partial<ISlideTabBarConfig>) {
if (config.slideTabBarContainer == null) {
throw new Error('not found slide-tab-bar root element');
@@ -400,11 +481,16 @@ export class SlideTabBar {
this._initConfig();
+ this._downAction = this._createDownAction();
+
+ this.addListener();
+ }
+
+ private _createDownAction(): (event: MouseEvent) => void {
let lastPageX = 0;
let lastPageY = 0;
let lastTime = 0;
- // eslint-disable-next-line max-lines-per-function
- this._downAction = (downEvent: MouseEvent) => {
+ return (downEvent: MouseEvent) => {
// Waiting for the rename of the previous TAB
if (this._activeTabItem?.isEditMode()) {
return;
@@ -417,7 +503,7 @@ export class SlideTabBar {
}
const slideItemId = (downEvent.target as HTMLElement)
- ?.closest(`${config.slideTabBarItemSelector}`)
+ ?.closest(this._config.slideTabBarItemSelector)
?.getAttribute('data-id');
const slideItemIndex = this._slideTabItems.findIndex((item) => item.getId() === slideItemId);
@@ -474,109 +560,22 @@ export class SlideTabBar {
lastPageY = pageY;
lastTime = current;
- // Set a timer to delay dragging for 300 milliseconds
- this._longPressTimer = setTimeout(() => {
- if (!activeSlideItemElement || this._activeTabItem?.isEditMode()) return;
-
- this._activeTabItem?.enableFixed();
- this._startAutoScroll();
- // 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._startLongPress(downEvent, activeSlideItemElement);
};
+ }
- this._upAction = (upEvent: MouseEvent) => {
- // Clear timer
- if (this._longPressTimer) {
- clearTimeout(this._longPressTimer);
- this._longPressTimer = null;
- }
-
- if (!this._activeTabItem) return;
-
- if (this._activeTabItem.isEditMode()) {
- const activeSlideItemElement = this._activeTabItem.getSlideTabItem();
- const pointerId = (upEvent as PointerEvent).pointerId;
- if (pointerId != null && activeSlideItemElement.hasPointerCapture(pointerId)) {
- activeSlideItemElement.releasePointerCapture(pointerId);
- }
- this._activeTabItem.removeEventListener('pointerup', this._upAction);
- return;
- }
-
- // When blurring after editing the table name, _activeTabItemIndex and _compareIndex may not be equal, causing slideEnd to be triggered
- const isFromScroll = this._autoScrollTime !== null;
-
- 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 &&
- isFromScroll
- ) {
- this.removeListener();
- this._config.onSlideEnd(upEvent, this._compareIndex || 0);
- }
-
- this._scrollIncremental = 0;
- this._downActionX = 0;
- this._moveActionX = 0;
- this._dragStartScrollX = this._slideScrollbar.getScrollX();
- 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) => {
- const viewportWidth = this._slideTabBar.parentElement?.clientWidth ?? this._slideTabBar.clientWidth;
- if (this._slideTabBar.scrollWidth <= viewportWidth) {
- return;
- }
-
- const dominantDelta = Math.abs(wheelEvent.deltaX) > Math.abs(wheelEvent.deltaY)
- ? wheelEvent.deltaX
- : wheelEvent.deltaY;
- if (dominantDelta === 0) {
- return;
- }
-
- const deltaModeMultiplier = wheelEvent.deltaMode === WheelEvent.DOM_DELTA_LINE
- ? 16
- : wheelEvent.deltaMode === WheelEvent.DOM_DELTA_PAGE
- ? viewportWidth
- : 1;
-
- wheelEvent.preventDefault();
- this.setScroll(dominantDelta * deltaModeMultiplier);
- };
+ private _startLongPress(downEvent: MouseEvent, activeSlideItemElement: HTMLElement): void {
+ // Set a timer to delay dragging for 300 milliseconds
+ this._longPressTimer = setTimeout(() => {
+ if (!activeSlideItemElement || this._activeTabItem?.isEditMode()) return;
- this.addListener();
+ this._activeTabItem?.enableFixed();
+ this._startAutoScroll();
+ // Set the mouse cursor to drag
+ activeSlideItemElement.setPointerCapture((downEvent as PointerEvent).pointerId);
+ activeSlideItemElement.style.cursor = 'move';
+ this._activeTabItem?.addEventListener('pointermove', this._moveAction);
+ }, SlideTabBar.LongPressDelay);
}
static checkedSkipSlide(event: MouseEvent): boolean {