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.

50.1 KB
Raw Blame
/**
 * Copyright 2023-present DreamNum Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import type {
    IRotationSkewFlipTransform,
    ISize,
} from '@univerjs/core';
import type { SpreadsheetSkeleton } from '@univerjs/engine-render';
import type { ICellOverGridPosition } from '@univerjs/sheets';
import type {
    ISheetDrawingPlacement,
    ISheetDrawingPlacementInput,
    ISheetImage,
} from '@univerjs/sheets-drawing';
import {
    ArrangeTypeEnum,
    DrawingTypeEnum,
    generateRandomId,
    ICommandService,
    ImageSourceType,
    Inject,
    Injector,
} from '@univerjs/core';
import { FBase } from '@univerjs/core/facade';
import { getImageSize } from '@univerjs/drawing';
import { convertPositionCellToSheetOverGrid, convertPositionSheetOverGridToAbsolute, SheetSkeletonService } from '@univerjs/sheets';
import {
    applySheetDrawingPlacement,
    getSheetDrawingPlacement,
    ISheetDrawingService,
    RemoveSheetDrawingCommand,
    SetDrawingArrangeCommand,
    SetSheetDrawingCommand,
    SetSheetDrawingPlacementCommand,
    SheetDrawingAnchorType,
    transformToAxisAlignPosition,
} from '@univerjs/sheets-drawing';

export interface IFOverGridImage extends Omit<ISheetImage, 'sheetTransform' | 'transform'>, ICellOverGridPosition, IRotationSkewFlipTransform, Required<ISize> {

}

/**
 * Convert the image parameter to a FOverGridImage
 * @param {ISheetImage} sheetImage The image parameter
 * @param {SpreadsheetSkeleton} skeleton The skeleton of the sheet where the image is located
 * @returns {IFOverGridImage} The FOverGridImage {@link IFOverGridImage}
 */
function convertSheetImageToFOverGridImage(sheetImage: ISheetImage, skeleton: SpreadsheetSkeleton): 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 },
        skeleton
    );

    const { width, height } = absolutePosition;

    return {
        ...sheetImage,
        column: fromColumn,
        columnOffset: fromColumnOffset,
        row: fromRow,
        rowOffset: fromRowOffset,
        width,
        height,
        flipY,
        flipX,
        angle,
        skewX,
        skewY,
    };
}

/**
 * Convert the FOverGridImage to a ISheetImage
 * @param {IFOverGridImage} fOverGridImage The FOverGridImage
 * @param {SheetSkeletonService} sheetSkeletonService The sheet skeleton service
 * @returns {ISheetImage} The ISheetImage {@link ISheetImage}
 */
function convertFOverGridImageToSheetImage(fOverGridImage: IFOverGridImage, sheetSkeletonService: SheetSkeletonService): ISheetImage {
    const skeleton = sheetSkeletonService.ensureSkeleton(fOverGridImage.unitId, fOverGridImage.subUnitId);
    if (!skeleton) {
        throw new Error(`Skeleton for unitId ${fOverGridImage.unitId} and subUnitId ${fOverGridImage.subUnitId} not found`);
    }

    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,
        skeleton
    );

    const { sheetTransform, transform } = absolutePosition;

    return {
        ...fOverGridImage,
        sheetTransform: {
            ...sheetTransform,
            flipY,
            flipX,
            angle,
            skewX,
            skewY,
        },
        transform: {
            ...transform,
            flipY,
            flipX,
            angle,
            skewX,
            skewY,
        },
        axisAlignSheetTransform: transformToAxisAlignPosition(transform, skeleton),
    };
}

/**
 * @hideconstructor
 */
export class FOverGridImageBuilder {
    private _image: IFOverGridImage;
    private _placement?: ISheetDrawingPlacementInput;
    constructor(
        unitId: string,
        subUnitId: string,
        @Inject(SheetSkeletonService) private readonly _sheetSkeletonService: SheetSkeletonService
    ) {
        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,
            axisAlignSheetTransform: {
                from: {
                    column: 0,
                    columnOffset: 0,
                    row: 0,
                    rowOffset: 0,
                },
                to: {
                    column: 0,
                    columnOffset: 0,
                    row: 0,
                    rowOffset: 0,
                },
            },
        };
    }

    /**
     * Set the initial image configuration for the image builder.
     * @param {ISheetImage} image - The image configuration
     * @returns {FOverGridImageBuilder} The `FOverGridImageBuilder` for chaining
     * @example
     * ```ts
     * // create a new image builder and set initial image configuration.
     * // then build `ISheetImage` and insert it into the sheet, position is start from F6 cell.
     * const fWorkbook = univerAPI.getActiveWorkbook();
     * const fWorksheet = fWorkbook.getSheetByName('Sheet1');
     * if (!fWorksheet) return;
     * const image = await fWorksheet.newOverGridImage()
     *   .setImage({
     *     drawingId: '123456',
     *     drawingType: univerAPI.Enum.DrawingType.DRAWING_IMAGE,
     *     imageSourceType: univerAPI.Enum.ImageSourceType.BASE64,
     *     source: 'https://avatars.githubusercontent.com/u/61444807?s=48&v=4',
     *     unitId: fWorkbook.getId(),
     *     subUnitId: fWorksheet.getSheetId(),
     *   })
     *   .setColumn(5)
     *   .setRow(5)
     *   .buildAsync();
     * fWorksheet.insertImages([image]);
     * ```
     */
    setImage(image: ISheetImage): FOverGridImageBuilder {
        const { unitId, subUnitId } = image;
        const skeleton = this._sheetSkeletonService.getSkeleton(unitId, subUnitId);
        if (!skeleton) {
            throw new Error(`Skeleton for unitId ${unitId} and subUnitId ${subUnitId} not found`);
        }

        if (image.sheetTransform == null) {
            image.sheetTransform = {
                from: {
                    column: 0,
                    columnOffset: 0,
                    row: 0,
                    rowOffset: 0,
                },
                to: {
                    column: 0,
                    columnOffset: 0,
                    row: 0,
                    rowOffset: 0,
                },
            };
        }
        if (image.axisAlignSheetTransform == null) {
            image.axisAlignSheetTransform = {
                from: {
                    column: 0,
                    columnOffset: 0,
                    row: 0,
                    rowOffset: 0,
                },
                to: {
                    column: 0,
                    columnOffset: 0,
                    row: 0,
                    rowOffset: 0,
                },
            };
        }
        this._image = convertSheetImageToFOverGridImage(image, skeleton);
        return this;
    }

    /**
     * Set the source of the image. The source type defaults to URL.
     * @param {string} source - The source of the image
     * @returns {FOverGridImageBuilder} The `FOverGridImageBuilder` for chaining
     */
    setSource(source: string): FOverGridImageBuilder;
    /**
     * Set the source of the image.
     * @param {string} source - The source of the image
     * @param {ImageSourceType} [sourceType] - The source type of the image, default is URL
     * @returns {FOverGridImageBuilder} The `FOverGridImageBuilder` for chaining
     * @example
     * ```ts
     * // create a new image builder and set image source.
     * // then build `ISheetImage` and insert it into the sheet, position is start from F6 cell.
     * const fWorkbook = univerAPI.getActiveWorkbook();
     * const fWorksheet = fWorkbook.getSheetByName('Sheet1');
     * if (!fWorksheet) return;
     * const image = await fWorksheet.newOverGridImage()
     *   .setSource('https://avatars.githubusercontent.com/u/61444807?s=48&v=4', univerAPI.Enum.ImageSourceType.URL)
     *   .setColumn(5)
     *   .setRow(5)
     *   .buildAsync();
     * fWorksheet.insertImages([image]);
     * ```
     */
    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;
    }

    /**
     * Get the source of the image
     * @returns {string} The source of the image
     * @example
     * ```ts
     * const fWorkbook = univerAPI.getActiveWorkbook();
     * const fWorksheet = fWorkbook.getSheetByName('Sheet1');
     * if (!fWorksheet) return;
     * const images = fWorksheet.getImages();
     * images.forEach((image) => {
     *   console.log(image, image.toBuilder().getSource());
     * });
     * ```
     */
    getSource(): string {
        return this._image.source;
    }

    /**
     * Get the source type of the image
     * @returns {ImageSourceType} The source type of the image
     * @example
     * ```ts
     * const fWorkbook = univerAPI.getActiveWorkbook();
     * const fWorksheet = fWorkbook.getSheetByName('Sheet1');
     * if (!fWorksheet) return;
     * const images = fWorksheet.getImages();
     * images.forEach((image) => {
     *   console.log(image, image.toBuilder().getSourceType());
     * });
     * ```
     */
    getSourceType(): ImageSourceType {
        return this._image.imageSourceType;
    }

    /**
     * Set the whole-image opacity from zero (transparent) through one (opaque).
     * @param {number} opacity The opacity from 0 through 1.
     * @returns {FOverGridImageBuilder} This builder.
     */
    setOpacity(opacity: number): FOverGridImageBuilder {
        validateImageOpacity(opacity);
        this._image.opacity = opacity;
        return this;
    }

    /**
     * Get the configured whole-image opacity.
     * @returns {number} The opacity from 0 (transparent) through 1 (opaque).
     */
    getOpacity(): number {
        return this._image.opacity ?? 1;
    }

    /**
     * Set the horizontal position of the image
     * @param {number} column - The column index of the image start position, start at 0
     * @returns {FOverGridImageBuilder} The `FOverGridImageBuilder` for chaining
     * @example
     * ```ts
     * // create a new image builder and set image source.
     * // then build `ISheetImage` and insert it into the sheet, position is start from F6 cell.
     * const fWorkbook = univerAPI.getActiveWorkbook();
     * const fWorksheet = fWorkbook.getSheetByName('Sheet1');
     * if (!fWorksheet) return;
     * const image = await fWorksheet.newOverGridImage()
     *   .setSource('https://avatars.githubusercontent.com/u/61444807?s=48&v=4', univerAPI.Enum.ImageSourceType.URL)
     *   .setColumn(5)
     *   .setRow(5)
     *   .buildAsync();
     * fWorksheet.insertImages([image]);
     * ```
     */
    setColumn(column: number): FOverGridImageBuilder {
        this._image.column = column;
        return this;
    }

    /**
     * Set the vertical position of the image
     * @param {number} row - The row index of the image start position, start at 0
     * @returns {FOverGridImageBuilder} The `FOverGridImageBuilder` for chaining
     * @example
     * ```ts
     * // create a new image builder and set image source.
     * // then build `ISheetImage` and insert it into the sheet, position is start from F6 cell.
     * const fWorkbook = univerAPI.getActiveWorkbook();
     * const fWorksheet = fWorkbook.getSheetByName('Sheet1');
     * if (!fWorksheet) return;
     * const image = await fWorksheet.newOverGridImage()
     *   .setSource('https://avatars.githubusercontent.com/u/61444807?s=48&v=4', univerAPI.Enum.ImageSourceType.URL)
     *   .setColumn(5)
     *   .setRow(5)
     *   .buildAsync();
     * fWorksheet.insertImages([image]);
     * ```
     */
    setRow(row: number): FOverGridImageBuilder {
        this._image.row = row;
        return this;
    }

    /**
     * Set the horizontal offset of the image
     * @param {number} offset - The column offset of the image start position, pixel unit
     * @returns {FOverGridImageBuilder} The `FOverGridImageBuilder` for chaining
     * @example
     * ```ts
     * // create a new image builder and set image source.
     * // then build `ISheetImage` and insert it into the sheet, position is start from F6 cell and horizontal offset is 10px.
     * const fWorkbook = univerAPI.getActiveWorkbook();
     * const fWorksheet = fWorkbook.getSheetByName('Sheet1');
     * if (!fWorksheet) return;
     * const image = await fWorksheet.newOverGridImage()
     *   .setSource('https://avatars.githubusercontent.com/u/61444807?s=48&v=4', univerAPI.Enum.ImageSourceType.URL)
     *   .setColumn(5)
     *   .setRow(5)
     *   .setColumnOffset(10)
     *   .buildAsync();
     * fWorksheet.insertImages([image]);
     * ```
     */
    setColumnOffset(offset: number): FOverGridImageBuilder {
        this._image.columnOffset = offset;
        return this;
    }

    /**
     * Set the vertical offset of the image
     * @param {number} offset - The row offset of the image start position, pixel unit
     * @returns {FOverGridImageBuilder} The `FOverGridImageBuilder` for chaining
     * @example
     * ```ts
     * // create a new image builder and set image source.
     * // then build `ISheetImage` and insert it into the sheet, position is start from F6 cell and vertical offset is 10px.
     * const fWorkbook = univerAPI.getActiveWorkbook();
     * const fWorksheet = fWorkbook.getSheetByName('Sheet1');
     * if (!fWorksheet) return;
     * const image = await fWorksheet.newOverGridImage()
     *   .setSource('https://avatars.githubusercontent.com/u/61444807?s=48&v=4', univerAPI.Enum.ImageSourceType.URL)
     *   .setColumn(5)
     *   .setRow(5)
     *   .setRowOffset(10)
     *   .buildAsync();
     * fWorksheet.insertImages([image]);
     * ```
     */
    setRowOffset(offset: number): FOverGridImageBuilder {
        this._image.rowOffset = offset;
        return this;
    }

    /**
     * Set the width of the image
     * @param {number} width - The width of the image, pixel unit
     * @returns {FOverGridImageBuilder} The `FOverGridImageBuilder` for chaining
     * @example
     * ```ts
     * // create a new image builder and set image source.
     * // then build `ISheetImage` and insert it into the sheet, position is start from F6 cell, width is 120px and height is 50px.
     * const fWorkbook = univerAPI.getActiveWorkbook();
     * const fWorksheet = fWorkbook.getSheetByName('Sheet1');
     * if (!fWorksheet) return;
     * const image = await fWorksheet.newOverGridImage()
     *   .setSource('https://avatars.githubusercontent.com/u/61444807?s=48&v=4', univerAPI.Enum.ImageSourceType.URL)
     *   .setColumn(5)
     *   .setRow(5)
     *   .setWidth(120)
     *   .setHeight(50)
     *   .buildAsync();
     * fWorksheet.insertImages([image]);
     * ```
     */
    setWidth(width: number): FOverGridImageBuilder {
        this._image.width = width;
        return this;
    }

    /**
     * Set the height of the image
     * @param {number} height - The height of the image, pixel unit
     * @returns {FOverGridImageBuilder} The `FOverGridImageBuilder` for chaining
     * @example
     * ```ts
     * // create a new image builder and set image source.
     * // then build `ISheetImage` and insert it into the sheet, position is start from F6 cell, width is 120px and height is 50px.
     * const fWorkbook = univerAPI.getActiveWorkbook();
     * const fWorksheet = fWorkbook.getSheetByName('Sheet1');
     * if (!fWorksheet) return;
     * const image = await fWorksheet.newOverGridImage()
     *   .setSource('https://avatars.githubusercontent.com/u/61444807?s=48&v=4', univerAPI.Enum.ImageSourceType.URL)
     *   .setColumn(5)
     *   .setRow(5)
     *   .setWidth(120)
     *   .setHeight(50)
     *   .buildAsync();
     * fWorksheet.insertImages([image]);
     * ```
     */
    setHeight(height: number): FOverGridImageBuilder {
        this._image.height = height;
        return this;
    }

    /**
     * Set the anchor type of the image, whether the position and size change with the cell
     * @param {SheetDrawingAnchorType} anchorType - The anchor type of the image
     * @returns {FOverGridImageBuilder} The `FOverGridImageBuilder` for chaining
     * @example
     * ```ts
     * const fWorkbook = univerAPI.getActiveWorkbook();
     * const fWorksheet = fWorkbook.getSheetByName('Sheet1');
     * if (!fWorksheet) return;
     *
     * // image1 position is start from A6 cell, anchor type is Position.
     * // Only the position of the drawing follows the cell changes. When rows or columns are inserted or deleted, the position of the drawing changes, but the size remains the same.
     * const image1 = await fWorksheet.newOverGridImage()
     *   .setSource('https://avatars.githubusercontent.com/u/61444807?s=48&v=4', univerAPI.Enum.ImageSourceType.URL)
     *   .setColumn(0)
     *   .setRow(5)
     *   .setAnchorType(univerAPI.Enum.SheetDrawingAnchorType.Position)
     *   .buildAsync();
     *
     * // image2 position is start from C6 cell, anchor type is Both.
     * // The size and position of the drawing follow the cell changes. When rows or columns are inserted or deleted, the size and position of the drawing change accordingly.
     * const image2 = await fWorksheet.newOverGridImage()
     *   .setSource('https://avatars.githubusercontent.com/u/61444807?s=48&v=4', univerAPI.Enum.ImageSourceType.URL)
     *   .setColumn(2)
     *   .setRow(5)
     *   .setAnchorType(univerAPI.Enum.SheetDrawingAnchorType.Both)
     *   .buildAsync();
     *
     * // image3 position is start from E6 cell, anchor type is None.
     * // The size and position of the drawing do not follow the cell changes. When rows or columns are inserted or deleted, the position and size of the drawing remain unchanged.
     * const image3 = await fWorksheet.newOverGridImage()
     *   .setSource('https://avatars.githubusercontent.com/u/61444807?s=48&v=4', univerAPI.Enum.ImageSourceType.URL)
     *   .setColumn(4)
     *   .setRow(5)
     *   .setAnchorType(univerAPI.Enum.SheetDrawingAnchorType.None)
     *   .buildAsync();
     *
     * // insert images into the sheet
     * fWorksheet.insertImages([image1, image2, image3]);
     *
     * // after 2 seconds, set the row height of the 5th row to 100px and insert a row before the 5th row.
     * // then observe the position and size changes of the images.
     * setTimeout(() => {
     *   fWorksheet.setRowHeight(5, 100).insertRowBefore(5);
     * }, 2000);
     * ```
     */
    setAnchorType(anchorType: SheetDrawingAnchorType): FOverGridImageBuilder {
        this._image.anchorType = anchorType;
        return this;
    }

    /**
     * Set an explicit OneCell, TwoCell, or Absolute placement for the image.
     *
     * This placement takes precedence over the individual row, column, size,
     * and anchor type builder fields. Use bounds inference for an existing
     * transform; use exact markers when a caller explicitly chose cells.
     * @param {ISheetDrawingPlacementInput} placement Exact placement or bounds with an explicit anchor type.
     * @returns {FOverGridImageBuilder} This builder.
     * @example
     * ```ts
     * const sheet = univerAPI.getActiveWorkbook().getActiveSheet();
     * const image = await sheet.newOverGridImage()
     *   .setSource('https://avatars.githubusercontent.com/u/61444807?s=96&v=4')
     *   .setPlacement({
     *     kind: univerAPI.Enum.SheetDrawingAnchorType.Position,
     *     from: { row: 2, column: 2, rowOffset: 8, columnOffset: 8 },
     *     width: 240,
     *     height: 120,
     *   })
     *   .buildAsync();
     * sheet.insertImages([image]);
     * ```
     * @example Infer Position markers from model-space bounds
     * ```ts
     * const sheet = univerAPI.getActiveWorkbook().getActiveSheet();
     * const image = await sheet.newOverGridImage()
     *   .setSource('https://avatars.githubusercontent.com/u/61444807?s=96&v=4')
     *   .setPlacement({
     *     kind: univerAPI.Enum.SheetDrawingAnchorType.Position,
     *     bounds: { left: 120, top: 80, width: 240, height: 120 },
     *   })
     *   .buildAsync();
     * sheet.insertImages([image]);
     * ```
     * @example TwoCell
     * ```ts
     * const sheet = univerAPI.getActiveWorkbook().getActiveSheet();
     * const image = await sheet.newOverGridImage()
     *   .setSource('https://avatars.githubusercontent.com/u/61444807?s=96&v=4')
     *   .setPlacement({
     *     kind: univerAPI.Enum.SheetDrawingAnchorType.Both,
     *     from: { row: 2, column: 2, rowOffset: 8, columnOffset: 8 },
     *     to: { row: 8, column: 6, rowOffset: 0, columnOffset: 0 },
     *   })
     *   .buildAsync();
     * sheet.insertImages([image]);
     * ```
     * @example Absolute
     * ```ts
     * const sheet = univerAPI.getActiveWorkbook().getActiveSheet();
     * const image = await sheet.newOverGridImage()
     *   .setSource('https://avatars.githubusercontent.com/u/61444807?s=96&v=4')
     *   .setPlacement({
     *     kind: univerAPI.Enum.SheetDrawingAnchorType.None,
     *     left: 640,
     *     top: 96,
     *     width: 240,
     *     height: 120,
     *   })
     *   .buildAsync();
     * sheet.insertImages([image]);
     * ```
     */
    setPlacement(placement: ISheetDrawingPlacementInput): FOverGridImageBuilder {
        this._placement = placement;
        return this;
    }

    /**
     * Set the cropping region of the image by defining the top edges, thereby displaying the specific part of the image you want.
     * @param {number} top - The number of pixels to crop from the top of the image
     * @returns {FOverGridImageBuilder} The `FOverGridImageBuilder` for chaining
     * @example
     * ```ts
     * // create a new image builder and set image source.
     * // then build `ISheetImage` and insert it into the sheet, position is start from F6 cell, top crop is 10px.
     * const fWorkbook = univerAPI.getActiveWorkbook();
     * const fWorksheet = fWorkbook.getSheetByName('Sheet1');
     * if (!fWorksheet) return;
     * const image = await fWorksheet.newOverGridImage()
     *   .setSource('https://avatars.githubusercontent.com/u/61444807?s=48&v=4', univerAPI.Enum.ImageSourceType.URL)
     *   .setColumn(5)
     *   .setRow(5)
     *   .setCropTop(10)
     *   .buildAsync();
     * fWorksheet.insertImages([image]);
     * ```
     */
    setCropTop(top: number): FOverGridImageBuilder {
        this._initializeSrcRect();
        this._image.srcRect!.top = top;
        return this;
    }

    /**
     * Set the cropping region of the image by defining the left edges, thereby displaying the specific part of the image you want.
     * @param {number} left - The number of pixels to crop from the left side of the image
     * @returns {FOverGridImageBuilder} The `FOverGridImageBuilder` for chaining
     * @example
     * ```ts
     * // create a new image builder and set image source.
     * // then build `ISheetImage` and insert it into the sheet, position is start from F6 cell, left crop is 10px.
     * const fWorkbook = univerAPI.getActiveWorkbook();
     * const fWorksheet = fWorkbook.getSheetByName('Sheet1');
     * if (!fWorksheet) return;
     * const image = await fWorksheet.newOverGridImage()
     *   .setSource('https://avatars.githubusercontent.com/u/61444807?s=48&v=4', univerAPI.Enum.ImageSourceType.URL)
     *   .setColumn(5)
     *   .setRow(5)
     *   .setCropLeft(10)
     *   .buildAsync();
     * fWorksheet.insertImages([image]);
     * ```
     */
    setCropLeft(left: number): FOverGridImageBuilder {
        this._initializeSrcRect();
        this._image.srcRect!.left = left;
        return this;
    }

    /**
     * Set the cropping region of the image by defining the bottom edges, thereby displaying the specific part of the image you want.
     * @param {number} bottom - The number of pixels to crop from the bottom of the image
     * @returns {FOverGridImageBuilder} The `FOverGridImageBuilder` for chaining
     * @example
     * ```ts
     * // create a new image builder and set image source.
     * // then build `ISheetImage` and insert it into the sheet, position is start from F6 cell, bottom crop is 10px.
     * const fWorkbook = univerAPI.getActiveWorkbook();
     * const fWorksheet = fWorkbook.getSheetByName('Sheet1');
     * if (!fWorksheet) return;
     * const image = await fWorksheet.newOverGridImage()
     *   .setSource('https://avatars.githubusercontent.com/u/61444807?s=48&v=4', univerAPI.Enum.ImageSourceType.URL)
     *   .setColumn(5)
     *   .setRow(5)
     *   .setCropBottom(10)
     *   .buildAsync();
     * fWorksheet.insertImages([image]);
     * ```
     */
    setCropBottom(bottom: number): FOverGridImageBuilder {
        this._initializeSrcRect();
        this._image.srcRect!.bottom = bottom;
        return this;
    }

    /**
     * Set the cropping region of the image by defining the right edges, thereby displaying the specific part of the image you want.
     * @param {number} right - The number of pixels to crop from the right side of the image
     * @returns {FOverGridImageBuilder} The `FOverGridImageBuilder` for chaining
     * @example
     * ```ts
     * // create a new image builder and set image source.
     * // then build `ISheetImage` and insert it into the sheet, position is start from F6 cell, right crop is 10px.
     * const fWorkbook = univerAPI.getActiveWorkbook();
     * const fWorksheet = fWorkbook.getSheetByName('Sheet1');
     * if (!fWorksheet) return;
     * const image = await fWorksheet.newOverGridImage()
     *   .setSource('https://avatars.githubusercontent.com/u/61444807?s=48&v=4', univerAPI.Enum.ImageSourceType.URL)
     *   .setColumn(5)
     *   .setRow(5)
     *   .setCropRight(10)
     *   .buildAsync();
     * fWorksheet.insertImages([image]);
     * ```
     */
    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 {number} angle - Degree of rotation of the image, for example, 90, 180, 270, etc.
     * @returns {FOverGridImageBuilder} The `FOverGridImageBuilder` for chaining
     * @example
     * ```ts
     * // create a new image builder and set image source.
     * // then build `ISheetImage` and insert it into the sheet, position is start from F6 cell, rotate 90 degrees.
     * const fWorkbook = univerAPI.getActiveWorkbook();
     * const fWorksheet = fWorkbook.getSheetByName('Sheet1');
     * if (!fWorksheet) return;
     * const image = await fWorksheet.newOverGridImage()
     *   .setSource('https://avatars.githubusercontent.com/u/61444807?s=48&v=4', univerAPI.Enum.ImageSourceType.URL)
     *   .setColumn(5)
     *   .setRow(5)
     *   .setRotate(90)
     *   .buildAsync();
     * fWorksheet.insertImages([image]);
     * ```
     */
    setRotate(angle: number): FOverGridImageBuilder {
        this._image.angle = angle;
        return this;
    }

    /**
     * Sets the workbook unit ID of the image to build.
     * @param {string} unitId The target workbook unit ID.
     * @returns {FOverGridImageBuilder} This builder, for chaining.
     */
    setUnitId(unitId: string): FOverGridImageBuilder {
        this._image.unitId = unitId;
        return this;
    }

    /**
     * Sets the worksheet ID of the image to build.
     * @param {string} subUnitId The target worksheet ID.
     * @returns {FOverGridImageBuilder} This builder, for chaining.
     */
    setSubUnitId(subUnitId: string): FOverGridImageBuilder {
        this._image.subUnitId = subUnitId;
        return this;
    }

    /**
     * Builds image data for insertion or updating; this does not insert the image.
     * An explicit placement takes precedence over the individual position and size fields.
     * Without explicit placement, zero width or height is filled from the source image's intrinsic size.
     * @returns {Promise<ISheetImage>} A promise resolving to the built sheet image data.
     * @example
     * ```ts
     * const sheet = univerAPI.getActiveWorkbook()?.getActiveSheet();
     * if (sheet) {
     *   const image = await sheet.newOverGridImage().setSource('https://example.com/image.png').buildAsync();
     *   sheet.insertImages([image]);
     * }
     * ```
     */
    async buildAsync(): Promise<ISheetImage> {
        const sheetSkeletonService = this._sheetSkeletonService;

        if (!this._placement && (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;
            }
        }

        if (this._placement?.kind === SheetDrawingAnchorType.None) {
            const { left, top, width, height } = 'bounds' in this._placement
                ? this._placement.bounds
                : this._placement;
            const sheetTransform = {
                from: {
                    column: 0,
                    columnOffset: left,
                    row: 0,
                    rowOffset: top,
                },
                to: {
                    column: 0,
                    columnOffset: left + width,
                    row: 0,
                    rowOffset: top + height,
                },
            };
            const image: ISheetImage = {
                ...this._image,
                transform: {
                    left,
                    top,
                    width,
                    height,
                    flipY: this._image.flipY,
                    flipX: this._image.flipX,
                    angle: this._image.angle,
                    skewX: this._image.skewX,
                    skewY: this._image.skewY,
                },
                sheetTransform,
                axisAlignSheetTransform: sheetTransform,
            };
            return applySheetDrawingPlacement(image, this._placement);
        }

        const image = convertFOverGridImageToSheetImage(this._image, sheetSkeletonService);
        if (!this._placement) {
            return image;
        }

        const skeleton = sheetSkeletonService.ensureSkeleton(image.unitId, image.subUnitId);
        return applySheetDrawingPlacement(image, this._placement, skeleton);
    }
}

/**
 * @hideconstructor
 */
export class FOverGridImage extends FBase {
    constructor(
        private _image: ISheetImage,
        @ICommandService protected readonly _commandService: ICommandService,
        @Inject(Injector) protected readonly _injector: Injector,
        @ISheetDrawingService private readonly _sheetDrawingService: ISheetDrawingService,
        @Inject(SheetSkeletonService) private readonly _sheetSkeletonService: SheetSkeletonService
    ) {
        super();
    }

    /**
     * Get the id of the image
     * @returns {string} The id of the image
     * @example
     * ```ts
     * const fWorkbook = univerAPI.getActiveWorkbook();
     * const fWorksheet = fWorkbook.getSheetByName('Sheet1');
     * if (!fWorksheet) return;
     * const images = fWorksheet.getImages();
     * images.forEach((image) => {
     *   console.log(image, image.getId());
     * });
     * ```
     */
    getId(): string {
        return this._image.drawingId;
    }

    /** Returns the workbook unit id that owns this image. */
    getUnitId(): string {
        return this._image.unitId;
    }

    /** Returns the worksheet id that owns this image. */
    getSubUnitId(): string {
        return this._image.subUnitId;
    }

    /**
     * Get the drawing type of the image
     * @returns {DrawingTypeEnum} The drawing type of the image
     * @example
     * ```ts
     * const fWorkbook = univerAPI.getActiveWorkbook();
     * const fWorksheet = fWorkbook.getSheetByName('Sheet1');
     * if (!fWorksheet) return;
     * const images = fWorksheet.getImages();
     * images.forEach((image) => {
     *   console.log(image, image.getType());
     * });
     * ```
     */
    getType(): DrawingTypeEnum {
        return this._image.drawingType;
    }

    /**
     * Get this image's explicit placement.
     * @returns {ISheetDrawingPlacement} OneCell, TwoCell, or Absolute placement.
     * @example
     * ```ts
     * const image = univerAPI.getActiveWorkbook().getActiveSheet().getImages()[0];
     * console.log(image.getPlacement());
     * ```
     */
    getPlacement(): ISheetDrawingPlacement {
        const current = this._sheetDrawingService.getDrawingByParam({
            unitId: this._image.unitId,
            subUnitId: this._image.subUnitId,
            drawingId: this._image.drawingId,
        });
        return getSheetDrawingPlacement(current ?? this._image);
    }

    /**
     * Get the current whole-image opacity.
     * @returns {number} The opacity from 0 (transparent) through 1 (opaque).
     */
    getOpacity(): number {
        const current = this._sheetDrawingService.getDrawingByParam({
            unitId: this._image.unitId,
            subUnitId: this._image.subUnitId,
            drawingId: this._image.drawingId,
        }) as ISheetImage | undefined;

        return current?.opacity ?? this._image.opacity ?? 1;
    }

    /**
     * Set the whole-image opacity from zero (transparent) through one (opaque).
     * @param {number} opacity The opacity from 0 through 1.
     * @returns {boolean} Whether the update succeeded.
     */
    setOpacity(opacity: number): boolean {
        validateImageOpacity(opacity);
        return this._commandService.syncExecuteCommand(SetSheetDrawingCommand.id, {
            unitId: this._image.unitId,
            drawings: [{
                unitId: this._image.unitId,
                subUnitId: this._image.subUnitId,
                drawingId: this._image.drawingId,
                opacity,
            }],
        });
    }

    /**
     * Set this image's explicit placement through the drawing command.
     * `Position`, `Both`, and `None` correspond to OneCell, TwoCell, and
     * Absolute. Bounds inference is preferable when preserving the current
     * visual bounds; exact markers are for user-selected cells and offsets.
     * @param {ISheetDrawingPlacementInput} placement Exact placement or bounds with an explicit anchor type.
     * @returns {boolean} `true` when the command succeeds.
     * @example OneCell
     * ```ts
     * const image = univerAPI.getActiveWorkbook().getActiveSheet().getImages()[0];
     * image.setPlacement({
     *   kind: univerAPI.Enum.SheetDrawingAnchorType.Position,
     *   from: { row: 4, column: 3, rowOffset: 8, columnOffset: 8 },
     *   width: 320,
     *   height: 180,
     * });
     * ```
     * @example Infer TwoCell markers while preserving current model-space bounds
     * ```ts
     * const image = univerAPI.getActiveWorkbook().getActiveSheet().getImages()[0];
     * image.setPlacement({
     *   kind: univerAPI.Enum.SheetDrawingAnchorType.Both,
     *   bounds: { left: 120, top: 80, width: 320, height: 160 },
     * });
     * ```
     * @example TwoCell
     * ```ts
     * const image = univerAPI.getActiveWorkbook().getActiveSheet().getImages()[0];
     * image.setPlacement({
     *   kind: univerAPI.Enum.SheetDrawingAnchorType.Both,
     *   from: { row: 4, column: 3, rowOffset: 8, columnOffset: 8 },
     *   to: { row: 10, column: 8, rowOffset: 0, columnOffset: 0 },
     * });
     * ```
     * @example Absolute
     * ```ts
     * const image = univerAPI.getActiveWorkbook().getActiveSheet().getImages()[0];
     * image.setPlacement({
     *   kind: univerAPI.Enum.SheetDrawingAnchorType.None,
     *   left: 640,
     *   top: 96,
     *   width: 320,
     *   height: 180,
     * });
     * ```
     */
    setPlacement(placement: ISheetDrawingPlacementInput): boolean {
        return this._commandService.syncExecuteCommand(SetSheetDrawingPlacementCommand.id, {
            unitId: this._image.unitId,
            subUnitId: this._image.subUnitId,
            drawings: [{ drawingId: this._image.drawingId, placement }],
        });
    }

    /**
     * Remove the image from the sheet
     *
     * For multiple images on the same worksheet, prefer {@link FWorksheet.deleteImages} with the image
     * handles instead of calling this method on each image.
     *
     * @returns {boolean} true if the image is removed successfully, otherwise false
     * @example
     * ```ts
     * const fWorkbook = univerAPI.getActiveWorkbook();
     * const fWorksheet = fWorkbook.getSheetByName('Sheet1');
     * if (!fWorksheet) return;
     * const image = fWorksheet.getImages()[0];
     * const result = image?.remove();
     * console.log(result);
     * ```
     */
    remove(): boolean {
        return this._commandService.syncExecuteCommand(RemoveSheetDrawingCommand.id, { unitId: this._image.unitId, drawings: [this._image] });
    }

    /**
     * Convert the image to a FOverGridImageBuilder
     * @returns {FOverGridImageBuilder} The builder FOverGridImageBuilder
     * @example
     * ```ts
     * const fWorkbook = univerAPI.getActiveWorkbook();
     * const fWorksheet = fWorkbook.getSheetByName('Sheet1');
     * if (!fWorksheet) return;
     * const images = fWorksheet.getImages();
     * images.forEach((image) => {
     *   console.log(image, image.toBuilder().getSource());
     * });
     * ```
     */
    toBuilder(): FOverGridImageBuilder {
        const builder = this._injector.createInstance(FOverGridImageBuilder, this._image.unitId, this._image.subUnitId);
        builder.setImage(this._image);
        return builder;
    }

    /**
     * Set the source of the image
     * @param {string} source - The source of the image
     * @returns {boolean} true if the source is set successfully, otherwise false
     * @example
     * ```ts
     * const fWorkbook = univerAPI.getActiveWorkbook();
     * const fWorksheet = fWorkbook.getSheetByName('Sheet1');
     * if (!fWorksheet) return;
     * const image = fWorksheet.getImages()[0];
     * const result = image?.setSource('https://avatars.githubusercontent.com/u/61444807?s=48&v=4');
     * console.log(result);
     * ```
     */
    setSource(source: string): boolean;
    /**
     * Set the source of the image, change image display.
     * @param {string} source - The source of the image
     * @param {ImageSourceType} [sourceType] - The source type of the image, default is URL
     * @returns {boolean} true if the source is set successfully, otherwise false
     * @example
     * ```ts
     * const fWorkbook = univerAPI.getActiveWorkbook();
     * const fWorksheet = fWorkbook.getSheetByName('Sheet1');
     * if (!fWorksheet) return;
     * const image = fWorksheet.getImages()[0];
     * const result = image?.setSource('https://avatars.githubusercontent.com/u/61444807?s=48&v=4', univerAPI.Enum.ImageSourceType.URL);
     * console.log(result);
     * ```
     */
    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 {number} row - The row index of the image start position
     * @param {number} column - The column index of the image start position
     * @returns {Promise<boolean>} A promise resolving to whether the image update succeeded.
     * @example
     * ```ts
     * // set the position of the image, the start position is F6 cell.
     * const fWorkbook = univerAPI.getActiveWorkbook();
     * const fWorksheet = fWorkbook.getSheetByName('Sheet1');
     * if (!fWorksheet) return;
     * const image = fWorksheet.getImages()[0];
     * const result = await image?.setPositionAsync(5, 5);
     * console.log(result);
     * ```
     */
    async setPositionAsync(row: number, column: number): Promise<boolean>;
    /**
     * @param {number} row - The row index of the image start position
     * @param {number} column - The column index of the image start position
     * @param {number} [rowOffset] - The row offset of the image start position, pixel unit
     * @param {number} [columnOffset] - The column offset of the image start position, pixel unit
     * @returns {Promise<boolean>} A promise resolving to whether the image update succeeded.
     * @example
     * ```ts
     * // set the position of the image, the start position is F6 cell, and the offset is 10px.
     * const fWorkbook = univerAPI.getActiveWorkbook();
     * const fWorksheet = fWorkbook.getSheetByName('Sheet1');
     * if (!fWorksheet) return;
     * const image = fWorksheet.getImages()[0];
     * const result = await image?.setPositionAsync(5, 5, 10, 10);
     * console.log(result);
     * ```
     */
    async setPositionAsync(row: number, column: number, rowOffset?: number, columnOffset?: number): Promise<boolean>;
    async setPositionAsync(row: number, column: number, rowOffset?: number, columnOffset?: number): Promise<boolean> {
        const builder = this.toBuilder();
        builder.setColumn(column);
        builder.setRow(row);
        if (rowOffset != null) {
            builder.setRowOffset(rowOffset);
        }
        if (columnOffset != null) {
            builder.setColumnOffset(columnOffset);
        }
        const param = await builder.buildAsync();
        return this._commandService.syncExecuteCommand(SetSheetDrawingCommand.id, { unitId: this._image.unitId, drawings: [param] });
    }

    /**
     * Set the size of the image
     * @param {number} width - The width of the image, pixel unit
     * @param {number} height - The height of the image, pixel unit
     * @returns {Promise<boolean>} A promise resolving to whether the image update succeeded.
     * @example
     * ```ts
     * // set the image width 120px and height 50px
     * const fWorkbook = univerAPI.getActiveWorkbook();
     * const fWorksheet = fWorkbook.getSheetByName('Sheet1');
     * if (!fWorksheet) return;
     * const image = fWorksheet.getImages()[0];
     * const result = await image?.setSizeAsync(120, 50);
     * console.log(result);
     * ```
     */
    async setSizeAsync(width: number, height: number): Promise<boolean> {
        const builder = this.toBuilder();
        builder.setWidth(width);
        builder.setHeight(height);
        const param = await builder.buildAsync();
        return this._commandService.syncExecuteCommand(SetSheetDrawingCommand.id, { unitId: this._image.unitId, drawings: [param] });
    }

    /**
     * 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 {number} [top] - The number of pixels to crop from the top of the image
     * @param {number} [left] - The number of pixels to crop from the left side of the image
     * @param {number} [bottom] - The number of pixels to crop from the bottom of the image
     * @param {number} [right] - The number of pixels to crop from the right side of the image
     * @returns {boolean} true if the crop is set successfully, otherwise false
     * @example
     * ```ts
     * // set the crop of the image, top 10px, left 10px, bottom 10px, right 10px.
     * const fWorkbook = univerAPI.getActiveWorkbook();
     * const fWorksheet = fWorkbook.getSheetByName('Sheet1');
     * if (!fWorksheet) return;
     * const image = fWorksheet.getImages()[0];
     * const result = image?.setCrop(10, 10, 10, 10);
     * console.log(result);
     * ```
     */
    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] });
    }

    /**
     * Set the rotation angle of the image
     * @param {number} angle - Degree of rotation of the image, for example, 90, 180, 270, etc.
     * @returns {boolean} true if the rotation is set successfully, otherwise false
     * @example
     * ```ts
     * // set 90 degrees rotation of the image
     * const fWorkbook = univerAPI.getActiveWorkbook();
     * const fWorksheet = fWorkbook.getSheetByName('Sheet1');
     * if (!fWorksheet) return;
     * const image = fWorksheet.getImages()[0];
     * const result = image?.setRotate(90);
     * console.log(result);
     * ```
     */
    setRotate(angle: number): boolean {
        this._image.sheetTransform.angle = angle;
        this._image.transform && (this._image.transform.angle = angle);
        if (this._image.transform) {
            const skeleton = this._sheetSkeletonService.getSkeleton(this._image.unitId, this._image.subUnitId);
            if (!skeleton) {
                throw new Error(`Skeleton for unitId ${this._image.unitId} and subUnitId ${this._image.subUnitId} not found`);
            }

            this._image.axisAlignSheetTransform && (this._image.axisAlignSheetTransform = transformToAxisAlignPosition(this._image.transform, skeleton));
        }

        return this._commandService.syncExecuteCommand(SetSheetDrawingCommand.id, { unitId: this._image.unitId, drawings: [this._image] });
    }

    /**
     * Move the image layer forward by one level
     * @returns {boolean} true if the image is moved forward successfully, otherwise false
     * @example
     * ```ts
     * const fWorkbook = univerAPI.getActiveWorkbook();
     * const fWorksheet = fWorkbook.getSheetByName('Sheet1');
     * if (!fWorksheet) return;
     * const image = fWorksheet.getImages()[0];
     * const result = image?.setForward();
     * console.log(result);
     * ```
     */
    setForward(): boolean {
        return this._commandService.syncExecuteCommand(SetDrawingArrangeCommand.id, {
            unitId: this._image.unitId,
            subUnitId: this._image.subUnitId,
            drawingIds: [this._image.drawingId],
            arrangeType: ArrangeTypeEnum.forward,
        });
    }

    /**
     * Move the image layer backward by one level
     * @returns {boolean} true if the image is moved backward successfully, otherwise false
     * @example
     * ```ts
     * const fWorkbook = univerAPI.getActiveWorkbook();
     * const fWorksheet = fWorkbook.getSheetByName('Sheet1');
     * if (!fWorksheet) return;
     * const image = fWorksheet.getImages()[0];
     * const result = image?.setBackward();
     * console.log(result);
     * ```
     */
    setBackward(): boolean {
        return this._commandService.syncExecuteCommand(SetDrawingArrangeCommand.id, {
            unitId: this._image.unitId,
            subUnitId: this._image.subUnitId,
            drawingIds: [this._image.drawingId],
            arrangeType: ArrangeTypeEnum.backward,
        });
    }

    /**
     * Move the image layer to the bottom layer
     * @returns {boolean} true if the image is moved to the bottom layer successfully, otherwise false
     * @example
     * ```ts
     * const fWorkbook = univerAPI.getActiveWorkbook();
     * const fWorksheet = fWorkbook.getSheetByName('Sheet1');
     * if (!fWorksheet) return;
     * const image = fWorksheet.getImages()[0];
     * const result = image?.setBack();
     * console.log(result);
     * ```
     */
    setBack(): boolean {
        return this._commandService.syncExecuteCommand(SetDrawingArrangeCommand.id, {
            unitId: this._image.unitId,
            subUnitId: this._image.subUnitId,
            drawingIds: [this._image.drawingId],
            arrangeType: ArrangeTypeEnum.back,
        });
    }

    /**
     * Move the image layer to the top layer
     * @returns {boolean} true if the image is moved to the top layer successfully, otherwise false
     * @example
     * ```ts
     * const fWorkbook = univerAPI.getActiveWorkbook();
     * const fWorksheet = fWorkbook.getSheetByName('Sheet1');
     * if (!fWorksheet) return;
     * const image = fWorksheet.getImages()[0];
     * const result = image?.setFront();
     * console.log(result);
     * ```
     */
    setFront(): boolean {
        return this._commandService.syncExecuteCommand(SetDrawingArrangeCommand.id, {
            unitId: this._image.unitId,
            subUnitId: this._image.subUnitId,
            drawingIds: [this._image.drawingId],
            arrangeType: ArrangeTypeEnum.front,
        });
    }
}

function validateImageOpacity(opacity: number): void {
    if (!Number.isFinite(opacity) || opacity < 0 || opacity > 1) {
        throw new RangeError('Sheet image opacity must be between 0 and 1.');
    }
}