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: auto complete2 (#4489)

lumix45bc9362ac8e
diff --git a/packages-experimental/debugger/src/commands/commands/float-dom.command.ts b/packages-experimental/debugger/src/commands/commands/float-dom.command.ts
index e360e649ad..a913949120 100644
--- a/packages-experimental/debugger/src/commands/commands/float-dom.command.ts
+++ b/packages-experimental/debugger/src/commands/commands/float-dom.command.ts
@@ -14,9 +14,9 @@
* limitations under the License.
*/
+import type { ICommand } from '@univerjs/core';
import { CommandType } from '@univerjs/core';
import { SheetCanvasFloatDomManagerService } from '@univerjs/sheets-drawing-ui';
-import type { ICommand } from '@univerjs/core';
export const CreateFloatDomCommand: ICommand = {
id: 'debugger.command.create-float-dom',
diff --git a/packages-experimental/debugger/src/components/float-button.tsx b/packages-experimental/debugger/src/components/float-button.tsx
new file mode 100644
index 0000000000..bbac223ed8
--- /dev/null
+++ b/packages-experimental/debugger/src/components/float-button.tsx
@@ -0,0 +1,38 @@
+/**
+ * Copyright 2023-present DreamNum Inc.
+ *
+ * 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 React from 'react';
+
+export const FloatButton = () => {
+ const divStyle = {
+ width: '100px',
+ height: '30px',
+ backgroundColor: '#fff',
+ border: '1px solid #ccc',
+ display: 'flex',
+ justifyContent: 'center',
+ alignItems: 'center',
+ textAlign: 'center' as const,
+ };
+ const clickHandler = () => {
+ console.warn('click');
+ };
+ return (
+ <div style={divStyle} onClick={clickHandler}>
+ FloatButton
+ </div>
+ );
+};
diff --git a/packages-experimental/debugger/src/components/range-loading.tsx b/packages-experimental/debugger/src/components/range-loading.tsx
new file mode 100644
index 0000000000..47874c1cb0
--- /dev/null
+++ b/packages-experimental/debugger/src/components/range-loading.tsx
@@ -0,0 +1,36 @@
+/**
+ * Copyright 2023-present DreamNum Inc.
+ *
+ * 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 React from 'react';
+
+export const RangeLoading = () => {
+ const divStyle = {
+ width: '100%',
+ height: '100%',
+ backgroundColor: '#fff',
+ border: '1px solid #ccc',
+ display: 'flex',
+ justifyContent: 'center',
+ alignItems: 'center',
+ textAlign: 'center' as const,
+ };
+
+ return (
+ <div style={divStyle}>
+ Loading...
+ </div>
+ );
+};
diff --git a/packages-experimental/debugger/src/controllers/debugger.controller.ts b/packages-experimental/debugger/src/controllers/debugger.controller.ts
index 2c609b4c81..56749569a3 100644
--- a/packages-experimental/debugger/src/controllers/debugger.controller.ts
+++ b/packages-experimental/debugger/src/controllers/debugger.controller.ts
@@ -34,6 +34,8 @@ import { SidebarOperation } from '../commands/operations/sidebar.operation';
import { ThemeOperation } from '../commands/operations/theme.operation';
import { ImageDemo } from '../components/Image';
+import { RangeLoading } from '../components/range-loading';
+import { FloatButton } from '../components/float-button';
// @ts-ignore
import VueI18nIcon from '../components/VueI18nIcon.vue';
// import { TEST_EDITOR_CONTAINER_COMPONENT } from '../views/test-editor/component-name';
@@ -88,5 +90,7 @@ export class DebuggerController extends Disposable {
framework: 'vue3',
}));
this.disposeWithMe(componentManager.register('ImageDemo', ImageDemo));
+ this.disposeWithMe(componentManager.register('RangeLoading', RangeLoading));
+ this.disposeWithMe(componentManager.register('FloatButton', FloatButton));
}
}
diff --git a/packages/engine-render/src/components/sheets/sheet-skeleton.ts b/packages/engine-render/src/components/sheets/sheet-skeleton.ts
index 136d42691a..eca07a06a0 100644
--- a/packages/engine-render/src/components/sheets/sheet-skeleton.ts
+++ b/packages/engine-render/src/components/sheets/sheet-skeleton.ts
@@ -777,6 +777,18 @@ export class SpreadsheetSkeleton extends Skeleton {
return Math.max(MIN_COL_WIDTH, colWidth); // min col width is 2
}
+ getColWidth(colIndex: number) {
+ const preColIndex = Math.max(0, colIndex - 1);
+ const currColWidth = this._columnWidthAccumulation[colIndex] - this._columnWidthAccumulation[preColIndex];
+ return currColWidth;
+ }
+
+ getRowHeight(rowIndex: number) {
+ const preRowIndex = Math.max(0, rowIndex - 1);
+ const currRowHeight = this._rowHeightAccumulation[rowIndex] - this._rowHeightAccumulation[preRowIndex];
+ return currRowHeight;
+ }
+
/**
* For _calculateColMaxWidth
* @param cell
diff --git a/packages/engine-render/src/floating/util.ts b/packages/engine-render/src/floating/util.ts
index 089f8948c2..348eb323e9 100644
--- a/packages/engine-render/src/floating/util.ts
+++ b/packages/engine-render/src/floating/util.ts
@@ -19,6 +19,15 @@ import { floor, max, min } from '@floating-ui/utils';
import { getDocumentElement } from '@floating-ui/utils/dom';
import { Observable } from 'rxjs';
+/**
+ * Tracks position and size changes of an element by monitoring:
+ * - Ancestor scrolling and resizing
+ * - Layout shifts
+ * - Element's bounding rectangle changes
+ *
+ * @param containerElement
+ * @returns Observable<void>
+ */
export function observeClientRect(containerElement: HTMLElement): Observable<void> {
return new Observable<void>((observer) => {
const disposable = autoClientRect(containerElement, () => observer.next());
@@ -116,6 +125,14 @@ function getBoundingClientRect(reference: Element) {
return reference.getBoundingClientRect();
}
+/**
+ * Tracks position and size changes of an element by monitoring:
+ * - Ancestor scrolling and resizing
+ * - Layout shifts
+ * - Element's bounding rectangle changes
+ *
+ * Returns a cleanup function to remove all listeners.
+ */
function autoClientRect(
reference: Element,
update: () => void
diff --git a/packages/engine-render/src/render-manager/render-manager.service.ts b/packages/engine-render/src/render-manager/render-manager.service.ts
index 78d95a80bb..b20d6f279c 100644
--- a/packages/engine-render/src/render-manager/render-manager.service.ts
+++ b/packages/engine-render/src/render-manager/render-manager.service.ts
@@ -44,10 +44,15 @@ export interface IRenderManagerService extends IDisposable {
removeRender(unitId: string): void;
setCurrent(unitId: string): void;
/**
- * get RenderUnit By Id, RenderUnit implements IRender
+ * Get RenderUnit By Id, RenderUnit implements IRender
* @param unitId
*/
getRenderById(unitId: string): Nullable<IRender>;
+ /**
+ * Get RenderUnit By Id, RenderUnit implements IRender
+ * @param unitId
+ */
+ getRenderUnitById(unitId: string): Nullable<IRender>;
getAllRenderersOfType(type: UniverInstanceType): RenderUnit[];
getCurrentTypeOfRenderer(type: UniverInstanceType): Nullable<RenderUnit>;
getRenderAll(): Map<string, IRender>;
@@ -340,7 +345,8 @@ export class RenderManagerService extends Disposable implements IRenderManagerSe
}
/**
- * get RenderUnit from this._renderMap
+ * @deprecated use getRenderUnitById instead
+ * Get RenderUnit from this._renderMap.
* @param unitId
* @returns RenderUnit, aka IRender
*/
@@ -348,6 +354,10 @@ export class RenderManagerService extends Disposable implements IRenderManagerSe
return this._renderMap.get(unitId);
}
+ getRenderUnitById(unitId: string): Nullable<IRender> {
+ return this._renderMap.get(unitId);
+ }
+
getRenderAll(): Map<string, IRender> {
return this._renderMap;
}
diff --git a/packages/sheets-drawing-ui/src/facade/f-worksheet.ts b/packages/sheets-drawing-ui/src/facade/f-worksheet.ts
index fed3fadb17..2e8f535ace 100644
--- a/packages/sheets-drawing-ui/src/facade/f-worksheet.ts
+++ b/packages/sheets-drawing-ui/src/facade/f-worksheet.ts
@@ -15,14 +15,16 @@
*/
import type { IDisposable, IFBlobSource, Nullable } from '@univerjs/core';
+import type { FRange } from '@univerjs/sheets/facade';
import { DrawingTypeEnum, ImageSourceType, toDisposable } from '@univerjs/core';
import { ISheetDrawingService, type ISheetImage } from '@univerjs/sheets-drawing';
-import { type ICanvasFloatDom, InsertSheetDrawingCommand, RemoveSheetDrawingCommand, SetSheetDrawingCommand, SheetCanvasFloatDomManagerService } from '@univerjs/sheets-drawing-ui';
+import { type ICanvasFloatDom, type IDOMRangeLayout, InsertSheetDrawingCommand, RemoveSheetDrawingCommand, SetSheetDrawingCommand, SheetCanvasFloatDomManagerService } from '@univerjs/sheets-drawing-ui';
import { type IFComponentKey, transformComponentKey } from '@univerjs/sheets-ui/facade';
import { FWorksheet } from '@univerjs/sheets/facade';
import { ComponentManager } from '@univerjs/ui';
import { FOverGridImage, FOverGridImageBuilder } from './f-over-grid-image';
+// why omit this key? if componentKey is missing, then which component should be used?
export interface IFICanvasFloatDom extends Omit<ICanvasFloatDom, 'componentKey' | 'unitId' | 'subUnitId'>, IFComponentKey {}
export interface IFWorksheetLegacy {
@@ -31,12 +33,118 @@ export interface IFWorksheetLegacy {
* @param layer float dom config
* @param id float dom id, if not given will be auto generated
* @returns float dom id and dispose function
+ * @example
+ * ```ts
+ let sheet = univerAPI.getActiveWorkbook().getActiveSheet();
+ sheet.addFloatDomToPosition({
+ allowTransform: false,
+ initPosition: {
+ startX: 200,
+ endX: 400,
+ startY: 200,
+ endY: 400,
+ },
+ componentKey: 'ImageDemo',
+ props: {
+ a: 1,
+ },
+ data: {
+ aa: '128',
+ },
+ });
+ * ```
*/
addFloatDomToPosition(layer: IFICanvasFloatDom, id?: string): Nullable<{
id: string;
dispose: () => void;
}>;
+ /**
+ * Add dom over range to FloatDOM, And FloatDOM is registerComponent(BuiltInUIPart.CONTENT)
+ * @param layer
+ * @param id
+ * @example
+ * ```ts
+ const sheet = univerAPI.getActiveWorkbook().getActiveSheet();
+ const range = sheet.getRange(0, 0, 3, 3);
+ univerAPI.getActiveWorkbook().setActiveRange(range);
+ const {id, dispose } = sheet.addFloatDomToRange(range, {
+ allowTransform: false,
+ componentKey: 'RangeLoading',
+ props: {
+ a: 1,
+ },
+ data: {
+ aa: '128',
+ },
+ }, {},
+ 'loadingcover'
+ )
+ setTimeout(()=> {
+ dispose();
+ }, 2000)
+
+ // another example-------------------
+ {
+ const sheet = univerAPI.getActiveWorkbook().getActiveSheet();
+ // const range = sheet.getRange(0, 0, 3, 3);
+ // univerAPI.getActiveWorkbook().setActiveRange(range);
+ univerAPI.getActiveWorkbook().getActiveSheet().getActiveRange()
+ const {id, dispose } = sheet.addFloatDomToRange(range, {
+ allowTransform: false,
+ componentKey: 'FloatButton', // React comp key registered in ComponentManager
+ props: {
+ a: 1,
+ },
+ data: {
+ aa: '128',
+ },
+ }, {
+ width: 100,
+ height: 30,
+ x: '100%',
+ y: '100%'},
+ 'AIButton') // dom id
+ }
+ * ```
+ */
+ addFloatDomToRange(range: FRange, layer: IFICanvasFloatDom, domLayout: IDOMRangeLayout, id?: string): Nullable<{
+ id: string;
+ dispose: () => void;
+ }>;
+
+ /**
+ * Add dom at column header, And FloatDOM is registerComponent(BuiltInUIPart.CONTENT)
+ * @param column
+ * @param layer
+ * @param domPos
+ * @param id
+ * @example
+ * ```ts
+ {
+ const sheet = univerAPI.getActiveWorkbook().getActiveSheet();
+ const rs = sheet.addFloatDomToColumnHeader(3,
+ {
+ allowTransform: false,
+ componentKey: 'FloatButton', // React comp key registered in ComponentManager
+ props: {
+ a: 1,
+ },
+ data: {
+ aa: '128',
+ },
+ },
+ {width: 100, height: 40, x: 0, y: 0},
+ 'ai-selector' // dom id
+ )
+ }
+ *```
+ */
+ addFloatDomToColumnHeader(column: number, layer: IFICanvasFloatDom, domPos: IDOMRangeLayout, id?: string): Nullable<{
+ id: string;
+ dispose: () => void;
+ }>;
+
/**
* Insert an image to the sheet
* @param url The image url
@@ -191,6 +299,56 @@ export class FWorksheetLegacy extends FWorksheet implements IFWorksheetLegacy {
return null;
}
+ override addFloatDomToRange(fRange: FRange, layer: IFICanvasFloatDom, domLayout: IDOMRangeLayout, id?: string): Nullable<{
+ id: string;
+ dispose: () => void;
+ }> {
+ const unitId = this._workbook.getUnitId();
+ const subUnitId = this._worksheet.getSheetId();
+ const { key, disposableCollection } = transformComponentKey(layer, this._injector.get(ComponentManager));
+ const floatDomService = this._injector.get(SheetCanvasFloatDomManagerService);
+ const res = floatDomService.addFloatDomToRange(fRange.getRange(), { ...layer, componentKey: key, unitId, subUnitId }, domLayout, id);
+
+ if (res) {
+ disposableCollection.add(res.dispose);
+ return {
+ id: res.id,
+ dispose: (): void => {
+ disposableCollection.dispose();
+ res.dispose();
+ },
+ };
+ }
+
+ disposableCollection.dispose();
+ return null;
+ }
+
+ override addFloatDomToColumnHeader(column: number, layer: IFICanvasFloatDom, domLayout: IDOMRangeLayout, id?: string): Nullable<{
+ id: string;
+ dispose: () => void;
+ }> {
+ const unitId = this._workbook.getUnitId();
+ const subUnitId = this._worksheet.getSheetId();
+ const { key, disposableCollection } = transformComponentKey(layer, this._injector.get(ComponentManager));
+ const floatDomService = this._injector.get(SheetCanvasFloatDomManagerService);
+ const domRangeDispose = floatDomService.addFloatDomToColumnHeader(column, { ...layer, componentKey: key, unitId, subUnitId }, domLayout, id);
+
+ if (domRangeDispose) {
+ disposableCollection.add(domRangeDispose.dispose);
+ return {
+ id: domRangeDispose.id,
+ dispose: (): void => {
+ disposableCollection.dispose();
+ domRangeDispose.dispose();
+ },
+ };
+ }
+
+ disposableCollection.dispose();
+ return null;
+ }
+
override async insertImage(url: IFBlobSource | string, column?: number, row?: number, offsetX?: number, offsetY?: number): Promise<boolean> {
const imageBuilder = this.newOverGridImage();
if (typeof url === 'string') {
diff --git a/packages/sheets-drawing-ui/src/index.ts b/packages/sheets-drawing-ui/src/index.ts
index aa06388462..b22fb4b790 100644
--- a/packages/sheets-drawing-ui/src/index.ts
+++ b/packages/sheets-drawing-ui/src/index.ts
@@ -17,7 +17,7 @@
import './global.css';
export { UniverSheetsDrawingUIPlugin } from './plugin';
-export { type ICanvasFloatDom, SheetCanvasFloatDomManagerService } from './services/canvas-float-dom-manager.service';
+export { type ICanvasFloatDom, type IDOMRangeLayout, SheetCanvasFloatDomManagerService } from './services/canvas-float-dom-manager.service';
export { SHEETS_IMAGE_MENU_ID } from './views/menu/image.menu';
// #region - all commands
diff --git a/packages/sheets-drawing-ui/src/services/canvas-float-dom-manager.service.ts b/packages/sheets-drawing-ui/src/services/canvas-float-dom-manager.service.ts
index 1937b209f3..8b8c508663 100644
--- a/packages/sheets-drawing-ui/src/services/canvas-float-dom-manager.service.ts
+++ b/packages/sheets-drawing-ui/src/services/canvas-float-dom-manager.service.ts
@@ -14,20 +14,23 @@
* limitations under the License.
*/
-import type { IDisposable, IPosition, ITransformState, Nullable, Serializable, Workbook, Worksheet } from '@univerjs/core';
+/* eslint-disable max-lines-per-function */
+/* eslint-disable complexity */
+/* eslint-disable no-console */
+import type { IDisposable, IDrawingSearch, IPosition, IRange, ITransformState, Nullable, Serializable, Workbook, Worksheet } from '@univerjs/core';
import type { IDrawingJsonUndo1 } from '@univerjs/drawing';
import type { BaseObject, IBoundRectNoAngle, IRectProps, IRender, Scene, SpreadsheetSkeleton } from '@univerjs/engine-render';
-import type { ISetFrozenMutationParams } from '@univerjs/sheets';
+import type { ISetFrozenMutationParams, ISetWorksheetRowAutoHeightMutationParams } from '@univerjs/sheets';
import type { IFloatDomData, ISheetDrawingPosition, ISheetFloatDom } from '@univerjs/sheets-drawing';
import type { IFloatDomLayout } from '@univerjs/ui';
import type { IInsertDrawingCommandParams } from '../commands/commands/interfaces';
-import { Disposable, DisposableCollection, DrawingTypeEnum, fromEventSubject, generateRandomId, ICommandService, Inject, IUniverInstanceService, LifecycleService, LifecycleStages, UniverInstanceType } from '@univerjs/core';
-import { getDrawingShapeKeyByDrawingSearch, IDrawingManagerService } from '@univerjs/drawing';
+import { Disposable, DisposableCollection, DrawingTypeEnum, fromEventSubject, generateRandomId, ICommandService, Inject, IUniverInstanceService, LifecycleService, LifecycleStages, Tools, UniverInstanceType } from '@univerjs/core';
+import { getDrawingShapeKeyByDrawingSearch, IDrawingManagerService } from '@univerjs/drawing';
import { DRAWING_OBJECT_LAYER_INDEX, IRenderManagerService, ObjectType, Rect, SHEET_VIEWPORT_KEY } from '@univerjs/engine-render';
-import { getSheetCommandTarget, SetFrozenMutation } from '@univerjs/sheets';
+import { COMMAND_LISTENER_SKELETON_CHANGE, getSheetCommandTarget, SetFrozenMutation, SetWorksheetRowAutoHeightMutation } from '@univerjs/sheets';
import { DrawingApplyType, ISheetDrawingService, SetDrawingApplyMutation } from '@univerjs/sheets-drawing';
-import { ISheetSelectionRenderService, SetZoomRatioOperation, SheetSkeletonManagerService } from '@univerjs/sheets-ui';
+import { ISheetSelectionRenderService, SetScrollOperation, SetZoomRatioOperation, SheetSkeletonManagerService } from '@univerjs/sheets-ui';
import { CanvasFloatDomService } from '@univerjs/ui';
import { BehaviorSubject, filter, map, Subject, switchMap, take } from 'rxjs';
import { InsertSheetDrawingCommand } from '../commands/commands/insert-sheet-drawing.command';
@@ -64,15 +67,44 @@ export interface ICanvasFloatDom {
type?: DrawingTypeEnum;
}
+enum ScrollDirectionResponse {
+ ALL = 'ALL',
+ HORIZONTAL = 'HORIZONTAL',
+ VERTICAL = 'VERTICAL',
+}
interface ICanvasFloatDomInfo {
position$: BehaviorSubject<IFloatDomLayout>;
dispose: IDisposable;
rect: Rect;
unitId: string;
subUnitId: string;
+ boundsOfViewArea?: IBoundRectNoAngle;
+ scrollDirectionResponse?: ScrollDirectionResponse; // update float dom pos by scrolling
+}
+
+export interface IDOMRangeLayout {
+ width: number;
+ height: number;
+ x?: number; // offsetX
+ y?: number; // offsetY
+}
+
+export interface ILimitBound extends IBoundRectNoAngle {
+ absolute: {
+ left: boolean;
+ top: boolean;
+ };
}
-export function transformBound2DOMBound(originBound: IBoundRectNoAngle, scene: Scene, skeleton: SpreadsheetSkeleton, worksheet: Worksheet) {
+/**
+ * Adjust dom bound size when scrolling (dom bound would shrink when scrolling if over the edge of viewMain)
+ * @param posOfFloatObject
+ * @param scene
+ * @param skeleton
+ * @param worksheet
+ * @returns ILimitBound
+ */
+export function transformBound2DOMBound(posOfFloatObject: IBoundRectNoAngle, scene: Scene, skeleton: SpreadsheetSkeleton, worksheet: Worksheet, floatDomInfo?: ICanvasFloatDomInfo): ILimitBound {
const { scaleX, scaleY } = scene.getAncestorScale();
const viewMain = scene.getViewport(SHEET_VIEWPORT_KEY.VIEW_MAIN);
const absolute = {
@@ -82,58 +114,76 @@ export function transformBound2DOMBound(originBound: IBoundRectNoAngle, scene: S
if (!viewMain) {
return {
- ...originBound,
+ ...posOfFloatObject,
absolute,
};
}
- const { left, right, top, bottom } = originBound;
+ const { left, right, top, bottom } = posOfFloatObject;
const freeze = worksheet.getFreeze();
const { startColumn, startRow, xSplit, ySplit } = freeze;
// freeze start
- const startSheetView = skeleton.getNoMergeCellPositionByIndexWithNoHeader(startRow - ySplit, startColumn - xSplit);
+ const startSheetView = skeleton.getNoMergeCellPositionByIndex(startRow - ySplit, startColumn - xSplit);
// freeze end
- const endSheetView = skeleton.getNoMergeCellPositionByIndexWithNoHeader(startRow, startColumn);
- const { rowHeaderWidth, columnHeaderHeight } = skeleton;
+ const endSheetView = skeleton.getNoMergeCellPositionByIndex(startRow, startColumn);
+ // const { rowHeaderWidth, columnHeaderHeight } = skeleton;
const freezeWidth = endSheetView.startX - startSheetView.startX;
const freezeHeight = endSheetView.startY - startSheetView.startY;
- const { top: freezeTop, left: freezeLeft, viewportScrollX: actualScrollX, viewportScrollY: actualScrollY } = viewMain;
+ let { top: topBoundOfViewArea, left: leftBoundViewArea, viewportScrollX: actualScrollX, viewportScrollY: actualScrollY } = viewMain;
+
+ // specify edge of viewbound. if not specify, use viewMain.
+ const { boundsOfViewArea, scrollDirectionResponse } = floatDomInfo || {};
+ if (boundsOfViewArea) {
+ if (Tools.isDefine(boundsOfViewArea.top)) {
+ topBoundOfViewArea = boundsOfViewArea.top;
+ }
+ if (Tools.isDefine(boundsOfViewArea.left)) {
+ leftBoundViewArea = boundsOfViewArea.left;
+ }
+ }
+ if (scrollDirectionResponse === ScrollDirectionResponse.HORIZONTAL) {
+ actualScrollY = 0;
+ }
+ if (scrollDirectionResponse === ScrollDirectionResponse.VERTICAL) {
+ actualScrollX = 0;
+ }
+
let offsetLeft: number;
let offsetRight: number;
// viewMain or viewTop
- if (left < freezeLeft) {
+ if (left < leftBoundViewArea) {
absolute.left = true;
- offsetLeft = ((freezeWidth + rowHeaderWidth) + (left - freezeLeft)) * scaleX;
+ offsetLeft = ((freezeWidth + leftBoundViewArea) + (left - leftBoundViewArea)) * scaleX;
offsetRight = Math.max(
Math.min(
- ((freezeWidth + rowHeaderWidth) + (right - freezeLeft)) * scaleX,
- (freezeWidth + rowHeaderWidth) * scaleX
+ ((freezeWidth + leftBoundViewArea) + (right - leftBoundViewArea)) * scaleX,
+ (freezeWidth + leftBoundViewArea) * scaleX
),
(right - actualScrollX) * scaleX);
} else {
absolute.left = false;
- offsetLeft = Math.max((left - actualScrollX) * scaleX, (freezeWidth + rowHeaderWidth) * scaleX);
- offsetRight = Math.max((right - actualScrollX) * scaleX, (freezeWidth + rowHeaderWidth) * scaleX);
+ offsetLeft = Math.max((left - actualScrollX) * scaleX, (leftBoundViewArea) * scaleX);
+ offsetRight = Math.max((right - actualScrollX) * scaleX, (leftBoundViewArea) * scaleX);
}
let offsetTop: number;
let offsetBottom: number;
// viewMain or viewTop
- if (top < freezeTop) {
+ if (top < topBoundOfViewArea) {
absolute.top = true;
- offsetTop = ((freezeHeight + columnHeaderHeight) + (top - freezeTop)) * scaleY;
+ offsetTop = ((freezeHeight + topBoundOfViewArea) + (top - topBoundOfViewArea)) * scaleY;
offsetBottom = Math.max(
Math.min(
- ((freezeHeight + columnHeaderHeight) + (right - freezeTop)) * scaleY,
- (freezeHeight + columnHeaderHeight) * scaleY
+ ((freezeHeight + topBoundOfViewArea) + (right - topBoundOfViewArea)) * scaleY,
+ (freezeHeight + topBoundOfViewArea) * scaleY
),
(bottom - actualScrollY) * scaleY
);
} else {
absolute.top = false;
- offsetTop = Math.max((top - actualScrollY) * scaleY, (freezeHeight + columnHeaderHeight) * scaleY);
- offsetBottom = Math.max((bottom - actualScrollY) * scaleY, (freezeHeight + columnHeaderHeight) * scaleY);
+ offsetTop = Math.max((top - actualScrollY) * scaleY, (topBoundOfViewArea) * scaleY);
+ offsetBottom = Math.max((bottom - actualScrollY) * scaleY, (topBoundOfViewArea) * scaleY);
}
return {
@@ -145,22 +195,31 @@ export function transformBound2DOMBound(originBound: IBoundRectNoAngle, scene: S
};
}
+/**
+ * Calculate the position of the floating dom, limited by bounds of viewMain in transformBound2DOMBound
+ * @param floatObject
+ * @param renderUnit
+ * @param skeleton
+ * @param worksheet
+ * @returns {IFloatDomLayout} position
+ */
const calcPosition = (
- targetObject: BaseObject,
- currentRender: IRender,
+ floatObject: BaseObject,
+ renderUnit: IRender,
skeleton: SpreadsheetSkeleton,
- worksheet: Worksheet
+ worksheet: Worksheet,
+ floatDomInfo?: ICanvasFloatDomInfo
): IFloatDomLayout => {
- const { scene } = currentRender;
- const { left, top, width, height, angle } = targetObject;
- const bound: IBoundRectNoAngle = {
+ const { scene } = renderUnit;
+ const { left, top, width, height, angle } = floatObject;
+ const boundOfFloatObject: IBoundRectNoAngle = {
left,
right: left + width,
top,
bottom: top + height,
};
- const offsetBound = transformBound2DOMBound(bound, scene, skeleton, worksheet);
+ const offsetBound = transformBound2DOMBound(boundOfFloatObject, scene, skeleton, worksheet, floatDomInfo);
const { scaleX, scaleY } = scene.getAncestorScale();
return {
@@ -180,6 +239,9 @@ export interface ISheetCanvasFloatDomHook {
}
export class SheetCanvasFloatDomManagerService extends Disposable {
+ /**
+ * for update dom container position when scrolling
+ */
private _domLayerMap: Map<string, Map<string, Map<string, { props?: any }>>> = new Map();
private _domLayerInfoMap: Map<string, ICanvasFloatDomInfo> = new Map();
@@ -241,18 +303,18 @@ export class SheetCanvasFloatDomManagerService extends Disposable {
return;
}
- const renderObject = this._renderManagerService.getRenderById(unitId);
+ const renderUnit = this._renderManagerService.getRenderById(unitId);
- const scene = renderObject?.scene;
+ const scene = renderUnit?.scene;
- if (renderObject == null || scene == null) {
+ if (renderUnit == null || scene == null) {
return null;
}
const transformer = scene.getTransformerByCreate();
- const canvas = renderObject.engine.getCanvasElement();
+ const canvas = renderUnit.engine.getCanvasElement();
- return { scene, transformer, renderObject, canvas };
+ return { scene, transformer, renderUnit, canvas };
}
private _getFloatDomProps(id: string) {
@@ -264,12 +326,10 @@ export class SheetCanvasFloatDomManagerService extends Disposable {
return props;
}
- // eslint-disable-next-line max-lines-per-function
private _drawingAddListener() {
this.disposeWithMe(
- // eslint-disable-next-line max-lines-per-function
- this._drawingManagerService.add$.subscribe((params) => {
- // eslint-disable-next-line max-lines-per-function
+
+ this._drawingManagerService.add$.subscribe((params: IDrawingSearch[]) => {
(params).forEach((param) => {
const { unitId, subUnitId, drawingId } = param;
const target = getSheetCommandTarget(this._univerInstanceService, { unitId, subUnitId });
@@ -358,7 +418,7 @@ export class SheetCanvasFloatDomManagerService extends Disposable {
}
const map = this._ensureMap(unitId, subUnitId);
const disposableCollection = new DisposableCollection();
- const initPosition = calcPosition(rect, renderObject.renderObject, skeleton.skeleton, target.worksheet);
+ const initPosition = calcPosition(rect, renderObject.renderUnit, skeleton.skeleton, target.worksheet);
const position$ = new BehaviorSubject<IFloatDomLayout>(initPosition);
const info: ICanvasFloatDomInfo = {
@@ -391,7 +451,7 @@ export class SheetCanvasFloatDomManagerService extends Disposable {
});
const listener = rect.onTransformChange$.subscribeEvent(() => {
- const newPosition = calcPosition(rect, renderObject.renderObject, skeleton.skeleton, target.worksheet);
+ const newPosition = calcPosition(rect, renderObject.renderUnit, skeleton.skeleton, target.worksheet);
position$.next(
newPosition
);
@@ -441,14 +501,15 @@ export class SheetCanvasFloatDomManagerService extends Disposable {
return;
}
ids.forEach((id) => {
- const info = this._domLayerInfoMap.get(id);
- if (info) {
- const position = calcPosition(info.rect, renderObject.renderObject, skeleton.skeleton, target.worksheet);
- info.position$.next(position);
+ const floatDomInfo = this._domLayerInfoMap.get(id);
+ if (floatDomInfo) {
+ const position = calcPosition(floatDomInfo.rect, renderObject.renderUnit, skeleton.skeleton, target.worksheet, floatDomInfo);
+ floatDomInfo.position$.next(position);
}
});
};
+ // #region scroll
this.disposeWithMe(
this._univerInstanceService.getCurrentTypeOfUnit$<Workbook>(UniverInstanceType.UNIVER_SHEET).pipe(
filter((workbook) => !!workbook),
@@ -467,7 +528,9 @@ export class SheetCanvasFloatDomManagerService extends Disposable {
updateSheet(unitId, subUnitId);
})
);
+ //#endregion
+ // #region zoom
this.disposeWithMe(this._commandService.onCommandExecuted((commandInfo) => {
if (commandInfo.id === SetZoomRatioOperation.id) {
const params = (commandInfo.params) as any;
@@ -481,6 +544,7 @@ export class SheetCanvasFloatDomManagerService extends Disposable {
updateSheet(unitId, subUnitId);
}
}));
+ //# endregion
}
private _getPosition(position: IPosition, unitId: string): Nullable<ISheetDrawingPosition> {
@@ -566,6 +630,7 @@ export class SheetCanvasFloatDomManagerService extends Disposable {
}
}
+ // CreateFloatDomCommand --> floatDomService.addFloatDomToPosition
addFloatDomToPosition(layer: ICanvasFloatDom, propId?: string) {
const target = getSheetCommandTarget(this._univerInstanceService, {
unitId: layer.unitId,
@@ -603,6 +668,8 @@ export class SheetCanvasFloatDomManagerService extends Disposable {
allowTransform,
};
+ // mutation
+ // ---> this._drawingManagerService.add$.subscribe
this._commandService.executeCommand(InsertSheetDrawingCommand.id, {
unitId,
drawings: [sheetDrawingParam],
@@ -656,4 +723,605 @@ export class SheetCanvasFloatDomManagerService extends Disposable {
},
};
}
+
+ addFloatDomToRange(range: IRange, layer: ICanvasFloatDom, domPos: IDOMRangeLayout, propId?: string) {
+ const target = getSheetCommandTarget(this._univerInstanceService, {
+ unitId: layer.unitId,
+ subUnitId: layer.subUnitId,
+ });
+ if (!target) {
+ throw new Error('cannot find current target!');
+ }
+ const { unitId, subUnitId } = target;
+ const renderObject = this._getSceneAndTransformerByDrawingSearch(unitId);
+ if (!renderObject) return;
+ const currentRender = this._renderManagerService.getRenderById(unitId);
+ if (!currentRender) return;
+ const skeletonParam = this._renderManagerService.getRenderById(unitId)?.with(SheetSkeletonManagerService).getWorksheetSkeleton(subUnitId);
+ if (!skeletonParam) return;
+ // const viewMain = renderObject.scene.getMainViewport();
+
+ const { componentKey, data, allowTransform = true } = layer;
+ const id = propId ?? generateRandomId();
+ // const drawingId = id;
+
+ const { position: rangePosition } = this._createRangePositionObserver(range, currentRender, skeletonParam.skeleton);
+ const sheetTransform = this._getPosition(rangePosition, unitId);
+ if (sheetTransform == null) {
+ return;
+ }
+ // this._ensureMap for what?
+ const map = this._ensureMap(unitId, subUnitId);
+ map.set(id, layer);
+ const rangeWidth = rangePosition.endX - rangePosition.startX;
+ const rangeHeight = rangePosition.endY - rangePosition.startY;
+ const domWidth = domPos.width ?? rangeWidth;
+ const domHeight = domPos.height ?? rangeHeight;
+
+ const domLeft = rangePosition.startX + calculateOffset(domPos.x, rangeWidth);
+ const domTop = rangePosition.startY + calculateOffset(domPos.y, rangeHeight);
+
+ const sheetDrawingParam: ISheetFloatDom = {
+ unitId,
+ subUnitId,
+ drawingId: id,
+ drawingType: layer.type || DrawingTypeEnum.DRAWING_DOM,
+ componentKey,
+ sheetTransform,
+ transform: {
+ left: domLeft,
+ top: domTop,
+ width: domWidth,
+ height: domHeight,
+ } as ITransformState,
+ data,
+ allowTransform,
+ };
+
+ // mutation
+ // ---> this._drawingManagerService.add$.subscribe
+ // this._commandService.executeCommand(InsertSheetDrawingCommand.id, {
+ // unitId,
+ // drawings: [sheetDrawingParam],
+ // } as IInsertDrawingCommandParams);
+ // this._add$.next({ unitId, subUnitId, id }); // seems no use
+
+ {
+ const { unitId, subUnitId, drawingId } = sheetDrawingParam;
+ const target = getSheetCommandTarget(this._univerInstanceService, { unitId, subUnitId });
+ // const floatDomParam = this._drawingManagerService.getDrawingByParam(sheetDrawingParam) as IFloatDomData;
+ const floatDomParam = sheetDrawingParam;
+
+ const workbook = this._univerInstanceService.getUnit<Workbook>(unitId, UniverInstanceType.UNIVER_SHEET);
+ if (!workbook) {
+ return;
+ }
+
+ const activeSheetId = workbook.getActiveSheet().getSheetId();
+
+ if (!floatDomParam || !target) {
+ return;
+ }
+
+ const skeleton = this._renderManagerService.getRenderById(unitId)?.with(SheetSkeletonManagerService).getWorksheetSkeleton(subUnitId);
+ if (!skeleton) {
+ return;
+ }
+
+ const { transform, drawingType, data } = floatDomParam;
+
+ if (drawingType !== DrawingTypeEnum.DRAWING_DOM && drawingType !== DrawingTypeEnum.DRAWING_CHART) {
+ return;
+ }
+
+ const renderObject = this._getSceneAndTransformerByDrawingSearch(unitId);
+
+ if (renderObject == null) {
+ return;
+ }
+ const { scene, canvas } = renderObject;
+
+ if (transform == null) {
+ return;
+ }
+
+ if (activeSheetId !== subUnitId) {
+ return;
+ }
+
+ const { left, top, width, height, angle, flipX, flipY, skewX, skewY } = transform;
+
+ const rectShapeKey = getDrawingShapeKeyByDrawingSearch({ unitId, subUnitId, drawingId });
+
+ const rectShape = scene.getObject(rectShapeKey);
+
+ if (rectShape != null) {
+ rectShape.transformByState({ left, top, width, height, angle, flipX, flipY, skewX, skewY });
+ return;
+ }
+
+ const domConfig: IRectProps = {
+ left,
+ top,
+ width,
+ height,
+ zIndex: this._drawingManagerService.getDrawingOrder(unitId, subUnitId).length - 1,
+ };
+
+ const isChart = drawingType === DrawingTypeEnum.DRAWING_CHART;
+
+ if (isChart) {
+ const backgroundColor = data ? (data as Record<string, string>).backgroundColor : 'white';
+ domConfig.fill = backgroundColor;
+ domConfig.rotateEnabled = false;
+ if (data && (data as Record<string, string>).border) {
+ domConfig.stroke = (data as Record<string, string>).border;
+ }
+ domConfig.paintFirst = 'stroke';
+ domConfig.strokeWidth = 1;
+ domConfig.borderEnabled = false;
+ domConfig.radius = 8;
+ }
+
+ const domRect = new Rect(rectShapeKey, domConfig);
+
+ if (isChart) {
+ domRect.setObjectType(ObjectType.CHART);
+ }
+
+ scene.addObject(domRect, DRAWING_OBJECT_LAYER_INDEX);
+ if (floatDomParam.allowTransform !== false) {
+ scene.attachTransformerTo(domRect);
+ }
+ const map = this._ensureMap(unitId, subUnitId);
+ const disposableCollection = new DisposableCollection();
+
+ const viewMain = scene.getMainViewport();
+ const boundsOfViewArea: IBoundRectNoAngle = {
+ top: viewMain.top,
+ left: viewMain.left,
+ bottom: viewMain.bottom,
+ right: viewMain.right,
+ };
+ // why call twice? there is another calcPosition below.
+
+ const floatDomInfo = {
+ dispose: disposableCollection,
+ rect: domRect,
+ boundsOfViewArea,
+ // position$,
+ unitId,
+ subUnitId,
+ } as unknown as ICanvasFloatDomInfo;
+
+ const initedPosition = calcPosition(domRect, renderObject.renderUnit, skeleton.skeleton, target.worksheet, floatDomInfo);
+ const position$ = new BehaviorSubject<IFloatDomLayout>(initedPosition);
+ floatDomInfo.position$ = position$;
+
+ this._canvasFloatDomService.addFloatDom({
+ position$,
+ id: drawingId,
+ componentKey: floatDomParam.componentKey,
+ onPointerDown: (evt) => {
+ canvas.dispatchEvent(new PointerEvent(evt.type, evt));
+ },
+ onPointerMove: (evt: PointerEvent | MouseEvent) => {
+ canvas.dispatchEvent(new PointerEvent(evt.type, evt));
+ },
+ onPointerUp: (evt: PointerEvent | MouseEvent) => {
+ canvas.dispatchEvent(new PointerEvent(evt.type, evt));
+ },
+ onWheel: (evt: WheelEvent) => {
+ canvas.dispatchEvent(new WheelEvent(evt.type, evt));
+ },
+ // props: map.get(drawingId)?.props ?? this._getFloatDomProps(drawingId),
+ data,
+ unitId,
+ });
+
+ const listener = domRect.onTransformChange$.subscribeEvent(() => {
+ const newPosition = calcPosition(domRect, renderObject.renderUnit, skeleton.skeleton, target.worksheet, floatDomInfo);
+ position$.next(
+ newPosition
+ );
+ });
+
+ disposableCollection.add(() => {
+ this._canvasFloatDomService.removeFloatDom(drawingId);
+ });
+ listener && disposableCollection.add(listener);
+ this._domLayerInfoMap.set(drawingId, floatDomInfo);
+ map.set(drawingId, {
+ ...map.get(drawingId),
+ });
+ }
+
+ return {
+ id,
+ dispose: () => {
+ this._removeDom(id, true);
+ },
+ };
+ }
+
+ addFloatDomToColumnHeader(column: number, layer: ICanvasFloatDom, domLayout: IDOMRangeLayout, propId?: string) {
+ const target = getSheetCommandTarget(this._univerInstanceService, {
+ unitId: layer.unitId,
+ subUnitId: layer.subUnitId,
+ });
+ if (!target) {
+ throw new Error('cannot find current target!');
+ }
+ const { unitId, subUnitId } = target;
+ const renderObject = this._getSceneAndTransformerByDrawingSearch(unitId);
+ if (!renderObject) return;
+ const currentRender = this._renderManagerService.getRenderById(unitId);
+ if (!currentRender) return;
+ const skeletonParam = this._renderManagerService.getRenderById(unitId)?.with(SheetSkeletonManagerService).getWorksheetSkeleton(subUnitId);
+ if (!skeletonParam) return;
+ // const viewMain = renderObject.scene.getMainViewport();
+
+ const { componentKey, data, allowTransform = true } = layer;
+ const id = propId ?? generateRandomId();
+ // const drawingId = id;
+
+ // rangePostion relative to canvas.(if no scrolling)
+ const { position: rangePosition } = this._createRangePositionObserver({
+ startRow: 0,
+ endRow: 0,
+ startColumn: column,
+ endColumn: column,
+ }, currentRender, skeletonParam.skeleton);
+ const headerPosition = rangePosition;
+ headerPosition.startY = 0;
+
+ const sheetTransform = this._getPosition(rangePosition, unitId);
+ if (sheetTransform == null) {
+ return;
+ }
+ // this._ensureMap for what?
+ const map = this._ensureMap(unitId, subUnitId);
+ map.set(id, layer);
+ const rangeWidth = rangePosition.endX - rangePosition.startX;
+ const rangeHeight = rangePosition.endY - rangePosition.startY;
+ const domWidth = domLayout.width ?? rangeWidth;
+ const domHeight = domLayout.height ?? rangeHeight;
+
+ const domLeft = headerPosition.startX + calculateOffset(domLayout.x, rangeWidth);
+ const domTop = headerPosition.startY + calculateOffset(domLayout.y, rangeHeight);
+
+ const sheetDrawingParam: ISheetFloatDom = {
+ unitId,
+ subUnitId,
+ drawingId: id,
+ drawingType: layer.type || DrawingTypeEnum.DRAWING_DOM,
+ componentKey,
+ sheetTransform,
+ transform: {
+ left: domLeft,
+ top: domTop,
+ width: domWidth,
+ height: domHeight,
+ } as ITransformState,
+ data,
+ allowTransform,
+ };
+
+ // mutation
+ // ---> this._drawingManagerService.add$.subscribe
+ // this._commandService.executeCommand(InsertSheetDrawingCommand.id, {
+ // unitId,
+ // drawings: [sheetDrawingParam],
+ // } as IInsertDrawingCommandParams);
+ // this._add$.next({ unitId, subUnitId, id }); // seems no use
+
+ {
+ const { unitId, subUnitId, drawingId } = sheetDrawingParam;
+ const target = getSheetCommandTarget(this._univerInstanceService, { unitId, subUnitId });
+ // const floatDomParam = this._drawingManagerService.getDrawingByParam(sheetDrawingParam) as IFloatDomData;
+ const floatDomParam = sheetDrawingParam;
+
+ const workbook = this._univerInstanceService.getUnit<Workbook>(unitId, UniverInstanceType.UNIVER_SHEET);
+ if (!workbook) {
+ return;
+ }
+
+ const activeSheetId = workbook.getActiveSheet().getSheetId();
+
+ if (!floatDomParam || !target) {
+ return;
+ }
+
+ const skeleton = this._renderManagerService.getRenderById(unitId)?.with(SheetSkeletonManagerService).getWorksheetSkeleton(subUnitId);
+ if (!skeleton) {
+ return;
+ }
+
+ const { transform, drawingType, data } = floatDomParam;
+
+ if (drawingType !== DrawingTypeEnum.DRAWING_DOM && drawingType !== DrawingTypeEnum.DRAWING_CHART) {
+ return;
+ }
+
+ const renderObject = this._getSceneAndTransformerByDrawingSearch(unitId);
+
+ if (renderObject == null) {
+ return;
+ }
+ const { scene, canvas } = renderObject;
+
+ if (transform == null) {
+ return;
+ }
+
+ if (activeSheetId !== subUnitId) {
+ return;
+ }
+
+ const { left, top, width, height, angle, flipX, flipY, skewX, skewY } = transform;
+
+ const rectShapeKey = getDrawingShapeKeyByDrawingSearch({ unitId, subUnitId, drawingId });
+
+ const rectShape = scene.getObject(rectShapeKey);
+
+ if (rectShape != null) {
+ rectShape.transformByState({ left, top, width, height, angle, flipX, flipY, skewX, skewY });
+ return;
+ }
+
+ const domConfig: IRectProps = {
+ left,
+ top,
+ width,
+ height,
+ zIndex: this._drawingManagerService.getDrawingOrder(unitId, subUnitId).length - 1,
+ };
+
+ const domRect = new Rect(rectShapeKey, domConfig);
+ scene.addObject(domRect, DRAWING_OBJECT_LAYER_INDEX);
+ if (floatDomParam.allowTransform !== false) {
+ scene.attachTransformerTo(domRect);
+ }
+ const map = this._ensureMap(unitId, subUnitId);
+ const disposableCollection = new DisposableCollection();
+
+ const viewMain = scene.getMainViewport();
+ const boundsOfViewArea: IBoundRectNoAngle = {
+ top: 0, //viewMain.top,
+ left: viewMain.left,
+ bottom: viewMain.bottom,
+ right: viewMain.right,
+ };
+ // why call twice? there is another calcPosition below.
+ const floatDomInfo = {
+ dispose: disposableCollection,
+ rect: domRect,
+ // position$,
+ unitId,
+ subUnitId,
+ boundsOfViewArea,
+ scrollDirectionResponse: ScrollDirectionResponse.HORIZONTAL,
+ } as unknown as ICanvasFloatDomInfo;
+
+ const initedPosition = calcPosition(domRect, renderObject.renderUnit, skeleton.skeleton, target.worksheet, floatDomInfo);
+ const position$ = new BehaviorSubject<IFloatDomLayout>(initedPosition);
+ floatDomInfo.position$ = position$;
+
+ this._canvasFloatDomService.addFloatDom({
+ position$,
+ id: drawingId,
+ componentKey: floatDomParam.componentKey,
+ onPointerDown: (evt) => {
+ canvas.dispatchEvent(new PointerEvent(evt.type, evt));
+ },
+ onPointerMove: (evt: PointerEvent | MouseEvent) => {
+ canvas.dispatchEvent(new PointerEvent(evt.type, evt));
+ },
+ onPointerUp: (evt: PointerEvent | MouseEvent) => {
+ canvas.dispatchEvent(new PointerEvent(evt.type, evt));
+ },
+ onWheel: (evt: WheelEvent) => {
+ canvas.dispatchEvent(new WheelEvent(evt.type, evt));
+ },
+ // props: map.get(drawingId)?.props ?? this._getFloatDomProps(drawingId),
+ data,
+ unitId,
+ });
+
+ const listener = domRect.onTransformChange$.subscribeEvent(() => {
+ const newPosition = calcPosition(domRect, renderObject.renderUnit, skeleton.skeleton, target.worksheet, floatDomInfo);
+ position$.next(
+ newPosition
+ );
+ });
+
+ disposableCollection.add(() => {
+ this._canvasFloatDomService.removeFloatDom(drawingId);
+ });
+ listener && disposableCollection.add(listener);
+ this._domLayerInfoMap.set(drawingId, floatDomInfo);
+ map.set(drawingId, {
+ ...map.get(drawingId),
+ });
+ }
+
+ return {
+ id,
+ dispose: () => {
+ this._removeDom(id, true);
+ },
+ };
+ }
+
+ /**
+ * Unlike _createCellPositionObserver, this accept a range not a single cell.
+ *
+ * @param initialRow
+ * @param initialCol
+ * @param currentRender
+ * @param skeleton
+ * @param activeViewport
+ * @returns position of cell to canvas.
+ */
+ private _createRangePositionObserver(
+ range: IRange,
+ currentRender: IRender,
+ skeleton: SpreadsheetSkeleton
+ // activeViewport: Viewport
+ ) {
+ // window.sk = skeleton;
+ let { startRow, startColumn } = range;
+ const topLeftCoord = calcCellPositionByCell(startRow, startColumn, skeleton);
+ const topLeftPos$ = new BehaviorSubject(topLeftCoord);
+
+ const rightBottomCoord = calcCellPositionByCell(range.endRow, range.endColumn, skeleton);
+ // const rightBottomCellWidth = skeleton.getColWidth(range.endColumn);
+ // const rightBottomCellHeight = skeleton.getRowHeight(range.endRow);
+
+ const rightBottomPos$ = new BehaviorSubject(rightBottomCoord);
+
+ const updatePosition = () => {
+ const topLeftCoord = calcCellPositionByCell(startRow, startColumn, skeleton);
+ const rightBottomCoord = calcCellPositionByCell(range.endRow, range.endColumn, skeleton);
+
+ topLeftPos$.next(topLeftCoord);
+ rightBottomPos$.next(rightBottomCoord);
+ };
+
+ const disposable = new DisposableCollection();
+ disposable.add(currentRender.engine.clientRect$.subscribe(() => updatePosition()));
+
+ disposable.add(this._commandService.onCommandExecuted((commandInfo) => {
+ if (commandInfo.id === SetWorksheetRowAutoHeightMutation.id) {
+ const params = commandInfo.params as ISetWorksheetRowAutoHeightMutationParams;
+ if (params.rowsAutoHeightInfo.findIndex((item) => item.row === startRow) > -1) {
+ updatePosition();
+ return;
+ }
+ }
+
+ if (
+ COMMAND_LISTENER_SKELETON_CHANGE.indexOf(commandInfo.id) > -1 ||
+ commandInfo.id === SetScrollOperation.id ||
+ commandInfo.id === SetZoomRatioOperation.id
+ ) {
+ updatePosition();
+ }
+ }));
+
+ const updateRowCol = (newRow: number, newCol: number) => {
+ startRow = newRow;
+ startColumn = newCol;
+
+ updatePosition();
+ };
+ // const position$ = combineLatest(topLeftPos$, rightBottomPos$);
+ // rotate: number;
+ // width: number;
+ // height: number;
+ // absolute: {
+ // left: boolean;
+ // top: boolean;
+ // };
+
+ const genPosition = () => {
+ return {
+ rotate: 0,
+ width: rightBottomCoord.right - topLeftCoord.left,
+ height: rightBottomCoord.bottom - topLeftCoord.top,
+ absolute: {
+ left: true,
+ top: true,
+ },
+ startX: topLeftCoord.left,
+ startY: topLeftCoord.top,
+ endX: rightBottomCoord.right,
+ endY: rightBottomCoord.bottom,
+ };
+ };
+ const position$ = topLeftPos$.pipe(
+ map((topLeft) => {
+ const rightBottomCoord = calcCellPositionByCell(range.endRow, range.endColumn, skeleton);
+ console.log('service', topLeft.left, topLeft.top);
+ return {
+ rotate: 0,
+ width: rightBottomCoord.right - topLeft.left,
+ height: rightBottomCoord.bottom - topLeft.top,
+ absolute: {
+ left: true,
+ top: true,
+ },
+ startX: topLeft.left,
+ startY: topLeft.top,
+ endX: rightBottomCoord.right,
+ endY: rightBottomCoord.bottom,
+ } as IFloatDomLayout;
+ })
+ );
+ const position: IFloatDomLayout = genPosition();
+ console.log('init position', position);
+
+ return {
+ position$,
+ position,
+ updateRowCol,
+ topLeftPos$,
+ rightBottomPos$,
+ disposable,
+ };
+ }
+}
+
+/**
+ * Unlike sheet popup, this Position only relative to sheet content, not window.
+ * @param row
+ * @param col
+ * @param currentRender
+ * @param skeleton
+ * @param activeViewport
+ * @returns
+ */
+function calcCellPositionByCell(
+ row: number,
+ col: number,
+ // currentRender: IRender,
+ skeleton: SpreadsheetSkeleton
+ // activeViewport?: Viewport
+): IBoundRectNoAngle {
+ // const { scene, engine } = currentRender;
+
+ const primaryWithCoord = skeleton.getCellWithCoordByIndex(row, col);
+ const cellInfo = primaryWithCoord.isMergedMainCell ? primaryWithCoord.mergeInfo : primaryWithCoord;
+
+ // const { scaleX, scaleY } = scene.getAncestorScale();
+ // const scrollXY = {
+ // x: activeViewport.viewportScrollX,
+ // y: activeViewport.viewportScrollY,
+ // };
+
+ // const canvasElement = 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 = width / widthOfCanvas;
+
+ return {
+ left: cellInfo.startX,
+ right: cellInfo.endX,
+ top: cellInfo.startY,
+ bottom: cellInfo.endY,
+ };
+}
+
+function calculateOffset(value: number | string | undefined, rangeWidth: number): number {
+ if (value === undefined) return 0;
+
+ // 如果是数字直接返回
+ if (typeof value === 'number') return value;
+
+ // 处理百分比字符串
+ const percentage = Number.parseFloat(value);
+ return (rangeWidth * percentage) / 100;
}
diff --git a/packages/sheets-ui/src/facade/f-range.ts b/packages/sheets-ui/src/facade/f-range.ts
index 7724d86532..85f289bc6f 100644
--- a/packages/sheets-ui/src/facade/f-range.ts
+++ b/packages/sheets-ui/src/facade/f-range.ts
@@ -82,6 +82,7 @@ interface IFRangeSheetsUIMixin {
```
let sheet = univerAPI.getActiveWorkbook().getActiveSheet();
let range = sheet.getRange(2, 2, 3, 3);
+ univerAPI.getActiveWorkbook().setActiveRange(range);
let disposable = range.attachPopup({
componentKey: 'univer.sheet.cell-alert',
extraProps: { alert: { type: 0, title: 'This is an Info', message: 'This is an info message' } },
@@ -102,6 +103,22 @@ interface IFRangeSheetsUIMixin {
* ```
*/
attachAlertPopup(alert: Omit<ICellAlert, 'location'>): IDisposable;
+ /**
+ * Attach a DOM popup to the start cell of current range.
+ * @param alert The alert to attach
+ * @returns The disposable object to detach the alert.
+ * @example
+ * ```ts
+ let sheet = univerAPI.getActiveWorkbook().getActiveSheet();
+ let range = sheet.getRange(2, 2, 3, 3);
+ univerAPI.getActiveWorkbook().setActiveRange(range);
+ let disposable = range.attachRangePopup({
+ componentKey: 'univer.sheet.single-dom-popup',
+ extraProps: { alert: { type: 0, title: 'This is an Info', message: 'This is an info message' } },
+ });
+ * ```
+ */
+ attachRangePopup(popup: IFCanvasPopup): Nullable<IDisposable>;
/**
* Highlight the range with the specified style and primary cell.
@@ -194,6 +211,40 @@ class FRangeSheetsUIMixin extends FRange implements IFRangeSheetsUIMixin {
};
}
+ /**
+ * attachDOMPopup
+ * @param popup
+ * @returns {IDisposable} disposable
+ let sheet = univerAPI.getActiveWorkbook().getActiveSheet();
+ let range = sheet.getRange(2, 2, 3, 3);
+ univerAPI.getActiveWorkbook().setActiveRange(range);
+ let disposable = range.attachDOMPopup({
+ componentKey: 'univer.sheet.single-dom-popup',
+ extraProps: { alert: { type: 0, title: 'This is an Info', message: 'This is an info message' } },
+ });
+ */
+ override attachRangePopup(popup: IFCanvasPopup): Nullable<IDisposable> {
+ popup.direction = popup.direction ?? 'horizontal';
+ popup.extraProps = popup.extraProps ?? {};
+ popup.offset = popup.offset ?? [0, 0];
+
+ const { key, disposableCollection } = transformComponentKey(popup, this._injector.get(ComponentManager));
+ const sheetsPopupService = this._injector.get(SheetCanvasPopManagerService);
+ const disposePopup = sheetsPopupService.attachRangePopup(
+ this._range,
+ { ...popup, componentKey: key },
+ this.getUnitId(),
+ this._worksheet.getSheetId()
+ );
+ if (disposePopup) {
+ disposableCollection.add(disposePopup);
+ return disposableCollection;
+ }
+
+ disposableCollection.dispose();
+ return null;
+ }
+
override highlight(style?: Nullable<Partial<ISelectionStyle>>, primary?: Nullable<ISelectionCell>): IDisposable {
const markSelectionService = this._injector.get(IMarkSelectionService);
const id = markSelectionService.addShape({ range: this._range, style, primary });
diff --git a/packages/sheets-ui/src/services/canvas-pop-manager.service.ts b/packages/sheets-ui/src/services/canvas-pop-manager.service.ts
index 86f9e6defb..a2f9de8e04 100644
--- a/packages/sheets-ui/src/services/canvas-pop-manager.service.ts
+++ b/packages/sheets-ui/src/services/canvas-pop-manager.service.ts
@@ -22,7 +22,7 @@ import { Disposable, DisposableCollection, ICommandService, Inject, IUniverInsta
import { IRenderManagerService } from '@univerjs/engine-render';
import { COMMAND_LISTENER_SKELETON_CHANGE, IRefSelectionsService, RefRangeService, SetFrozenMutation, SetWorksheetRowAutoHeightMutation, SheetsSelectionsService } from '@univerjs/sheets';
import { ICanvasPopupService } from '@univerjs/ui';
-import { BehaviorSubject } from 'rxjs';
+import { BehaviorSubject, map } from 'rxjs';
import { SetScrollOperation } from '../commands/operations/scroll.operation';
import { SetZoomRatioOperation } from '../commands/operations/set-zoom-ratio.operation';
import { getViewportByCell, transformBound2OffsetBound } from '../common/utils';
@@ -193,6 +193,7 @@ export class SheetCanvasPopManagerService extends Disposable {
}
// #region attach to object
+ // Unlike _createCellPositionObserver, this bind to a certain position.
private _createPositionObserver(
bound: IBoundRectNoAngle,
currentRender: IRender,
@@ -407,7 +408,8 @@ export class SheetCanvasPopManagerService extends Disposable {
// #region attach to cell
/**
- *
+ * Bind popup to the right part of cell at(row, col).
+ * This popup would move with the cell.
* @param row
* @param col
* @param popup
@@ -490,6 +492,105 @@ export class SheetCanvasPopManagerService extends Disposable {
};
}
+ /**
+ * attach Comp to floatDOM
+ * @param range
+ * @param popup
+ * @param _unitId
+ * @param _subUnitId
+ * @param viewport
+ * @param showOnSelectionMoving
+ * @returns
+ */
+ attachRangePopup(range: IRange, popup: ICanvasPopup, _unitId?: string, _subUnitId?: string, viewport?: Viewport, showOnSelectionMoving = false): Nullable<INeedCheckDisposable> {
+ const workbook = this._univerInstanceService.getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET)!;
+ const worksheet = workbook.getActiveSheet();
+ if (!worksheet) {
+ return null;
+ }
+
+ const unitId = workbook.getUnitId();
+ const subUnitId = worksheet.getSheetId();
+ if ((_unitId && unitId !== _unitId) || (_subUnitId && subUnitId !== _subUnitId)) {
+ return null;
+ }
+ const currentRender = this._renderManagerService.getRenderById(unitId);
+ const skeleton = currentRender?.with(SheetSkeletonManagerService).getOrCreateSkeleton({
+ sheetId: subUnitId,
+ });
+ const sheetSelectionRenderService = currentRender?.with(ISheetSelectionRenderService);
+
+ if (!currentRender || !skeleton || !sheetSelectionRenderService) {
+ return null;
+ }
+
+ if (sheetSelectionRenderService.selectionMoving && !showOnSelectionMoving) {
+ return;
+ }
+
+ const activeViewport = viewport ?? getViewportByCell(range.startRow, range.startColumn, currentRender.scene, worksheet);
+ if (!activeViewport) {
+ return null;
+ }
+
+ const { position, position$, disposable: positionObserverDisposable, updateRowCol,
+ topLeftPos$,
+ rightBottomPos$,
+ } = this._createRangePositionObserver(range, currentRender, skeleton, activeViewport);
+
+ const { rects$, disposable: rectsObserverDisposable } = this._createHiddenRectObserver({
+ row: range.startRow,
+ column: range.startColumn,
+ worksheet,
+ skeleton,
+ currentRender,
+ });
+ const id = this._globalPopupManagerService.addPopup({
+ ...popup,
+ unitId,
+ subUnitId,
+ anchorRect: position,
+ anchorRect$: position$,
+ canvasElement: currentRender.engine.getCanvasElement(),
+ hiddenRects$: rects$,
+ });
+ const disposableCollection = new DisposableCollection();
+ disposableCollection.add(positionObserverDisposable);
+ disposableCollection.add(toDisposable(() => {
+ this._globalPopupManagerService.removePopup(id);
+ // position$.complete();
+ topLeftPos$.complete();
+ rightBottomPos$.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 = { ...range };
+ disposableCollection.add(this._refRangeService.watchRange(unitId, subUnitId, watchedRange, (_, after) => {
+ if (!after) {
+ disposableCollection.dispose();
+ } else {
+ updateRowCol(after.startRow, after.startColumn);
+ }
+ }));
+
+ return {
+ dispose() {
+ disposableCollection.dispose();
+ },
+ canDispose: () => this._globalPopupManagerService.activePopupId !== id,
+ };
+ }
+
+ /**
+ *
+ * @param initialRow
+ * @param initialCol
+ * @param currentRender
+ * @param skeleton
+ * @param activeViewport
+ * @returns
+ */
private _createCellPositionObserver(
initialRow: number,
initialCol: number,
@@ -539,6 +640,7 @@ export class SheetCanvasPopManagerService extends Disposable {
};
}
+ // TODO @lumixraku to a normal function, not method.
private _calcCellPositionByCell(
row: number,
col: number,
@@ -572,8 +674,90 @@ export class SheetCanvasPopManagerService extends Disposable {
bottom: ((cellInfo.endY - scrollXY.y) * scaleAdjust * scaleY) + top,
};
}
-
// #endregion
+
+ /**
+ * Unlike _createCellPositionObserver, this accept a range not a single cell.
+ * @param initialRow
+ * @param initialCol
+ * @param currentRender
+ * @param skeleton
+ * @param activeViewport
+ */
+ private _createRangePositionObserver(
+ range: IRange,
+ currentRender: IRender,
+ skeleton: SpreadsheetSkeleton,
+ activeViewport: Viewport
+ ) {
+ let { startRow, startColumn } = range;
+ const topLeftCoord = this._calcCellPositionByCell(startRow, startColumn, currentRender, skeleton, activeViewport);
+ const topLeftPos$ = new BehaviorSubject(topLeftCoord);
+ const rightBottomCoord = this._calcCellPositionByCell(range.endRow, range.endColumn, currentRender, skeleton, activeViewport);
+ const rightBottomPos$ = new BehaviorSubject(rightBottomCoord);
+
+ const updatePosition = () => {
+ const topLeftCoord = this._calcCellPositionByCell(startRow, startColumn, currentRender, skeleton, activeViewport);
+ const rightBottomCoord = this._calcCellPositionByCell(range.endRow, range.endColumn, currentRender, skeleton, activeViewport);
+
+ topLeftPos$.next(topLeftCoord);
+ rightBottomPos$.next(rightBottomCoord);
+ };
+
+ const disposable = new DisposableCollection();
+ disposable.add(currentRender.engine.clientRect$.subscribe(() => updatePosition()));
+
+ disposable.add(this._commandService.onCommandExecuted((commandInfo) => {
+ if (commandInfo.id === SetWorksheetRowAutoHeightMutation.id) {
+ const params = commandInfo.params as ISetWorksheetRowAutoHeightMutationParams;
+ if (params.rowsAutoHeightInfo.findIndex((item) => item.row === startRow) > -1) {
+ updatePosition();
+ return;
+ }
+ }
+
+ if (
+ COMMAND_LISTENER_SKELETON_CHANGE.indexOf(commandInfo.id) > -1 ||
+ commandInfo.id === SetScrollOperation.id ||
+ commandInfo.id === SetZoomRatioOperation.id
+ ) {
+ updatePosition();
+ }
+ }));
+
+ const updateRowCol = (newRow: number, newCol: number) => {
+ startRow = newRow;
+ startColumn = newCol;
+
+ updatePosition();
+ };
+ // const position$ = combineLatest(topLeftPos$, rightBottomPos$);
+ const position$ = topLeftPos$.pipe(
+ map((topLeft) => {
+ const rightBottomCoord = this._calcCellPositionByCell(range.endRow, range.endColumn, currentRender, skeleton, activeViewport);
+ return {
+ top: topLeft.top,
+ left: topLeft.left,
+ right: rightBottomCoord.right,
+ bottom: rightBottomCoord.bottom,
+ };
+ })
+ );
+ const position: IBoundRectNoAngle = {
+ top: topLeftCoord.top,
+ left: topLeftCoord.left,
+ right: rightBottomCoord.right,
+ bottom: rightBottomCoord.bottom,
+ };
+ return {
+ position$,
+ position,
+ updateRowCol,
+ topLeftPos$,
+ rightBottomPos$,
+ disposable,
+ };
+ }
}
function pxToNum(width: string): number {
diff --git a/packages/sheets/src/facade/f-worksheet.ts b/packages/sheets/src/facade/f-worksheet.ts
index 9941a2cb94..1b5a21d26c 100644
--- a/packages/sheets/src/facade/f-worksheet.ts
+++ b/packages/sheets/src/facade/f-worksheet.ts
@@ -20,7 +20,7 @@ import type { FDefinedName } from './f-defined-name';
import type { FWorkbook } from './f-workbook';
import { BooleanNumber, Direction, FBaseInitialable, ICommandService, ILogService, Inject, Injector, ObjectMatrix, RANGE_TYPE } from '@univerjs/core';
import { deserializeRangeWithSheet } from '@univerjs/engine-formula';
-import { CancelFrozenCommand, ClearSelectionAllCommand, ClearSelectionContentCommand, ClearSelectionFormatCommand, copyRangeStyles, InsertColByRangeCommand, InsertRowByRangeCommand, MoveColsCommand, MoveRowsCommand, RemoveColByRangeCommand, RemoveRowByRangeCommand, SetColDataCommand, SetColHiddenCommand, SetColWidthCommand, SetFrozenCommand, SetGridlinesColorCommand, SetRangeValuesMutation, SetRowDataCommand, SetRowHeightCommand, SetRowHiddenCommand, SetSpecificColsVisibleCommand, SetSpecificRowsVisibleCommand, SetTabColorCommand, SetWorksheetDefaultStyleMutation, SetWorksheetHideCommand, SetWorksheetNameCommand, SetWorksheetRowIsAutoHeightCommand, SetWorksheetShowCommand, SheetsSelectionsService, ToggleGridlinesCommand } from '@univerjs/sheets';
+import { CancelFrozenCommand, ClearSelectionAllCommand, ClearSelectionContentCommand, ClearSelectionFormatCommand, copyRangeStyles, InsertColByRangeCommand, InsertRowByRangeCommand, MoveColsCommand, MoveRowsCommand, RemoveColByRangeCommand, RemoveRowByRangeCommand, SetColDataCommand, SetColHiddenCommand, SetColWidthCommand, SetFrozenCommand, SetGridlinesColorCommand, SetRangeValuesMutation, SetRowDataCommand, SetRowHeightCommand, SetRowHiddenCommand, SetSpecificColsVisibleCommand, SetSpecificRowsVisibleCommand, SetTabColorCommand, SetWorksheetDefaultStyleMutation, SetWorksheetHideCommand, SetWorksheetNameCommand, SetWorksheetRowIsAutoHeightCommand, SetWorksheetRowIsAutoHeightMutation, SetWorksheetShowCommand, SheetsSelectionsService, ToggleGridlinesCommand } from '@univerjs/sheets';
import { FDefinedNameBuilder } from './f-defined-name';
import { FRange } from './f-range';
import { FSelection } from './f-selection';
@@ -764,6 +764,37 @@ export class FWorksheet extends FBaseInitialable {
return this.setRowHeights(rowPosition, 1, height);
}
+ /**
+ *
+ * @param rowPosition
+ * @param auto
+ * @returns {FWorksheet} this
+ * @example
+ * ```ts
+ const fWorkbook = univerAPI.getActiveWorkbook();
+ const fWorkSheet = fWorkbook.getActiveSheet();
+ fWorkSheet.autoFitRow(24);
+ * ```
+ */
+ autoFitRow(rowPosition: number, auto: BooleanNumber = BooleanNumber.TRUE): FWorksheet {
+ const unitId = this._workbook.getUnitId();
+ const subUnitId = this._worksheet.getSheetId();
+ const ranges = [{
+ startRow: rowPosition,
+ endRow: rowPosition,
+ startColumn: 0,
+ endColumn: this._worksheet.getColumnCount() - 1,
+ }];
+ this._commandService.syncExecuteCommand(SetWorksheetRowIsAutoHeightMutation.id,
+ {
+ unitId,
+ subUnitId,
+ ranges,
+ autoHeightInfo: auto,
+ });
+ return this;
+ }
+
/**
* Sets the height of the given rows in pixels.
* By default, rows grow to fit cell contents. If you want to force rows to a specified height, use setRowHeightsForced(startRow, numRows, height).
diff --git a/packages/ui/src/controllers/ui/ui-desktop.controller.tsx b/packages/ui/src/controllers/ui/ui-desktop.controller.tsx
index 6dda7128b9..ba182b3b6d 100644
--- a/packages/ui/src/controllers/ui/ui-desktop.controller.tsx
+++ b/packages/ui/src/controllers/ui/ui-desktop.controller.tsx
@@ -102,6 +102,7 @@ export class DesktopUIController extends Disposable {
private _initBuiltinComponents(): void {
this.disposeWithMe(this._uiPartsService.registerComponent(BuiltInUIPart.FLOATING, () => connectInjector(CanvasPopup, this._injector)));
+ // this.disposeWithMe(this._uiPartsService.registerComponent(BuiltInUIPart.CONTENT, () => connectInjector(ContentDOMPopup, this._injector)));
this.disposeWithMe(this._uiPartsService.registerComponent(BuiltInUIPart.CONTENT, () => connectInjector(FloatDom, this._injector)));
}
}
diff --git a/packages/ui/src/controllers/ui/ui-mobile.controller.tsx b/packages/ui/src/controllers/ui/ui-mobile.controller.tsx
index b323afa111..10cb6938a0 100644
--- a/packages/ui/src/controllers/ui/ui-mobile.controller.tsx
+++ b/packages/ui/src/controllers/ui/ui-mobile.controller.tsx
@@ -14,21 +14,21 @@
* limitations under the License.
*/
+import type { IDisposable } from '@univerjs/core';
+import type { IUniverUIConfig } from '../config.schema';
+import type { IUIController, IWorkbenchOptions } from './ui.controller';
import { connectInjector, Disposable, Inject, Injector, IUniverInstanceService, LifecycleService, LifecycleStages, Optional, toDisposable, UniverInstanceType } from '@univerjs/core';
import { IRenderManagerService } from '@univerjs/engine-render';
-import type { IDisposable } from '@univerjs/core';
+
import { render as createRoot, unmount } from 'rc-util/lib/React/render';
import React from 'react';
-
import { ILayoutService } from '../../services/layout/layout.service';
+import { IMenuManagerService } from '../../services/menu/menu-manager.service';
import { BuiltInUIPart, IUIPartsService } from '../../services/parts/parts.service';
-import { CanvasPopup } from '../../views/components/popup/CanvasPopup';
import { FloatDom } from '../../views/components/dom/FloatDom';
+import { CanvasPopup } from '../../views/components/popup/CanvasPopup';
import { MobileApp } from '../../views/MobileApp';
-import type { IUniverUIConfig } from '../config.schema';
-import { IMenuManagerService } from '../../services/menu/menu-manager.service';
import { menuSchema } from '../menus/menu.schema';
-import type { IUIController, IWorkbenchOptions } from './ui.controller';
const STEADY_TIMEOUT = 3000;
diff --git a/packages/ui/src/facade/f-univer.ts b/packages/ui/src/facade/f-univer.ts
index 3e93c561aa..bcac926cb3 100644
--- a/packages/ui/src/facade/f-univer.ts
+++ b/packages/ui/src/facade/f-univer.ts
@@ -16,7 +16,7 @@
import type { IDisposable } from '@univerjs/core';
import type { IMessageProps } from '@univerjs/design';
-import type { BuiltInUIPart, IDialogPartMethodOptions, ISidebarMethodOptions } from '@univerjs/ui';
+import type { BuiltInUIPart, ComponentType, IComponentOptions, IDialogPartMethodOptions, ISidebarMethodOptions } from '@univerjs/ui';
import type { IFacadeMenuItem, IFacadeSubmenuItem } from './f-menu-builder';
import { connectInjector, FUniver } from '@univerjs/core';
import { ComponentManager, CopyCommand, IDialogService, IMessageService, ISidebarService, IUIPartsService, PasteCommand } from '@univerjs/ui';
@@ -140,6 +140,16 @@ export interface IFUniverUIMixin {
* ```
*/
registerUIPart(key: BuiltInUIPart, component: any): IDisposable;
+
+ /**
+ * register an component.
+ * @param component
+ * @example
+ * ```ts
+ * univerAPI.registerComponent(() => React.createElement('h1', null, 'Custom Header'));
+ * ```
+ */
+ registerComponent(name: string, component: ComponentType, options?: IComponentOptions): IDisposable;
}
export class FUniverUIMixin extends FUniver implements IFUniverUIMixin {
@@ -212,6 +222,11 @@ export class FUniverUIMixin extends FUniver implements IFUniverUIMixin {
const uiPartService = this._injector.get(IUIPartsService);
return uiPartService.registerComponent(key, () => connectInjector(component, this._injector));
}
+
+ override registerComponent(name: string, component: any, options?: IComponentOptions): IDisposable {
+ const componentManager = this._injector.get(ComponentManager);
+ return this.disposeWithMe(componentManager.register(name, component, options));
+ }
}
FUniver.extend(FUniverUIMixin);
diff --git a/packages/ui/src/views/components/popup/dom-popup.tsx b/packages/ui/src/views/components/popup/dom-popup.tsx
new file mode 100644
index 0000000000..dc3db800ef
--- /dev/null
+++ b/packages/ui/src/views/components/popup/dom-popup.tsx
@@ -0,0 +1,101 @@
+/**
+ * Copyright 2023-present DreamNum Inc.
+ *
+ * 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 { IPopup } from '../../../services/popup/canvas-popup.service';
+import React, { useEffect, useMemo, useState } from 'react';
+import { animationFrameScheduler, combineLatest, map, of, throttleTime } from 'rxjs';
+import { useObservableRef } from '../../../components/hooks/observable';
+import { RectPopup } from './RectPopup';
+
+interface ISingleDOMPopupProps {
+ popup: IPopup;
+ children?: React.ReactNode;
+}
+
+/**
+ * Align position is diff from SingleCanvasPopup
+ */
+const SingleDOMPopup = ({ popup, children }: ISingleDOMPopupProps) => {
+ const [hidden, setHidden] = useState(false);
+ 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 excludeRectsRef = useObservableRef(excludeRects$, popup.excludeRects);
+ const { canvasElement, hideOnInvisible = true, hiddenType = 'destroy' } = popup;
+
+ useEffect(() => {
+ if (!hideOnInvisible) {
+ return;
+ }
+
+ 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 (
+ <RectPopup
+ hidden={hidden}
+ anchorRect$={anchorRect$}
+ direction={popup.direction}
+ onClickOutside={popup.onClickOutside}
+ excludeOutside={popup.excludeOutside}
+ excludeRects={excludeRectsRef}
+ onPointerEnter={popup.onPointerEnter}
+ onPointerLeave={popup.onPointerLeave}
+ onClick={popup.onClick}
+ onContextMenu={popup.onContextMenu}
+ >
+ {children}
+ </RectPopup>
+ );
+};
+
+export type { ISingleDOMPopupProps };
+export { SingleDOMPopup };
diff --git a/packages/ui/src/views/components/popup/single-canvas-popup.tsx b/packages/ui/src/views/components/popup/single-canvas-popup.tsx
new file mode 100644
index 0000000000..2e19ec2978
--- /dev/null
+++ b/packages/ui/src/views/components/popup/single-canvas-popup.tsx
@@ -0,0 +1,98 @@
+/**
+ * Copyright 2023-present DreamNum Inc.
+ *
+ * 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 { IPopup } from '../../../services/popup/canvas-popup.service';
+import React, { useEffect, useMemo, useState } from 'react';
+import { animationFrameScheduler, combineLatest, map, of, throttleTime } from 'rxjs';
+import { useObservableRef } from '../../../components/hooks/observable';
+import { RectPopup } from './RectPopup';
+
+interface ISingleCanvasPopupProps {
+ popup: IPopup;
+ children?: React.ReactNode;
+}
+
+const SingleCanvasPopup = ({ popup, children }: ISingleCanvasPopupProps) => {
+ const [hidden, setHidden] = useState(false);
+ 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 excludeRectsRef = useObservableRef(excludeRects$, popup.excludeRects);
+ const { canvasElement, hideOnInvisible = true, hiddenType = 'destroy' } = popup;
+
+ useEffect(() => {
+ if (!hideOnInvisible) {
+ return;
+ }
+
+ 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 (
+ <RectPopup
+ hidden={hidden}
+ anchorRect$={anchorRect$}
+ direction={popup.direction}
+ onClickOutside={popup.onClickOutside}
+ excludeOutside={popup.excludeOutside}
+ excludeRects={excludeRectsRef}
+ onPointerEnter={popup.onPointerEnter}
+ onPointerLeave={popup.onPointerLeave}
+ onClick={popup.onClick}
+ onContextMenu={popup.onContextMenu}
+ >
+ {children}
+ </RectPopup>
+ );
+};
+
+export type { ISingleCanvasPopupProps };
+export { SingleCanvasPopup };