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(editor): editor modifications to accommodate the range selector (#1460)
Univer22b2734a2a5b
diff --git a/examples/src/docs/main.ts b/examples/src/docs/main.tsindex ccd14ee0c7..e073375c61 100644--- a/examples/src/docs/main.ts+++ b/examples/src/docs/main.ts@@ -22,6 +22,7 @@ import { UniverDocsUIPlugin } from '@univerjs/docs-ui';import { UniverRenderEnginePlugin } from '@univerjs/engine-render';import { UniverUIPlugin } from '@univerjs/ui';+import { UniverFormulaEnginePlugin } from '@univerjs/engine-formula';import { DEFAULT_DOCUMENT_DATA_CN } from '../data';import { DebuggerPlugin } from '../plugins/debugger';import { locales } from './locales';@@ -44,6 +45,7 @@ const univer = new Univer({// core pluginsuniver.registerPlugin(UniverRenderEnginePlugin);+univer.registerPlugin(UniverFormulaEnginePlugin);univer.registerPlugin(DebuggerPlugin);univer.registerPlugin(UniverUIPlugin, {container: 'app',diff --git a/examples/src/plugins/debugger/views/test-editor/TestTextEditor.tsx b/examples/src/plugins/debugger/views/test-editor/TestTextEditor.tsxindex b0791340b4..0c62a3fa05 100644--- a/examples/src/plugins/debugger/views/test-editor/TestTextEditor.tsx+++ b/examples/src/plugins/debugger/views/test-editor/TestTextEditor.tsx@@ -27,10 +27,7 @@ const containerStyle: React.CSSProperties = {};const editorStyle: React.CSSProperties = {- position: 'relative',width: '100%',- height: '40px',- border: '1px solid #000',};/**@@ -42,13 +39,13 @@ export const TestEditorContainer = () => {<divstyle={containerStyle}>- <TextEditor id="test-editor-1" style={editorStyle} canvasStyle={{ fontSize: 10 }} value="I found one cent on the roadside." />+ <TextEditor id="test-editor-1" isReadonly={true} style={editorStyle} canvasStyle={{ fontSize: 10 }} value="I found one cent on the roadside." /><br></br>- <TextEditor id="test-editor-2" style={editorStyle} canvasStyle={{ fontSize: 12 }} />+ <TextEditor id="test-editor-2" onlyInputFormula={true} style={editorStyle} canvasStyle={{ fontSize: 10 }} /><br></br>- <TextEditor id="test-editor-3" style={editorStyle} canvasStyle={{ fontSize: 14 }} />+ <TextEditor id="test-editor-3" onlyInputRange={true} style={editorStyle} canvasStyle={{ fontSize: 10 }} /><br></br>- <TextEditor id="test-editor-4" style={editorStyle} canvasStyle={{ fontSize: 18 }} />+ <TextEditor id="test-editor-4" isSingle={false} onlyInputContent={true} style={{ ...editorStyle, height: '140px' }} canvasStyle={{ fontSize: 14 }} /></div>);};diff --git a/packages/core/src/services/context/context.ts b/packages/core/src/services/context/context.tsindex fdaa6809fc..e2c53bf29a 100644--- a/packages/core/src/services/context/context.ts+++ b/packages/core/src/services/context/context.ts@@ -26,3 +26,5 @@ export const FOCUSING_EDITOR_INPUT_FORMULA = 'FOCUSING_EDITOR_INPUT_FORMULA';export const FOCUSING_FORMULA_EDITOR = 'FOCUSING_FORMULA_EDITOR';export const FOCUSING_UNIVER_EDITOR = 'FOCUSING_UNIVER_EDITOR';++export const FOCUSING_UNIVER_EDITOR_SINGLE_MODE = 'FOCUSING_UNIVER_EDITOR_SINGLE_MODE';diff --git a/packages/core/src/shared/debounce.ts b/packages/core/src/shared/debounce.tsnew file mode 100644index 0000000000..33deec81a0--- /dev/null+++ b/packages/core/src/shared/debounce.ts@@ -0,0 +1,33 @@+/**+ * 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.+ */++type debounceFn<T extends (...args: any[]) => any> = (this: ThisParameterType<T>, ...args: Parameters<T>) => void;++export function debounce<T extends (...args: any[]) => any>(func: T, wait: number): debounceFn<T> {+ let timeout: NodeJS.Timeout | null;++ return function (this: ThisParameterType<T>, ...args: Parameters<T>) {+ const context = this;++ const later = function () {+ timeout = null;+ func.apply(context, args);+ };++ clearTimeout(timeout as NodeJS.Timeout);+ timeout = setTimeout(later, wait);+ };+}diff --git a/packages/core/src/shared/index.ts b/packages/core/src/shared/index.tsindex 9477163716..aa82ff4e57 100644--- a/packages/core/src/shared/index.ts+++ b/packages/core/src/shared/index.ts@@ -36,3 +36,4 @@ export * from './sequence';export * from './sort-rules';export * from './tools';export * from './types';+export * from './debounce';diff --git a/packages/docs-ui/src/controllers/doc-editor-bridge.controller.ts b/packages/docs-ui/src/controllers/doc-editor-bridge.controller.tsindex c4e27e605e..5498c29ca0 100644--- a/packages/docs-ui/src/controllers/doc-editor-bridge.controller.ts+++ b/packages/docs-ui/src/controllers/doc-editor-bridge.controller.ts@@ -40,9 +40,11 @@ export class DocEditorBridgeController extends Disposable {}private _initialize() {- this._editorService.resize$.subscribe((unitId: string) => {- this._resize(unitId);- });+ this.disposeWithMe(+ this._editorService.resize$.subscribe((unitId: string) => {+ this._resize(unitId);+ })+ );this._editorService.getAllEditor().forEach((editor) => {const unitId = editor.editorUnitId;@@ -60,6 +62,8 @@ export class DocEditorBridgeController extends Disposable {this._initialBlur();this._initialFocus();++ this._initialValueChange();}private _resize(unitId: Nullable<string>) {@@ -108,7 +112,7 @@ export class DocEditorBridgeController extends Disposable {mainComponent?.resize(contentWidth, contentHeight);- if (editor.isSingle === false) {+ if (!editor.isSingle()) {if (actualHeight > height) {if (scrollBar == null) {viewportMain && new ScrollBar(viewportMain, { enableHorizontal: false, barSize: 8 });@@ -136,28 +140,64 @@ export class DocEditorBridgeController extends Disposable {}private _initialSetValue() {- this._editorService.setValue$.subscribe((param) => {- this._commandService.executeCommand(CoverContentCommand.id, {- unitId: param.editorUnitId,- body: param.body,- segmentId: null,- });- });+ this.disposeWithMe(+ this._editorService.setValue$.subscribe((param) => {+ this._commandService.executeCommand(CoverContentCommand.id, {+ unitId: param.editorUnitId,+ body: param.body,+ segmentId: null,+ });+ })+ );}private _initialBlur() {- this._editorService.blur$.subscribe(() => {- this._textSelectionRenderManager.removeAllTextRanges();+ this.disposeWithMe(+ this._editorService.blur$.subscribe(() => {+ this._textSelectionRenderManager.removeAllTextRanges();- this._textSelectionRenderManager.blur();- });+ this._textSelectionRenderManager.blur();+ })+ );}private _initialFocus() {- this._editorService.focus$.subscribe((textRange) => {- this._textSelectionRenderManager.removeAllTextRanges();- this._textSelectionRenderManager.addTextRanges([textRange]);- });+ this.disposeWithMe(+ this._editorService.focus$.subscribe((textRange) => {+ this._textSelectionRenderManager.removeAllTextRanges();+ this._textSelectionRenderManager.addTextRanges([textRange]);+ })+ );+ }++ private _initialValueChange() {+ this.disposeWithMe(+ this._textSelectionRenderManager.onCompositionupdate$.subscribe(this._valueChange.bind(this))+ );+ this.disposeWithMe(+ this._textSelectionRenderManager.onInput$.subscribe(this._valueChange.bind(this))+ );+ this.disposeWithMe(+ this._textSelectionRenderManager.onKeydown$.subscribe(this._valueChange.bind(this))+ );+ this.disposeWithMe(+ this._textSelectionRenderManager.onPaste$.subscribe(this._valueChange.bind(this))+ );+ }++ private _valueChange() {+ const unitId = this._currentUniverService.getCurrentUniverDocInstance().getUnitId();+ if (unitId == null) {+ return;+ }++ const editor = this._editorService.getEditor(unitId);++ if (editor == null || editor.isSheetEditor()) {+ return;+ }++ this._editorService.refreshValueChange(unitId);}/**@@ -177,6 +217,8 @@ export class DocEditorBridgeController extends Disposable {}this._resize(unitId);++ this._valueChange();}}));diff --git a/packages/docs/src/controllers/text-selection.controller.ts b/packages/docs-ui/src/controllers/text-selection.controller.tssimilarity index 81%rename from packages/docs/src/controllers/text-selection.controller.tsrename to packages/docs-ui/src/controllers/text-selection.controller.tsindex 4b5e38882d..312a290e87 100644--- a/packages/docs/src/controllers/text-selection.controller.ts+++ b/packages/docs-ui/src/controllers/text-selection.controller.ts@@ -20,11 +20,9 @@ import type { Documents, IMouseEvent, IPointerEvent, RenderComponentType } fromimport { CURSOR_TYPE, IRenderManagerService, ITextSelectionRenderManager } from '@univerjs/engine-render';import { Inject } from '@wendellhu/redi';-import { getDocObjectById } from '../basics/component-tools';-import type { ISetDocZoomRatioOperationParams } from '../commands/operations/set-doc-zoom-ratio.operation';-import { SetDocZoomRatioOperation } from '../commands/operations/set-doc-zoom-ratio.operation';-import { DocSkeletonManagerService } from '../services/doc-skeleton-manager.service';-import { TextSelectionManagerService } from '../services/text-selection-manager.service';+import { IEditorService } from '@univerjs/ui';+import type { ISetDocZoomRatioOperationParams } from '@univerjs/docs';+import { DocSkeletonManagerService, getDocObjectById, SetDocZoomRatioOperation, TextSelectionManagerService } from '@univerjs/docs';@OnLifecycle(LifecycleStages.Rendered, TextSelectionController)export class TextSelectionController extends Disposable {@@ -37,7 +35,8 @@ export class TextSelectionController extends Disposable {@IRenderManagerService private readonly _renderManagerService: IRenderManagerService,@ITextSelectionRenderManagerprivate readonly _textSelectionRenderManager: ITextSelectionRenderManager,- @Inject(TextSelectionManagerService) private readonly _textSelectionManagerService: TextSelectionManagerService+ @Inject(TextSelectionManagerService) private readonly _textSelectionManagerService: TextSelectionManagerService,+ @IEditorService private readonly _editorService: IEditorService) {super();@@ -92,6 +91,9 @@ export class TextSelectionController extends Disposable {this.disposeWithMe(toDisposable(document.onPointerEnterObserver.add(() => {+ if (this._isEditorReadOnly(unitId)) {+ return;+ }document.cursor = CURSOR_TYPE.TEXT;}))@@ -109,6 +111,10 @@ export class TextSelectionController extends Disposable {this.disposeWithMe(toDisposable(document?.onPointerDownObserver.add((evt: IPointerEvent | IMouseEvent, state) => {+ if (this._isEditorReadOnly(unitId)) {+ return;+ }+const currentDocInstance = this._currentUniverService.getCurrentUniverDocInstance();if (currentDocInstance.getUnitId() !== unitId) {@@ -117,6 +123,8 @@ export class TextSelectionController extends Disposable {this._textSelectionRenderManager.eventTrigger(evt);+ this._setEditorFocus(unitId);+if (evt.button !== 2) {state.stopPropagation();}@@ -141,6 +149,28 @@ export class TextSelectionController extends Disposable {);}+ private _isEditorReadOnly(unitId: string) {+ const editor = this._editorService.getEditor(unitId);+ if (!editor) {+ return false;+ }++ return editor.isReadOnly();+ }++ private _setEditorFocus(unitId: string) {+ /**+ * The object for selecting data in the editor is set to the current sheet.+ */+ const sheetInstances = this._currentUniverService.getAllUniverSheetsInstance();+ if (sheetInstances.length > 0) {+ const workbook = this._currentUniverService.getCurrentUniverSheetInstance();+ this._editorService.setOperationSheetUnitId(workbook.getUnitId());+ // this._editorService.setOperationSheetSubUnitId(workbook.getActiveSheet().getSheetId());+ }+ this._editorService.focusStyle(unitId);+ }+private _commandExecutedListener() {const updateCommandList = [SetDocZoomRatioOperation.id];diff --git a/packages/docs-ui/src/docs-ui-plugin.ts b/packages/docs-ui/src/docs-ui-plugin.tsindex faca1acf2a..b811426aef 100644--- a/packages/docs-ui/src/docs-ui-plugin.ts+++ b/packages/docs-ui/src/docs-ui-plugin.ts@@ -54,6 +54,7 @@ import { DocCanvasView } from './views/doc-canvas-view';import { FloatingObjectController } from './controllers/floating-object.controller';import { PageRenderController } from './controllers/page-render.controller';import { ZoomController } from './controllers/zoom.controller';+import { TextSelectionController } from './controllers/text-selection.controller';import { BackScrollController } from './controllers/back-scroll.controller';export class UniverDocsUIPlugin extends Plugin {@@ -112,6 +113,7 @@ export class UniverDocsUIPlugin extends Plugin {[FloatingObjectController],[PageRenderController],[ZoomController],+ [TextSelectionController],[BackScrollController],[// controllersdiff --git a/packages/docs-ui/src/shortcuts/core-editing.shortcut.ts b/packages/docs-ui/src/shortcuts/core-editing.shortcut.tsindex 13920ae2a2..0ff0be2ea1 100644--- a/packages/docs-ui/src/shortcuts/core-editing.shortcut.ts+++ b/packages/docs-ui/src/shortcuts/core-editing.shortcut.ts@@ -18,11 +18,11 @@ import type { IShortcutItem } from '@univerjs/ui';import { KeyCode } from '@univerjs/ui';import { BreakLineCommand, DeleteLeftCommand, DeleteRightCommand } from '@univerjs/docs';-import { whenDocAndEditorFocused } from './utils';+import { whenDocAndEditorFocused, whenDocAndEditorFocusedWithBreakLine } from './utils';export const BreakLineShortcut: IShortcutItem = {id: BreakLineCommand.id,- preconditions: whenDocAndEditorFocused,+ preconditions: whenDocAndEditorFocusedWithBreakLine,binding: KeyCode.ENTER,};diff --git a/packages/docs-ui/src/shortcuts/utils.ts b/packages/docs-ui/src/shortcuts/utils.tsindex b033863a81..5f467553fb 100644--- a/packages/docs-ui/src/shortcuts/utils.ts+++ b/packages/docs-ui/src/shortcuts/utils.ts@@ -15,8 +15,12 @@*/import type { IContextService } from '@univerjs/core';-import { FOCUSING_DOC, FOCUSING_UNIVER_EDITOR } from '@univerjs/core';+import { FOCUSING_DOC, FOCUSING_UNIVER_EDITOR, FOCUSING_UNIVER_EDITOR_SINGLE_MODE } from '@univerjs/core';export function whenDocAndEditorFocused(contextService: IContextService): boolean {return contextService.getContextValue(FOCUSING_DOC) && contextService.getContextValue(FOCUSING_UNIVER_EDITOR);}++export function whenDocAndEditorFocusedWithBreakLine(contextService: IContextService): boolean {+ return contextService.getContextValue(FOCUSING_DOC) && contextService.getContextValue(FOCUSING_UNIVER_EDITOR) && !contextService.getContextValue(FOCUSING_UNIVER_EDITOR_SINGLE_MODE);+}diff --git a/packages/docs/src/doc-plugin.ts b/packages/docs/src/doc-plugin.tsindex 2088195692..1c5e13c3ed 100644--- a/packages/docs/src/doc-plugin.ts+++ b/packages/docs/src/doc-plugin.ts@@ -54,7 +54,6 @@ import { IMEInputController } from './controllers/ime-input.controller';import { InlineFormatController } from './controllers/inline-format.controller';import { MoveCursorController } from './controllers/move-cursor.controller';import { NormalInputController } from './controllers/normal-input.controller';-import { TextSelectionController } from './controllers/text-selection.controller';import { DocSkeletonManagerService } from './services/doc-skeleton-manager.service';import { DocViewModelManagerService } from './services/doc-view-model-manager.service';import { IMEInputManagerService } from './services/ime-input-manager.service';@@ -154,7 +153,6 @@ export class UniverDocsPlugin extends Plugin {[TextSelectionManagerService],// controllers- [TextSelectionController],[NormalInputController],[IMEInputController],[InlineFormatController],diff --git a/packages/docs/src/index.ts b/packages/docs/src/index.tsindex ceb0d5d151..7cb94a4558 100644--- a/packages/docs/src/index.ts+++ b/packages/docs/src/index.ts@@ -15,7 +15,7 @@*/export type { IDocObjectParam } from './basics/component-tools';-export { getDocObject } from './basics/component-tools';+export { getDocObject, getDocObjectById } from './basics/component-tools';export * from './basics/docs-view-key';export { BreakLineCommand } from './commands/commands/break-line.command';export {@@ -60,5 +60,5 @@ export { DocStateChangeManagerService, type IDocStateChangeParams } from './servexport { IMEInputManagerService } from './services/ime-input-manager.service';export { SelectAllOperation } from './commands/operations/select-all.operation';export { CutContentCommand, InnerPasteCommand } from './commands/commands/clipboard.inner.command';-export { SetDocZoomRatioOperation } from './commands/operations/set-doc-zoom-ratio.operation';+export { SetDocZoomRatioOperation, type ISetDocZoomRatioOperationParams } from './commands/operations/set-doc-zoom-ratio.operation';export { SetDocZoomRatioCommand } from './commands/commands/set-doc-zoom-ratio.command';diff --git a/packages/engine-formula/src/basics/__tests__/regex.spec.ts b/packages/engine-formula/src/basics/__tests__/regex.spec.tsnew file mode 100644index 0000000000..722f3ea904--- /dev/null+++ b/packages/engine-formula/src/basics/__tests__/regex.spec.ts@@ -0,0 +1,60 @@+/**+ * 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 { describe, expect, it } from 'vitest';+import { REFERENCE_MULTIPLE_RANGE_REGEX, REFERENCE_REGEX_COLUMN, REFERENCE_REGEX_ROW, REFERENCE_SINGLE_RANGE_REGEX, REFERENCE_TABLE_MULTIPLE_COLUMN_REGEX, REFERENCE_TABLE_SINGLE_COLUMN_REGEX } from '../regex';++describe('Test ref regex', () => {+ it('Single range', () => {+ expect(new RegExp(REFERENCE_SINGLE_RANGE_REGEX).test('A1')).toBe(true);+ expect(new RegExp(REFERENCE_SINGLE_RANGE_REGEX).test('Sheet1!A1')).toBe(true);+ expect(new RegExp(REFERENCE_SINGLE_RANGE_REGEX).test('[workbook]Sheet1!A1')).toBe(true);+ expect(new RegExp(REFERENCE_SINGLE_RANGE_REGEX).test('[workbook]\'Sheet-1\'!A1')).toBe(true);+ expect(new RegExp(REFERENCE_SINGLE_RANGE_REGEX).test('\'[workbook]Sheet1\'!A1')).toBe(true);+ });++ it('Multiple range', () => {+ expect(new RegExp(REFERENCE_MULTIPLE_RANGE_REGEX).test('A1:B10')).toBe(true);+ expect(new RegExp(REFERENCE_MULTIPLE_RANGE_REGEX).test('Sheet1!A1:B10')).toBe(true);+ expect(new RegExp(REFERENCE_MULTIPLE_RANGE_REGEX).test('[workbook]Sheet1!A1:B10')).toBe(true);+ expect(new RegExp(REFERENCE_MULTIPLE_RANGE_REGEX).test('[workbook]\'Sheet-1\'!A1:B10')).toBe(true);+ expect(new RegExp(REFERENCE_MULTIPLE_RANGE_REGEX).test('\'[workbook]Sheet1\'!A1:B10')).toBe(true);+ });++ it('Row range', () => {+ expect(new RegExp(REFERENCE_REGEX_ROW).test('1:10')).toBe(true);+ expect(new RegExp(REFERENCE_REGEX_ROW).test('Sheet1!1:10')).toBe(true);+ expect(new RegExp(REFERENCE_REGEX_ROW).test('[workbook]Sheet1!1:10')).toBe(true);+ expect(new RegExp(REFERENCE_REGEX_ROW).test('[workbook]\'Sheet-1\'!1:10')).toBe(true);+ expect(new RegExp(REFERENCE_REGEX_ROW).test('\'[workbook]Sheet1\'!1:10')).toBe(true);+ });++ it('Column range', () => {+ expect(new RegExp(REFERENCE_REGEX_COLUMN).test('A:B')).toBe(true);+ expect(new RegExp(REFERENCE_REGEX_COLUMN).test('Sheet1!A:B')).toBe(true);+ expect(new RegExp(REFERENCE_REGEX_COLUMN).test('[workbook]Sheet1!A:B')).toBe(true);+ expect(new RegExp(REFERENCE_REGEX_COLUMN).test('[workbook]\'Sheet-1\'!A:B')).toBe(true);+ expect(new RegExp(REFERENCE_REGEX_COLUMN).test('\'[workbook]Sheet1\'!A:B')).toBe(true);+ });++ it('Table single range', () => {+ expect(new RegExp(REFERENCE_TABLE_SINGLE_COLUMN_REGEX).test('Table1[[#Title],[#Data],[Column1]]')).toBe(true);+ });++ it('Table multiple range', () => {+ expect(new RegExp(REFERENCE_TABLE_MULTIPLE_COLUMN_REGEX).test('Table1[[#Title],[#Data],[Column1]:[Column10]]')).toBe(true);+ });+});diff --git a/packages/engine-formula/src/basics/regex.ts b/packages/engine-formula/src/basics/regex.tsindex 3f57cc0ae0..783b76988e 100644--- a/packages/engine-formula/src/basics/regex.ts+++ b/packages/engine-formula/src/basics/regex.ts@@ -14,10 +14,13 @@* limitations under the License.*/-import { UNIT_NAME_REGEX } from '../engine/utils/reference';import { prefixToken, suffixToken } from './token';// export const UNIT_NAME_REGEX = '\'?\\[((?![\\/?:"<>|*\\\\]).)*\\]';+// export const UNIT_NAME_REGEX = '\'?\\[((?![\\/?:"<>|*\\\\]).)*?\\]';+// export const UNIT_NAME_REGEX = '\\[((?![\\/?:"<>|*\\\\]).)*?\\]';++export const UNIT_NAME_REGEX = '\\[([^\\[\\]\\/?:"<>|*\\\\]+)\\]'; // '[Book-1.xlsx]Sheet1'!$A$4 gets [Book-1.xlsx] as unitIdexport const SHEET_NAME_REGEX = '((?![\\[\\]\\/?*\\\\]).)*!';@@ -25,19 +28,21 @@ export const ABSOLUTE_SYMBOL = '$';export const RANGE_SYMBOL = '\\s*?:\\s*?';+export const UNIT_NAME_SHEET_NAME_REGEX = `'?(${UNIT_NAME_REGEX})?(${SHEET_NAME_REGEX})?'?`;+export const SIMPLE_SINGLE_RANGE_REGEX = `\\${ABSOLUTE_SYMBOL}?[A-Za-z]+\\${ABSOLUTE_SYMBOL}?[0-9]+`;-export const REFERENCE_MULTIPLE_RANGE_REGEX = `^(${prefixToken.AT})?(${UNIT_NAME_REGEX})?(${SHEET_NAME_REGEX})?${SIMPLE_SINGLE_RANGE_REGEX}${RANGE_SYMBOL}${SIMPLE_SINGLE_RANGE_REGEX}$`;+export const REFERENCE_MULTIPLE_RANGE_REGEX = `^(${prefixToken.AT})?${UNIT_NAME_SHEET_NAME_REGEX}${SIMPLE_SINGLE_RANGE_REGEX}${RANGE_SYMBOL}${SIMPLE_SINGLE_RANGE_REGEX}$`;-export const REFERENCE_SINGLE_RANGE_REGEX = `^(${UNIT_NAME_REGEX})?(${SHEET_NAME_REGEX})?\\s*?${SIMPLE_SINGLE_RANGE_REGEX}(${suffixToken.POUND})?$`;+export const REFERENCE_SINGLE_RANGE_REGEX = `^${UNIT_NAME_SHEET_NAME_REGEX}\\s*?${SIMPLE_SINGLE_RANGE_REGEX}(${suffixToken.POUND})?$`;-export const REFERENCE_REGEX_ROW = `^(${UNIT_NAME_REGEX})?(${SHEET_NAME_REGEX})?\\${ABSOLUTE_SYMBOL}?[0-9]+${RANGE_SYMBOL}\\${ABSOLUTE_SYMBOL}?[0-9]+$`;+export const REFERENCE_REGEX_ROW = `^${UNIT_NAME_SHEET_NAME_REGEX}\\${ABSOLUTE_SYMBOL}?[0-9]+${RANGE_SYMBOL}\\${ABSOLUTE_SYMBOL}?[0-9]+$`;-export const REFERENCE_REGEX_COLUMN = `^(${UNIT_NAME_REGEX})?(${SHEET_NAME_REGEX})?\\${ABSOLUTE_SYMBOL}?[A-Za-z]+${RANGE_SYMBOL}\\${ABSOLUTE_SYMBOL}?[A-Za-z]+$`;+export const REFERENCE_REGEX_COLUMN = `^${UNIT_NAME_SHEET_NAME_REGEX}\\${ABSOLUTE_SYMBOL}?[A-Za-z]+${RANGE_SYMBOL}\\${ABSOLUTE_SYMBOL}?[A-Za-z]+$`;-export const REFERENCE_REGEX_SINGLE_ROW = `^(${UNIT_NAME_REGEX})?(${SHEET_NAME_REGEX})?\\s*?\\${ABSOLUTE_SYMBOL}?[0-9]+$`;+export const REFERENCE_REGEX_SINGLE_ROW = `^${UNIT_NAME_SHEET_NAME_REGEX}\\s*?\\${ABSOLUTE_SYMBOL}?[0-9]+$`;-export const REFERENCE_REGEX_SINGLE_COLUMN = `^(${UNIT_NAME_REGEX})?(${SHEET_NAME_REGEX})?\\s*?\\${ABSOLUTE_SYMBOL}?[A-Za-z]+$`;+export const REFERENCE_REGEX_SINGLE_COLUMN = `^${UNIT_NAME_SHEET_NAME_REGEX}\\s*?\\${ABSOLUTE_SYMBOL}?[A-Za-z]+$`;const TABLE_NAME_REGEX = '((?![~!@#$%^&*()_+<>?:,./;’,。、‘:“《》?~!@#¥%……()【】\\[\\]\\/\\\\]).)+';diff --git a/packages/engine-formula/src/engine/analysis/__tests__/lexer-tree-builder.spec.ts b/packages/engine-formula/src/engine/analysis/__tests__/lexer-tree-builder.spec.tsindex 1c9938df4c..0f6dfaa02d 100644--- a/packages/engine-formula/src/engine/analysis/__tests__/lexer-tree-builder.spec.ts+++ b/packages/engine-formula/src/engine/analysis/__tests__/lexer-tree-builder.spec.ts@@ -149,6 +149,11 @@ describe('lexer nodeMaker test', () => {const node = lexerTreeBuilder.treeBuilder('= ( 2019-09-09 ) ') as LexerNode;expect(JSON.stringify(node.serialize())).toStrictEqual('{"token":"R_1","st":-1,"ed":-1,"children":[" 2019","09","-","09 ","-"]}');});++ it('sheet range', () => {+ const node = lexerTreeBuilder.treeBuilder('=SUM(SUM(Sheet5:Sheet6!A1:B10) + 100, 1)') as LexerNode;+ expect(JSON.stringify(node.serialize())).toStrictEqual('{"token":"R_1","st":-1,"ed":-1,"children":[{"token":"SUM","st":0,"ed":2,"children":[{"token":"P_1","st":0,"ed":2,"children":[{"token":"SUM","st":4,"ed":6,"children":[{"token":"P_1","st":4,"ed":6,"children":[{"token":":","st":-1,"ed":-1,"children":[{"token":"P_1","st":-1,"ed":-1,"children":[{"token":"Sheet5","st":-1,"ed":-1,"children":[]}]},{"token":"P_1","st":-1,"ed":-1,"children":[{"token":":","st":-1,"ed":-1,"children":[{"token":"P_1","st":-1,"ed":-1,"children":[{"token":"Sheet6!A1","st":-1,"ed":-1,"children":[]}]},{"token":"P_1","st":-1,"ed":-1,"children":[{"token":"B10","st":-1,"ed":-1,"children":[]}]}]}]}]}]}]}," 100"," +"]},{"token":"P_1","st":32,"ed":34,"children":[" 1"]}]}]}');+ });});describe('checkIfAddBracket', () => {@@ -172,4 +177,35 @@ describe('lexer nodeMaker test', () => {expect(lexerTreeBuilder.checkIfAddBracket('=sum(sum(sum(sum(')).toStrictEqual(4);});});++ describe('sequenceNodesBuilder', () => {+ it('workbook ref build', () => {+ expect(lexerTreeBuilder.sequenceNodesBuilder('=[workbook-01]工作表11!G14:M20')).toStrictEqual([+ {+ endIndex: 25,+ nodeType: 4,+ startIndex: 0,+ token: '[workbook-01]工作表11!G14:M20',+ },+ ]);+ });++ it('special workbook ref build', () => {+ expect(lexerTreeBuilder.sequenceNodesBuilder('=\'[workbook-01]工作表11\'!G14:M20,\'[workbook-01]工作表11\'!K27:N32')).toStrictEqual([+ {+ endIndex: 27,+ nodeType: 4,+ startIndex: 0,+ token: "'[workbook-01]工作表11'!G14:M20",+ },+ ',',+ {+ endIndex: 56,+ nodeType: 4,+ startIndex: 29,+ token: "'[workbook-01]工作表11'!K27:N32",+ },+ ]);+ });+ });});diff --git a/packages/engine-formula/src/engine/utils/reference.ts b/packages/engine-formula/src/engine/utils/reference.tsindex 9fecb1f613..8027a98749 100644--- a/packages/engine-formula/src/engine/utils/reference.ts+++ b/packages/engine-formula/src/engine/utils/reference.ts@@ -18,10 +18,7 @@ import type { IRange } from '@univerjs/core';import { AbsoluteRefType, RANGE_TYPE, Tools } from '@univerjs/core';import { includeFormulaLexerToken } from '../../basics/match-token';--// export const UNIT_NAME_REGEX = '\'?\\[((?![\\/?:"<>|*\\\\]).)*?\\]';-// export const UNIT_NAME_REGEX = '\\[((?![\\/?:"<>|*\\\\]).)*?\\]';-export const UNIT_NAME_REGEX = '\\[([^\\[\\]\\/?:"<>|*\\\\]+)\\]'; // '[Book-1.xlsx]Sheet1'!$A$4 gets [Book-1.xlsx] as unitId+import { UNIT_NAME_REGEX } from '../../basics/regex';const $ROW_REGEX = /[^0-9]/g;const $COLUMN_REGEX = /[^A-Za-z]/g;@@ -154,7 +151,6 @@ export function serializeRange(range: IRange): string {* Serialize an `IRange` and a sheetID into a string.* @param sheetName* @param range- * @returns*/export function serializeRangeWithSheet(sheetName: string, range: IRange): string {if (needsQuoting(sheetName)) {@@ -168,7 +164,6 @@ export function serializeRangeWithSheet(sheetName: string, range: IRange): strin* @param unit unitId or unitName* @param sheetName* @param range- * @returns*/export function serializeRangeWithSpreadsheet(unit: string, sheetName: string, range: IRange): string {if (needsQuoting(unit) || needsQuoting(sheetName)) {@@ -273,9 +268,9 @@ export function deserializeRangeWithSheet(refString: string): IGridRangeName {const endColumn = endGrid.column;let rangeType = RANGE_TYPE.NORMAL;- if (isNaN(startRow) && isNaN(endRow)) {+ if (Number.isNaN(startRow) && Number.isNaN(endRow)) {rangeType = RANGE_TYPE.COLUMN;- } else if (isNaN(startColumn) && isNaN(endColumn)) {+ } else if (Number.isNaN(startColumn) && Number.isNaN(endColumn)) {rangeType = RANGE_TYPE.ROW;}diff --git a/packages/engine-formula/src/index.ts b/packages/engine-formula/src/index.tsindex 6f741e3992..822f602d00 100644--- a/packages/engine-formula/src/index.ts+++ b/packages/engine-formula/src/index.ts@@ -34,8 +34,7 @@ export { FunctionType, type IFunctionInfo, type IFunctionParam } from './basics/export { type IFunctionNames } from './basics/function';export { includeFormulaLexerToken, isFormulaLexerToken, normalizeSheetName } from './basics/match-token';export { convertUnitDataToRuntime } from './basics/runtime';-export { matchToken } from './basics/token';-export { compareToken } from './basics/token';+export { matchToken, compareToken, operatorToken } from './basics/token';export { RegisterFunctionMutation } from './commands/mutations/register-function.mutation';export {type ISetArrayFormulaDataMutationParams,@@ -81,7 +80,6 @@ export {serializeRangeToRefString,serializeRangeWithSheet,serializeRangeWithSpreadsheet,- UNIT_NAME_REGEX,} from './engine/utils/reference';export { generateStringWithSequence, type ISequenceNode, sequenceNodeType } from './engine/utils/sequence';export { ArrayValueObject, ValueObjectFactory } from './engine/value-object/array-value-object';@@ -137,3 +135,4 @@ export { FormulaExecuteStageType, type IExecutionInProgressParams } from './servexport { FormulaExecutedStateType, type IAllRuntimeData } from './services/runtime.service';export { SetNumfmtFormulaDataMutation } from './commands/mutations/set-numfmt-formula-data.mutation';export type { ISetNumfmtFormulaDataMutationParams } from './commands/mutations/set-numfmt-formula-data.mutation';+export { isReferenceString } from './basics/regex';diff --git a/packages/engine-formula/src/models/formula-data.model.ts b/packages/engine-formula/src/models/formula-data.model.tsindex 62d3a9085e..8bc4cf1e68 100644--- a/packages/engine-formula/src/models/formula-data.model.ts+++ b/packages/engine-formula/src/models/formula-data.model.ts@@ -275,7 +275,9 @@ export class FormulaDataModel extends Disposable {// load formula data from workbook config dataconst unitFile = this._currentUniverService.getAllUniverSheetsInstance();-+ if (unitFile.length === 0) {+ return;+ }const workbook = this._currentUniverService.getCurrentUniverSheetInstance();const unitId = workbook.getUnitId();this._formulaData[unitId] = {};diff --git a/packages/sheets-formula/src/controllers/prompt.controller.ts b/packages/sheets-formula/src/controllers/prompt.controller.tsindex e1ee991c36..34f0b2aa1d 100644--- a/packages/sheets-formula/src/controllers/prompt.controller.ts+++ b/packages/sheets-formula/src/controllers/prompt.controller.ts@@ -258,22 +258,20 @@ export class PromptController extends Disposable {return;}- if (- (this._editorService.isSheetEditor(params.unitId) && this._editorBridgeService.isVisible().visible === false) ||- this._formulaPromptService.isSelectionMoving()- ) {+ const editor = this._editorService.getEditor(params.unitId);++ if (!editor || editor.onlyInputContent()) {return;}- if (!this._editorService.isEditor(params.unitId)) {+ if (+ (editor.isSheetEditor() && this._editorBridgeService.isVisible().visible === false) ||+ this._formulaPromptService.isSelectionMoving()+ ) {return;}- const currentBody = this._getCurrentBody();-- const dataStream = currentBody?.dataStream || '';-- this._contextSwitch(dataStream);+ this._contextSwitch();this._changeKeepVisibleHideState();@@ -288,6 +286,11 @@ export class PromptController extends Disposable {// if (this._isLockedOnSelectionInsertRefString) {// return;// }++ if (editor.onlyInputRange()) {+ return;+ }+// TODO@Dushusir: use real text infothis._changeFunctionPanelState();})@@ -635,11 +638,13 @@ export class PromptController extends Disposable {return;}- const currentBody = this._getCurrentBody();+ // const currentBody = this._getCurrentBody();- const dataStream = currentBody?.dataStream || '';+ // const dataStream = currentBody?.dataStream || '';- const functionAndParameter = this._lexerTreeBuilder.getFunctionAndParameter(dataStream, startOffset - 1);+ const config = this._getCurrentBodyDataStreamAndOffset();++ const functionAndParameter = this._lexerTreeBuilder.getFunctionAndParameter(config?.dataStream || '', startOffset - 1 + (config?.offset || 0));if (functionAndParameter == null) {this._hideFunctionPanel();@@ -740,15 +745,15 @@ export class PromptController extends Disposable {const { startOffset } = activeRange;- const body = this._getCurrentBody();+ const config = this._getCurrentBodyDataStreamAndOffset();- if (body == null || startOffset == null) {+ if (config == null || startOffset == null) {return;}- const dataStream = body.dataStream;+ const dataStream = config.dataStream;- return dataStream[startOffset - 1];+ return dataStream[startOffset - 1 + config.offset];}/**@@ -770,9 +775,29 @@ export class PromptController extends Disposable {}}- private _getCurrentBody() {+ // private _getCurrentBody() {+ // const documentModel = this._currentUniverService.getCurrentUniverDocInstance();+ // return documentModel?.snapshot?.body;+ // }++ private _getCurrentBodyDataStreamAndOffset() {const documentModel = this._currentUniverService.getCurrentUniverDocInstance();- return documentModel?.snapshot?.body;++ if (!documentModel?.snapshot?.body) {+ return;+ }++ const unitId = documentModel.getUnitId();++ const editor = this._editorService.getEditor(unitId);++ const dataStream = documentModel.snapshot.body.dataStream;++ if (!editor || !editor.onlyInputRange()) {+ return { dataStream, offset: 0 };+ }++ return { dataStream: compareToken.EQUALS + dataStream, offset: 1 };}private _getFormulaAndCellEditorBody(unitIds: string[]) {@@ -801,12 +826,14 @@ export class PromptController extends Disposable {* otherwise, close the formula panel.* @param currentInputValue The text content entered by the user in the editor.*/- private _contextSwitch(currentInputValue: string) {- if (isFormulaString(currentInputValue)) {+ private _contextSwitch() {+ const config = this._getCurrentBodyDataStreamAndOffset();++ if (config && isFormulaString(config.dataStream)) {this._contextService.setContextValue(FOCUSING_EDITOR_INPUT_FORMULA, true);const lastSequenceNodes =- this._lexerTreeBuilder.sequenceNodesBuilder(currentInputValue.replace(/\r/g, '').replace(/\n/g, '')) ||+ this._lexerTreeBuilder.sequenceNodesBuilder(config.dataStream.replace(/\r/g, '').replace(/\n/g, '')) ||[];this._formulaPromptService.setSequenceNodes(lastSequenceNodes);@@ -819,20 +846,22 @@ export class PromptController extends Disposable {const { startOffset } = activeRange;- this._currentInsertRefStringIndex = startOffset - 1;- } else {- this._contextService.setContextValue(FOCUSING_EDITOR_INPUT_FORMULA, false);+ this._currentInsertRefStringIndex = startOffset - 1 + config.offset;++ return;+ }++ this._contextService.setContextValue(FOCUSING_EDITOR_INPUT_FORMULA, false);- this._formulaPromptService.disableLockedSelectionChange();+ this._formulaPromptService.disableLockedSelectionChange();- this._formulaPromptService.disableLockedSelectionInsert();+ this._formulaPromptService.disableLockedSelectionInsert();// this._lastSequenceNodes = [];- this._formulaPromptService.clearSequenceNodes();+ this._formulaPromptService.clearSequenceNodes();- this._hideFunctionPanel();- }+ this._hideFunctionPanel();}private _getContextState() {@@ -910,6 +939,8 @@ export class PromptController extends Disposable {const refSelections: IRefSelection[] = [];let refColorIndex = 0;+ const offset = this._getCurrentBodyDataStreamAndOffset()?.offset || 0;+for (let i = 0, len = sequenceNodes.length; i < len; i++) {const node = sequenceNodes[i];if (typeof node === 'string') {@@ -939,8 +970,8 @@ export class PromptController extends Disposable {if (themeColor && themeColor.length > 0) {textRuns.push({- st: startIndex + 1,- ed: endIndex + 2,+ st: startIndex + 1 - offset,+ ed: endIndex + 2 - offset,ts: {cl: {rgb: themeColor,@@ -1226,17 +1257,26 @@ export class PromptController extends Disposable {this._fitEditorSize();+ const editor = this._editorService.getEditor(editorUnitId);++ let formulaString = dataStream;+ let offset = 1;+ if (!editor || !editor.onlyInputRange()) {+ formulaString = `${compareToken.EQUALS}${dataStream}`;+ offset = 0;+ }+if (canUndo) {this._commandService.executeCommand(ReplaceContentCommand.id, {unitId: editorUnitId,body: {- dataStream: `=${dataStream}`,+ dataStream: formulaString,textRuns,},textRanges: [{- startOffset: textSelectionOffset + 1,- endOffset: textSelectionOffset + 1,+ startOffset: textSelectionOffset + 1 - offset,+ endOffset: textSelectionOffset + 1 - offset,collapsed,style,},@@ -1244,11 +1284,11 @@ export class PromptController extends Disposable {segmentId: null,});} else {- this._updateEditorModel(`=${dataStream}\r\n`, textRuns);+ this._updateEditorModel(`${formulaString}\r\n`, textRuns);this._textSelectionManagerService.replaceTextRanges([{- startOffset: textSelectionOffset + 1,- endOffset: textSelectionOffset + 1,+ startOffset: textSelectionOffset + 1 - offset,+ endOffset: textSelectionOffset + 1 - offset,style,},]);diff --git a/packages/sheets-numfmt/src/controllers/__tests__/test.util.ts b/packages/sheets-numfmt/src/controllers/__tests__/test.util.tsindex d3718848f2..5abbbb475d 100644--- a/packages/sheets-numfmt/src/controllers/__tests__/test.util.ts+++ b/packages/sheets-numfmt/src/controllers/__tests__/test.util.ts@@ -16,6 +16,7 @@import type { IWorkbookData } from '@univerjs/core';import { ICommandService, IUniverInstanceService, LocaleType, Plugin, PluginType, Univer } from '@univerjs/core';+import { LexerTreeBuilder } from '@univerjs/engine-formula';import {INumfmtService,NumfmtService,@@ -69,7 +70,7 @@ export const createTestBed = (dependencies?: Dependency[]) => {injector.add([INumfmtService, { useClass: NumfmtService }]);injector.add([SheetInterceptorService]);injector.add([SheetSkeletonManagerService]);-+ injector.add([LexerTreeBuilder]);dependencies?.forEach((d) => injector.add(d));}diff --git a/packages/sheets-ui/src/commands/commands/__tests__/create-command-test-bed.ts b/packages/sheets-ui/src/commands/commands/__tests__/create-command-test-bed.tsindex 4ea13bc07a..e8d5ba0cfd 100644--- a/packages/sheets-ui/src/commands/commands/__tests__/create-command-test-bed.ts+++ b/packages/sheets-ui/src/commands/commands/__tests__/create-command-test-bed.ts@@ -30,6 +30,7 @@ import { BorderStyleManagerService, SelectionManagerService, SheetInterceptorSerimport type { Dependency } from '@wendellhu/redi';import { Inject, Injector } from '@wendellhu/redi';+import { LexerTreeBuilder } from '@univerjs/engine-formula';import enUS from '../../../locale/en-US';const getTestWorkbookDataDemo = (): IWorkbookData => {@@ -95,6 +96,7 @@ export function createCommandTestBed(workbookConfig?: IWorkbookData, dependencieinjector.add([SelectionManagerService]);injector.add([BorderStyleManagerService]);injector.add([SheetInterceptorService]);+ injector.add([LexerTreeBuilder]);dependencies?.forEach((d) => injector.add(d));}diff --git a/packages/sheets-ui/src/views/editor-container/EditorContainer.tsx b/packages/sheets-ui/src/views/editor-container/EditorContainer.tsxindex 67a87e71fc..3725b22978 100644--- a/packages/sheets-ui/src/views/editor-container/EditorContainer.tsx+++ b/packages/sheets-ui/src/views/editor-container/EditorContainer.tsx@@ -114,7 +114,14 @@ export const EditorContainer: React.FC<ICellIEditorProps> = () => {height: state.height,}}>- <TextEditor id={DOCS_NORMAL_EDITOR_UNIT_ID_KEY} className={styles.editorInput} snapshot={snapshot} cancelDefaultResizeListener={true} isSheetEditor={true} />+ <TextEditor+ id={DOCS_NORMAL_EDITOR_UNIT_ID_KEY}+ className={styles.editorInput}+ snapshot={snapshot}+ cancelDefaultResizeListener={true}+ isSheetEditor={true}+ isSingle={false}+ /></div>);};diff --git a/packages/sheets-ui/src/views/formula-bar/FormulaBar.tsx b/packages/sheets-ui/src/views/formula-bar/FormulaBar.tsxindex 7ec9ff4f51..9e4a4ac3f0 100644--- a/packages/sheets-ui/src/views/formula-bar/FormulaBar.tsx+++ b/packages/sheets-ui/src/views/formula-bar/FormulaBar.tsx@@ -159,6 +159,7 @@ export function FormulaBar() {onContextMenu={(e) => e.preventDefault()}className={styles.formulaContent}snapshot={INITIAL_SNAPSHOT}+ isSingle={false}/><div className={styles.arrowContainer} onClick={handleArrowClick}>{arrowDirection === ArrowDirection.Downdiff --git a/packages/sheets-ui/src/views/status-bar/StatusBar.tsx b/packages/sheets-ui/src/views/status-bar/StatusBar.tsxindex ac9f78f20c..a563316412 100644--- a/packages/sheets-ui/src/views/status-bar/StatusBar.tsx+++ b/packages/sheets-ui/src/views/status-bar/StatusBar.tsx@@ -18,6 +18,7 @@ import { useDependency } from '@wendellhu/redi/react-bindings';import clsx from 'clsx';import React, { useEffect, useState } from 'react';+import { debounce } from '@univerjs/core';import { IStatusBarService } from '../../services/status-bar.service';import type { IStatisticItem } from './CopyableStatisticItem';import { CopyableStatisticItem } from './CopyableStatisticItem';@@ -126,21 +127,3 @@ export const StatusBar = () => {));};--type DebounceFn<T extends (...args: any[]) => any> = (this: ThisParameterType<T>, ...args: Parameters<T>) => void;--function debounce<T extends (...args: any[]) => any>(func: T, wait: number): DebounceFn<T> {- let timeout: NodeJS.Timeout | null;-- return function (this: ThisParameterType<T>, ...args: Parameters<T>) {- const context = this;-- const later = function () {- timeout = null;- func.apply(context, args);- };-- clearTimeout(timeout as NodeJS.Timeout);- timeout = setTimeout(later, wait);- };-}diff --git a/packages/ui/src/components/editor/TextEditor.tsx b/packages/ui/src/components/editor/TextEditor.tsxindex 68bb5507d3..803da1f4eb 100644--- a/packages/ui/src/components/editor/TextEditor.tsx+++ b/packages/ui/src/components/editor/TextEditor.tsx@@ -14,38 +14,83 @@* limitations under the License.*/-import type { IDocumentData, Nullable } from '@univerjs/core';+import { debounce, type IDocumentData, LocaleService, type Nullable } from '@univerjs/core';import { useDependency } from '@wendellhu/redi/react-bindings';-import React, { useEffect, useRef } from 'react';+import React, { useEffect, useRef, useState } from 'react';+import { Popup } from '@univerjs/design';import type { IEditorCanvasStyle } from '../../services/editor/editor.service';import { IEditorService } from '../../services/editor/editor.service';+import styles from './index.module.less';type MyComponentProps = React.DetailedHTMLProps<React.HTMLAttributes<HTMLDivElement>, HTMLDivElement>;-const excludeProps = ['snapshot', 'resizeCallBack', 'cancelDefaultResizeListener', 'isSheetEditor', 'canvasStyle'];+const excludeProps = new Set([+ 'snapshot',+ 'resizeCallBack',+ 'cancelDefaultResizeListener',+ 'isSheetEditor',+ 'canvasStyle',+ 'isSingle',+ 'isReadonly',+ 'onlyInputFormula',+ 'onlyInputRange',+ 'value',+ 'onlyInputContent',+]);export interface ITextEditorProps {id: string;+ className?: string;+snapshot?: IDocumentData;resizeCallBack?: (editor: Nullable<HTMLDivElement>) => void;cancelDefaultResizeListener?: boolean;isSheetEditor?: boolean;canvasStyle?: IEditorCanvasStyle;+value?: string;++ isSingle?: boolean;+ isReadonly?: boolean;+ onlyInputFormula?: boolean;+ onlyInputRange?: boolean;+ onlyInputContent?: boolean;}/*** The component to render toolbar item label and menu item label.* @param props- * @returns*/export function TextEditor(props: ITextEditorProps & MyComponentProps): JSX.Element | null {- const { id, snapshot, resizeCallBack, cancelDefaultResizeListener, isSheetEditor = false, canvasStyle = {}, value } = props;+ const {+ id,+ snapshot,+ resizeCallBack,+ cancelDefaultResizeListener,+ isSheetEditor = false,+ canvasStyle = {},+ value,+ isSingle = true,+ isReadonly = false,+ onlyInputFormula = false,+ onlyInputRange = false,+ onlyInputContent = false,+ } = props;const editorService = useDependency(IEditorService);+ const localeService = useDependency(LocaleService);++ const [validationContent, setValidationContent] = useState<string>('');++ const [validationVisible, setValidationVisible] = useState(false);++ const [validationOffset, setValidationOffset] = useState<[number, number]>([0, 0]);+const editorRef = useRef<HTMLDivElement>(null);+ const [active, setActive] = useState(false);+useEffect(() => {const editor = editorRef.current;@@ -62,13 +107,62 @@ export function TextEditor(props: ITextEditorProps & MyComponentProps): JSX.ElemresizeObserver.observe(editor);- editorService.register({ editorUnitId: id, initialSnapshot: snapshot, cancelDefaultResizeListener, isSheetEditor, canvasStyle, isSingle: true }, editor);+ editorService.register({+ editorUnitId: id,+ initialSnapshot: snapshot,+ cancelDefaultResizeListener,+ isSheetEditor,+ canvasStyle,+ isSingle,+ isReadonly,+ onlyInputFormula,+ onlyInputRange,+ onlyInputContent,+ },+ editor);++ const focusStyleSubscription = editorService.focusStyle$.subscribe((unitId: string) => {+ if (unitId === id) {+ setActive(true);+ } else {+ setActive(false);+ }+ });++ const valueChangeSubscription = editorService.valueChange$.subscribe((editor) => {+ if (!editor.onlyInputFormula() && !editor.onlyInputRange()) {+ return;+ }++ if (editor.editorUnitId !== id) {+ return;+ }++ debounce(() => {+ const unitId = editor.editorUnitId;+ const isLegality = editorService.checkValueLegality(unitId);+ setValidationVisible(!isLegality);+ const rect = editor.getBoundingClientRect();++ setValidationOffset([rect.left, rect.top - 16]);++ if (editor.onlyInputFormula()) {+ setValidationContent(localeService.t('textEditor.formulaError'));+ } else {+ setValidationContent(localeService.t('textEditor.rangeError'));+ }+ }, 100)();+ });// Clean up on unmountreturn () => {resizeObserver.unobserve(editor);editorService.unRegister(id);++ focusStyleSubscription?.unsubscribe();++ valueChangeSubscription?.unsubscribe();};}, []);@@ -80,8 +174,30 @@ export function TextEditor(props: ITextEditorProps & MyComponentProps): JSX.Elem}, [value]);const propsNew = Object.fromEntries(- Object.entries(props).filter(([key]) => !excludeProps.includes(key))+ Object.entries(props).filter(([key]) => !excludeProps.has(key)));- return <div {...propsNew} ref={editorRef}></div>;+ let className = styles.textEditorContainer;+ if (props.className != null) {+ className = props.className;+ }++ let borderStyle = '';++ if (active && props.className == null) {+ if (validationVisible) {+ borderStyle = ` ${styles.textEditorContainerError}`;+ } else {+ borderStyle = ` ${styles.textEditorContainerActive}`;+ }+ }++ return (+ <>+ <div {...propsNew} className={className + borderStyle} ref={editorRef}></div>+ <Popup visible={validationVisible} offset={validationOffset}>+ <div className={styles.textEditorValidationError}>{validationContent}</div>+ </Popup>+ </>+ );}diff --git a/packages/ui/src/components/editor/index.module.less b/packages/ui/src/components/editor/index.module.lessnew file mode 100644index 0000000000..a801261f3a--- /dev/null+++ b/packages/ui/src/components/editor/index.module.less@@ -0,0 +1,41 @@+@font-size-xxxs: 10px;++.text-editor-container {+ position: relative;+ width: 100%;+ height: 30px;+ user-select: none;+ border: 1px solid rgb(var(--border-color));+ transition: all 0.15s;+ border-radius: var(--border-radius-base);++ &:hover {+ border: 1px solid rgb(var(--primary-color));+ }++ &:active {+ border: 1px solid rgb(var(--primary-color));+ }+}++.text-editor-container-active {+ border: 1px solid rgb(var(--primary-color));+}++.text-editor-container-error {+ border: 1px solid rgb(var(--error-color));++ &:hover {+ border: 1px solid rgb(var(--error-color));+ }+}++.text-editor-validation-error {+ // border: 1px solid rgb(var(--error-color));+ // background: rgb(var(--red-50));+ // border-radius: var(--border-radius-base);+ // padding: 2px 3px;++ font-size: @font-size-xxxs;+ color: rgb(var(--error-color));+}diff --git a/packages/ui/src/locale/en-US.ts b/packages/ui/src/locale/en-US.tsindex eaec3e85b6..46d28dfd68 100644--- a/packages/ui/src/locale/en-US.ts+++ b/packages/ui/src/locale/en-US.ts@@ -61,6 +61,10 @@ const locale: typeof zhCN = {content: 'Please allow Univer to access your clipboard.',},},+ textEditor: {+ formulaError: 'Please enter a valid formula, such as =SUM(A1)',+ rangeError: 'Please enter a valid range, such as A1:B10',+ },};export default locale;diff --git a/packages/ui/src/locale/zh-CN.ts b/packages/ui/src/locale/zh-CN.tsindex 2243e64da6..44314d11fc 100644--- a/packages/ui/src/locale/zh-CN.ts+++ b/packages/ui/src/locale/zh-CN.ts@@ -59,6 +59,10 @@ const locale = {content: '请允许 Univer 访问您的剪贴板。',},},+ textEditor: {+ formulaError: '请输入合法的公式,例如=SUM(A1)',+ rangeError: '请输入合法的范围,例如 A1:B10',+ },};export default locale;diff --git a/packages/ui/src/services/editor/editor.service.ts b/packages/ui/src/services/editor/editor.service.tsindex 6e05dd4941..7e71dea8bd 100644--- a/packages/ui/src/services/editor/editor.service.ts+++ b/packages/ui/src/services/editor/editor.service.ts@@ -15,13 +15,14 @@*/import type { DocumentDataModel, IDocumentBody, IDocumentData, IDocumentStyle, IPosition, Nullable } from '@univerjs/core';-import { DEFAULT_EMPTY_DOCUMENT_VALUE, Disposable, HorizontalAlign, IUniverInstanceService, toDisposable, VerticalAlign } from '@univerjs/core';+import { DEFAULT_EMPTY_DOCUMENT_VALUE, Disposable, FOCUSING_UNIVER_EDITOR_SINGLE_MODE, HorizontalAlign, IContextService, IUniverInstanceService, toDisposable, VerticalAlign } from '@univerjs/core';import type { IDisposable } from '@wendellhu/redi';-import { createIdentifier } from '@wendellhu/redi';+import { createIdentifier, Inject } from '@wendellhu/redi';import type { Observable } from 'rxjs';import { Subject } from 'rxjs';import type { IRender, ISuccinctTextRangeParam, Scene } from '@univerjs/engine-render';import { IRenderManagerService, UNIVER_GLOBAL_DEFAULT_FONT_SIZE } from '@univerjs/engine-render';+import { isReferenceString, LexerTreeBuilder, operatorToken } from '@univerjs/engine-formula';export interface IEditorStateParam extends Partial<IPosition> {visible?: boolean;@@ -37,8 +38,14 @@ export interface IEditorConfigParam {initialSnapshot?: IDocumentData;cancelDefaultResizeListener?: boolean;canvasStyle?: IEditorCanvasStyle;- isSingle?: boolean;isSheetEditor: boolean;++ isSingle: boolean;+ isReadonly: boolean;+ onlyInputFormula: boolean;+ onlyInputRange: boolean;+ onlyInputContent: boolean;+}export interface IEditorSetParam extends IEditorConfigParam, IEditorStateParam {@@ -58,6 +65,10 @@ export interface IEditorInputFormulaParam {}class Editor {+ private _focus = false;++ private _valueLegality = true;+constructor(private _param: IEditorSetParam) {}@@ -78,8 +89,40 @@ class Editor {return this._param.render;}- get isSingle() {- return this._param.isSingle;+ isValueLegality() {+ return this._valueLegality === true;+ }++ setValueLegality(state = true) {+ this._valueLegality = state;+ }++ isFocus() {+ return this._focus;+ }++ setFocus(state = false) {+ this._focus = state;+ }++ isSingle() {+ return this._param.isSingle === true || this.onlyInputFormula() || this.onlyInputFormula();+ }++ isReadOnly() {+ return this._param.isReadonly === true;+ }++ onlyInputContent() {+ return this._param.onlyInputContent === true;+ }++ onlyInputFormula() {+ return this._param.onlyInputFormula === true;+ }++ onlyInputRange() {+ return this._param.onlyInputRange === true;}getBoundingClientRect() {@@ -112,7 +155,14 @@ class Editor {verticalAlign() {const documentDataModel = this._param?.documentDataModel;- if (documentDataModel == null || this._param.isSingle === false) {+ if (documentDataModel == null) {+ return;+ }++ const { width, height } = this._param.editorDom.getBoundingClientRect();++ if (!this.isSingle()) {+ documentDataModel.updateDocumentDataPageSize(width, undefined);return;}@@ -122,13 +172,13 @@ class Editor {fontSize = this._param.canvasStyle.fontSize;}- const { height } = this._param.editorDom.getBoundingClientRect();-const top = (height - (fontSize * 4 / 3)) / 2 - 2;documentDataModel.updateDocumentDataMargin({t: top < 0 ? 0 : top,});++ documentDataModel.updateDocumentDataPageSize(undefined, undefined);}updateCanvasStyle() {@@ -172,10 +222,18 @@ export interface IEditorService {getAllEditor(): Map<string, Editor>;+ /**+ * The sheet currently being operated on will determine+ * whether to include unitId information in the ref.+ */setOperationSheetUnitId(unitId: Nullable<string>): void;getOperationSheetUnitId(): Nullable<string>;+ /**+ * The sub-table within the sheet currently being operated on+ * will determine whether to include subUnitId information in the ref.+ */setOperationSheetSubUnitId(sheetId: Nullable<string>): void;getOperationSheetSubUnitId(): Nullable<string>;@@ -205,6 +263,14 @@ export interface IEditorService {setRichValue(body: IDocumentBody, editorUnitId?: string): void;getFirstEditor(): Editor;++ focusStyle$: Observable<string>;++ focusStyle(editorUnitId: string): void;++ refreshValueChange(editorId: string): void;++ checkValueLegality(editorId: string): boolean;}export class EditorService extends Disposable implements IEditorService, IDisposable {@@ -238,9 +304,15 @@ export class EditorService extends Disposable implements IEditorService, IDisposprivate readonly _valueChange$ = new Subject<Readonly<Editor>>();readonly valueChange$ = this._valueChange$.asObservable();+ private readonly _focusStyle$ = new Subject<string>();++ readonly focusStyle$ = this._focusStyle$.asObservable();+constructor(@IUniverInstanceService private readonly _currentUniverService: IUniverInstanceService,- @IRenderManagerService private readonly _renderManagerService: IRenderManagerService+ @IRenderManagerService private readonly _renderManagerService: IRenderManagerService,+ @Inject(LexerTreeBuilder) private readonly _lexerTreeBuilder: LexerTreeBuilder,+ @IContextService private readonly _contextService: IContextService) {super();}@@ -266,6 +338,23 @@ export class EditorService extends Disposable implements IEditorService, IDisposthis.blur();}+ focusStyle(editorUnitId: string) {+ const editor = this.getEditor(editorUnitId);+ if (!editor) {+ return false;+ }++ this.getAllEditor().forEach((editor) => {+ editor.setFocus(false);+ });++ editor.setFocus(true);++ this._contextService.setContextValue(FOCUSING_UNIVER_EDITOR_SINGLE_MODE, editor.isSingle());++ this._focusStyle$.next(editorUnitId);+ }+blur() {this._blur$.next(null);}@@ -399,7 +488,7 @@ export class EditorService extends Disposable implements IEditorService, IDispos}register(config: IEditorConfigParam, container: HTMLDivElement): IDisposable {- const { initialSnapshot, editorUnitId, isSheetEditor, canvasStyle = {}, isSingle = true } = config;+ const { initialSnapshot, editorUnitId, canvasStyle = {} } = config;const documentDataModel = this._currentUniverService.createDoc(initialSnapshot || this._getBlank(editorUnitId));@@ -412,7 +501,7 @@ export class EditorService extends Disposable implements IEditorService, IDisposrender.engine.setContainer(container);- const editor = new Editor({ ...config, isSheetEditor, render, documentDataModel, editorDom: container, canvasStyle, isSingle });+ const editor = new Editor({ ...config, render, documentDataModel, editorDom: container, canvasStyle });this._editors.set(editorUnitId, editor);@@ -445,6 +534,45 @@ export class EditorService extends Disposable implements IEditorService, IDisposthis._currentUniverService.disposeDocument(editorUnitId);}+ refreshValueChange(editorUnitId: string) {+ this._refreshValueChange(editorUnitId);+ }++ checkValueLegality(editorUnitId: string) {+ const editor = this._editors.get(editorUnitId);++ if (editor == null) {+ return true;+ }++ let value = editor.getValue();++ editor.setValueLegality();++ value = value.replace(/\r\n/g, '').replace(/\n/g, '').replace(/\n/g, '');++ if (value.length === 0) {+ return true;+ }++ if (editor.onlyInputFormula()) {+ if (value.substring(0, 1) !== operatorToken.EQUALS) {+ editor.setValueLegality(false);+ return false;+ }+ const bracketCount = this._lexerTreeBuilder.checkIfAddBracket(value);+ editor.setValueLegality(bracketCount === 0);+ } else if (editor.onlyInputRange()) {+ const valueArray = value.split(',');+ const result = valueArray.every((refString) => {+ return isReferenceString(refString.trim());+ });+ editor.setValueLegality(result);+ }++ return editor.isValueLegality();+ }+private _refreshValueChange(editorId: string) {const editor = this.getEditor(editorId);if (editor == null) {@@ -480,8 +608,9 @@ export class EditorService extends Disposable implements IEditorService, IDisposverticalAlign: VerticalAlign.TOP,horizontalAlign: HorizontalAlign.LEFT,},- marginLeft: 2,+ marginLeft: 6,marginTop: 2,+ marginRight: 6,},} as IDocumentData;}