Build your own AI office with Univer Office SDK. Bring editing, calculation, collaboration, and file processing into your product for people and AI agents. Built on an extensible open-source core.
TypeScript boardcollaborationdocdocxexceloffce365officepdfpptpptxpresentationsdksheetslidesspreadsheetuniverwordwordprocessorworkspacexlsx
feat(formula): add support for IMAGE formula (#6189)
wpxp123456b78810504494
diff --git a/packages/core/src/shared/object-matrix.ts b/packages/core/src/shared/object-matrix.tsindex cca9095f68..f8148b5c7f 100644--- a/packages/core/src/shared/object-matrix.ts+++ b/packages/core/src/shared/object-matrix.ts@@ -566,10 +566,11 @@ export class ObjectMatrix<T> {getRealRange(): IRange {const rows = Object.keys(this._matrix);- const startRow = rows.length > 0 ? Number(rows[0]) : 0;- const endRow = rows.length > 0 ? Number(rows[rows.length - 1]) : 0;+ const rowLength = rows.length;+ const startRow = rowLength > 0 ? Number(rows[0]) : 0;+ const endRow = rowLength > 0 ? Number(rows[rowLength - 1]) : 0;- let startColumn = 0;+ let startColumn = -Infinity;let endColumn = 0;for (const rowKey of rows) {@@ -580,7 +581,7 @@ export class ObjectMatrix<T> {const rowStartColumn = Number(columns[0]);const rowEndColumn = Number(columns[columns.length - 1]);- if (startColumn === 0 || rowStartColumn < startColumn) {+ if (startColumn === -Infinity || rowStartColumn < startColumn) {startColumn = rowStartColumn;}@@ -599,6 +600,18 @@ export class ObjectMatrix<T> {};}+ getRealRowRange() {+ const rows = Object.keys(this._matrix);+ const rowLength = rows.length;+ const startRow = rowLength > 0 ? Number(rows[0]) : 0;+ const endRow = rowLength > 0 ? Number(rows[rowLength - 1]) : 0;++ return {+ startRow,+ endRow,+ };+ }+toNativeArray(): T[] {const native = new Array<T>();this.forValue((row: number, col: number, value: T) => {diff --git a/packages/core/src/sheets/worksheet.ts b/packages/core/src/sheets/worksheet.tsindex 236d0fdec5..96bec97dde 100644--- a/packages/core/src/sheets/worksheet.ts+++ b/packages/core/src/sheets/worksheet.ts@@ -938,7 +938,7 @@ export class Worksheet {* @returns the position of the last row that has content.*/getLastRowWithContent(): number {- return this._cellData.getLength() - 1;+ return this._cellData.getRealRowRange().endRow;}/**@@ -946,7 +946,11 @@ export class Worksheet {* @returns the position of the last column that has content.*/getLastColumnWithContent(): number {- return this._cellData.getRange().endColumn;+ return this.getDataRealRange().endColumn;+ }++ getDataRealRange(): IRange {+ return this._cellData.getRealRange();}getDataRangeScope(): IRange {diff --git a/packages/engine-formula/src/basics/common.ts b/packages/engine-formula/src/basics/common.tsindex a11c8276ee..bb06715d9b 100644--- a/packages/engine-formula/src/basics/common.ts+++ b/packages/engine-formula/src/basics/common.ts@@ -26,6 +26,7 @@ import type {ObjectMatrix,Styles,} from '@univerjs/core';+import type { IImageFormulaInfo } from '../engine/value-object/primitive-object';export const ERROR_VALUE_OBJECT_CLASS_TYPE = 'errorValueObject';@@ -122,6 +123,17 @@ export interface IFeatureDirtyRangeType {[unitId: string]: Nullable<{ [sheetId: string]: IRange[] }>;}+export interface IRuntimeImageFormulaDataType extends IImageFormulaInfo {+ unitId: string;+ sheetId: string;+ row: number;+ column: number;+}++export interface IUnitImageFormulaDataType {+ [unitId: string]: Nullable<{ [sheetId: string]: ObjectMatrix<Nullable<IImageFormulaInfo>> }>;+}+export interface IArrayFormulaUnitCellType extends IRuntimeUnitDataPrimitiveType {}export interface IFormulaData {diff --git a/packages/engine-formula/src/commands/mutations/set-image-formula-data.mutation.ts b/packages/engine-formula/src/commands/mutations/set-image-formula-data.mutation.tsnew file mode 100644index 0000000000..15ba6885a8--- /dev/null+++ b/packages/engine-formula/src/commands/mutations/set-image-formula-data.mutation.ts@@ -0,0 +1,35 @@+/**+ * 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 { IAccessor, IMutation } from '@univerjs/core';+import type { IRuntimeImageFormulaDataType } from '../../basics/common';++import { CommandType } from '@univerjs/core';++export interface ISetImageFormulaDataMutationParams {+ imageFormulaData: IRuntimeImageFormulaDataType[];+}++/**+ * There is no need to process data here, it is used as the main thread to send data to the worker. The main thread has already updated the data in advance, and there is no need to update it again here.+ */+export const SetImageFormulaDataMutation: IMutation<ISetImageFormulaDataMutationParams> = {+ id: 'formula.mutation.set-image-formula-data',+ type: CommandType.MUTATION,+ handler: (accessor: IAccessor, params: ISetImageFormulaDataMutationParams) => {+ return true;+ },+};diff --git a/packages/engine-formula/src/controller/calculate.controller.ts b/packages/engine-formula/src/controller/calculate.controller.tsindex 599ae0ad57..1aff8273a6 100644--- a/packages/engine-formula/src/controller/calculate.controller.ts+++ b/packages/engine-formula/src/controller/calculate.controller.ts@@ -15,7 +15,6 @@*/import type { ICommandInfo } from '@univerjs/core';-import type { ISetArrayFormulaDataMutationParams } from '../commands/mutations/set-array-formula-data.mutation';import type { ISetFormulaCalculationStartMutation } from '../commands/mutations/set-formula-calculation.mutation';import type { IFormulaDirtyData } from '../services/current-data.service';@@ -29,6 +28,7 @@ import {SetFormulaCalculationStartMutation,SetFormulaCalculationStopMutation,} from '../commands/mutations/set-formula-calculation.mutation';+import { SetImageFormulaDataMutation } from '../commands/mutations/set-image-formula-data.mutation';import { FormulaDataModel } from '../models/formula-data.model';import { ICalculateFormulaService } from '../services/calculate-formula.service';import { FormulaExecutedStateType } from '../services/runtime.service';@@ -145,7 +145,7 @@ export class CalculateController extends Disposable {}private async _applyResult(data: IAllRuntimeData) {- const { unitData, unitOtherData, arrayFormulaRange, arrayFormulaCellData, clearArrayFormulaCellData, arrayFormulaEmbedded } = data;+ const { unitData, unitOtherData, arrayFormulaRange, arrayFormulaCellData, clearArrayFormulaCellData, arrayFormulaEmbedded, imageFormulaData } = data;if (!unitData) {console.error('No sheetData from Formula Engine!');@@ -170,6 +170,19 @@ export class CalculateController extends Disposable {);}+ // handle image formula data+ if (imageFormulaData && imageFormulaData.length > 0) {+ this._commandService.executeCommand(+ SetImageFormulaDataMutation.id,+ {+ imageFormulaData,+ },+ {+ onlyLocal: true,+ }+ );+ }+this._commandService.executeCommand(SetFormulaCalculationResultMutation.id,{diff --git a/packages/engine-formula/src/controller/formula.controller.ts b/packages/engine-formula/src/controller/formula.controller.tsindex 97a76f4981..313098da91 100644--- a/packages/engine-formula/src/controller/formula.controller.ts+++ b/packages/engine-formula/src/controller/formula.controller.ts@@ -31,6 +31,7 @@ import {SetFormulaCalculationStopMutation,} from '../commands/mutations/set-formula-calculation.mutation';import { SetFormulaDataMutation } from '../commands/mutations/set-formula-data.mutation';+import { SetImageFormulaDataMutation } from '../commands/mutations/set-image-formula-data.mutation';import { RemoveOtherFormulaMutation, SetOtherFormulaMutation } from '../commands/mutations/set-other-formula.mutation';import { RemoveSuperTableMutation, SetSuperTableMutation, SetSuperTableOptionMutation } from '../commands/mutations/set-super-table.mutation';import { functionArray } from '../functions/array/function-map';@@ -73,6 +74,7 @@ export class FormulaController extends Disposable {[SetFormulaDataMutation,SetArrayFormulaDataMutation,+ SetImageFormulaDataMutation,SetFormulaCalculationStartMutation,SetFormulaCalculationStopMutation,SetFormulaCalculationNotificationMutation,diff --git a/packages/engine-formula/src/engine/value-object/base-value-object.ts b/packages/engine-formula/src/engine/value-object/base-value-object.tsindex e1b718193e..ea4f9a9b7a 100644--- a/packages/engine-formula/src/engine/value-object/base-value-object.ts+++ b/packages/engine-formula/src/engine/value-object/base-value-object.ts@@ -119,6 +119,10 @@ export class BaseValueObject extends ObjectClassType {return false;}+ isImage() {+ return false;+ }+sum(): BaseValueObject {return ErrorValueObject.create(ErrorType.VALUE);}diff --git a/packages/engine-formula/src/engine/value-object/primitive-object.ts b/packages/engine-formula/src/engine/value-object/primitive-object.tsindex a195f605a3..41c54df76c 100644--- a/packages/engine-formula/src/engine/value-object/primitive-object.ts+++ b/packages/engine-formula/src/engine/value-object/primitive-object.ts@@ -14,7 +14,7 @@* limitations under the License.*/-import { getNumfmtParseValueFilter, isRealNum, numfmt } from '@univerjs/core';+import { getNumfmtParseValueFilter, isRealNum, numfmt, Tools } from '@univerjs/core';import { FormulaAstLRU } from '../../basics/cache-lru';import { reverseCompareOperator } from '../../basics/calculate';import { BooleanValue, ConcatenateType } from '../../basics/common';@@ -1360,9 +1360,28 @@ export class NumberValueObject extends BaseValueObject {}}-interface IStringValueObjectOptions {+export interface IImageFormulaInfo {+ source: string;+ altText: string;+ sizing: number;+ height: number;+ width: number;+ isErrorImage?: boolean;+ imageNaturalHeight?: number;+ imageNaturalWidth?: number;+}++export interface IStringValueObjectOptions {+ /**+ * Whether it is a hyperlink value from HYPERLINK function+ */isHyperlink?: boolean;hyperlinkUrl?: string;+ /**+ * Whether it is an image value from IMAGE function+ */+ isImage?: boolean;+ imageInfo?: IImageFormulaInfo;}const STRING_CACHE_LRU_COUNT = 100000;@@ -1372,6 +1391,8 @@ export class StringValueObject extends BaseValueObject {private _value: string;private _isHyperlink: boolean = false;private _hyperlinkUrl: string = '';+ private _isImage: boolean = false;+ private _imageInfo: IStringValueObjectOptions['imageInfo'];static create(value: string, options?: IStringValueObjectOptions) {const cached = StringValueObjectCache.get(value);@@ -1383,6 +1404,10 @@ export class StringValueObject extends BaseValueObject {instance._isHyperlink = options.isHyperlink;instance._hyperlinkUrl = options.hyperlinkUrl ?? '';}+ if (options?.isImage) {+ instance._isImage = options.isImage;+ instance._imageInfo = options.imageInfo;+ }StringValueObjectCache.set(value, instance);return instance;}@@ -1396,6 +1421,14 @@ export class StringValueObject extends BaseValueObject {return false;}+ if (cached.isImage() !== options.isImage) {+ return false;+ }++ if (!Tools.diffValue(cached.getImageInfo(), options.imageInfo)) {+ return false;+ }+return true;};@@ -1420,6 +1453,14 @@ export class StringValueObject extends BaseValueObject {return this._hyperlinkUrl;}+ override isImage(): boolean {+ return this._isImage;+ }++ getImageInfo(): IStringValueObjectOptions['imageInfo'] {+ return this._imageInfo;+ }+override concatenateFront(valueObject: BaseValueObject): BaseValueObject {if (valueObject.isArray()) {return valueObject.concatenateBack(this);diff --git a/packages/engine-formula/src/functions/lookup/function-map.ts b/packages/engine-formula/src/functions/lookup/function-map.tsindex e971484ea4..f53aca11de 100644--- a/packages/engine-formula/src/functions/lookup/function-map.ts+++ b/packages/engine-formula/src/functions/lookup/function-map.ts@@ -29,6 +29,7 @@ import { FUNCTION_NAMES_LOOKUP } from './function-names';import { Hlookup } from './hlookup';import { Hstack } from './hstack';import { Hyperlink } from './hyperlink';+import { ImageFunction } from './image';import { Index } from './index';import { Indirect } from './indirect';import { Lookup } from './lookup';@@ -65,6 +66,7 @@ export const functionLookup = [[Hlookup, FUNCTION_NAMES_LOOKUP.HLOOKUP],[Hstack, FUNCTION_NAMES_LOOKUP.HSTACK],[Hyperlink, FUNCTION_NAMES_LOOKUP.HYPERLINK],+ [ImageFunction, FUNCTION_NAMES_LOOKUP.IMAGE],[Index, FUNCTION_NAMES_LOOKUP.INDEX],[Indirect, FUNCTION_NAMES_LOOKUP.INDIRECT],[Lookup, FUNCTION_NAMES_LOOKUP.LOOKUP],diff --git a/packages/engine-formula/src/functions/lookup/image/index.ts b/packages/engine-formula/src/functions/lookup/image/index.tsnew file mode 100644index 0000000000..2d21d45835--- /dev/null+++ b/packages/engine-formula/src/functions/lookup/image/index.ts@@ -0,0 +1,162 @@+/**+ * 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 { ArrayValueObject } from '../../../engine/value-object/array-value-object';+import type { BaseValueObject } from '../../../engine/value-object/base-value-object';+import { ErrorType } from '../../../basics/error-type';+import { expandArrayValueObject } from '../../../engine/utils/array-object';+import { ErrorValueObject } from '../../../engine/value-object/base-value-object';+import { NumberValueObject, StringValueObject } from '../../../engine/value-object/primitive-object';+import { BaseFunction } from '../../base-function';++export class ImageFunction extends BaseFunction {+ override minParams = 1;++ override maxParams = 5;++ // eslint-disable-next-line complexity+ override calculate(source: BaseValueObject, altText?: BaseValueObject, sizing?: BaseValueObject, height?: BaseValueObject, width?: BaseValueObject): BaseValueObject {+ const maxRowLength = Math.max(+ source.isArray() ? (source as ArrayValueObject).getRowCount() : 1,+ altText?.isArray() ? (altText as ArrayValueObject).getRowCount() : 1,+ sizing?.isArray() ? (sizing as ArrayValueObject).getRowCount() : 1,+ height?.isArray() ? (height as ArrayValueObject).getRowCount() : 1,+ width?.isArray() ? (width as ArrayValueObject).getRowCount() : 1+ );++ const maxColumnLength = Math.max(+ source.isArray() ? (source as ArrayValueObject).getColumnCount() : 1,+ altText?.isArray() ? (altText as ArrayValueObject).getColumnCount() : 1,+ sizing?.isArray() ? (sizing as ArrayValueObject).getColumnCount() : 1,+ height?.isArray() ? (height as ArrayValueObject).getColumnCount() : 1,+ width?.isArray() ? (width as ArrayValueObject).getColumnCount() : 1+ );++ const sourceArray = expandArrayValueObject(maxRowLength, maxColumnLength, source, ErrorValueObject.create(ErrorType.NA));+ const altTextArray = altText ? expandArrayValueObject(maxRowLength, maxColumnLength, altText, ErrorValueObject.create(ErrorType.NA)) : undefined;+ const sizingArray = sizing ? expandArrayValueObject(maxRowLength, maxColumnLength, sizing, ErrorValueObject.create(ErrorType.NA)) : undefined;+ const heightArray = height ? expandArrayValueObject(maxRowLength, maxColumnLength, height, ErrorValueObject.create(ErrorType.NA)) : undefined;+ const widthArray = width ? expandArrayValueObject(maxRowLength, maxColumnLength, width, ErrorValueObject.create(ErrorType.NA)) : undefined;++ const resultArray = sourceArray.mapValue((sourceObject, rowIndex, columnIndex) => {+ if (sourceObject.isError()) {+ return sourceObject;+ }++ const altTextObject = altTextArray ? altTextArray.get(rowIndex, columnIndex) as BaseValueObject : undefined;+ if (altTextObject?.isError()) {+ return altTextObject;+ }++ const sizingObject = sizingArray ? sizingArray.get(rowIndex, columnIndex) as BaseValueObject : undefined;+ if (sizingObject?.isError()) {+ return sizingObject;+ }++ const heightObject = heightArray ? heightArray.get(rowIndex, columnIndex) as BaseValueObject : undefined;+ if (heightObject?.isError()) {+ return heightObject;+ }++ const widthObject = widthArray ? widthArray.get(rowIndex, columnIndex) as BaseValueObject : undefined;+ if (widthObject?.isError()) {+ return widthObject;+ }++ return this._handleSingleObject(sourceObject, altTextObject, sizingObject, heightObject, widthObject);+ });++ if (maxRowLength === 1 && maxColumnLength === 1) {+ return (resultArray as ArrayValueObject).get(0, 0) as BaseValueObject;+ }++ return resultArray;+ }++ // eslint-disable-next-line complexity+ private _handleSingleObject(source: BaseValueObject, altText?: BaseValueObject, sizing?: BaseValueObject, height?: BaseValueObject, width?: BaseValueObject): BaseValueObject {+ if (!source.isString()) {+ return ErrorValueObject.create(ErrorType.VALUE);+ }++ const sourceValue = source.getValue() as string;++ let altTextValue = '';+ if (altText) {+ if (altText.isBoolean()) {+ altTextValue = altText.getValue() ? 'TRUE' : 'FALSE';+ } else if (!altText.isNull()) {+ altTextValue = `${altText.getValue()}`;+ }+ }++ let _sizing = sizing ?? NumberValueObject.create(0);+ if (_sizing.isString()) {+ _sizing = _sizing.convertToNumberObjectValue();+ }+ if (_sizing.isError()) {+ return _sizing;+ }++ const sizingValue = Math.abs(Math.trunc(+_sizing.getValue()));++ // If sizing is not between 0-3, return #VALUE! error.+ if (sizingValue < 0 || sizingValue > 3) {+ return ErrorValueObject.create(ErrorType.VALUE);+ }++ // If sizing is 0, 1, or 2 and height or width is provided, return #VALUE! error.+ if ([0, 1, 2].includes(sizingValue) && (height || width)) {+ return ErrorValueObject.create(ErrorType.VALUE);+ }++ let _height = height ?? NumberValueObject.create(0);+ if (_height.isString()) {+ _height = _height.convertToNumberObjectValue();+ }+ if (_height.isError()) {+ return _height;+ }++ const heightValue = Math.ceil(+_height.getValue());++ let _width = width ?? NumberValueObject.create(0);+ if (_width.isString()) {+ _width = _width.convertToNumberObjectValue();+ }+ if (_width.isError()) {+ return _width;+ }++ const widthValue = Math.ceil(+_width.getValue());++ // If sizing is 3 and height or width is less than 1, return #VALUE! error.+ if (sizingValue === 3 && heightValue < 1 && widthValue < 1) {+ return ErrorValueObject.create(ErrorType.VALUE);+ }++ return StringValueObject.create('', {+ isImage: true,+ imageInfo: {+ source: sourceValue,+ altText: altTextValue,+ sizing: sizingValue,+ height: heightValue,+ width: widthValue,+ },+ });+ }+}diff --git a/packages/engine-formula/src/index.ts b/packages/engine-formula/src/index.tsindex ab3e01b4fb..9b64435b24 100644--- a/packages/engine-formula/src/index.ts+++ b/packages/engine-formula/src/index.ts@@ -26,9 +26,11 @@ export type {IFormulaData,IFormulaDataItem,IFormulaDatasetConfig,+ IRuntimeImageFormulaDataType,IRuntimeUnitDataType,ISheetData,IUnitData,+ IUnitImageFormulaDataType,IUnitSheetNameMap,} from './basics/common';export { BooleanValue } from './basics/common';@@ -60,6 +62,7 @@ export {SetFormulaCalculationStopMutation,} from './commands/mutations/set-formula-calculation.mutation';export { type ISetFormulaDataMutationParams, SetFormulaDataMutation } from './commands/mutations/set-formula-data.mutation';+export { type ISetImageFormulaDataMutationParams, SetImageFormulaDataMutation } from './commands/mutations/set-image-formula-data.mutation';export { type IRemoveOtherFormulaMutationParams, type ISetOtherFormulaMutationParams, RemoveOtherFormulaMutation, SetOtherFormulaMutation } from './commands/mutations/set-other-formula.mutation';export { RemoveSuperTableMutation, SetSuperTableMutation, SetSuperTableOptionMutation } from './commands/mutations/set-super-table.mutation';export type { ISetSuperTableMutationParam, ISetSuperTableMutationSearchParam } from './commands/mutations/set-super-table.mutation';@@ -118,7 +121,7 @@ export { generateStringWithSequence, type ISequenceNode, sequenceNodeType } fromexport { ArrayValueObject, ValueObjectFactory } from './engine/value-object/array-value-object';export { BaseValueObject, ErrorValueObject } from './engine/value-object/base-value-object';export { LambdaValueObjectObject } from './engine/value-object/lambda-value-object';-export type { FormulaFunctionResultValueType, FormulaFunctionValueType, PrimitiveValueType } from './engine/value-object/primitive-object';+export type { FormulaFunctionResultValueType, FormulaFunctionValueType, IImageFormulaInfo, PrimitiveValueType } from './engine/value-object/primitive-object';export { BooleanValueObject, NullValueObject, NumberValueObject, StringValueObject } from './engine/value-object/primitive-object';export { functionArray } from './functions/array/function-map';export { FUNCTION_NAMES_ARRAY } from './functions/array/function-names';diff --git a/packages/engine-formula/src/models/formula-data.model.ts b/packages/engine-formula/src/models/formula-data.model.tsindex 5cd070451f..b401f4a6f1 100644--- a/packages/engine-formula/src/models/formula-data.model.ts+++ b/packages/engine-formula/src/models/formula-data.model.ts@@ -24,11 +24,12 @@ import type {IRuntimeUnitDataType,ISheetData,IUnitData,+ IUnitImageFormulaDataType,IUnitRowData,IUnitSheetNameMap,IUnitStylesData,} from '../basics/common';-+import type { IImageFormulaInfo } from '../engine/value-object/primitive-object';import { BooleanNumber, Disposable, Inject, isFormulaId, isFormulaString, IUniverInstanceService, ObjectMatrix, RANGE_TYPE, UniverInstanceType } from '@univerjs/core';import { LexerTreeBuilder } from '../engine/analysis/lexer-tree-builder';import { clearArrayFormulaCellDataByCell, updateFormulaDataByCellValue } from './utils/formula-data-util';@@ -43,6 +44,8 @@ export class FormulaDataModel extends Disposable {private _arrayFormulaCellData: IArrayFormulaUnitCellType = {};+ private _unitImageFormulaData: IUnitImageFormulaDataType = {};+constructor(@IUniverInstanceService private readonly _univerInstanceService: IUniverInstanceService,@Inject(LexerTreeBuilder) private readonly _lexerTreeBuilder: LexerTreeBuilder@@ -54,6 +57,7 @@ export class FormulaDataModel extends Disposable {super.dispose();this._arrayFormulaRange = {};this._arrayFormulaCellData = {};+ this._unitImageFormulaData = {};}clearPreviousArrayFormulaCellData(clearArrayFormulaCellData: IRuntimeUnitDataType) {@@ -213,6 +217,14 @@ export class FormulaDataModel extends Disposable {this._arrayFormulaCellData = value;}+ getUnitImageFormulaData() {+ return this._unitImageFormulaData;+ }++ setUnitImageFormulaData(value: IUnitImageFormulaDataType) {+ this._unitImageFormulaData = value;+ }+mergeArrayFormulaRange(formulaData: IArrayFormulaRangeType) {Object.keys(formulaData).forEach((unitId) => {const sheetData = formulaData[unitId];@@ -240,6 +252,38 @@ export class FormulaDataModel extends Disposable {});}+ mergeUnitImageFormulaData(formulaData: IUnitImageFormulaDataType) {+ const unitIds = Object.keys(formulaData);++ for (let i = 0; i < unitIds.length; i++) {+ const unitId = unitIds[i];++ const sheetData = formulaData[unitId];+ if (!sheetData) continue;++ if (!this._unitImageFormulaData[unitId]) {+ this._unitImageFormulaData[unitId] = {};+ }++ const sheetIds = Object.keys(sheetData);++ for (let j = 0; j < sheetIds.length; j++) {+ const sheetId = sheetIds[j];++ const imageFormulaMatrix = sheetData[sheetId];+ if (!imageFormulaMatrix) continue;++ if (!this._unitImageFormulaData[unitId][sheetId]) {+ this._unitImageFormulaData[unitId][sheetId] = new ObjectMatrix<Nullable<IImageFormulaInfo>>();+ }++ imageFormulaMatrix.forValue((r, c, v) => {+ this._unitImageFormulaData[unitId]![sheetId].setValue(r, c, v);+ });+ }+ }+ }+deleteArrayFormulaRange(unitId: string, sheetId: string, row: number, column: number) {const cellMatrixData = this._arrayFormulaRange[unitId]?.[sheetId];if (cellMatrixData == null) {@@ -449,6 +493,19 @@ export class FormulaDataModel extends Disposable {});}+ updateImageFormulaData(unitId: string, sheetId: string, cellValue: IObjectMatrixPrimitiveType<Nullable<ICellData>>) {+ const imageFormulaData = this._unitImageFormulaData[unitId]?.[sheetId];+ if (!imageFormulaData) {+ return;+ }++ const cellMatrix = new ObjectMatrix(cellValue);++ cellMatrix.forValue((r, c) => {+ imageFormulaData.realDeleteValue(r, c);+ });+ }+getFormulaStringByCell(row: number, column: number, sheetId: string, unitId: string) {const workbook = this._univerInstanceService.getUnit<Workbook>(unitId);if (workbook == null) {diff --git a/packages/engine-formula/src/services/runtime.service.ts b/packages/engine-formula/src/services/runtime.service.tsindex 65bf3ff156..625894a001 100644--- a/packages/engine-formula/src/services/runtime.service.ts+++ b/packages/engine-formula/src/services/runtime.service.ts@@ -19,6 +19,7 @@ import type {IArrayFormulaEmbeddedMap,IArrayFormulaRangeType,IFeatureDirtyRangeType,+ IRuntimeImageFormulaDataType,IRuntimeOtherUnitDataType,IRuntimeUnitDataType,} from '../basics/common';@@ -72,6 +73,7 @@ export interface IAllRuntimeData {functionsExecutedState: FormulaExecutedStateType;arrayFormulaCellData: IRuntimeUnitDataType;clearArrayFormulaCellData: IRuntimeUnitDataType;+ imageFormulaData: IRuntimeImageFormulaDataType[];runtimeFeatureRange: { [featureId: string]: IFeatureDirtyRangeType };runtimeFeatureCellData: { [featureId: string]: IRuntimeUnitDataType };@@ -186,6 +188,8 @@ export interface IFormulaRuntimeService {setUnitArrayFormulaEmbeddedMap(): void;clearArrayObjectCache(): void;++ getRuntimeImageFormulaData(): IRuntimeImageFormulaDataType[];}export class FormulaRuntimeService extends Disposable implements IFormulaRuntimeService {@@ -218,6 +222,8 @@ export class FormulaRuntimeService extends Disposable implements IFormulaRuntimeprivate _runtimeFeatureCellData: { [featureId: string]: IRuntimeUnitDataType } = {};+ private _runtimeImageFormulaData: IRuntimeImageFormulaDataType[] = [];+private _functionsExecutedState: FormulaExecutedStateType = FormulaExecutedStateType.INITIAL;// lambdaId: { key: BaseAstNode }@@ -369,6 +375,7 @@ export class FormulaRuntimeService extends Disposable implements IFormulaRuntimethis._unitArrayFormulaEmbeddedMap = {};this._runtimeArrayFormulaCellData = {};this._runtimeClearArrayFormulaCellData = {};+ this._runtimeImageFormulaData = [];// this._runtimeFeatureCellData = {};// this._runtimeFeatureRange = {};@@ -471,6 +478,7 @@ export class FormulaRuntimeService extends Disposable implements IFormulaRuntimeconst sheetId = this._currentSubUnitId;const unitId = this._currentUnitId;+ // Get current sheet dataif (this._runtimeData[unitId] == null) {this._runtimeData[unitId] = {};}@@ -481,6 +489,9 @@ export class FormulaRuntimeService extends Disposable implements IFormulaRuntimeunitData[sheetId] = new ObjectMatrix<Nullable<ICellData>>();}+ const sheetData = unitData[sheetId];++ // Get current sheet array formula rangeif (this._unitArrayFormulaRange[unitId] == null) {this._unitArrayFormulaRange[unitId] = {};}@@ -493,6 +504,7 @@ export class FormulaRuntimeService extends Disposable implements IFormulaRuntimeconst arrayData = new ObjectMatrix<IRange>(arrayFormulaRange[sheetId]);+ // Get current sheet array formula cell dataif (this._runtimeArrayFormulaCellData[unitId] === undefined) {this._runtimeArrayFormulaCellData[unitId] = {};}@@ -503,6 +515,9 @@ export class FormulaRuntimeService extends Disposable implements IFormulaRuntimeruntimeArrayFormulaCellData[sheetId] = new ObjectMatrix<Nullable<ICellData>>();}+ const runtimeArrayUnitData = runtimeArrayFormulaCellData[sheetId];++ // Get current sheet clear array formula cell dataif (this._runtimeClearArrayFormulaCellData[unitId] === undefined) {this._runtimeClearArrayFormulaCellData[unitId] = {};}@@ -513,10 +528,6 @@ export class FormulaRuntimeService extends Disposable implements IFormulaRuntimeclearArrayFormulaCellData[sheetId] = new ObjectMatrix<Nullable<ICellData>>();}- const sheetData = unitData[sheetId];-- const runtimeArrayUnitData = runtimeArrayFormulaCellData[sheetId];-const clearArrayUnitData = clearArrayFormulaCellData[sheetId];if (@@ -640,6 +651,20 @@ export class FormulaRuntimeService extends Disposable implements IFormulaRuntimeconst valueObject = this._getValueObjectOfRuntimeData(functionVariant as BaseValueObject);sheetData.setValue(row, column, valueObject);+ // If it is the result of the IMAGE formula, the image info needs to be saved to runtimeImageFormulaData+ if ((functionVariant as BaseValueObject).isString() && (functionVariant as StringValueObject).isImage()) {+ const imageInfo = (functionVariant as StringValueObject).getImageInfo();+ if (imageInfo) {+ this._runtimeImageFormulaData.push({+ ...imageInfo,+ unitId,+ sheetId,+ row,+ column,+ });+ }+ }+// Formula calculation results are saved to cacheCELL_INVERTED_INDEX_CACHE.set(unitId,@@ -727,6 +752,10 @@ export class FormulaRuntimeService extends Disposable implements IFormulaRuntimethis._runtimeFeatureCellData[featureId] = featureData;}+ getRuntimeImageFormulaData() {+ return this._runtimeImageFormulaData;+ }+getAllRuntimeData(): IAllRuntimeData {return {unitData: this.getUnitData(),@@ -736,6 +765,7 @@ export class FormulaRuntimeService extends Disposable implements IFormulaRuntimefunctionsExecutedState: this._functionsExecutedState,arrayFormulaCellData: this.getRuntimeArrayFormulaCellData(),clearArrayFormulaCellData: this.getRuntimeClearArrayFormulaCellData(),+ imageFormulaData: this.getRuntimeImageFormulaData(),runtimeFeatureRange: this.getRuntimeFeatureRange(),runtimeFeatureCellData: this.getRuntimeFeatureCellData(),diff --git a/packages/sheets-formula-ui/src/controllers/image-formula-render.controller.ts b/packages/sheets-formula-ui/src/controllers/image-formula-render.controller.tsnew file mode 100644index 0000000000..6cf831e923--- /dev/null+++ b/packages/sheets-formula-ui/src/controllers/image-formula-render.controller.ts@@ -0,0 +1,46 @@+/**+ * 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 { Workbook } from '@univerjs/core';+import { Disposable, Inject, IUniverInstanceService, UniverInstanceType } from '@univerjs/core';+import { IRenderManagerService } from '@univerjs/engine-render';+import { ImageFormulaCellInterceptorController } from '@univerjs/sheets-formula';+import { SheetSkeletonManagerService } from '@univerjs/sheets-ui';++export class ImageFormulaRenderController extends Disposable {+ constructor(+ @Inject(ImageFormulaCellInterceptorController) private readonly _imageFormulaCellInterceptorController: ImageFormulaCellInterceptorController,+ @IRenderManagerService private readonly _renderManagerService: IRenderManagerService,+ @IUniverInstanceService private readonly _univerInstanceService: IUniverInstanceService+ ) {+ super();++ this._imageFormulaCellInterceptorController.registerRefreshRenderFunction(() => {+ const workbook = this._univerInstanceService.getCurrentUnitOfType<Workbook>(UniverInstanceType.UNIVER_SHEET);+ if (!workbook) return;++ const render = this._renderManagerService.getRenderById(workbook.getUnitId());+ if (!render) return;++ render.with(SheetSkeletonManagerService).reCalculate();++ const mainComponent = render.mainComponent;+ if (!mainComponent) return;++ mainComponent.makeDirty();+ });+ }+}diff --git a/packages/sheets-formula-ui/src/locale/function-list/lookup/ca-ES.ts b/packages/sheets-formula-ui/src/locale/function-list/lookup/ca-ES.tsindex bf2098079d..2a91d26d43 100644--- a/packages/sheets-formula-ui/src/locale/function-list/lookup/ca-ES.ts+++ b/packages/sheets-formula-ui/src/locale/function-list/lookup/ca-ES.ts@@ -272,8 +272,11 @@ const locale: typeof enUS = {},],functionParameter: {- number1: { name: 'nombre1', detail: 'primer' },- number2: { name: 'nombre2', detail: 'segon' },+ source: { name: 'origen', detail: 'La ruta de acceso URL, mediante un protocolo "https", del archivo de imagen.' },+ altText: { name: 'texto_alternativo', detail: 'Texto alternativo que describe la imagen para accesibilidad.' },+ sizing: { name: 'dimensiones', detail: 'Especifica las dimensiones de la imagen.' },+ height: { name: 'alto', detail: 'La altura personalizada de la imagen en píxeles.' },+ width: { name: 'ancho', detail: 'La anchura personalizada de la imagen en píxeles.' },},},INDEX: {diff --git a/packages/sheets-formula-ui/src/locale/function-list/lookup/en-US.ts b/packages/sheets-formula-ui/src/locale/function-list/lookup/en-US.tsindex 13a9276eb8..dfefda2517 100644--- a/packages/sheets-formula-ui/src/locale/function-list/lookup/en-US.ts+++ b/packages/sheets-formula-ui/src/locale/function-list/lookup/en-US.ts@@ -270,8 +270,11 @@ const locale = {},],functionParameter: {- number1: { name: 'number1', detail: 'first' },- number2: { name: 'number2', detail: 'second' },+ source: { name: 'source', detail: 'The URL path, using an "https" protocol, of the image file.' },+ altText: { name: 'alt_text', detail: 'Alternative text that describes the image for accessibility.' },+ sizing: { name: 'sizing', detail: 'Specifies the image dimensions.' },+ height: { name: 'height', detail: 'The custom height of the image in pixels.' },+ width: { name: 'width', detail: 'The custom width of the image in pixels.' },},},INDEX: {diff --git a/packages/sheets-formula-ui/src/locale/function-list/lookup/es-ES.ts b/packages/sheets-formula-ui/src/locale/function-list/lookup/es-ES.tsindex e8ebff9b48..c221f3d701 100644--- a/packages/sheets-formula-ui/src/locale/function-list/lookup/es-ES.ts+++ b/packages/sheets-formula-ui/src/locale/function-list/lookup/es-ES.ts@@ -272,8 +272,11 @@ const locale: typeof enUS = {},],functionParameter: {- number1: { name: 'número1', detail: 'primero' },- number2: { name: 'número2', detail: 'segundo' },+ source: { name: 'origen', detail: 'La ruta de acceso URL, mediante un protocolo "https", del archivo de imagen.' },+ altText: { name: 'texto_alternativo', detail: 'Texto alternativo que describe la imagen para accesibilidad.' },+ sizing: { name: 'dimensiones', detail: 'Especifica las dimensiones de la imagen.' },+ height: { name: 'alto', detail: 'La altura personalizada de la imagen en píxeles.' },+ width: { name: 'ancho', detail: 'La anchura personalizada de la imagen en píxeles.' },},},INDEX: {diff --git a/packages/sheets-formula-ui/src/locale/function-list/lookup/ja-JP.ts b/packages/sheets-formula-ui/src/locale/function-list/lookup/ja-JP.tsindex 1f928a5a02..22b2b2388d 100644--- a/packages/sheets-formula-ui/src/locale/function-list/lookup/ja-JP.ts+++ b/packages/sheets-formula-ui/src/locale/function-list/lookup/ja-JP.ts@@ -263,8 +263,11 @@ const locale: typeof enUS = {},],functionParameter: {- number1: { name: 'number1', detail: 'first' },- number2: { name: 'number2', detail: 'second' },+ source: { name: 'ソース', detail: '"https" プロトコルを使用した画像ファイルの URL パス。' },+ altText: { name: '代替テキスト', detail: 'アクセシビリティのために画像を説明する代替テキスト。' },+ sizing: { name: 'サイズ', detail: '画像の寸法を指定します。' },+ height: { name: '高さ', detail: '画像のカスタムの高さ (ピクセル単位)。' },+ width: { name: '幅', detail: '画像のカスタム幅 (ピクセル単位)。' },},},INDEX: {diff --git a/packages/sheets-formula-ui/src/locale/function-list/lookup/ko-KR.ts b/packages/sheets-formula-ui/src/locale/function-list/lookup/ko-KR.tsindex 83fc33d5e9..b88a39aa02 100644--- a/packages/sheets-formula-ui/src/locale/function-list/lookup/ko-KR.ts+++ b/packages/sheets-formula-ui/src/locale/function-list/lookup/ko-KR.ts@@ -272,8 +272,11 @@ const locale: typeof enUS = {},],functionParameter: {- number1: { name: 'number1', detail: '첫 번째' },- number2: { name: 'number2', detail: '두 번째' },+ source: { name: 'source', detail: '이미지 파일의 "https" 프로토콜을 사용하는 URL 경로입니다. 필수.' },+ altText: { name: 'alt_text', detail: '접근성을 위해 이미지를 설명하는 대체 텍스트입니다.' },+ sizing: { name: 'sizing', detail: '이미지 차원을 지정합니다.' },+ height: { name: 'height', detail: '이미지의 사용자 지정 높이(픽셀)입니다.' },+ width: { name: 'width', detail: '이미지의 사용자 지정 너비(픽셀)입니다.' },},},INDEX: {diff --git a/packages/sheets-formula-ui/src/locale/function-list/lookup/ru-RU.ts b/packages/sheets-formula-ui/src/locale/function-list/lookup/ru-RU.tsindex ca73d29b40..7f347e85ec 100644--- a/packages/sheets-formula-ui/src/locale/function-list/lookup/ru-RU.ts+++ b/packages/sheets-formula-ui/src/locale/function-list/lookup/ru-RU.ts@@ -272,8 +272,11 @@ const locale: typeof enUS = {},],functionParameter: {- number1: { name: 'число1', detail: 'первое' },- number2: { name: 'число2', detail: 'второе' },+ source: { name: 'источник', detail: 'Путь в виде URL-адреса с использованием протокола HTTPS к файлу изображения.' },+ altText: { name: 'замещающий_текст', detail: 'Замещающий текст, описывающий изображение для специальных возможностей.' },+ sizing: { name: 'размер', detail: 'Указывает размеры изображения.' },+ height: { name: 'высота', detail: 'Настраиваемая высота изображения в пикселях.' },+ width: { name: 'ширина', detail: 'Настраиваемая ширина изображения в пикселях.' },},},INDEX: {diff --git a/packages/sheets-formula-ui/src/locale/function-list/lookup/vi-VN.ts b/packages/sheets-formula-ui/src/locale/function-list/lookup/vi-VN.tsindex cef7b378d0..5c84af3178 100644--- a/packages/sheets-formula-ui/src/locale/function-list/lookup/vi-VN.ts+++ b/packages/sheets-formula-ui/src/locale/function-list/lookup/vi-VN.ts@@ -260,17 +260,20 @@ const locale: typeof enUS = {},},IMAGE: {- description: 'Returns an image from a given source',- abstract: 'Returns an image from a given source',+ description: 'Trả về hình ảnh từ một nguồn nhất định.',+ abstract: 'Trả về hình ảnh từ một nguồn nhất định.',links: [{- title: 'Instruction',- url: 'https://support.microsoft.com/en-us/office/image-function-7e112975-5e52-4f2a-b9da-1d913d51f5d5',+ title: 'Hướng dẫn',+ url: 'https://support.microsoft.com/vi-vn/office/image-function-7e112975-5e52-4f2a-b9da-1d913d51f5d5',},],functionParameter: {- number1: { name: 'number1', detail: 'first' },- number2: { name: 'number2', detail: 'second' },+ source: { name: 'nguồn', detail: 'Đường dẫn URL sử dụng giao thức "https" của tệp hình ảnh. Bắt buộc.' },+ altText: { name: 'văn bản thay thế', detail: 'Văn bản thay thế mô tả hình ảnh cho khả năng truy nhập.' },+ sizing: { name: 'định cỡ', detail: 'Chỉ định kích thước hình ảnh.' },+ height: { name: 'chiều cao', detail: 'Chiều cao tùy chỉnh của hình ảnh tính bằng pixel.' },+ width: { name: 'độ rộng', detail: 'Chiều rộng tùy chỉnh của hình ảnh tính bằng pixel.' },},},INDEX: {diff --git a/packages/sheets-formula-ui/src/locale/function-list/lookup/zh-CN.ts b/packages/sheets-formula-ui/src/locale/function-list/lookup/zh-CN.tsindex 654773f2dd..39fdf05f2e 100644--- a/packages/sheets-formula-ui/src/locale/function-list/lookup/zh-CN.ts+++ b/packages/sheets-formula-ui/src/locale/function-list/lookup/zh-CN.ts@@ -263,8 +263,11 @@ const locale: typeof enUS = {},],functionParameter: {- number1: { name: 'number1', detail: 'first' },- number2: { name: 'number2', detail: 'second' },+ source: { name: '图像源', detail: '图像文件的 URL 路径(使用“https”协议)。' },+ altText: { name: '描述文字', detail: '描述图像以提供辅助功能的可选文字。' },+ sizing: { name: '维度', detail: '指定图像维度。' },+ height: { name: '高度', detail: '图像的自定义高度(以像素为单位)。' },+ width: { name: '宽度', detail: '图像的自定义宽度(以像素为单位)。' },},},INDEX: {diff --git a/packages/sheets-formula-ui/src/locale/function-list/lookup/zh-TW.ts b/packages/sheets-formula-ui/src/locale/function-list/lookup/zh-TW.tsindex 164bca57a2..c1ce321714 100644--- a/packages/sheets-formula-ui/src/locale/function-list/lookup/zh-TW.ts+++ b/packages/sheets-formula-ui/src/locale/function-list/lookup/zh-TW.ts@@ -263,8 +263,11 @@ const locale: typeof enUS = {},],functionParameter: {- number1: { name: 'number1', detail: 'first' },- number2: { name: 'number2', detail: 'second' },+ source: { name: 'source', detail: '使用 「HTTP」 通訊協定之影像檔案的 URL 路徑。' },+ altText: { name: 'alt_text', detail: '描述協助工具影像的替代文字。' },+ sizing: { name: 'sizing', detail: '指定影像維度。' },+ height: { name: 'height', detail: '影像的自訂高度 (像素)。' },+ width: { name: 'width', detail: '影像的自訂寬度 (像素)。' },},},INDEX: {diff --git a/packages/sheets-formula-ui/src/plugin.ts b/packages/sheets-formula-ui/src/plugin.tsindex 935708bdf3..dc879c18dd 100644--- a/packages/sheets-formula-ui/src/plugin.ts+++ b/packages/sheets-formula-ui/src/plugin.ts@@ -34,6 +34,7 @@ import { FormulaEditorShowController } from './controllers/formula-editor-show.cimport { FormulaRenderManagerController } from './controllers/formula-render.controller';import { FormulaReorderController } from './controllers/formula-reorder.controller';import { FormulaUIController } from './controllers/formula-ui.controller';+import { ImageFormulaRenderController } from './controllers/image-formula-render.controller';import { FormulaPromptService, IFormulaPromptService } from './services/prompt.service';import { GlobalRangeSelectorService } from './services/range-selector.service';import { RefSelectionsRenderService } from './services/render-services/ref-selections.render-service';@@ -79,6 +80,7 @@ export class UniverSheetsFormulaUIPlugin extends Plugin {[FormulaEditorShowController],[FormulaRenderManagerController],[FormulaReorderController],+ [ImageFormulaRenderController],]);this._initUIPart();@@ -104,6 +106,7 @@ export class UniverSheetsFormulaUIPlugin extends Plugin {[FormulaUIController], // FormulaProgressBar relies on TriggerCalculationController, but it is necessary to ensure that the formula calculation is done after rendered.[FormulaClipboardController],[FormulaRenderManagerController],+ [ImageFormulaRenderController],]);}diff --git a/packages/sheets-formula/src/controllers/image-formula-cell-interceptor.controller.ts b/packages/sheets-formula/src/controllers/image-formula-cell-interceptor.controller.tsnew file mode 100644index 0000000000..c5775f9269--- /dev/null+++ b/packages/sheets-formula/src/controllers/image-formula-cell-interceptor.controller.ts@@ -0,0 +1,228 @@+/**+ * 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 { ICellData, ICommandInfo, Nullable } from '@univerjs/core';+import type { IImageFormulaInfo, IRuntimeImageFormulaDataType, ISetImageFormulaDataMutationParams, IUnitImageFormulaDataType } from '@univerjs/engine-formula';+import { BooleanNumber, BuildTextUtils, CellValueType, createDocumentModelWithStyle, Disposable, DrawingTypeEnum, generateRandomId, ICommandService, ImageSourceType, Inject, InterceptorEffectEnum, ObjectMatrix, ObjectRelativeFromH, ObjectRelativeFromV, PositionedObjectLayoutType, WrapTextType } from '@univerjs/core';+import { ErrorType, FormulaDataModel, SetImageFormulaDataMutation } from '@univerjs/engine-formula';+import { INTERCEPTOR_POINT, SheetInterceptorService } from '@univerjs/sheets';++export class ImageFormulaCellInterceptorController extends Disposable {+ private _errorValueCell: ICellData = {+ v: ErrorType.VALUE,+ t: CellValueType.STRING,+ };++ private _refreshRender: () => void;++ constructor(+ @ICommandService private readonly _commandService: ICommandService,+ @Inject(SheetInterceptorService) private _sheetInterceptorService: SheetInterceptorService,+ @Inject(FormulaDataModel) private readonly _formulaDataModel: FormulaDataModel+ ) {+ super();++ this._initialize();+ }++ private _initialize(): void {+ this._commandExecutedListener();++ this._initInterceptorCellContent();+ }++ private _commandExecutedListener() {+ this.disposeWithMe(+ this._commandService.onCommandExecuted(async (command: ICommandInfo) => {+ // Synchronous data from worker+ if (command.id === SetImageFormulaDataMutation.id) {+ const params = command.params as ISetImageFormulaDataMutationParams;+ if (!params) return;++ const { imageFormulaData } = params;+ if (!imageFormulaData || imageFormulaData.length === 0) return;++ const updateRuntimeImageFormulaData = await Promise.all(+ imageFormulaData.map((imageFormulaInfo) => {+ return this._getImageNatureSize(imageFormulaInfo);+ })+ );++ const unitImageFormulaData: IUnitImageFormulaDataType = {};++ updateRuntimeImageFormulaData.forEach((imageFormulaInfo) => {+ const { unitId, sheetId, row, column, ...imageInfo } = imageFormulaInfo;+ if (!unitImageFormulaData[unitId]) {+ unitImageFormulaData[unitId] = {};+ }+ if (!unitImageFormulaData[unitId]![sheetId]) {+ unitImageFormulaData[unitId]![sheetId] = new ObjectMatrix<Nullable<IImageFormulaInfo>>();+ }+ unitImageFormulaData[unitId]![sheetId]!.setValue(row, column, imageInfo);+ });++ this._formulaDataModel.mergeUnitImageFormulaData(unitImageFormulaData);++ // Refresh render+ this._refreshRender();+ }+ })+ );+ }++ // eslint-disable-next-line max-lines-per-function+ private _initInterceptorCellContent() {+ this.disposeWithMe(+ this._sheetInterceptorService.intercept(INTERCEPTOR_POINT.CELL_CONTENT, {+ priority: 100,+ effect: InterceptorEffectEnum.Value,+ // eslint-disable-next-line max-lines-per-function+ handler: (cell, location, next) => {+ const { unitId, subUnitId, row, col } = location;+ const unitImageFormulaData = this._formulaDataModel.getUnitImageFormulaData();+ const imageInfo = unitImageFormulaData?.[unitId]?.[subUnitId]?.getValue(row, col);++ if (!imageInfo) {+ return next(cell);+ }++ const {+ source,+ // altText,+ // sizing,+ height,+ width,+ isErrorImage,+ imageNaturalWidth,+ imageNaturalHeight,+ } = imageInfo;++ // If the image failed to load, return #VALUE! error.+ if (isErrorImage) {+ return next(this._errorValueCell);+ }++ const finalWidth = width || imageNaturalWidth;+ const finalHeight = height || imageNaturalHeight;++ // TODO: @Wpxp123456 - now not support altText and sizing, need to be implemented in the future.++ const docDataModel = createDocumentModelWithStyle('', {});+ const docDrawingParam = {+ unitId,+ subUnitId,+ drawingId: generateRandomId(),+ drawingType: DrawingTypeEnum.DRAWING_IMAGE,+ imageSourceType: ImageSourceType.URL,+ source,+ transform: {+ left: 0,+ top: 0,+ width: finalWidth,+ height: finalHeight,+ },+ docTransform: {+ size: {+ width: finalWidth,+ height: finalHeight,+ },+ positionH: {+ relativeFrom: ObjectRelativeFromH.PAGE,+ posOffset: 0,+ },+ positionV: {+ relativeFrom: ObjectRelativeFromV.PARAGRAPH,+ posOffset: 0,+ },+ angle: 0,+ },+ behindDoc: BooleanNumber.FALSE,+ title: '',+ description: '',+ layoutType: PositionedObjectLayoutType.INLINE, // Insert inline drawing by default.+ wrapText: WrapTextType.BOTH_SIDES,+ distB: 0,+ distL: 0,+ distR: 0,+ distT: 0,+ };+ const jsonXActions = BuildTextUtils.drawing.add({+ documentDataModel: docDataModel,+ drawings: [docDrawingParam],+ selection: {+ collapsed: true,+ startOffset: 0,+ endOffset: 0,+ },+ });++ if (jsonXActions) {+ docDataModel.apply(jsonXActions);+ return next({+ p: docDataModel.getSnapshot(),+ });+ }++ return next(this._errorValueCell);+ },+ })+ );+ }++ private async _getImageNatureSize(imageFormulaInfo: IRuntimeImageFormulaDataType): Promise<IRuntimeImageFormulaDataType> {+ const imageInfo = await this._getImageSize(imageFormulaInfo.source);++ if (!imageInfo.image) {+ return { ...imageFormulaInfo, isErrorImage: true };+ }++ return {+ ...imageFormulaInfo,+ isErrorImage: false,+ imageNaturalHeight: imageInfo.height,+ imageNaturalWidth: imageInfo.width,+ };+ }++ private async _getImageSize(src: string): Promise<Required<{+ width: number;+ height: number;+ image: HTMLImageElement | null;+ }>> {+ return new Promise((resolve) => {+ const image = new Image();+ image.src = src;+ image.onload = () => {+ resolve({+ width: image.width,+ height: image.height,+ image,+ });+ };+ image.onerror = () => {+ resolve({+ width: 0,+ height: 0,+ image: null,+ });+ };+ });+ };++ registerRefreshRenderFunction(refreshRender: () => void) {+ this._refreshRender = refreshRender;+ }+}diff --git a/packages/sheets-formula/src/controllers/update-formula.controller.ts b/packages/sheets-formula/src/controllers/update-formula.controller.tsindex 7f2af4a5e5..e7540ef9d3 100644--- a/packages/sheets-formula/src/controllers/update-formula.controller.ts+++ b/packages/sheets-formula/src/controllers/update-formula.controller.ts@@ -29,10 +29,8 @@ import type {ISetRangeValuesMutationParams,} from '@univerjs/sheets';import type { IUniverSheetsFormulaBaseConfig } from './config.schema';-import type { IFormulaReferenceMoveParam } from './utils/ref-range-formula';import type { IUnitRangeWithOffset } from './utils/ref-range-move';-import {Disposable,ICommandService,@@ -44,7 +42,6 @@ import {Tools,UniverInstanceType,} from '@univerjs/core';-import { deserializeRangeWithSheetWithCache, ErrorType, FormulaDataModel, generateStringWithSequence, IDefinedNamesService, initSheetFormulaData, LexerTreeBuilder, sequenceNodeType, serializeRangeToRefString, SetArrayFormulaDataMutation, SetFormulaCalculationStartMutation, SetFormulaDataMutation } from '@univerjs/engine-formula';import {ClearSelectionFormatCommand,@@ -170,6 +167,9 @@ export class UpdateFormulaController extends Disposable {this._formulaDataModel.updateArrayFormulaCellData(unitId, sheetId, cellValue);this._formulaDataModel.updateArrayFormulaRange(unitId, sheetId, cellValue);+ // update image formula data+ this._formulaDataModel.updateImageFormulaData(unitId, sheetId, cellValue);+// TODO@Dushusir: When the amount of data is large, the communication overhead is high. The main thread and the worker update their own models to reduce the communication overhead.this._commandService.executeCommand(SetFormulaDataMutation.id,diff --git a/packages/sheets-formula/src/index.ts b/packages/sheets-formula/src/index.tsindex e3fabcceee..2312cde62c 100644--- a/packages/sheets-formula/src/index.ts+++ b/packages/sheets-formula/src/index.ts@@ -19,6 +19,7 @@ export { QuickSumCommand } from './commands/commands/quick-sum.command';export { OtherFormulaMarkDirty } from './commands/mutations/formula.mutation';export { CalculationMode, PLUGIN_CONFIG_KEY_BASE } from './controllers/config.schema';export type { IUniverSheetsFormulaBaseConfig, IUniverSheetsFormulaRemoteConfig } from './controllers/config.schema';+export { ImageFormulaCellInterceptorController } from './controllers/image-formula-cell-interceptor.controller';export { TriggerCalculationController } from './controllers/trigger-calculation.controller';export { UpdateDefinedNameController } from './controllers/update-defined-name.controller';export { UpdateFormulaController } from './controllers/update-formula.controller';diff --git a/packages/sheets-formula/src/plugin.ts b/packages/sheets-formula/src/plugin.tsindex 46ac884230..7683600b57 100644--- a/packages/sheets-formula/src/plugin.ts+++ b/packages/sheets-formula/src/plugin.ts@@ -31,6 +31,7 @@ import {} from './controllers/config.schema';import { DefinedNameController } from './controllers/defined-name.controller';import { FormulaController } from './controllers/formula.controller';+import { ImageFormulaCellInterceptorController } from './controllers/image-formula-cell-interceptor.controller';import { SuperTableController } from './controllers/super-table.controller';import { TriggerCalculationController } from './controllers/trigger-calculation.controller';import { UpdateDefinedNameController } from './controllers/update-defined-name.controller';@@ -101,6 +102,7 @@ export class UniverSheetsFormulaPlugin extends Plugin {[FormulaRefRangeService],[RegisterOtherFormulaService],[ArrayFormulaCellInterceptorController],+ [ImageFormulaCellInterceptorController],[TriggerCalculationController],[UpdateFormulaController],[ActiveDirtyController],@@ -126,6 +128,7 @@ export class UniverSheetsFormulaPlugin extends Plugin {[FormulaController],[ActiveDirtyController],[ArrayFormulaCellInterceptorController],+ [ImageFormulaCellInterceptorController],[UpdateFormulaController],[UpdateDefinedNameController],]);diff --git a/packages/sheets-formula/src/services/function-list/lookup.ts b/packages/sheets-formula/src/services/function-list/lookup.tsindex 44554a350c..57dbfd6af5 100644--- a/packages/sheets-formula/src/services/function-list/lookup.ts+++ b/packages/sheets-formula/src/services/function-list/lookup.ts@@ -411,17 +411,38 @@ export const FUNCTION_LIST_LOOKUP: IFunctionInfo[] = [abstract: 'formula.functionList.IMAGE.abstract',functionParameter: [{- name: 'formula.functionList.IMAGE.functionParameter.number1.name',- detail: 'formula.functionList.IMAGE.functionParameter.number1.detail',- example: 'A1:A20',+ name: 'formula.functionList.IMAGE.functionParameter.source.name',+ detail: 'formula.functionList.IMAGE.functionParameter.source.detail',+ example: '"https://github.com/dream-num.png"',require: 1,repeat: 0,},{- name: 'formula.functionList.IMAGE.functionParameter.number2.name',- detail: 'formula.functionList.IMAGE.functionParameter.number2.detail',- example: 'A1:A20',- require: 1,+ name: 'formula.functionList.IMAGE.functionParameter.altText.name',+ detail: 'formula.functionList.IMAGE.functionParameter.altText.detail',+ example: '"Univer Logo"',+ require: 0,+ repeat: 0,+ },+ {+ name: 'formula.functionList.IMAGE.functionParameter.sizing.name',+ detail: 'formula.functionList.IMAGE.functionParameter.sizing.detail',+ example: '3',+ require: 0,+ repeat: 0,+ },+ {+ name: 'formula.functionList.IMAGE.functionParameter.height.name',+ detail: 'formula.functionList.IMAGE.functionParameter.height.detail',+ example: '100',+ require: 0,+ repeat: 0,+ },+ {+ name: 'formula.functionList.IMAGE.functionParameter.width.name',+ detail: 'formula.functionList.IMAGE.functionParameter.width.detail',+ example: '100',+ require: 0,repeat: 0,},],diff --git a/packages/sheets/src/facade/f-worksheet.ts b/packages/sheets/src/facade/f-worksheet.tsindex 754bfb2804..997344d65f 100644--- a/packages/sheets/src/facade/f-worksheet.ts+++ b/packages/sheets/src/facade/f-worksheet.ts@@ -2261,7 +2261,7 @@ export class FWorksheet extends FBaseInitialable {/*** Returns a Range corresponding to the dimensions in which data is present.- * This is functionally equivalent to creating a Range bounded by A1 and (Sheet.getLastColumns(), Sheet.getLastRows()).+ * This is functionally equivalent to creating a Range bounded by A1 and (Sheet.getLastColumn(), Sheet.getLastRow()).* @returns {FRange} The range of the data in the sheet.* @example* ```ts@@ -2274,9 +2274,8 @@ export class FWorksheet extends FBaseInitialable {* ```*/getDataRange(): FRange {- const lastRow = this.getLastRows();- const lastColumn = this.getLastColumns();- return this.getRange(0, 0, lastRow + 1, lastColumn + 1);+ const { startRow, endRow, startColumn, endColumn } = this._worksheet.getDataRealRange();+ return this.getRange(startRow, startColumn, endRow - startRow + 1, endColumn - startColumn + 1);}/**