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(sheets-hyper-link-ui): show popup on rotate cell (#3943)
zhangwce16b4103efd
diff --git a/packages/design/src/components/popup/index.module.less b/packages/design/src/components/popup/index.module.lessindex f5fba0f94d..aa495d1780 100644--- a/packages/design/src/components/popup/index.module.less+++ b/packages/design/src/components/popup/index.module.less@@ -1,10 +1,3 @@-.popup-fixed {- position: fixed;- z-index: 1000;- top: -9999px;- left: -9999px;-}-.popup {position: fixed;z-index: 1070;diff --git a/packages/design/src/components/popup/index.ts b/packages/design/src/components/popup/index.tsindex 32976a2ba1..9ad882bc4d 100644--- a/packages/design/src/components/popup/index.ts+++ b/packages/design/src/components/popup/index.ts@@ -15,4 +15,3 @@*/export { type IPopupProps, Popup } from './Popup';-export { RectPopup, type IRectPopupProps } from './RectPopup';diff --git a/packages/design/src/index.ts b/packages/design/src/index.tsindex 6b26a2d547..fee70cff9c 100644--- a/packages/design/src/index.ts+++ b/packages/design/src/index.ts@@ -46,7 +46,7 @@ export { type IInputNumberProps, InputNumber } from './components/input-number';export { Menu, MenuItem, MenuItemGroup, type MenuRef, SubMenu } from './components/menu';export { type IMessageOptions, type IMessageProps, Message, MessageType } from './components/message';export { type IPagerProps, Pager } from './components/pager';-export { type IPopupProps, type IRectPopupProps, Popup, RectPopup } from './components/popup';+export { type IPopupProps, Popup } from './components/popup';export { type IRadioProps, Radio } from './components/radio';export { type IRadioGroupProps, RadioGroup } from './components/radio-group';export { type IScrollbarProps, Scrollbar } from './components/scrollbar';diff --git a/packages/docs-ui/src/commands/commands/break-line.command.ts b/packages/docs-ui/src/commands/commands/break-line.command.tsindex 8108fcf600..590929e70c 100644--- a/packages/docs-ui/src/commands/commands/break-line.command.ts+++ b/packages/docs-ui/src/commands/commands/break-line.command.ts@@ -63,7 +63,6 @@ export const BreakLineCommand: ICommand = {const univerInstanceService = accessor.get(IUniverInstanceService);const commandService = accessor.get(ICommandService);const docMenuStyleService = accessor.get(DocMenuStyleService);-const activeTextRange = docSelectionManagerService.getActiveTextRange();const rectRanges = docSelectionManagerService.getRectRanges();if (activeTextRange == null) {diff --git a/packages/docs-ui/src/commands/commands/clipboard.inner.command.ts b/packages/docs-ui/src/commands/commands/clipboard.inner.command.tsindex a09a162322..b13844bc9e 100644--- a/packages/docs-ui/src/commands/commands/clipboard.inner.command.ts+++ b/packages/docs-ui/src/commands/commands/clipboard.inner.command.ts@@ -194,14 +194,14 @@ export const InnerPasteCommand: ICommand<IInnerPasteCommandParams> = {cloneBody.customRanges = [{...customRange,startIndex: 0,- endIndex: body.dataStream.length,+ endIndex: body.dataStream.length - 1,}];}if (customDecorations.length) {cloneBody.customDecorations = customDecorations.map((customDecoration) => ({...customDecoration,startIndex: 0,- endIndex: body.dataStream.length,+ endIndex: body.dataStream.length - 1,}));}if (collapsed) {diff --git a/packages/docs-ui/src/commands/commands/ime-input.command.ts b/packages/docs-ui/src/commands/commands/ime-input.command.tsindex da1b60e0bc..54c9ec1506 100644--- a/packages/docs-ui/src/commands/commands/ime-input.command.ts+++ b/packages/docs-ui/src/commands/commands/ime-input.command.ts@@ -141,13 +141,13 @@ export const IMEInputCommand: ICommand<IIMEInputCommandParams> = {? [{...curCustomRange,startIndex: 0,- endIndex: newText.length,+ endIndex: newText.length - 1,}]: [],customDecorations: customDecorations.map((customDecoration) => ({...customDecoration,startIndex: 0,- endIndex: newText.length,+ endIndex: newText.length - 1,})),},len: newText.length,diff --git a/packages/docs-ui/src/controllers/render-controllers/doc-input.controller.ts b/packages/docs-ui/src/controllers/render-controllers/doc-input.controller.tsindex 2113daf30e..fcd1c0ec65 100644--- a/packages/docs-ui/src/controllers/render-controllers/doc-input.controller.ts+++ b/packages/docs-ui/src/controllers/render-controllers/doc-input.controller.ts@@ -97,13 +97,13 @@ export class DocInputController extends Disposable implements IRenderModule {? [{...curCustomRange,startIndex: 0,- endIndex: content.length,+ endIndex: content.length - 1,}]: [],customDecorations: curCustomDecorations.map((customDecoration) => ({...customDecoration,startIndex: 0,- endIndex: content.length,+ endIndex: content.length - 1,})),},range: activeRange,diff --git a/packages/docs-ui/src/services/clipboard/clipboard.service.ts b/packages/docs-ui/src/services/clipboard/clipboard.service.tsindex f01967ee6d..0ef15d023b 100644--- a/packages/docs-ui/src/services/clipboard/clipboard.service.ts+++ b/packages/docs-ui/src/services/clipboard/clipboard.service.ts@@ -140,7 +140,6 @@ export class DocClipboardService extends Disposable implements IDocClipboardServpartDocData.body!.textRuns = [];}}-return this._paste(partDocData);}diff --git a/packages/sheets-data-validation-ui/src/views/components/list-dropdown/index.tsx b/packages/sheets-data-validation-ui/src/views/components/list-dropdown/index.tsxindex 8b594a6b50..b97089f03b 100644--- a/packages/sheets-data-validation-ui/src/views/components/list-dropdown/index.tsx+++ b/packages/sheets-data-validation-ui/src/views/components/list-dropdown/index.tsx@@ -23,14 +23,14 @@ import type { IUniverSheetsDataValidationUIConfig } from '../../../controllers/cimport type { IDropdownComponentProps } from '../../../services/dropdown-manager.service';import { BuildTextUtils, DataValidationRenderMode, DataValidationType, ICommandService, IConfigService, IUniverInstanceService, LocaleService, UniverInstanceType, useDependency } from '@univerjs/core';import { DataValidationModel } from '@univerjs/data-validation';-import { RectPopup, Scrollbar } from '@univerjs/design';+import { Scrollbar } from '@univerjs/design';import { RichTextEditingMutation } from '@univerjs/docs';import { DeviceInputEventType } from '@univerjs/engine-render';import { CheckMarkSingle } from '@univerjs/icons';import { RangeProtectionPermissionEditPoint, SetRangeValuesCommand, WorkbookEditablePermission, WorksheetEditPermission } from '@univerjs/sheets';import { deserializeListOptions, getDataValidationCellValue, serializeListOptions } from '@univerjs/sheets-data-validation';import { IEditorBridgeService, SetCellEditVisibleOperation, SheetPermissionInterceptorBaseController } from '@univerjs/sheets-ui';-import { KeyCode, useObservable } from '@univerjs/ui';+import { KeyCode, RectPopup, useObservable } from '@univerjs/ui';import React, { useEffect, useMemo, useState } from 'react';import { debounceTime } from 'rxjs';import { OpenValidationPanelOperation } from '../../../commands/operations/data-validation.operation';@@ -147,7 +147,7 @@ export function ListDropDown(props: IDropdownComponentProps) {const ruleChange$ = useMemo(() => dataValidationModel.ruleChange$.pipe(debounceTime(16)), []);useObservable(ruleChange$);const anchorRect = RectPopup.useContext();- const cellWidth = anchorRect.right - anchorRect.left;+ const cellWidth = (anchorRect.current?.right ?? 0) - (anchorRect.current?.left ?? 0);useEffect(() => {const dispose = commandService.onCommandExecuted((command) => {diff --git a/packages/sheets-hyper-link-ui/src/controllers/popup.controller.ts b/packages/sheets-hyper-link-ui/src/controllers/popup.controller.tsindex 110b69d316..5c448bc814 100644--- a/packages/sheets-hyper-link-ui/src/controllers/popup.controller.ts+++ b/packages/sheets-hyper-link-ui/src/controllers/popup.controller.ts@@ -104,12 +104,16 @@ export class SheetsHyperLinkPopupController extends Disposable {this._sheetsHyperLinkPopupService.hideCurrentPopup();return;}-const { unitId, subUnitId, row, col } = currentCell;const renderer = this._renderManagerService.getRenderById(unitId);if (!renderer) {return;}+ const workbook = this._univerInstanceService.getUnit<Workbook>(unitId, UniverInstanceType.UNIVER_SHEET);+ const worksheet = workbook?.getSheetBySheetId(subUnitId);+ if (!worksheet) {+ return;+ }const hoverRenderController = renderer.with(HoverRenderController);if (!hoverRenderController.active) {this._sheetsHyperLinkPopupService.hideCurrentPopup(HyperLinkEditSourceType.VIEWING);@@ -136,7 +140,14 @@ export class SheetsHyperLinkPopupController extends Disposable {const { viewPermission, editPermission, copyPermission } = this._getLinkPermission(currentCell);- if (!viewPermission || !currentCell.customRange) {+ if (!viewPermission) {+ this._sheetsHyperLinkPopupService.hideCurrentPopup();+ return;+ }+ const cell = worksheet.getCellStyleOnly(targetRow, targetCol);+ const style = workbook!.getStyles().getStyleByCell(cell);+ const tr = style?.tr;+ if (!tr && !currentCell.customRange) {this._sheetsHyperLinkPopupService.hideCurrentPopup();return;}@@ -151,6 +162,7 @@ export class SheetsHyperLinkPopupController extends Disposable {type: HyperLinkEditSourceType.VIEWING,unitId,subUnitId,+ showAll: Boolean(tr),});}));diff --git a/packages/sheets-hyper-link-ui/src/services/popup.service.ts b/packages/sheets-hyper-link-ui/src/services/popup.service.tsindex a0b60074c3..8c5a4aa80a 100644--- a/packages/sheets-hyper-link-ui/src/services/popup.service.ts+++ b/packages/sheets-hyper-link-ui/src/services/popup.service.ts@@ -20,7 +20,7 @@ import type { ISheetLocationBase } from '@univerjs/sheets';import type { ICanvasPopup } from '@univerjs/sheets-ui';import { BuildTextUtils, CustomRangeType, Disposable, DOCS_ZEN_EDITOR_UNIT_ID_KEY, Inject, Injector, IUniverInstanceService, UniverInstanceType } from '@univerjs/core';import { DocSelectionManagerService } from '@univerjs/docs';-import { DocCanvasPopManagerService, IEditorService, IRangeSelectorService } from '@univerjs/docs-ui';+import { DocCanvasPopManagerService } from '@univerjs/docs-ui';import { getCustomRangePosition, getEditingCustomRangePosition, IEditorBridgeService, SheetCanvasPopManagerService } from '@univerjs/sheets-ui';import { IZenZoneService } from '@univerjs/ui';import { BehaviorSubject, Subject } from 'rxjs';@@ -36,8 +36,9 @@ export interface IHyperLinkPopup {col: number;editPermission?: boolean;copyPermission?: boolean;- customRange?: ICustomRange;+ customRange?: Nullable<ICustomRange>;type: HyperLinkEditSourceType;+ showAll?: boolean;}interface IHyperLinkEditing {@@ -65,6 +66,7 @@ interface IHyperLinkPopupOptions extends ISheetLocationBase {copyPermission?: boolean;customRange?: Nullable<ICustomRange>;customRangeRect?: Nullable<IBoundRectNoAngle>;+ showAll?: boolean;type: HyperLinkEditSourceType;}@@ -94,8 +96,6 @@ export class SheetsHyperLinkPopupService extends Disposable {@IEditorBridgeService private readonly _editorBridgeService: IEditorBridgeService,@Inject(DocSelectionManagerService) private readonly _textSelectionManagerService: DocSelectionManagerService,@Inject(DocCanvasPopManagerService) private readonly _docCanvasPopManagerService: DocCanvasPopManagerService,- @IEditorService private readonly _editorService: IEditorService,- @IRangeSelectorService private readonly _rangeSelectorService: IRangeSelectorService,@IZenZoneService private readonly _zenZoneService: IZenZoneService) {super();@@ -132,9 +132,6 @@ export class SheetsHyperLinkPopupService extends Disposable {}const { unitId, subUnitId, row, col, customRangeRect, customRange } = location;- if (!customRange) {- return;- }let disposable: Nullable<INeedCheckDisposable>;const popup: ICanvasPopup = {componentKey: CellLinkPopup.componentKey,@@ -147,11 +144,17 @@ export class SheetsHyperLinkPopupService extends Disposable {},};if (location.type === HyperLinkEditSourceType.EDITING) {+ if (!customRange) {+ return;+ }disposable = customRangeRect && this._sheetCanvasPopManagerService.attachPopupToAbsolutePosition(customRangeRect,popup);} else if (location.type === HyperLinkEditSourceType.ZEN_EDITOR) {+ if (!customRange) {+ return;+ }disposable = this._docCanvasPopManagerService.attachPopupToRange({startOffset: customRange.startIndex,@@ -162,10 +165,19 @@ export class SheetsHyperLinkPopupService extends Disposable {DOCS_ZEN_EDITOR_UNIT_ID_KEY);} else {- disposable = customRangeRect && this._sheetCanvasPopManagerService.attachPopupByPosition(- customRangeRect,- popup- );+ if (location.showAll) {+ disposable = this._sheetCanvasPopManagerService.attachPopupToCell(location.row, location.col, popup, unitId, subUnitId);+ } else {+ if (!customRange) {+ return;+ }++ disposable = customRangeRect && this._sheetCanvasPopManagerService.attachPopupByPosition(+ customRangeRect,+ popup,+ location+ );+ }}if (disposable) {@@ -179,6 +191,7 @@ export class SheetsHyperLinkPopupService extends Disposable {copyPermission: !!location.copyPermission,customRange,type: location.type,+ showAll: location.showAll,};this._currentPopup$.next(this._currentPopup);}@@ -307,6 +320,7 @@ export class SheetsHyperLinkPopupService extends Disposable {}}+ // eslint-disable-next-line complexity, max-lines-per-functionstartEditing(link: Required<IHyperLinkEditing>) {this._currentEditingPopup?.dispose();this.hideCurrentPopup(undefined, true);@@ -356,18 +370,38 @@ export class SheetsHyperLinkPopupService extends Disposable {subUnitId);} else {+ const workbook = this._univerInstanceService.getUnit<Workbook>(unitId, UniverInstanceType.UNIVER_SHEET);+ const worksheet = workbook?.getSheetBySheetId(subUnitId);+ const cell = worksheet?.getCellRaw(link.row, link.col);+ const style = workbook?.getStyles().getStyleByCell(cell);+ const tr = style?.tr;+const customRangeInfo = getCustomRangePosition(this._injector, link.unitId, link.subUnitId, link.row, link.col, link.customRangeId);if (!customRangeInfo || !customRangeInfo.rects?.length) {return;}customRange = customRangeInfo.customRange;label = customRangeInfo.label;- this._currentEditingPopup = this._sheetCanvasPopManagerService.attachPopupByPosition(- customRangeInfo.rects.pop()!,- this._editPopup,- unitId,- subUnitId- );+ if (tr) {+ this._currentEditingPopup = this._sheetCanvasPopManagerService.attachPopupToCell(+ link.row,+ link.col,+ this._editPopup,+ unitId,+ subUnitId+ );+ } else {+ this._currentEditingPopup = this._sheetCanvasPopManagerService.attachPopupByPosition(+ customRangeInfo.rects.pop()!,+ this._editPopup,+ {+ unitId,+ subUnitId,+ row: link.row,+ col: link.col,+ }+ );+ }}this._currentEditing$.next({...link,diff --git a/packages/sheets-hyper-link-ui/src/views/CellLinkPopup/index.module.less b/packages/sheets-hyper-link-ui/src/views/CellLinkPopup/index.module.lessindex 5a722a84ae..e355a810d5 100644--- a/packages/sheets-hyper-link-ui/src/views/CellLinkPopup/index.module.less+++ b/packages/sheets-hyper-link-ui/src/views/CellLinkPopup/index.module.less@@ -10,6 +10,7 @@background: rgb(var(--color-white));max-width: 328px;overflow: hidden;+ margin-bottom: var(--margin-xxs);}.cell-link-type {diff --git a/packages/sheets-hyper-link-ui/src/views/CellLinkPopup/index.tsx b/packages/sheets-hyper-link-ui/src/views/CellLinkPopup/index.tsxindex 9e88419cfb..d38de612fb 100644--- a/packages/sheets-hyper-link-ui/src/views/CellLinkPopup/index.tsx+++ b/packages/sheets-hyper-link-ui/src/views/CellLinkPopup/index.tsx@@ -14,8 +14,9 @@* limitations under the License.*/+import type { ICustomRange, Nullable, Workbook } from '@univerjs/core';import type { IHyperLinkPopup } from '../../services/popup.service';-import { DOCS_ZEN_EDITOR_UNIT_ID_KEY, ICommandService, LocaleService, useDependency, useObservable } from '@univerjs/core';+import { DOCS_ZEN_EDITOR_UNIT_ID_KEY, ICommandService, IUniverInstanceService, LocaleService, UniverInstanceType, useDependency } from '@univerjs/core';import { MessageType, Tooltip } from '@univerjs/design';import { AllBorderSingle, CopySingle, LinkSingle, UnlinkSingle, WriteSingle, Xlsx } from '@univerjs/icons';import { CancelHyperLinkCommand, CancelRichHyperLinkCommand, SheetHyperLinkType, SheetsHyperLinkParserService } from '@univerjs/sheets-hyper-link';@@ -37,33 +38,28 @@ const iconsMap = {[SheetHyperLinkType.INVALID]: <AllBorderSingle />,};-export const CellLinkPopup = () => {+interface ICellLinkPopupPureProps {+ customRange?: Nullable<ICustomRange>;+ row: number;+ col: number;+ unitId: string;+ subUnitId: string;+ editPermission?: boolean;+ copyPermission?: boolean;+ type: HyperLinkEditSourceType;+}++export const CellLinkPopupPure = (props: ICellLinkPopupPureProps) => {const popupService = useDependency(SheetsHyperLinkPopupService);const commandService = useDependency(ICommandService);const messageService = useDependency(IMessageService);const localeService = useDependency(LocaleService);- const [currentPopup, setCurrentPopup] = useState<IHyperLinkPopup | null>(null);const resolverService = useDependency(SheetsHyperLinkResolverService);const editorBridgeService = useDependency(IEditorBridgeService);const parserHyperLinkService = useDependency(SheetsHyperLinkParserService);const zenZoneService = useDependency(IZenZoneService);- const visible = useObservable(zenZoneService.visible$);+ const { customRange, row, col, unitId, subUnitId, editPermission, copyPermission, type } = props;- useEffect(() => {- setCurrentPopup(popupService.currentPopup);- const ob = popupService.currentPopup$.subscribe((popup) => {- setCurrentPopup(popup);- });- return () => {- ob.unsubscribe();- };- }, [popupService.currentPopup, popupService.currentPopup$]);-- if (!currentPopup) {- return null;- }-- const { unitId, subUnitId, customRange, row, col } = currentPopup;if (!customRange?.properties?.url) {return null;}@@ -94,7 +90,7 @@ export const CellLinkPopup = () => {</Tooltip></div><div className={styles.cellLinkOperations}>- {currentPopup.copyPermission && (+ {copyPermission && (<divclassName={cs(styles.cellLinkOperation, { [styles.cellLinkOperationError]: isError })}onClick={() => {@@ -120,7 +116,7 @@ export const CellLinkPopup = () => {</div>)}- {currentPopup.editPermission && (+ {editPermission && (<><divclassName={styles.cellLinkOperation}@@ -131,7 +127,7 @@ export const CellLinkPopup = () => {row,col,customRangeId: customRange.rangeId,- type: currentPopup.type,+ type,});}}>@@ -142,14 +138,14 @@ export const CellLinkPopup = () => {<divclassName={styles.cellLinkOperation}onClick={() => {- const commandId = (currentPopup.type === HyperLinkEditSourceType.EDITING || currentPopup.type === HyperLinkEditSourceType.ZEN_EDITOR) ? CancelRichHyperLinkCommand.id : CancelHyperLinkCommand.id;+ const commandId = (type === HyperLinkEditSourceType.EDITING || type === HyperLinkEditSourceType.ZEN_EDITOR) ? CancelRichHyperLinkCommand.id : CancelHyperLinkCommand.id;if (commandService.syncExecuteCommand(commandId, {unitId,subUnitId,id: customRange.rangeId,row,column: col,- documentId: currentPopup.type === HyperLinkEditSourceType.ZEN_EDITOR ?+ documentId: type === HyperLinkEditSourceType.ZEN_EDITOR ?DOCS_ZEN_EDITOR_UNIT_ID_KEY: editorBridgeService.getCurrentEditorId(),})) {@@ -168,4 +164,40 @@ export const CellLinkPopup = () => {);};+export const CellLinkPopup = () => {+ const popupService = useDependency(SheetsHyperLinkPopupService);+ const [currentPopup, setCurrentPopup] = useState<IHyperLinkPopup | null>(null);+ const univerInstanceService = useDependency(IUniverInstanceService);++ useEffect(() => {+ setCurrentPopup(popupService.currentPopup);+ const ob = popupService.currentPopup$.subscribe((popup) => {+ setCurrentPopup(popup);+ });+ return () => {+ ob.unsubscribe();+ };+ }, [popupService.currentPopup, popupService.currentPopup$]);++ if (!currentPopup) {+ return null;+ }+ if (currentPopup.showAll) {+ const workbook = univerInstanceService.getUnit<Workbook>(currentPopup.unitId, UniverInstanceType.UNIVER_SHEET);+ const worksheet = workbook?.getSheetBySheetId(currentPopup.subUnitId);+ const cell = worksheet?.getCell(currentPopup.row, currentPopup.col);+ const customRanges = cell?.p?.body?.customRanges;+ return customRanges?.length+ ? (+ <div>+ {customRanges.map((customRange) => {+ return <CellLinkPopupPure key={customRange.rangeId} {...currentPopup} customRange={customRange} />;+ })}+ </div>+ )+ : null;+ }+ return <CellLinkPopupPure {...currentPopup} />;+};+CellLinkPopup.componentKey = 'univer.sheet.cell-link-popup';diff --git a/packages/sheets-ui/src/common/utils.ts b/packages/sheets-ui/src/common/utils.tsindex 34a45bfab0..5192e190ac 100644--- a/packages/sheets-ui/src/common/utils.ts+++ b/packages/sheets-ui/src/common/utils.ts@@ -148,19 +148,19 @@ export function getViewportByCell(row: number, column: number, scene: Scene, worreturn scene.getViewport(SHEET_VIEWPORT_KEY.VIEW_MAIN);}- if (row > freeze.startRow && column > freeze.startColumn) {+ if (row >= freeze.startRow && column >= freeze.startColumn) {return scene.getViewport(SHEET_VIEWPORT_KEY.VIEW_MAIN);}- if (row <= freeze.startRow && column <= freeze.startColumn) {+ if (row < freeze.startRow && column < freeze.startColumn) {return scene.getViewport(SHEET_VIEWPORT_KEY.VIEW_MAIN_LEFT_TOP);}- if (row <= freeze.startRow && column > freeze.startColumn) {+ if (row < freeze.startRow && column >= freeze.startColumn) {return scene.getViewport(SHEET_VIEWPORT_KEY.VIEW_MAIN_TOP);}- if (row > freeze.startRow && column <= freeze.startColumn) {+ if (row >= freeze.startRow && column < freeze.startColumn) {return scene.getViewport(SHEET_VIEWPORT_KEY.VIEW_MAIN_LEFT);}}diff --git a/packages/sheets-ui/src/services/canvas-pop-manager.service.ts b/packages/sheets-ui/src/services/canvas-pop-manager.service.tsindex 64ea5592a7..e6bbbcb511 100644--- a/packages/sheets-ui/src/services/canvas-pop-manager.service.ts+++ b/packages/sheets-ui/src/services/canvas-pop-manager.service.ts@@ -16,11 +16,11 @@import type { INeedCheckDisposable, IRange, Nullable, Workbook, Worksheet } from '@univerjs/core';import type { BaseObject, IBoundRectNoAngle, IRender, SpreadsheetSkeleton, Viewport } from '@univerjs/engine-render';-import type { ISetWorksheetRowAutoHeightMutationParams } from '@univerjs/sheets';+import type { ISetWorksheetRowAutoHeightMutationParams, ISheetLocationBase } from '@univerjs/sheets';import type { IPopup } from '@univerjs/ui';import { Disposable, DisposableCollection, ICommandService, Inject, IUniverInstanceService, toDisposable, UniverInstanceType } from '@univerjs/core';import { IRenderManagerService } from '@univerjs/engine-render';-import { COMMAND_LISTENER_SKELETON_CHANGE, RefRangeService, SetWorksheetRowAutoHeightMutation } from '@univerjs/sheets';+import { COMMAND_LISTENER_SKELETON_CHANGE, RefRangeService, SetFrozenMutation, SetWorksheetRowAutoHeightMutation } from '@univerjs/sheets';import { ICanvasPopupService } from '@univerjs/ui';import { BehaviorSubject } from 'rxjs';import { SetScrollOperation } from '../commands/operations/scroll.operation';@@ -45,6 +45,84 @@ export class SheetCanvasPopManagerService extends Disposable {super();}+ private _createHiddenRectObserver(params: { row: number; column: number; worksheet: Worksheet; skeleton: SpreadsheetSkeleton; currentRender: IRender }) {+ const { row, column, worksheet, skeleton, currentRender } = params;+ const calc = () => {+ const freeze = worksheet.getFreeze();+ const { startRow: freezeStartRow, startColumn: freezeStartColumn, xSplit, ySplit } = freeze;+ const startRow = freezeStartRow - ySplit;+ const startColumn = freezeStartColumn - xSplit;+ const { rowHeightAccumulation, columnWidthAccumulation, rowHeaderWidth, columnHeaderHeight } = skeleton;+ const canvasFreezeWidth = rowHeaderWidth + (startColumn === -1 ? 0 : (columnWidthAccumulation[startColumn + xSplit - 1] - (columnWidthAccumulation[startColumn - 1] ?? 0)));+ const canvasFreezeHeight = columnHeaderHeight + (startRow === -1 ? 0 : (rowHeightAccumulation[startRow + ySplit - 1] - (rowHeightAccumulation[startRow] ?? 0)));+ const canvasElement = currentRender.engine.getCanvasElement();+ const canvasClientRect = canvasElement.getBoundingClientRect();++ // We should take the scale into account when canvas is scaled by CSS.+ const widthOfCanvas = pxToNum(canvasElement.style.width); // declared width+ // const { top, left, width } = canvasClientRect; // real width affected by scale+ const scaleAdjust = canvasClientRect.width / widthOfCanvas;+ const canvasScale = currentRender.scene.getAncestorScale().scaleX;++ const freezeWidth = canvasFreezeWidth * scaleAdjust * canvasScale;+ const freezeHeight = canvasFreezeHeight * scaleAdjust * canvasScale;+ const viewTopLeft = {+ left: -Infinity,+ top: -Infinity,+ right: canvasClientRect.left + freezeWidth,+ bottom: canvasClientRect.top + freezeHeight,+ };++ const viewTopRight = {+ left: canvasClientRect.left + freezeWidth,+ top: -Infinity,+ right: Infinity,+ bottom: canvasClientRect.top + freezeHeight,+ };++ const viewBottomLeft = {+ left: -Infinity,+ top: canvasClientRect.top + freezeHeight,+ right: canvasClientRect.left + freezeWidth,+ bottom: Infinity,+ };+ const position = [];+ if (row < freezeStartRow) {+ position.push(viewTopLeft);+ }+ if (column < freezeStartColumn) {+ position.push(viewBottomLeft);+ }+ if (row < freezeStartRow && column < freezeStartColumn) {+ return [];+ } else if (row < freezeStartRow) {+ return [viewTopLeft];+ } else if (column < freezeStartColumn) {+ return [viewTopLeft];+ } else {+ return [viewTopLeft, viewTopRight, viewBottomLeft];+ }+ };++ const rects = calc();++ const rects$ = new BehaviorSubject(rects);++ const disposable = new DisposableCollection();++ disposable.add(this._commandService.onCommandExecuted((commandInfo) => {+ if (commandInfo.id === SetFrozenMutation.id) {+ const newRects = calc();+ rects$.next(newRects);+ }+ }));++ return {+ rects$,+ disposable,+ };+ }+// #region attach to objectprivate _createPositionObserver(bound: IBoundRectNoAngle,@@ -154,7 +232,7 @@ export class SheetCanvasPopManagerService extends Disposable {// #endregion// #region attach to position- attachPopupByPosition(bound: IBoundRectNoAngle, popup: ICanvasPopup, _unitId?: string, _subUnitId?: string): Nullable<INeedCheckDisposable> {+ attachPopupByPosition(bound: IBoundRectNoAngle, popup: ICanvasPopup, location: ISheetLocationBase): Nullable<INeedCheckDisposable> {const workbook = this._univerInstanceService.getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET)!;const worksheet = workbook.getActiveSheet();if (!worksheet) {@@ -163,7 +241,7 @@ export class SheetCanvasPopManagerService extends Disposable {const unitId = workbook.getUnitId();const subUnitId = worksheet.getSheetId();- if ((_unitId && unitId !== _unitId) || (_subUnitId && _subUnitId !== subUnitId)) {+ if ((unitId !== location.unitId) || (location.subUnitId !== subUnitId)) {return null;}@@ -177,12 +255,20 @@ export class SheetCanvasPopManagerService extends Disposable {}const { position, position$, disposable } = this._createPositionObserver(bound, currentRender, skeleton, worksheet);+ const { rects$, disposable: rectsObserverDisposable } = this._createHiddenRectObserver({+ row: location.row,+ column: location.col,+ worksheet,+ skeleton,+ currentRender,+ });const id = this._globalPopupManagerService.addPopup({...popup,unitId,subUnitId,anchorRect: position,anchorRect$: position$,+ hiddenRects$: rects$,canvasElement: currentRender.engine.getCanvasElement(),});@@ -191,6 +277,7 @@ export class SheetCanvasPopManagerService extends Disposable {this._globalPopupManagerService.removePopup(id);position$.complete();disposable.dispose();+ rectsObserverDisposable.dispose();},canDispose: () => this._globalPopupManagerService.activePopupId !== id,};@@ -285,6 +372,13 @@ export class SheetCanvasPopManagerService extends Disposable {}const { position, position$, disposable: positionObserverDisposable, updateRowCol } = this._createCellPositionObserver(row, col, currentRender, skeleton, activeViewport);+ const { rects$, disposable: rectsObserverDisposable } = this._createHiddenRectObserver({+ row,+ column: col,+ worksheet,+ skeleton,+ currentRender,+ });const id = this._globalPopupManagerService.addPopup({...popup,unitId,@@ -292,6 +386,7 @@ export class SheetCanvasPopManagerService extends Disposable {anchorRect: position,anchorRect$: position$,canvasElement: currentRender.engine.getCanvasElement(),+ hiddenRects$: rects$,});const disposableCollection = new DisposableCollection();@@ -300,6 +395,7 @@ export class SheetCanvasPopManagerService extends Disposable {this._globalPopupManagerService.removePopup(id);position$.complete();}));+ disposableCollection.add(rectsObserverDisposable);// If the range changes, the popup should change with it. And if the range vanished, the popup should be removed.const watchedRange: IRange = { startRow: row, endRow: row, startColumn: col, endColumn: col };diff --git a/packages/ui/src/components/hooks/observable.ts b/packages/ui/src/components/hooks/observable.tsindex 3a70200e1f..38b1a9df04 100644--- a/packages/ui/src/components/hooks/observable.ts+++ b/packages/ui/src/components/hooks/observable.ts@@ -16,9 +16,10 @@/* eslint-disable ts/no-explicit-any */-import { useEffect, useMemo, useRef, useState } from 'react';import type { Nullable } from '@univerjs/core';+import type { RefObject } from 'react';import type { Observable, Subscription } from 'rxjs';+import { useEffect, useMemo, useRef, useState } from 'react';type ObservableOrFn<T> = Observable<T> | (() => Observable<T>);@@ -92,3 +93,19 @@ export function useObservable<T>(observable: Nullable<ObservableOrFn<T>>, defaulreturn valueRef.current;}++export function useObservableRef<T>(observable: Nullable<ObservableOrFn<T>>, defaultValue?: T): RefObject<Nullable<T>> {+ const ref = useRef<Nullable<T>>(defaultValue);++ useEffect(() => {+ if (observable) {+ const sub = unwrap(observable).subscribe((value) => {+ ref.current = value;+ });++ return () => sub.unsubscribe();+ }+ }, [observable]);++ return ref;+}diff --git a/packages/ui/src/index.ts b/packages/ui/src/index.tsindex 5e9f54b034..8839e32724 100644--- a/packages/ui/src/index.ts+++ b/packages/ui/src/index.ts@@ -20,7 +20,8 @@ export { mergeMenuConfigs } from './common/menu-merge-configs';export * from './components';export { useEvent } from './components/hooks/event';export { t } from './components/hooks/locale';-export { useObservable } from './components/hooks/observable';+export { useObservable, useObservableRef } from './components/hooks/observable';+export { RectPopup } from './views/components/popup/RectPopup';export { useVirtualList } from './components/hooks/virtual-list';export { Menu } from './components/menu/desktop/Menu';export { type INotificationOptions, type NotificationType } from './components/notification/Notification';diff --git a/packages/ui/src/services/popup/canvas-popup.service.ts b/packages/ui/src/services/popup/canvas-popup.service.tsindex 42fb7e011a..60813ac340 100644--- a/packages/ui/src/services/popup/canvas-popup.service.ts+++ b/packages/ui/src/services/popup/canvas-popup.service.ts@@ -15,15 +15,17 @@*/import type { Nullable } from '@univerjs/core';-import type { IRectPopupProps } from '@univerjs/design';import type { IBoundRectNoAngle } from '@univerjs/engine-render';import type { Observable } from 'rxjs';+import type { IRectPopupProps } from '../../views/components/popup/RectPopup';import { createIdentifier, Disposable, Tools } from '@univerjs/core';import { BehaviorSubject } from 'rxjs';-export interface IPopup extends Omit<IRectPopupProps, 'children' | 'hidden'> {+export interface IPopup extends Omit<IRectPopupProps, 'children' | 'hidden' | 'excludeRects' | 'anchorRect$'> {anchorRect$: Observable<IBoundRectNoAngle>;+ anchorRect?: IBoundRectNoAngle;excludeRects$?: Observable<IBoundRectNoAngle[]>;+ excludeRects?: Nullable<IBoundRectNoAngle[]>;componentKey: string;unitId: string;@@ -33,6 +35,8 @@ export interface IPopup extends Omit<IRectPopupProps, 'children' | 'hidden'> {canvasElement: HTMLCanvasElement;hideOnInvisible?: boolean;hiddenType?: 'hide' | 'destroy';+ hiddenRects$?: Observable<IBoundRectNoAngle[]>;+}export interface ICanvasPopupService {diff --git a/packages/ui/src/views/components/popup/CanvasPopup.tsx b/packages/ui/src/views/components/popup/CanvasPopup.tsxindex 1085ea156e..acc999544a 100644--- a/packages/ui/src/views/components/popup/CanvasPopup.tsx+++ b/packages/ui/src/views/components/popup/CanvasPopup.tsx@@ -16,12 +16,12 @@import type { IPopup } from '../../../services/popup/canvas-popup.service';import { useDependency } from '@univerjs/core';-import { RectPopup } from '@univerjs/design';import React, { useEffect, useMemo, useState } from 'react';-import { animationFrameScheduler, throttleTime } from 'rxjs';+import { animationFrameScheduler, combineLatest, map, of, throttleTime } from 'rxjs';import { ComponentManager } from '../../../common';-import { useObservable } from '../../../components/hooks/observable';+import { useObservable, useObservableRef } from '../../../components/hooks/observable';import { ICanvasPopupService } from '../../../services/popup/canvas-popup.service';+import { RectPopup } from './RectPopup';interface ISingleCanvasPopupProps {popup: IPopup;@@ -30,53 +30,64 @@ interface ISingleCanvasPopupProps {const SingleCanvasPopup = ({ popup, children }: ISingleCanvasPopupProps) => {const [hidden, setHidden] = useState(false);- const anchorRect$ = useMemo(() => popup.anchorRect$.pipe(throttleTime(0, animationFrameScheduler)), [popup.anchorRect$]);+ const anchorRect$ = useMemo(() => popup.anchorRect$.pipe(+ throttleTime(0, animationFrameScheduler),+ map((anchorRect) => {+ const { bottom, left, right, top } = anchorRect;+ const [x = 0, y = 0] = popup.offset ?? [];+ return {+ left: left - x,+ right: right + x,+ top: top - y,+ bottom: bottom + y,+ };+ })+ ), [popup.anchorRect$, popup.offset]);+ const hiddenRects$ = useMemo(() => popup.hiddenRects$?.pipe(throttleTime(0, animationFrameScheduler)) ?? of([]), [popup.hiddenRects$]);const excludeRects$ = useMemo(() => popup.excludeRects$?.pipe(throttleTime(0, animationFrameScheduler)), [popup.excludeRects$]);- const anchorRect = useObservable(anchorRect$, popup.anchorRect);- const excludeRects = useObservable(excludeRects$, popup.excludeRects);- const { offset, canvasElement, hideOnInvisible = true, hiddenType = 'destroy' } = popup;-- // We add an offset to the anchor rect to make the popup offset with the anchor.- const rectWithOffset = useMemo(() => {- if (!anchorRect) {- return null;- }-- const { bottom, left, right, top } = anchorRect;- const [x = 0, y = 0] = offset ?? [];- return {- left: left - x,- right: right + x,- top: top - y,- bottom: bottom + y,- };- }, [anchorRect, offset]);+ const excludeRectsRef = useObservableRef(excludeRects$, popup.excludeRects);+ const { canvasElement, hideOnInvisible = true, hiddenType = 'destroy' } = popup;useEffect(() => {- if (!hideOnInvisible || !rectWithOffset) {+ if (!hideOnInvisible) {return;}- const rect = canvasElement.getBoundingClientRect();- const { top, left, bottom, right } = rect;- if (rectWithOffset.bottom < top || rectWithOffset.top > bottom || rectWithOffset.right < left || rectWithOffset.left > right) {- setHidden(true);- } else {- setHidden(false);- }- }, [rectWithOffset, canvasElement, hideOnInvisible]);- if ((hidden && hiddenType === 'destroy') || !rectWithOffset) {+ const anchorRectSub = combineLatest([anchorRect$, hiddenRects$]).subscribe(([rectWithOffset, hiddenRects]) => {+ const rect = canvasElement.getBoundingClientRect();+ const { top, left, bottom, right } = rect;+ const rectHeight = rectWithOffset.bottom - rectWithOffset.top;+ const rectWidth = rectWithOffset.right - rectWithOffset.left;++ const isInHiddenRect = hiddenRects.some((hiddenRect) => {+ return rectWithOffset.top >= (hiddenRect.top - (0.5 * rectHeight)) &&+ rectWithOffset.bottom <= (hiddenRect.bottom + (0.5 * rectHeight)) &&+ rectWithOffset.left >= (hiddenRect.left - (0.5 * rectWidth)) &&+ rectWithOffset.right <= (hiddenRect.right + (0.5 * rectWidth));+ });++ if (rectWithOffset.bottom < top || rectWithOffset.top > bottom || rectWithOffset.right < left || rectWithOffset.left > right || isInHiddenRect) {+ setHidden(true);+ } else {+ setHidden(false);+ }+ });++ return () => anchorRectSub.unsubscribe();+ }, [canvasElement, hideOnInvisible, anchorRect$, hiddenRects$]);++ if ((hidden && hiddenType === 'destroy')) {return null;}return (<RectPopuphidden={hidden}- anchorRect={rectWithOffset}+ anchorRect$={anchorRect$}direction={popup.direction}onClickOutside={popup.onClickOutside}excludeOutside={popup.excludeOutside}- excludeRects={excludeRects}+ excludeRects={excludeRectsRef}onPointerEnter={popup.onPointerEnter}onPointerLeave={popup.onPointerLeave}onClick={popup.onClick}diff --git a/packages/design/src/components/popup/RectPopup.tsx b/packages/ui/src/views/components/popup/RectPopup.tsxsimilarity index 73%rename from packages/design/src/components/popup/RectPopup.tsxrename to packages/ui/src/views/components/popup/RectPopup.tsxindex d8b0eec513..0ed557b97c 100644--- a/packages/design/src/components/popup/RectPopup.tsx+++ b/packages/ui/src/views/components/popup/RectPopup.tsx@@ -14,8 +14,11 @@* limitations under the License.*/+import type { Nullable } from '@univerjs/core';+import type { RefObject } from 'react';+import type { Observable } from 'rxjs';import { useEvent } from 'rc-util';-import React, { createContext, useContext, useEffect, useMemo, useRef, useState } from 'react';+import React, { createContext, useContext, useEffect, useRef } from 'react';import styles from './index.module.less';interface IAbsolutePosition {@@ -25,7 +28,7 @@ interface IAbsolutePosition {bottom: number;}-const RectPopupContext = createContext({ top: 0, bottom: 0, left: 0, right: 0 });+const RectPopupContext = createContext<RefObject<IAbsolutePosition | undefined>>({ current: undefined });export interface IRectPopupProps {children?: React.ReactNode;@@ -33,8 +36,8 @@ export interface IRectPopupProps {/*** the anchor element bounding rect*/- anchorRect: IAbsolutePosition;- excludeRects?: IAbsolutePosition[];+ anchorRect$: Observable<IAbsolutePosition>;+ excludeRects?: RefObject<Nullable<IAbsolutePosition[]>>;direction?: 'vertical' | 'horizontal' | 'left' | 'top' | 'right' | 'left' | 'bottom' | 'bottom-center' | 'top-center';hidden?: boolean;@@ -103,46 +106,47 @@ function calcPopupPosition(layout: IPopupLayoutInfo): { top: number; left: numbe};function RectPopup(props: IRectPopupProps) {- const { children, anchorRect, direction = 'vertical', onClickOutside, excludeOutside, excludeRects, onPointerEnter, onPointerLeave, onClick, hidden, onContextMenu } = props;+ const { children, anchorRect$, direction = 'vertical', onClickOutside, excludeOutside, excludeRects, onPointerEnter, onPointerLeave, onClick, hidden, onContextMenu } = props;const nodeRef = useRef<HTMLElement>(null);const clickOtherFn = useEvent(onClickOutside ?? (() => { /* empty */ }));const contextMenuFn = useEvent(onContextMenu ?? (() => { /* empty */ }));- const [position, setPosition] = useState<Partial<IAbsolutePosition>>({+ const positionRef = useRef<Partial<IAbsolutePosition>>({top: -9999,left: -9999,});- const excludeRectsRef = useRef(excludeRects);- excludeRectsRef.current = excludeRects;+ const excludeRectsRef = excludeRects;+ const anchorRectRef = useRef<IAbsolutePosition>();- const style = useMemo(() => ({ ...position }), [position]);useEffect(() => {- requestAnimationFrame(() => {- if (!nodeRef.current) return;-- const { clientWidth, clientHeight } = nodeRef.current;- const innerWidth = window.innerWidth;- const innerHeight = window.innerHeight;-- setPosition(calcPopupPosition(- {- position: anchorRect,- width: clientWidth,- height: clientHeight,- containerWidth: innerWidth,- containerHeight: innerHeight,- direction,- }- ));+ const anchorRectSub = anchorRect$.subscribe((anchorRect) => {+ anchorRectRef.current = anchorRect;+ requestAnimationFrame(() => {+ if (!nodeRef.current) return;++ const { clientWidth, clientHeight } = nodeRef.current;+ const innerWidth = window.innerWidth;+ const innerHeight = window.innerHeight;++ positionRef.current = calcPopupPosition(+ {+ position: anchorRect,+ width: clientWidth,+ height: clientHeight,+ containerWidth: innerWidth,+ containerHeight: innerHeight,+ direction,+ }+ );+ nodeRef.current.style.top = `${positionRef.current.top}px`;+ nodeRef.current.style.left = `${positionRef.current.left}px`;+ });});++ return () => anchorRectSub.unsubscribe();},- // eslint-disable-next-line react-hooks/exhaustive-deps- [- anchorRect.left,- anchorRect.top,- anchorRect.bottom,- anchorRect.right,- direction,- ]);++ [anchorRect$, direction]+ );useEffect(() => {const handleClickOther = (e: MouseEvent) => {@@ -158,7 +162,10 @@ function RectPopup(props: IRectPopupProps) {}const x = e.clientX;const y = e.clientY;- const rects = [anchorRect, ...excludeRectsRef.current ?? []];+ const rects = [...excludeRectsRef?.current ?? []];+ if (anchorRectRef.current) {+ rects.push(anchorRectRef.current);+ }for (const rect of rects) {if (x <= rect.right && x >= rect.left && y <= rect.bottom && y >= rect.top) {return;@@ -171,7 +178,7 @@ function RectPopup(props: IRectPopupProps) {return () => {window.removeEventListener('pointerdown', handleClickOther);};- }, [anchorRect, anchorRect.bottom, anchorRect.left, anchorRect.right, anchorRect.top, clickOtherFn, excludeOutside]);+ }, [clickOtherFn, excludeOutside, excludeRectsRef]);useEffect(() => {const handleContextMenu = (e: MouseEvent) => {@@ -191,12 +198,12 @@ function RectPopup(props: IRectPopupProps) {onPointerEnter={onPointerEnter}onPointerLeave={onPointerLeave}ref={nodeRef}- style={{ ...style, ...hidden ? { display: 'none' } : null }}+ style={{ ...positionRef.current, ...hidden ? { display: 'none' } : null }}className={styles.popupFixed}onPointerDown={(e) => e.stopPropagation()}onClick={onClick}>- <RectPopupContext.Provider value={anchorRect}>+ <RectPopupContext.Provider value={anchorRectRef}>{children}</RectPopupContext.Provider></section>diff --git a/packages/ui/src/views/components/popup/index.module.less b/packages/ui/src/views/components/popup/index.module.lessnew file mode 100644index 0000000000..d1ad720237--- /dev/null+++ b/packages/ui/src/views/components/popup/index.module.less@@ -0,0 +1,6 @@+.popup-fixed {+ position: fixed;+ z-index: 1000;+ top: -9999px;+ left: -9999px;+}