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(image): facade api (#4322)

Univerb41e499057d4
diff --git a/examples/src/sheets/main.ts b/examples/src/sheets/main.ts
index 191a77b6c3..57eeb2dcec 100644
--- a/examples/src/sheets/main.ts
+++ b/examples/src/sheets/main.ts
@@ -56,6 +56,7 @@ import '@univerjs/sheets-hyper-link-ui/facade';
import '@univerjs/sheets-thread-comment/facade';
import '@univerjs/sheets-conditional-formatting/facade';
+import '@univerjs/sheets-drawing-ui/facade';
import '../global.css';
/* eslint-disable-next-line node/prefer-global/process */
diff --git a/packages/core/src/facade/f-blob.ts b/packages/core/src/facade/f-blob.ts
new file mode 100644
index 0000000000..31aa642e40
--- /dev/null
+++ b/packages/core/src/facade/f-blob.ts
@@ -0,0 +1,205 @@
+/**
+ * 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 { Nullable } from '../shared';
+import { Inject, Injector } from '@wendellhu/redi';
+import { FBase } from './f-base';
+
+export interface IFBlobSource {
+ /**
+ * Return the data inside this object as a blob.
+ */
+ getBlob(): FBlob;
+
+ /**
+ * Return the data inside this object as a blob converted to the specified content type.
+ * @param contentType the content type refer to https://developer.mozilla.org/en-US/docs/Web/HTTP/MIME_types/Common_types
+ */
+ getAs(contentType: string): FBlob;
+}
+
+export class FBlob extends FBase {
+ constructor(
+ private _blob: Nullable<Blob>,
+ @Inject(Injector) protected readonly _injector: Injector
+ ) {
+ super();
+ }
+
+ /**
+ * Returns a copy of this blob.
+ * @returns a new blob by copying the current blob
+ * @example
+ * ```ts
+ * const blob = UniverApi.newBlob(blob);
+ * const newBlob = blob.copyBlob();
+ * console.log(newBlob);
+ * ```
+ */
+ copyBlob() {
+ return this._injector.createInstance(FBlob, this._blob);
+ }
+
+ /**
+ * Return the data inside this object as a blob converted to the specified content type.
+ * @param contentType the content type refer to https://developer.mozilla.org/en-US/docs/Web/HTTP/MIME_types/Common_types
+ * @returns a new blob by converting the current blob to the specified content type
+ * @example
+ * ```ts
+ * const blob = UniverApi.newBlob(blob);
+ * const newBlob = blob.getBlob();
+ * ```
+ */
+ getAs(contentType: string) {
+ const newBlob = this.copyBlob();
+ newBlob.setContentType(contentType);
+ return newBlob;
+ }
+
+ /**
+ * get the blob as a string
+ * @returns
+ * @example
+ * ```ts
+ * const blob = UniverApi.newBlob(blob);
+ * const newBlob = blob.getDataAsString();
+ * console.log(newBlob);
+ * ```
+ */
+ getDataAsString(): Promise<string>;
+ /**
+ * get the blob as a string
+ * @param charset the charset
+ * @returns the blob content as a string
+ * @example
+ * ```ts
+ * const blob = UniverApi.newBlob(blob);
+ * const newBlob = blob.getDataAsString('iso-8859-1');
+ * console.log(newBlob);
+ * ```
+ */
+ getDataAsString(charset?: string): Promise<string>;
+ getDataAsString(charset?: string): Promise<string> {
+ if (this._blob === null) {
+ return Promise.resolve('');
+ }
+
+ if (charset === undefined) {
+ return this._blob!.text();
+ }
+ return new Promise((resolve, reject) => {
+ this._blob!.arrayBuffer().then((arrayBuffer) => {
+ const text = new TextDecoder(charset).decode(arrayBuffer); // 解码为字符串
+ resolve(text);
+ }).catch((error) => {
+ reject(new Error(`Failed to read Blob as ArrayBuffer: ${error.message}`));
+ });
+ });
+ }
+
+ /**
+ * Gets the data stored in this blob.
+ * @returns the blob content as a byte array
+ * @example
+ * ```ts
+ * const blob = UniverApi.newBlob(blob);
+ * const newBlob = blob.getBytes();
+ * console.log(newBlob);
+ * ```
+ */
+ getBytes(): Promise<Uint8Array> {
+ if (!this._blob) {
+ return Promise.reject(new Error('Blob is undefined or null.'));
+ }
+ return this._blob.arrayBuffer().then((buffer) => new Uint8Array(buffer));
+ }
+
+ /**
+ * Sets the data stored in this blob.
+ * @param bytes a byte array
+ * @returns the blob object
+ * @example
+ * ```ts
+ * const blob = UniverApi.newBlob();
+ * const bytes = new Uint8Array(10);
+ * blob.setBytes(bytes);
+ * ```
+ */
+ setBytes(bytes: Uint8Array): FBlob {
+ this._blob = new Blob([bytes]);
+ return this;
+ }
+
+ /**
+ * Sets the data stored in this blob.
+ * @param data blob data string
+ * @returns the blob object
+ * @example
+ * ```ts
+ * const blob = UniverApi.newBlob();
+ * blob.setDataFromString('Hello, World!');
+ * ```
+ */
+ setDataFromString(data: string): FBlob;
+ /**
+ * Sets the data stored in this blob.
+ * @param data a string
+ * @param contentType the content type refer to https://developer.mozilla.org/en-US/docs/Web/HTTP/MIME_types/Common_types
+ * @returns the blob object
+ * @example
+ * ```ts
+ * const blob = UniverApi.newBlob();
+ * blob.setDataFromString('Hello, World!', 'text/plain');
+ * ```
+ */
+ setDataFromString(data: string, contentType?: string): FBlob;
+ setDataFromString(data: string, contentType?: string): FBlob {
+ const contentTypeVal = contentType ?? 'text/plain';
+ const blob = new Blob([data], { type: contentTypeVal });
+ this._blob = blob;
+ return this;
+ }
+
+ /**
+ * Gets the content type of the data stored in this blob.
+ * @returns the content type
+ * @example
+ * ```ts
+ * const blob = UniverApi.newBlob(blob);
+ * const newBlob = blob.getContentType();
+ * console.log(newBlob);
+ * ```
+ */
+ getContentType() {
+ return this._blob?.type;
+ }
+
+ /**
+ * Sets the content type of the data stored in this blob.
+ * @param contentType the content type refer to https://developer.mozilla.org/en-US/docs/Web/HTTP/MIME_types/Common_types
+ * @returns the blob object
+ * @example
+ * ```ts
+ * const blob = UniverApi.newBlob(blob);
+ * const newBlob = blob.setContentType('text/plain');
+ * console.log(newBlob);
+ * ```
+ */
+ setContentType(contentType: string): FBlob {
+ this._blob = this._blob?.slice(0, this._blob.size, contentType);
+ return this;
+ }
+}
diff --git a/packages/core/src/facade/f-univer.ts b/packages/core/src/facade/f-univer.ts
index 22810cc03a..afad97371a 100644
--- a/packages/core/src/facade/f-univer.ts
+++ b/packages/core/src/facade/f-univer.ts
@@ -24,6 +24,7 @@ import { LifecycleService } from '../services/lifecycle/lifecycle.service';
import { RedoCommand, UndoCommand } from '../services/undoredo/undoredo.service';
import { Univer } from '../univer';
import { FBase } from './f-base';
+import { FBlob } from './f-blob';
import { FHooks } from './f-hooks';
export class FUniver extends FBase {
@@ -148,4 +149,17 @@ export class FUniver extends FBase {
getHooks(): FHooks {
return this._injector.createInstance(FHooks);
}
+
+ /**
+ * Create a new blob.
+ *
+ * @returns {FBlob} The new blob instance
+ * @example
+ * ```ts
+ * const blob = UniverApi.newBlob();
+ * ```
+ */
+ newBlob(): FBlob {
+ return this._injector.createInstance(FBlob);
+ }
}
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index 09fdd142ca..63b6003b8d 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -43,6 +43,7 @@ export { mixinClass } from './common/mixin';
export { FBase } from './facade/f-base';
export { FUniver } from './facade/f-univer';
export { FHooks } from './facade/f-hooks';
+export { FBlob, type IFBlobSource } from './facade/f-blob';
export { isNumeric, isSafeNumeric } from './common/number';
export { Registry, RegistryAsMap } from './common/registry';
export { requestImmediateMacroTask } from './common/request-immediate-macro-task';
diff --git a/packages/sheets-drawing-ui/src/basics/transform-position.ts b/packages/sheets-drawing-ui/src/basics/transform-position.ts
index 56b77e22b5..788428367f 100644
--- a/packages/sheets-drawing-ui/src/basics/transform-position.ts
+++ b/packages/sheets-drawing-ui/src/basics/transform-position.ts
@@ -17,56 +17,65 @@
import type { ITransformState, Nullable } from '@univerjs/core';
import type { ISheetDrawingPosition } from '@univerjs/sheets-drawing';
import { precisionTo } from '@univerjs/engine-render';
-import { attachRangeWithCoord, type ISheetSelectionRenderService, type SheetSkeletonManagerService } from '@univerjs/sheets-ui';
+import { convertPositionSheetOverGridToAbsolute, type ISheetSelectionRenderService, type SheetSkeletonManagerService } from '@univerjs/sheets-ui';
export function drawingPositionToTransform(
position: ISheetDrawingPosition,
selectionRenderService: ISheetSelectionRenderService,
sheetSkeletonManagerService: SheetSkeletonManagerService): Nullable<ITransformState> {
const { from, to, flipY = false, flipX = false, angle = 0, skewX = 0, skewY = 0 } = position;
- const { column: fromColumn, columnOffset: fromColumnOffset, row: fromRow, rowOffset: fromRowOffset } = from;
- const { column: toColumn, columnOffset: toColumnOffset, row: toRow, rowOffset: toRowOffset } = to;
+ const skeletonParam = sheetSkeletonManagerService.getCurrent();
+ if (skeletonParam == null) {
+ return;
+ }
+
+ const absolutePosition = convertPositionSheetOverGridToAbsolute(
+ skeletonParam.unitId, skeletonParam.sheetId, { from, to }, sheetSkeletonManagerService
+ );
+
+ let { left, top, width, height } = absolutePosition;
+
const skeleton = sheetSkeletonManagerService.getCurrentSkeleton()!;
- const startSelectionCell = attachRangeWithCoord(skeleton, {
- startColumn: fromColumn,
- endColumn: fromColumn,
- startRow: fromRow,
- endRow: fromRow,
- });
+ // const startSelectionCell = attachRangeWithCoord(skeleton, {
+ // startColumn: fromColumn,
+ // endColumn: fromColumn,
+ // startRow: fromRow,
+ // endRow: fromRow,
+ // });
- if (startSelectionCell == null) {
- return;
- }
+ // if (startSelectionCell == null) {
+ // return;
+ // }
- const endSelectionCell = attachRangeWithCoord(skeleton, {
- startColumn: toColumn,
- endColumn: toColumn,
- startRow: toRow,
- endRow: toRow,
- });
+ // const endSelectionCell = attachRangeWithCoord(skeleton, {
+ // startColumn: toColumn,
+ // endColumn: toColumn,
+ // startRow: toRow,
+ // endRow: toRow,
+ // });
- if (endSelectionCell == null) {
- return;
- }
+ // if (endSelectionCell == null) {
+ // return;
+ // }
- const { startX: startSelectionX, startY: startSelectionY } = startSelectionCell;
+ // const { startX: startSelectionX, startY: startSelectionY } = startSelectionCell;
- const { startX: endSelectionX, startY: endSelectionY } = endSelectionCell;
+ // const { startX: endSelectionX, startY: endSelectionY } = endSelectionCell;
- let left = precisionTo(startSelectionX + fromColumnOffset, 1);
- let top = precisionTo(startSelectionY + fromRowOffset, 1);
+ // let left = precisionTo(startSelectionX + fromColumnOffset, 1);
+ // let top = precisionTo(startSelectionY + fromRowOffset, 1);
- let width = precisionTo(endSelectionX + toColumnOffset - left, 1);
- let height = precisionTo(endSelectionY + toRowOffset - top, 1);
+ // let width = precisionTo(endSelectionX + toColumnOffset - left, 1);
+ // let height = precisionTo(endSelectionY + toRowOffset - top, 1);
- if (startSelectionCell.startX === endSelectionCell.endX) {
- width = 0;
- }
+ // if (startSelectionCell.startX === endSelectionCell.endX) {
+ // width = 0;
+ // }
- if (startSelectionCell.startY === endSelectionCell.endY) {
- height = 0;
- }
+ // if (startSelectionCell.startY === endSelectionCell.endY) {
+ // height = 0;
+ // }
const sheetWidth = skeleton.rowHeaderWidth + skeleton.columnTotalWidth;
const sheetHeight = skeleton.columnHeaderHeight + skeleton.rowTotalHeight;
diff --git a/packages/sheets-drawing-ui/src/facade/f-over-grid-image.ts b/packages/sheets-drawing-ui/src/facade/f-over-grid-image.ts
new file mode 100644
index 0000000000..3d8b25a861
--- /dev/null
+++ b/packages/sheets-drawing-ui/src/facade/f-over-grid-image.ts
@@ -0,0 +1,465 @@
+/**
+ * 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 { IRotationSkewFlipTransform, ISize } from '@univerjs/core';
+import type { ICellOverGridPosition } from '@univerjs/sheets';
+import type { ISheetImage, SheetDrawingAnchorType } from '@univerjs/sheets-drawing';
+import { DrawingTypeEnum, FBase, generateRandomId, ICommandService, ImageSourceType, Inject, Injector } from '@univerjs/core';
+import { getImageSize } from '@univerjs/drawing';
+import { IRenderManagerService } from '@univerjs/engine-render';
+import { SetSheetDrawingCommand } from '@univerjs/sheets-drawing-ui';
+import { convertPositionCellToSheetOverGrid, convertPositionSheetOverGridToAbsolute, ISheetSelectionRenderService, SheetSkeletonManagerService } from '@univerjs/sheets-ui';
+
+export interface IFOverGridImage extends Omit<ISheetImage, 'sheetTransform' | 'transform'>, ICellOverGridPosition, IRotationSkewFlipTransform, Required<ISize> {
+
+}
+
+function convertSheetImageToFOverGridImage(sheetImage: ISheetImage, sheetSkeletonManagerService: SheetSkeletonManagerService): IFOverGridImage {
+ const { from, to, flipY = false, flipX = false, angle = 0, skewX = 0, skewY = 0 } = sheetImage.sheetTransform;
+
+ const { column: fromColumn, columnOffset: fromColumnOffset, row: fromRow, rowOffset: fromRowOffset } = from;
+
+ const absolutePosition = convertPositionSheetOverGridToAbsolute(
+ sheetImage.unitId, sheetImage.subUnitId, { from, to }, sheetSkeletonManagerService
+ );
+
+ const { left, top, width, height } = absolutePosition;
+
+ return {
+ ...sheetImage,
+ column: fromColumn,
+ columnOffset: fromColumnOffset,
+ row: fromRow,
+ rowOffset: fromRowOffset,
+ width,
+ height,
+ flipY,
+ flipX,
+ angle,
+ skewX,
+ skewY,
+ };
+}
+
+function convertFOverGridImageToSheetImage(fOverGridImage: IFOverGridImage, selectionRenderService: ISheetSelectionRenderService, sheetSkeletonManagerService: SheetSkeletonManagerService): ISheetImage {
+ const { column: fromColumn, columnOffset: fromColumnOffset, row: fromRow, rowOffset: fromRowOffset, flipY = false, flipX = false, angle = 0, skewX = 0, skewY = 0, width, height } = fOverGridImage;
+
+ const absolutePosition = convertPositionCellToSheetOverGrid(
+ fOverGridImage.unitId, fOverGridImage.subUnitId, { column: fromColumn, columnOffset: fromColumnOffset, row: fromRow, rowOffset: fromRowOffset }, width, height, selectionRenderService, sheetSkeletonManagerService
+ );
+
+ const { sheetTransform, transform } = absolutePosition;
+
+ return {
+ ...fOverGridImage,
+ sheetTransform: {
+ ...sheetTransform,
+ flipY,
+ flipX,
+ angle,
+ skewX,
+ skewY,
+ },
+ transform: {
+ ...transform,
+ flipY,
+ flipX,
+ angle,
+ skewX,
+ skewY,
+ },
+ };
+}
+
+export class FOverGridImageBuilder {
+ private _image: IFOverGridImage;
+ constructor(
+ unitId: string,
+ subUnitId: string,
+ @Inject(Injector) protected readonly _injector: Injector
+ // @Inject(SheetSkeletonManagerService) protected readonly _skeletonManagerService: SheetSkeletonManagerService,
+ // @ISheetSelectionRenderService protected readonly _selectionRenderService: ISheetSelectionRenderService
+ ) {
+ this._image = {
+ drawingId: generateRandomId(6),
+ drawingType: DrawingTypeEnum.DRAWING_IMAGE,
+ imageSourceType: ImageSourceType.BASE64,
+ source: '',
+ unitId,
+ subUnitId,
+ column: 0,
+ columnOffset: 0,
+ row: 0,
+ rowOffset: 0,
+ width: 0,
+ height: 0,
+ };
+ }
+
+ setImage(image: ISheetImage): FOverGridImageBuilder {
+ const renderManagerService = this._injector.get(IRenderManagerService);
+ const render = renderManagerService.getRenderById(image.unitId);
+ if (!render) {
+ throw new Error(`Render Unit with unitId ${image.unitId} not found`);
+ }
+ const skeletonManagerService = render.with(SheetSkeletonManagerService);
+
+ this._image = convertSheetImageToFOverGridImage(image, skeletonManagerService);
+ return this;
+ }
+
+ /**
+ * Set the unit id of the image
+ * @param unitId The unit id of the image
+ * @returns The builder
+ * @example
+ * ```ts
+ * // create a new image builder.
+ * const activeSpreadsheet = univerAPI.getActiveWorkbook();
+ * const activeSheet = activeSpreadsheet.getActiveSheet();
+ * const imageBuilder = activeSheet.newOverGridImage();
+ * const param = imageBuilder.setSource('https://avatars.githubusercontent.com/u/61444807?s=48&v=4').setColumn(5).setRow(5).build();
+ * activeSheet.insertImages([param]);
+ * ```
+ */
+ setSource(source: string): FOverGridImageBuilder;
+ setSource(source: string, sourceType?: ImageSourceType): FOverGridImageBuilder;
+ setSource(source: string, sourceType?: ImageSourceType): FOverGridImageBuilder {
+ const sourceTypeVal = sourceType ?? ImageSourceType.URL;
+ this._image.source = source;
+ this._image.imageSourceType = sourceTypeVal;
+ return this;
+ }
+
+ getsource(): string {
+ return this._image.source;
+ }
+
+ getSourceType(): ImageSourceType {
+ return this._image.imageSourceType;
+ }
+
+ setColumn(column: number): FOverGridImageBuilder {
+ this._image.column = column;
+ return this;
+ }
+
+ setRow(row: number): FOverGridImageBuilder {
+ this._image.row = row;
+ return this;
+ }
+
+ setColumnOffset(offset: number): FOverGridImageBuilder {
+ this._image.columnOffset = offset;
+ return this;
+ }
+
+ setRowOffset(offset: number): FOverGridImageBuilder {
+ this._image.rowOffset = offset;
+ return this;
+ }
+
+ setWidth(width: number): FOverGridImageBuilder {
+ this._image.width = width;
+ return this;
+ }
+
+ setHeight(height: number): FOverGridImageBuilder {
+ this._image.height = height;
+ return this;
+ }
+
+ setAnchorType(anchorType: SheetDrawingAnchorType): FOverGridImageBuilder {
+ this._image.anchorType = anchorType;
+ return this;
+ }
+
+ setCropTop(top: number): FOverGridImageBuilder {
+ this._initializeSrcRect();
+ this._image.srcRect!.top = top;
+ return this;
+ }
+
+ setCropLeft(left: number): FOverGridImageBuilder {
+ this._initializeSrcRect();
+ this._image.srcRect!.left = left;
+ return this;
+ }
+
+ setCropBottom(bottom: number): FOverGridImageBuilder {
+ this._initializeSrcRect();
+ this._image.srcRect!.bottom = bottom;
+ return this;
+ }
+
+ setCropRight(right: number): FOverGridImageBuilder {
+ this._initializeSrcRect();
+ this._image.srcRect!.right = right;
+ return this;
+ }
+
+ private _initializeSrcRect(): void {
+ if (this._image.srcRect == null) {
+ this._image.srcRect = {
+ top: 0,
+ left: 0,
+ bottom: 0,
+ right: 0,
+ };
+ }
+ }
+
+ /**
+ * Set the rotation angle of the image
+ * @param angle Degree of rotation of the image, for example, 90, 180, 270, etc.
+ * @returns The builder
+ */
+ setRotate(angle: number): FOverGridImageBuilder {
+ this._image.angle = angle;
+ return this;
+ }
+
+ // setPresetGeometry(prstGeom: PresetGeometryType): FOverGridImageBuilder {
+ // this._image.prstGeom = prstGeom;
+ // return this;
+ // }
+
+ setUnitId(unitId: string): FOverGridImageBuilder {
+ this._image.unitId = unitId;
+ return this;
+ }
+
+ setSubUnitId(subUnitId: string): FOverGridImageBuilder {
+ this._image.subUnitId = subUnitId;
+ return this;
+ }
+
+ async build(): Promise<ISheetImage> {
+ const renderManagerService = this._injector.get(IRenderManagerService);
+ const render = renderManagerService.getRenderById(this._image.unitId);
+ if (!render) {
+ throw new Error(`Render Unit with unitId ${this._image.unitId} not found`);
+ }
+ const selectionRenderService = render.with(ISheetSelectionRenderService);
+ const skeletonManagerService = render.with(SheetSkeletonManagerService);
+
+ if (this._image.width === 0 || this._image.height === 0) {
+ const size = await getImageSize(this._image.source);
+ const width = size.width;
+ const height = size.height;
+
+ if (this._image.width === 0) {
+ this._image.width = width;
+ }
+
+ if (this._image.height === 0) {
+ this._image.height = height;
+ }
+ }
+
+ return convertFOverGridImageToSheetImage(this._image, selectionRenderService, skeletonManagerService);
+ }
+}
+
+export class FOverGridImage extends FBase {
+ constructor(
+ private _image: ISheetImage,
+ @ICommandService protected readonly _commandService: ICommandService,
+ @Inject(Injector) protected readonly _injector: Injector
+ ) {
+ super();
+ }
+
+ getId(): string {
+ return this._image.drawingId;
+ }
+
+ getType(): DrawingTypeEnum {
+ return this._image.drawingType;
+ }
+
+ /**
+ * Remove the image from the sheet
+ * @returns success or not
+ * @example
+ * ```ts
+ * // remove the image from the sheet
+ * const activeSpreadsheet = univerAPI.getActiveWorkbook();
+ * const activeSheet = activeSpreadsheet.getActiveSheet();
+ * const image = activeSheet.getImages[0];
+ * console.log('Delete state is ', image?.remove());
+ * ```
+ */
+ remove(): boolean {
+ return this._commandService.syncExecuteCommand(SetSheetDrawingCommand.id, { unitId: this._image.unitId, drawings: [this._image] });
+ }
+
+ /**
+ * Convert the image to a FOverGridImageBuilder
+ * @returns The builder FOverGridImageBuilder
+ * @example
+ * ```ts
+ * // convert the image to a builder
+ * const activeSpreadsheet = univerAPI.getActiveWorkbook();
+ * const activeSheet = activeSpreadsheet.getActiveSheet();
+ * const image = activeSheet.getImages[0];
+ * const builder = image.toBuilder();
+ * builder.setSource('https://avatars.githubusercontent.com/u/61444807?s=48&v=4').setColumn(5).setRow(5).build();
+ * activeSheet.updateImages([builder.build()]);
+ * ```
+ */
+ toBuilder(): FOverGridImageBuilder {
+ const builder = this._injector.createInstance(FOverGridImageBuilder);
+ builder.setImage(this._image);
+ return builder;
+ }
+
+ /**
+ * Set the source of the image
+ * @param source The source of the image
+ * @returns success or not
+ * @example
+ * ```ts
+ * // set the source of the image
+ * const activeSpreadsheet = univerAPI.getActiveWorkbook();
+ * const activeSheet = activeSpreadsheet.getActiveSheet();
+ * const image = activeSheet.getImages[0];
+ * console.log('Set source state is ', image.setSource('https://avatars.githubusercontent.com/u/61444807?s=48&v=4'));
+ */
+ setSource(source: string): boolean;
+ /**
+ * Set the source of the image, change image display.
+ * @param source The source of the image
+ * @param sourceType The source type of the image
+ * @returns success or not
+ */
+ setSource(source: string, sourceType?: ImageSourceType): boolean;
+ setSource(source: string, sourceType?: ImageSourceType): boolean {
+ const sourceTypeVal = sourceType ?? ImageSourceType.URL;
+ this._image.source = source;
+ this._image.imageSourceType = sourceTypeVal;
+ return this._commandService.syncExecuteCommand(SetSheetDrawingCommand.id, { unitId: this._image.unitId, drawings: [this._image] });
+ }
+
+ /**
+ * Set the position of the image
+ * @param row The sheet start row of the image
+ * @param column The sheet start column of the image
+ * @returns success or not
+ * @example
+ * ```ts
+ * // set the position of the image
+ * const activeSpreadsheet = univerAPI.getActiveWorkbook();
+ * const activeSheet = activeSpreadsheet.getActiveSheet();
+ * const image = activeSheet.getImages[0];
+ * console.log('Set position state is ', image.setPosition(5, 5));
+ * ```
+ */
+ setPosition(row: number, column: number): boolean;
+ /**
+ *
+ * @param column The sheet start column of the image
+ * @param row The sheet start row of the image
+ * @param rowOffset The offset of the start row
+ * @param columnOffset The offset of the start column
+ */
+ setPosition(row: number, column: number, rowOffset?: number, columnOffset?: number): boolean;
+ setPosition(row: number, column: number, rowOffset?: number, columnOffset?: number): boolean {
+ const builder = this.toBuilder();
+ builder.setColumn(column);
+ builder.setRow(row);
+ if (rowOffset != null) {
+ builder.setRowOffset(rowOffset);
+ }
+ if (columnOffset != null) {
+ builder.setColumnOffset(columnOffset);
+ }
+ return this._commandService.syncExecuteCommand(SetSheetDrawingCommand.id, { unitId: this._image.unitId, drawings: [builder.build()] });
+ }
+
+ /**
+ * Set the size of the image
+ * @param width The width of the image
+ * @param height The height of the image
+ * @returns success or not
+ */
+ setSize(width: number, height: number): boolean {
+ const builder = this.toBuilder();
+ builder.setWidth(width);
+ builder.setHeight(height);
+ return this._commandService.syncExecuteCommand(SetSheetDrawingCommand.id, { unitId: this._image.unitId, drawings: [builder.build()] });
+ }
+
+ /**
+ * Set the cropping region of the image by defining the top, bottom, left, and right edges, thereby displaying the specific part of the image you want.
+ * @param top The number of pixels to crop from the top of the image.
+ * @param left The number of pixels to crop from the left side of the image.
+ * @param bottom The number of pixels to crop from the bottom of the image.
+ * @param right The number of pixels to crop from the right side of the image.
+ * @returns success or not
+ * @example
+ * ```ts
+ * // set the crop of the image
+ * const activeSpreadsheet = univerAPI.getActiveWorkbook();
+ * const activeSheet = activeSpreadsheet.getActiveSheet();
+ * const image = activeSheet.getImages[0];
+ * console.log('Set crop state is ', image.setCrop(0, 0, 0, 0));
+ * ```
+ */
+ setCrop(top?: number, left?: number, bottom?: number, right?: number): boolean {
+ if (this._image.srcRect == null) {
+ this._image.srcRect = {
+ top: 0,
+ left: 0,
+ bottom: 0,
+ right: 0,
+ };
+ }
+
+ if (top != null) {
+ this._image.srcRect.top = top;
+ }
+
+ if (left != null) {
+ this._image.srcRect.left = left;
+ }
+
+ if (bottom != null) {
+ this._image.srcRect.bottom = bottom;
+ }
+
+ if (right != null) {
+ this._image.srcRect.right = right;
+ }
+
+ return this._commandService.syncExecuteCommand(SetSheetDrawingCommand.id, { unitId: this._image.unitId, drawings: [this._image] });
+ }
+
+ // setPresetGeometry(prstGeom: PresetGeometryType): boolean {
+ // this._image.prstGeom = prstGeom;
+ // return this._commandService.syncExecuteCommand(SetSheetDrawingCommand.id, { unitId: this._image.unitId, drawings: [this._image] });
+ // }
+
+ /**
+ * Set the rotation angle of the image
+ * @param angle Degree of rotation of the image, for example, 90, 180, 270, etc.
+ * @returns success or not
+ */
+ setRotate(angle: number): boolean {
+ this._image.sheetTransform.angle = angle;
+ return this._commandService.syncExecuteCommand(SetSheetDrawingCommand.id, { unitId: this._image.unitId, drawings: [this._image] });
+ }
+}
diff --git a/packages/sheets-drawing-ui/src/facade/f-worksheet.ts b/packages/sheets-drawing-ui/src/facade/f-worksheet.ts
index 43168c25ab..ab43965a60 100644
--- a/packages/sheets-drawing-ui/src/facade/f-worksheet.ts
+++ b/packages/sheets-drawing-ui/src/facade/f-worksheet.ts
@@ -14,11 +14,13 @@
* limitations under the License.
*/
-import type { Nullable } from '@univerjs/core';
-import { FWorksheet } from '@univerjs/sheets/facade';
-import { type ICanvasFloatDom, SheetCanvasFloatDomManagerService } from '@univerjs/sheets-drawing-ui';
+import { type IFBlobSource, ImageSourceType, type Nullable } 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 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';
export interface IFICanvasFloatDom extends Omit<ICanvasFloatDom, 'componentKey' | 'unitId' | 'subUnitId'>, IFComponentKey {}
@@ -33,6 +35,102 @@ export interface IFWorksheetLegacy {
id: string;
dispose: () => void;
}>;
+
+ /**
+ * Insert an image to the sheet
+ * @param url The image url
+ * @param column The column to insert the image
+ * @param row The row to insert the image
+ * @param offsetX The offset x of the image
+ * @param offsetY The offset y of the image
+ * @returns true if the image is inserted successfully
+ * @example
+ * ```ts
+ * const activeSpreadsheet = univerAPI.getActiveWorkbook();
+ * const activeSheet = activeSpreadsheet.getActiveSheet();
+ * activeSheet.insertImage('https://avatars.githubusercontent.com/u/61444807?s=48&v=4', 5, 5, 0, 0);
+ * ```
+ */
+ insertImage(url: string): Promise<boolean>;
+ insertImage(url: string, column: number, row: number): Promise<boolean>;
+ insertImage(url: string, column: number, row: number, offsetX: number, offsetY: number): Promise<boolean>;
+ insertImage(url: IFBlobSource): Promise<boolean>;
+ insertImage(url: IFBlobSource, column: number, row: number): Promise<boolean>;
+ insertImage(url: IFBlobSource, column: number, row: number, offsetX: number, offsetY: number): Promise<boolean>;
+ insertImage(url: IFBlobSource | string, column: number, row: number, offsetX: number, offsetY: number): Promise<boolean>;
+
+ /**
+ * Insert images to the sheet
+ * @param sheetImages The images to insert
+ * @returns true if the image is inserted successfully
+ * @example
+ * ```ts
+ * const activeSpreadsheet = univerAPI.getActiveWorkbook();
+ * const activeSheet = activeSpreadsheet.getActiveSheet();
+ * const imageBuilder = activeSheet.newOverGridImage();
+ * const param = await imageBuilder.setSource('https://avatars.githubusercontent.com/u/61444807?s=48&v=4').setColumn(5).setRow(5).setWidth(500).setHeight(300).build();
+ * activeSheet.insertImages([param]);
+ *
+ *
+ * const image = activeSheet.getImageById(param.drawingId);
+ * console.log(image);
+
+ * setTimeout(async ()=>{
+ * const builder = image.toBuilder();
+ * const param = await builder.setHeight(50).setWidth(100).build();
+ * activeSheet.updateImages([param]);
+ * }, 4000);
+ */
+ insertImages(sheetImages: ISheetImage[]): void;
+
+ getImages(): FOverGridImage[];
+
+ getImageById(id: string): FOverGridImage | null;
+
+ deleteImages(sheetImages: FOverGridImage[]): void;
+
+ /**
+ * Update images to the sheet
+ * @param sheetImages The images to insert
+ * @returns true if the image is inserted successfully
+ * @example
+ * ```ts
+ * const activeSpreadsheet = univerAPI.getActiveWorkbook();
+ * const activeSheet = activeSpreadsheet.getActiveSheet();
+ * const imageBuilder = activeSheet.newOverGridImage();
+ * const param = await imageBuilder.setSource('https://avatars.githubusercontent.com/u/61444807?s=48&v=4').setColumn(5).setRow(5).setWidth(500).setHeight(300).build();
+ * activeSheet.insertImages([param]);
+ *
+ *
+ * const image = activeSheet.getImageById(param.drawingId);
+ * console.log(image);
+
+ * setTimeout(async ()=>{
+ * const builder = image.toBuilder();
+ * const param = await builder.setHeight(50).setWidth(100).build();
+ * activeSheet.updateImages([param]);
+ * }, 4000);
+ */
+ updateImages(sheetImages: ISheetImage[]): void;
+
+ getActiveImages(): FOverGridImage[];
+
+ onImageInserted(callback: (images: FOverGridImage[]) => void): void;
+
+ onImageDeleted(callback: (images: FOverGridImage[]) => void): void;
+
+ onImageChanged(callback: (images: FOverGridImage[]) => void): void;
+
+ /**
+ * Create a new over grid image builder.
+ * @returns The builder
+ * @example
+ * ```ts
+ * // create a new over grid image builder.
+ * const builder = UniverApi.newOverGridImage();
+ * ```
+ */
+ newOverGridImage(): FOverGridImageBuilder;
}
export class FWorksheetLegacy extends FWorksheet implements IFWorksheetLegacy {
@@ -60,6 +158,138 @@ export class FWorksheetLegacy extends FWorksheet implements IFWorksheetLegacy {
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') {
+ imageBuilder.setSource(url);
+ } else {
+ const blobSource = url.getBlob();
+ const base64 = await blobSource.getDataAsString();
+ imageBuilder.setSource(base64, ImageSourceType.BASE64);
+ }
+
+ if (column !== undefined) {
+ imageBuilder.setColumn(column);
+ } else {
+ imageBuilder.setColumn(0);
+ }
+
+ if (row !== undefined) {
+ imageBuilder.setRow(row);
+ } else {
+ imageBuilder.setRow(0);
+ }
+
+ if (offsetX !== undefined) {
+ imageBuilder.setColumnOffset(offsetX);
+ } else {
+ imageBuilder.setColumnOffset(0);
+ }
+
+ if (offsetY !== undefined) {
+ imageBuilder.setRowOffset(offsetY);
+ } else {
+ imageBuilder.setRowOffset(0);
+ }
+
+ const param = await imageBuilder.build();
+
+ return this._commandService.syncExecuteCommand(InsertSheetDrawingCommand.id, { unitId: this._fWorkbook.getId(), drawings: [param] });
+ }
+
+ override insertImages(sheetImages: ISheetImage[]): void {
+ const param = sheetImages.map((image) => {
+ image.unitId = this._fWorkbook.getId();
+ image.subUnitId = this.getSheetId();
+ return image;
+ });
+
+ this._commandService.syncExecuteCommand(InsertSheetDrawingCommand.id, { unitId: this._fWorkbook.getId(), drawings: param });
+ }
+
+ override deleteImages(sheetImages: FOverGridImage[]): void {
+ const drawings = sheetImages.map((image) => {
+ return {
+ unitId: this._fWorkbook.getId(),
+ drawingId: image.getId(),
+ subUnitId: this.getSheetId(),
+ drawingType: image.getType(),
+ };
+ });
+ this._commandService.syncExecuteCommand(RemoveSheetDrawingCommand.id, { unitId: this._fWorkbook.getId(), drawings });
+ }
+
+ override getImages(): FOverGridImage[] {
+ const sheetDrawingService = this._injector.get(ISheetDrawingService);
+ const drawingData = sheetDrawingService.getDrawingData(this._fWorkbook.getId(), this.getSheetId());
+ const images: FOverGridImage[] = [];
+ for (const drawingId in drawingData) {
+ const drawing = drawingData[drawingId];
+ images.push(this._injector.createInstance(FOverGridImage, drawing as ISheetImage));
+ }
+ return images;
+ }
+
+ override getImageById(id: string): FOverGridImage | null {
+ const sheetDrawingService = this._injector.get(ISheetDrawingService);
+ const drawing = sheetDrawingService.getDrawingByParam({ unitId: this._fWorkbook.getId(), subUnitId: this.getSheetId(), drawingId: id });
+ if (drawing) {
+ return this._injector.createInstance(FOverGridImage, drawing as ISheetImage);
+ }
+ return null;
+ }
+
+ override getActiveImages(): FOverGridImage[] {
+ const sheetDrawingService = this._injector.get(ISheetDrawingService);
+ const drawingData = sheetDrawingService.getFocusDrawings();
+ const images: FOverGridImage[] = [];
+ for (const drawingId in drawingData) {
+ const drawing = drawingData[drawingId];
+ images.push(this._injector.createInstance(FOverGridImage, drawing as ISheetImage));
+ }
+ return images;
+ }
+
+ override updateImages(sheetImages: ISheetImage[]): void {
+ this._commandService.syncExecuteCommand(SetSheetDrawingCommand.id, { unitId: this._fWorkbook.getId(), drawings: sheetImages });
+ }
+
+ override onImageInserted(callback: (images: FOverGridImage[]) => void): void {
+ const sheetDrawingService = this._injector.get(ISheetDrawingService);
+ sheetDrawingService.add$.subscribe((drawingSearches) => {
+ const drawings = drawingSearches.map(
+ (drawingSearch) => this._injector.createInstance(FOverGridImage, sheetDrawingService.getDrawingByParam(drawingSearch) as ISheetImage)
+ );
+ callback(drawings);
+ });
+ }
+
+ override onImageDeleted(callback: (images: FOverGridImage[]) => void): void {
+ const sheetDrawingService = this._injector.get(ISheetDrawingService);
+ sheetDrawingService.remove$.subscribe((drawingSearches) => {
+ const drawings = drawingSearches.map(
+ (drawingSearch) => this._injector.createInstance(FOverGridImage, sheetDrawingService.getDrawingByParam(drawingSearch) as ISheetImage)
+ );
+ callback(drawings);
+ });
+ }
+
+ override onImageChanged(callback: (images: FOverGridImage[]) => void): void {
+ const sheetDrawingService = this._injector.get(ISheetDrawingService);
+ sheetDrawingService.update$.subscribe((drawingSearches) => {
+ const drawings = drawingSearches.map(
+ (drawingSearch) => this._injector.createInstance(FOverGridImage, sheetDrawingService.getDrawingByParam(drawingSearch) as ISheetImage)
+ );
+ callback(drawings);
+ });
+ }
+
+ override newOverGridImage(): FOverGridImageBuilder {
+ const unitId = this._fWorkbook.getId();
+ const subUnitId = this.getSheetId();
+ return this._injector.createInstance(FOverGridImageBuilder, unitId, subUnitId);
+ }
}
FWorksheet.extend(FWorksheetLegacy);
diff --git a/packages/sheets-drawing-ui/src/facade/index.ts b/packages/sheets-drawing-ui/src/facade/index.ts
index 8e0a40109e..c5650dbb98 100644
--- a/packages/sheets-drawing-ui/src/facade/index.ts
+++ b/packages/sheets-drawing-ui/src/facade/index.ts
@@ -14,6 +14,8 @@
* limitations under the License.
*/
+import './f-over-grid-image';
import './f-worksheet';
+export type * from './f-over-grid-image';
export type * from './f-worksheet';
diff --git a/packages/sheets-drawing/package.json b/packages/sheets-drawing/package.json
index 029c8ab422..ee179dfa06 100644
--- a/packages/sheets-drawing/package.json
+++ b/packages/sheets-drawing/package.json
@@ -57,7 +57,8 @@
},
"dependencies": {
"@univerjs/core": "workspace:*",
- "@univerjs/drawing": "workspace:*"
+ "@univerjs/drawing": "workspace:*",
+ "@univerjs/sheets": "workspace:*"
},
"devDependencies": {
"@univerjs-infra/shared": "workspace:*",
diff --git a/packages/sheets-drawing/src/index.ts b/packages/sheets-drawing/src/index.ts
index 5c4e458433..7b53198cd0 100644
--- a/packages/sheets-drawing/src/index.ts
+++ b/packages/sheets-drawing/src/index.ts
@@ -17,7 +17,7 @@
export { UniverSheetsDrawingPlugin } from './plugin';
export { ISheetDrawingService, SheetDrawingAnchorType } from './services/sheet-drawing.service';
export { SHEET_DRAWING_PLUGIN } from './controllers/sheet-drawing.controller';
-export type { IFloatDomData, ISheetDrawing, ISheetDrawingPosition, ISheetFloatDom } from './services/sheet-drawing.service';
+export type { IFloatDomData, ISheetDrawing, ISheetDrawingPosition, ISheetFloatDom, ISheetImage } from './services/sheet-drawing.service';
// #region - all commands
diff --git a/packages/sheets-drawing/src/services/sheet-drawing.service.ts b/packages/sheets-drawing/src/services/sheet-drawing.service.ts
index 4685dfc27d..8535164ccb 100644
--- a/packages/sheets-drawing/src/services/sheet-drawing.service.ts
+++ b/packages/sheets-drawing/src/services/sheet-drawing.service.ts
@@ -15,25 +15,18 @@
*/
import type { IDrawingParam, IRotationSkewFlipTransform, Serializable } from '@univerjs/core';
+import type { ISheetOverGridPosition } from '@univerjs/sheets';
import { createIdentifier } from '@univerjs/core';
import { type IImageData, type IUnitDrawingService, UnitDrawingService } from '@univerjs/drawing';
-interface ICellPosition {
- column: number; // column number
- columnOffset: number; // column offset, unit is EMUs
- row: number; // row number
- rowOffset: number; // row offset, unit is EMUs
-}
-
export enum SheetDrawingAnchorType {
Position = '0',
Both = '1',
None = '2',
}
-export interface ISheetDrawingPosition extends IRotationSkewFlipTransform {
- from: ICellPosition;
- to: ICellPosition;
+export interface ISheetDrawingPosition extends IRotationSkewFlipTransform, ISheetOverGridPosition {
+
}
export interface ISheetDrawingBase {
diff --git a/packages/sheets-ui/src/index.ts b/packages/sheets-ui/src/index.ts
index 8c0e67a21c..04bee121f7 100644
--- a/packages/sheets-ui/src/index.ts
+++ b/packages/sheets-ui/src/index.ts
@@ -180,5 +180,6 @@ export { SheetPermissionOpenDialogOperation } from './commands/operations/sheet-
export { SheetPermissionOpenPanelOperation } from './commands/operations/sheet-permission-open-panel.operation';
export { SidebarDefinedNameOperation } from './commands/operations/sidebar-defined-name.operation';
export { UNIVER_SHEET_PERMISSION_BACKGROUND, UNIVER_SHEET_PERMISSION_USER_PART } from './consts/permission';
+export { convertPositionCellToSheetOverGrid, convertPositionSheetOverGridToAbsolute } from './services/utils/drawing-position-util';
export type { IScrollState, IViewportScrollState } from './services/scroll-manager.service';
// #endregion
diff --git a/packages/sheets-ui/src/services/selection/base-selection-render.service.ts b/packages/sheets-ui/src/services/selection/base-selection-render.service.ts
index c2a4695c09..1d78b0f54c 100644
--- a/packages/sheets-ui/src/services/selection/base-selection-render.service.ts
+++ b/packages/sheets-ui/src/services/selection/base-selection-render.service.ts
@@ -79,7 +79,7 @@ export interface ISheetSelectionRenderService {
*/
getSelectionCellByPosition(x: number, y: number): ICellWithCoord;
- getCellWithCoordByOffset(x: number, y: number): Nullable<ICellWithCoord>; // drawing
+ getCellWithCoordByOffset(x: number, y: number, skeleton?: SpreadsheetSkeleton): Nullable<ICellWithCoord>; // drawing
setSingleSelectionEnabled(enabled: boolean): void;
@@ -627,9 +627,9 @@ export class BaseSelectionRenderService extends Disposable implements ISheetSele
return this.getCellWithCoordByOffset(x, y);
}
- getCellWithCoordByOffset(x: number, y: number): ICellWithCoord {
+ getCellWithCoordByOffset(x: number, y: number, skeletonParam?: SpreadsheetSkeleton): ICellWithCoord {
const scene = this._scene;
- const skeleton = this._skeleton;
+ const skeleton = skeletonParam ?? this._skeleton;
const scrollXY = scene.getViewportScrollXY(scene.getViewport(SHEET_VIEWPORT_KEY.VIEW_MAIN)!);
const { scaleX, scaleY } = scene.getAncestorScale();
diff --git a/packages/sheets-ui/src/services/utils/drawing-position-util.ts b/packages/sheets-ui/src/services/utils/drawing-position-util.ts
new file mode 100644
index 0000000000..9840745963
--- /dev/null
+++ b/packages/sheets-ui/src/services/utils/drawing-position-util.ts
@@ -0,0 +1,130 @@
+/**
+ * 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 { ICellOverGridPosition, ISheetOverGridPosition } from '@univerjs/sheets';
+import type { ISheetSelectionRenderService } from '../selection/base-selection-render.service';
+import type { SheetSkeletonManagerService } from '../sheet-skeleton-manager.service';
+import { precisionTo } from '@univerjs/engine-render';
+import { attachRangeWithCoord } from '../selection/util';
+
+export function convertPositionSheetOverGridToAbsolute(unitId: string, subUnitId: string, sheetOverGridPosition: ISheetOverGridPosition, sheetSkeletonManagerService: SheetSkeletonManagerService) {
+ const { from, to } = sheetOverGridPosition;
+
+ const { column: fromColumn, columnOffset: fromColumnOffset, row: fromRow, rowOffset: fromRowOffset } = from;
+ const { column: toColumn, columnOffset: toColumnOffset, row: toRow, rowOffset: toRowOffset } = to;
+
+ const skeleton = sheetSkeletonManagerService.getOrCreateSkeleton({ sheetId: subUnitId });
+
+ if (skeleton == null) {
+ throw new Error('No current skeleton');
+ }
+
+ const startSelectionCell = attachRangeWithCoord(skeleton, {
+ startColumn: fromColumn,
+ endColumn: fromColumn,
+ startRow: fromRow,
+ endRow: fromRow,
+ });
+
+ const endSelectionCell = attachRangeWithCoord(skeleton, {
+ startColumn: toColumn,
+ endColumn: toColumn,
+ startRow: toRow,
+ endRow: toRow,
+ });
+
+ const { startX: startSelectionX, startY: startSelectionY } = startSelectionCell;
+
+ const { startX: endSelectionX, startY: endSelectionY } = endSelectionCell;
+
+ const left = precisionTo(startSelectionX + fromColumnOffset, 1);
+ const top = precisionTo(startSelectionY + fromRowOffset, 1);
+
+ let width = precisionTo(endSelectionX + toColumnOffset - left, 1);
+ let height = precisionTo(endSelectionY + toRowOffset - top, 1);
+
+ if (startSelectionCell.startX === endSelectionCell.endX) {
+ width = 0;
+ }
+
+ if (startSelectionCell.startY === endSelectionCell.endY) {
+ height = 0;
+ }
+
+ return {
+ unitId,
+ subUnitId,
+ left,
+ top,
+ width,
+ height,
+ };
+}
+
+export function convertPositionCellToSheetOverGrid(unitId: string, subUnitId: string, cellOverGridPosition: ICellOverGridPosition, width: number, height: number, selectionRenderService: ISheetSelectionRenderService, sheetSkeletonManagerService: SheetSkeletonManagerService) {
+ const { column: fromColumn, columnOffset: fromColumnOffset, row: fromRow, rowOffset: fromRowOffset } = cellOverGridPosition;
+
+ const skeleton = sheetSkeletonManagerService.getOrCreateSkeleton({ sheetId: subUnitId });
+
+ if (skeleton == null) {
+ throw new Error('No current skeleton');
+ }
+
+ const startSelectionCell = attachRangeWithCoord(skeleton, {
+ startColumn: fromColumn,
+ endColumn: fromColumn,
+ startRow: fromRow,
+ endRow: fromRow,
+ });
+
+ const { startX: startSelectionX, startY: startSelectionY } = startSelectionCell;
+
+ const left = precisionTo(startSelectionX + fromColumnOffset, 1);
+ const top = precisionTo(startSelectionY + fromRowOffset, 1);
+
+ const endSelectionCell = selectionRenderService.getCellWithCoordByOffset(left + width, top + height, skeleton);
+
+ if (endSelectionCell == null) {
+ throw new Error('No end selection cell');
+ }
+
+ const to = {
+ column: endSelectionCell.actualColumn,
+ columnOffset: precisionTo(left + width - endSelectionCell.startX, 1),
+ row: endSelectionCell.actualRow,
+ rowOffset: precisionTo(top + height - endSelectionCell.startY, 1),
+ };
+
+ return {
+ unitId,
+ subUnitId,
+ sheetTransform: {
+ from: {
+ column: fromColumn,
+ columnOffset: fromColumnOffset,
+ row: fromRow,
+ rowOffset: fromRowOffset,
+ },
+ to,
+ },
+ transform: {
+ left,
+ top,
+ width,
+ height,
+ },
+ };
+}
diff --git a/packages/sheets/src/basics/cell-position.ts b/packages/sheets/src/basics/cell-position.ts
new file mode 100644
index 0000000000..35891011cf
--- /dev/null
+++ b/packages/sheets/src/basics/cell-position.ts
@@ -0,0 +1,27 @@
+/**
+ * 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.
+ */
+
+export interface ICellOverGridPosition {
+ column: number; // column number
+ columnOffset: number; // column offset, pixel unit
+ row: number; // row number
+ rowOffset: number; // row offset, pixel unit
+}
+
+export interface ISheetOverGridPosition {
+ from: ICellOverGridPosition; // Start position in its own sheet.
+ to: ICellOverGridPosition; // End position in its own sheet.
+}
diff --git a/packages/sheets/src/basics/index.ts b/packages/sheets/src/basics/index.ts
index e4c19b883d..07569e9364 100644
--- a/packages/sheets/src/basics/index.ts
+++ b/packages/sheets/src/basics/index.ts
@@ -14,6 +14,7 @@
* limitations under the License.
*/
+export * from './cell-position';
export * from './const/index';
export * from './interfaces/index';
export * from './selection';
diff --git a/packages/sheets/src/index.ts b/packages/sheets/src/index.ts
index faba482646..eb675b3cdc 100644
--- a/packages/sheets/src/index.ts
+++ b/packages/sheets/src/index.ts
@@ -421,4 +421,5 @@ export { type ISetSelectionsOperationParams, SetSelectionsOperation } from './co
export { type ISetWorksheetActiveOperationParams, SetWorksheetActiveOperation } from './commands/operations/set-worksheet-active.operation';
export { type IToggleCellCheckboxCommandParams, ToggleCellCheckboxCommand } from './commands/commands/toggle-checkbox.command';
export { SCOPE_WORKBOOK_VALUE_DEFINED_NAME } from './controllers/defined-name-data.controller';
+export type { ICellOverGridPosition, ISheetOverGridPosition } from './basics/cell-position';
// #endregion
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index d42b9c4237..b96a05487f 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -49,7 +49,7 @@ importers:
version: link:packages/design
'@vitejs/plugin-react':
specifier: ^4.3.4
eslint:
specifier: 9.16.0
version: 9.16.0([email protected])
@@ -2286,6 +2286,9 @@ importers:
'@univerjs/drawing':
specifier: workspace:*
version: link:../drawing
+ '@univerjs/sheets':
+ specifier: workspace:*
+ version: link:../sheets
devDependencies:
'@univerjs-infra/shared':
specifier: workspace:*
@@ -12508,6 +12511,17 @@ snapshots:
'@grpc/grpc-js': 1.10.9
rxjs: 7.8.1
+ dependencies:
+ '@babel/core': 7.26.0
+ '@babel/plugin-transform-react-jsx-self': 7.25.9(@babel/[email protected])
+ '@babel/plugin-transform-react-jsx-source': 7.25.9(@babel/[email protected])
+ '@types/babel__core': 7.20.5
+ react-refresh: 0.14.2
+ transitivePeerDependencies:
+ - supports-color
+
dependencies:
'@babel/core': 7.26.0