Build your own AI office with Univer Office SDK. Bring editing, calculation, collaboration, and file processing into your product for people and AI agents. Built on an extensible open-source core.
TypeScript boardcollaborationdocdocxexceloffce365officepdfpptpptxpresentationsdksheetslidesspreadsheetuniverwordwordprocessorworkspacexlsx
fix(formula): formula carries numfmt of ref cell (#2756)
Dushusir30b3b24d356e
diff --git a/packages/engine-formula/src/engine/reference-object/base-reference-object.ts b/packages/engine-formula/src/engine/reference-object/base-reference-object.tsindex 334a98dab1..d50e9e24e4 100644--- a/packages/engine-formula/src/engine/reference-object/base-reference-object.ts+++ b/packages/engine-formula/src/engine/reference-object/base-reference-object.ts@@ -398,7 +398,8 @@ export class BaseReferenceObject extends ObjectClassType {}if (cell.t === CellValueType.NUMBER) {- return createNumberValueObjectByRawValue(value);+ const pattern = this._getPatternByCell(cell);+ return createNumberValueObjectByRawValue(value, pattern);}if (cell.t === CellValueType.STRING || cell.t === CellValueType.FORCE_STRING) {// A1 is `"test"`, =A1 also needs to get `"test"`@@ -411,6 +412,15 @@ export class BaseReferenceObject extends ObjectClassType {return ValueObjectFactory.create(value);}+ private _getPatternByCell(cell: ICellData) {+ const styles = this._unitStylesData[this.getUnitId()];++ if (!styles) return '';++ const style = styles.getStyleByCell(cell);+ return style?.n?.pattern || '';+ }+getCellByRow(row: number) {return this.getCellByPosition(row);}diff --git a/packages/engine-formula/src/engine/utils/numfmt-kit.ts b/packages/engine-formula/src/engine/utils/numfmt-kit.tsindex f5ccc46654..7d47a3bcd3 100644--- a/packages/engine-formula/src/engine/utils/numfmt-kit.ts+++ b/packages/engine-formula/src/engine/utils/numfmt-kit.ts@@ -119,7 +119,10 @@ export function handleNumfmtInCell(oldCell: Nullable<ICellData>, cell: Nullable<return cell;}- const newPattern = compareNumfmtPriority(oldPattern, pattern);+ // The number format calculated by the formula, if the current cell already has a number format, the original format is used, if not, a new one is set.+ // Why?+ // Due to the forced calculation mechanism during initialization, if the formula may overwrite the original number format, the number format set for the formula cell may never take effect.+ const newPattern = oldPattern || pattern;cellStyle!.n!.pattern = newPattern;diff --git a/packages/engine-formula/src/engine/value-object/primitive-object.ts b/packages/engine-formula/src/engine/value-object/primitive-object.tsindex ed914c80f2..07b45584bb 100644--- a/packages/engine-formula/src/engine/value-object/primitive-object.ts+++ b/packages/engine-formula/src/engine/value-object/primitive-object.ts@@ -1453,20 +1453,20 @@ export function createStringValueObjectByRawValue(rawValue: string | number | boreturn StringValueObject.create(value);}-export function createNumberValueObjectByRawValue(rawValue: string | number | boolean) {+export function createNumberValueObjectByRawValue(rawValue: string | number | boolean, pattern: string = '') {if (typeof rawValue === 'boolean') {let result = 0;if (rawValue) {result = 1;}- return NumberValueObject.create(result);+ return NumberValueObject.create(result, pattern);} else if (typeof rawValue === 'number') {if (!Number.isFinite(rawValue)) {return ErrorValueObject.create(ErrorType.NUM);}- return NumberValueObject.create(rawValue);+ return NumberValueObject.create(rawValue, pattern);} else if (isRealNum(rawValue)) {- return NumberValueObject.create(Number(rawValue));+ return NumberValueObject.create(Number(rawValue), pattern);}return ErrorValueObject.create(ErrorType.VALUE);}diff --git a/packages/sheets-formula/src/controllers/formula-editor-show.controller.ts b/packages/sheets-formula/src/controllers/formula-editor-show.controller.tsindex 02960148cc..db1a7d31a1 100644--- a/packages/sheets-formula/src/controllers/formula-editor-show.controller.ts+++ b/packages/sheets-formula/src/controllers/formula-editor-show.controller.ts@@ -117,7 +117,8 @@ export class FormulaEditorShowController extends Disposable implements IRenderMo*/const matrixRange = arrayFormulaMatrixRange?.[unitId]?.[subUnitId];if (matrixRange != null) {- this._displayArrayFormulaRangeShape(matrixRange, row, col, unitId, subUnitId, worksheet, cellInfo);+ // For cells other than the upper left corner, the cellInfo information will be updated+ cellInfo = this._displayArrayFormulaRangeShape(matrixRange, row, col, unitId, subUnitId, worksheet, cellInfo);}if (cellInfo) {@@ -200,6 +201,8 @@ export class FormulaEditorShowController extends Disposable implements IRenderMoreturn false;}});++ return cellInfo;}private _createArrayFormulaRangeShape(arrayRange: IRange, unitId: string) {diff --git a/packages/sheets-formula/src/views/prompt/help-function/HelpFunction.tsx b/packages/sheets-formula/src/views/prompt/help-function/HelpFunction.tsxindex c2c6238c44..723075afd8 100644--- a/packages/sheets-formula/src/views/prompt/help-function/HelpFunction.tsx+++ b/packages/sheets-formula/src/views/prompt/help-function/HelpFunction.tsx@@ -18,13 +18,16 @@ import { IUniverInstanceService, LocaleService } from '@univerjs/core';import { Popup } from '@univerjs/design';import type { IFunctionInfo, IFunctionParam } from '@univerjs/engine-formula';import { CloseSingle, DetailsSingle, MoreSingle } from '@univerjs/icons';-import { useDependency } from '@wendellhu/redi/react-bindings';+import { useDependency, useInjector } from '@wendellhu/redi/react-bindings';import React, { useEffect, useState } from 'react';-import { IEditorService } from '@univerjs/ui';+import { IEditorService, ISidebarService } from '@univerjs/ui';+import { ITextSelectionRenderManager } from '@univerjs/engine-render';+import { throttleTime } from 'rxjs';import type { IHelpFunctionOperationParams } from '../../../services/prompt.service';import { IFormulaPromptService } from '../../../services/prompt.service';import { generateParam } from '../../../services/utils';+import { useResizeScrollObserver } from '../resize-scroll-observer';import styles from './index.module.less';export function HelpFunction() {@@ -42,6 +45,11 @@ export function HelpFunction() {const univerInstanceService = useDependency(IUniverInstanceService);const editorService = useDependency(IEditorService);+ const sidebarService = useDependency(ISidebarService);+ const injector = useInjector();++ // window resize/scroll, update HelpFunction position+ useResizeScrollObserver(updatePosition);useEffect(() => {const subscription = promptService.help$.subscribe((params: IHelpFunctionOperationParams) => {@@ -70,11 +78,29 @@ export function HelpFunction() {setVisible(visible);});+ const sidebarSubscription = sidebarService.scrollEvent$.pipe(throttleTime(100)).subscribe(updatePosition);+return () => {subscription?.unsubscribe();+ sidebarSubscription.unsubscribe();};}, []);+ function updatePosition() {+ if (!helpVisible) {+ return;+ }++ const position = getPosition();++ if (position == null) {+ return;+ }++ const { left, top, height } = position;+ setOffset([left, top + height]);+ }+function getPosition() {const documentDataModel = univerInstanceService.getCurrentUniverDocInstance()!;@@ -95,7 +121,9 @@ export function HelpFunction() {function handleClose() {setHelpVisible(!helpVisible);- // TODO focus editor+ // focus editor+ const textSelectionRenderManager = injector.get(ITextSelectionRenderManager);+ textSelectionRenderManager.focus();}return (diff --git a/packages/sheets-formula/src/views/prompt/resize-scroll-observer.ts b/packages/sheets-formula/src/views/prompt/resize-scroll-observer.tsnew file mode 100644index 0000000000..b299d2b98b--- /dev/null+++ b/packages/sheets-formula/src/views/prompt/resize-scroll-observer.ts@@ -0,0 +1,47 @@+/**+ * Copyright 2023-present DreamNum Inc.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import { useEffect } from 'react';++type Callback = () => void;++export const useResizeScrollObserver = (callback: Callback, delay: number = 100): void => {+ useEffect(() => {+ let throttleTimeout: number | null = null;++ const throttledCallback = () => {+ if (throttleTimeout === null) {+ throttleTimeout = window.setTimeout(() => {+ callback();+ throttleTimeout = null;+ }, delay);+ }+ };++ window.addEventListener('scroll', throttledCallback);+ window.addEventListener('resize', throttledCallback);++ return () => {+ if (throttleTimeout !== null) {+ clearTimeout(throttleTimeout);+ }+ window.removeEventListener('scroll', throttledCallback);+ window.removeEventListener('resize', throttledCallback);+ };+ }, [callback, delay]);+};++export default useResizeScrollObserver;diff --git a/packages/ui/src/components/editor/TextEditor.tsx b/packages/ui/src/components/editor/TextEditor.tsxindex c2855d751f..4eb3a59e5f 100644--- a/packages/ui/src/components/editor/TextEditor.tsx+++ b/packages/ui/src/components/editor/TextEditor.tsx@@ -18,7 +18,6 @@ import type { IDocumentData, Nullable } from '@univerjs/core';import { debounce, isInternalEditorID, LocaleService } from '@univerjs/core';import { useDependency } from '@wendellhu/redi/react-bindings';import React, { useEffect, useRef, useState } from 'react';-import { Popup } from '@univerjs/design';import type { Editor, IEditorCanvasStyle } from '../../services/editor/editor.service';import { IEditorService } from '../../services/editor/editor.service';import { isElementVisible } from '../../utils/util';@@ -307,11 +306,13 @@ export function TextEditor(props: ITextEditorProps & Omit<MyComponentProps, 'onCreturn (<><div {...propsNew} className={className + borderStyle} ref={editorRef}>+ <div style={{ display: validationVisible ? 'none' : 'block' }} className={styles.textEditorValidationError}>{validationContent}</div><div style={{ display: hasValue() ? 'none' : 'unset' }} className={styles.textEditorContainerPlaceholder}>{placeholderValue}</div></div>- <Popup visible={!validationVisible} offset={validationOffset}>+ {/* Don't delete it yet, test the stability without popup */}+ {/* <Popup visible={!validationVisible} offset={validationOffset}><div className={styles.textEditorValidationError}>{validationContent}</div>- </Popup>+ </Popup> */}</>);}diff --git a/packages/ui/src/components/editor/index.module.less b/packages/ui/src/components/editor/index.module.lessindex f139dcd815..3440f16518 100644--- a/packages/ui/src/components/editor/index.module.less+++ b/packages/ui/src/components/editor/index.module.less@@ -57,7 +57,8 @@// background: rgb(var(--red-50));// border-radius: var(--border-radius-base);// padding: 2px 3px;-+ position: absolute;+ top: -16px;font-size: @font-size-xxxs;color: rgb(var(--red-400));}