Skip to content

Build your own AI office with Univer Office SDK. Bring editing, calculation, collaboration, and file processing into your product for people and AI agents. Built on an extensible open-source core.

feat(sheet): shot cut f4 and editor id (#535)

Univere0a0dd12b675
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index fc0ba964db..742575450d 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -69,7 +69,10 @@ export * from './shared';
export { Range } from './sheets/range';
export {
+ AbsoluteRefType,
deserializeRangeWithSheet,
+ getAbsoluteRefTypeWithSingleString,
+ getAbsoluteRefTypeWitString,
serializeRange,
serializeRangeToRefString,
serializeRangeWithSheet,
diff --git a/packages/core/src/sheets/reference.ts b/packages/core/src/sheets/reference.ts
index 8b5a212db7..3c175af3f0 100644
--- a/packages/core/src/sheets/reference.ts
+++ b/packages/core/src/sheets/reference.ts
@@ -11,6 +11,13 @@ export interface IGridRangeName {
range: IRange;
}
+export enum AbsoluteRefType {
+ NONE,
+ ROW,
+ COLUMN,
+ ALL,
+}
+
function singleReferenceToGrid(refBody: string) {
const row = parseInt(refBody.replace($ROW_REGEX, '')) - 1;
const column = Tools.ABCatNum(refBody.replace($COLUMN_REGEX, ''));
@@ -21,15 +28,72 @@ function singleReferenceToGrid(refBody: string) {
};
}
+/**
+ *
+ * @param singleRefString for example A1 or B10, not A1:B10
+ */
+export function getAbsoluteRefTypeWithSingleString(singleRefString: string) {
+ const isColumnAbsolute = singleRefString[0] === '$';
+ const remainChar = singleRefString.substring(1);
+
+ const isRowAbsolute = remainChar.indexOf('$') > -1;
+
+ if (isColumnAbsolute && isRowAbsolute) {
+ return AbsoluteRefType.ALL;
+ }
+ if (isColumnAbsolute) {
+ return AbsoluteRefType.COLUMN;
+ }
+ if (isRowAbsolute) {
+ return AbsoluteRefType.ROW;
+ }
+
+ return AbsoluteRefType.NONE;
+}
+
+/**
+ *
+ * @param refString for example A1:B10
+ */
+export function getAbsoluteRefTypeWitString(refString: string) {
+ const sheetArray = refString.split('!');
+
+ if (sheetArray.length > 1) {
+ refString = sheetArray[sheetArray.length - 1];
+ }
+
+ const refArray = refString.split(':');
+
+ if (refArray.length > 1) {
+ return getAbsoluteRefTypeWithSingleString(refArray[0]) && getAbsoluteRefTypeWithSingleString(refArray[1]);
+ }
+
+ return getAbsoluteRefTypeWithSingleString(refArray[0]);
+}
+
/**
* Serialize an `IRange` into a string.
* @param range The `IRange` to be serialized
*/
-export function serializeRange(range: IRange): string {
+export function serializeRange(range: IRange, type: AbsoluteRefType = AbsoluteRefType.NONE): string {
const { startColumn, startRow, endColumn, endRow } = range;
- const startStr = `${Tools.chatAtABC(startColumn) + (startRow + 1)}`;
- const endStr = `${Tools.chatAtABC(endColumn)}${endRow + 1}`;
+ let rowAbsoluteString = '';
+
+ let columnAbsoluteString = '';
+
+ if (type === AbsoluteRefType.ROW) {
+ rowAbsoluteString = '$';
+ } else if (type === AbsoluteRefType.COLUMN) {
+ columnAbsoluteString = '$';
+ } else if (type === AbsoluteRefType.ALL) {
+ rowAbsoluteString = '$';
+ columnAbsoluteString = '$';
+ }
+
+ const startStr = `${columnAbsoluteString}${Tools.chatAtABC(startColumn)}${rowAbsoluteString}${startRow + 1}`;
+
+ const endStr = `${columnAbsoluteString}${Tools.chatAtABC(endColumn)}${rowAbsoluteString}${endRow + 1}`;
if (startStr === endStr) {
return startStr;
@@ -44,8 +108,12 @@ export function serializeRange(range: IRange): string {
* @param range
* @returns
*/
-export function serializeRangeWithSheet(sheetName: string, range: IRange): string {
- return `${sheetName}!${serializeRange(range)}`;
+export function serializeRangeWithSheet(
+ sheetName: string,
+ range: IRange,
+ type: AbsoluteRefType = AbsoluteRefType.NONE
+): string {
+ return `${sheetName}!${serializeRange(range, type)}`;
}
/**
@@ -55,8 +123,13 @@ export function serializeRangeWithSheet(sheetName: string, range: IRange): strin
* @param range
* @returns
*/
-export function serializeRangeWithSpreadsheet(unit: string, sheetName: string, range: IRange): string {
- return `[${unit}]${sheetName}!${serializeRange(range)}`;
+export function serializeRangeWithSpreadsheet(
+ unit: string,
+ sheetName: string,
+ range: IRange,
+ type: AbsoluteRefType = AbsoluteRefType.NONE
+): string {
+ return `[${unit}]${sheetName}!${serializeRange(range, type)}`;
}
export function serializeRangeToRefString(gridRangeName: IGridRangeName) {
diff --git a/packages/sheets-plugin-formula-ui/src/commands/operations/reference-absolute.operation.ts b/packages/sheets-plugin-formula-ui/src/commands/operations/reference-absolute.operation.ts
new file mode 100644
index 0000000000..674b82a9e3
--- /dev/null
+++ b/packages/sheets-plugin-formula-ui/src/commands/operations/reference-absolute.operation.ts
@@ -0,0 +1,8 @@
+import { CommandType, ICommand } from '@univerjs/core';
+import { IAccessor } from '@wendellhu/redi';
+
+export const ReferenceAbsoluteOperation: ICommand = {
+ id: 'formula-ui.operation.change-ref-to-absolute',
+ type: CommandType.OPERATION,
+ handler: async (accessor: IAccessor) => true,
+};
diff --git a/packages/sheets-plugin-formula-ui/src/controllers/formula-input.controller.ts b/packages/sheets-plugin-formula-ui/src/controllers/formula-input.controller.ts
new file mode 100644
index 0000000000..50470163c7
--- /dev/null
+++ b/packages/sheets-plugin-formula-ui/src/controllers/formula-input.controller.ts
@@ -0,0 +1,213 @@
+import { TextSelectionManagerService } from '@univerjs/base-docs';
+import { FormulaEngineService, matchToken, sequenceNodeType } from '@univerjs/base-formula-engine';
+import { IRenderManagerService, ITextSelectionRenderManager } from '@univerjs/base-render';
+import { SelectionManagerService } from '@univerjs/base-sheets';
+import { KeyCode } from '@univerjs/base-ui';
+import {
+ AbsoluteRefType,
+ deserializeRangeWithSheet,
+ Disposable,
+ getAbsoluteRefTypeWithSingleString,
+ getAbsoluteRefTypeWitString,
+ ICommandInfo,
+ ICommandService,
+ IContextService,
+ IUniverInstanceService,
+ LifecycleStages,
+ LocaleService,
+ OnLifecycle,
+ serializeRange,
+ ThemeService,
+ toDisposable,
+} from '@univerjs/core';
+import {
+ EditorBridgeService,
+ getEditorObject,
+ IEditorBridgeService,
+ ISelectionRenderService,
+ SheetSkeletonManagerService,
+} from '@univerjs/ui-plugin-sheets';
+import { Inject } from '@wendellhu/redi';
+
+import { ReferenceAbsoluteOperation } from '../commands/operations/reference-absolute.operation';
+import { IDescriptionService } from '../services/description.service';
+import { IFormulaInputService } from '../services/formula-input.service';
+import { IFormulaPromptService } from '../services/prompt.service';
+
+@OnLifecycle(LifecycleStages.Ready, FormulaInputController)
+export class FormulaInputController extends Disposable {
+ private _userCursorMove: boolean = false;
+
+ constructor(
+ @ICommandService private readonly _commandService: ICommandService,
+ @Inject(LocaleService) private readonly _localeService: LocaleService,
+ @IContextService private readonly _contextService: IContextService,
+ @ITextSelectionRenderManager private readonly _textSelectionRenderManager: ITextSelectionRenderManager,
+ @Inject(IEditorBridgeService) private readonly _editorBridgeService: EditorBridgeService,
+ @Inject(IFormulaPromptService) private readonly _formulaPromptService: IFormulaPromptService,
+ @Inject(FormulaEngineService) private readonly _formulaEngineService: FormulaEngineService,
+ @IRenderManagerService private readonly _renderManagerService: IRenderManagerService,
+ @Inject(ThemeService) private readonly _themeService: ThemeService,
+ @Inject(SelectionManagerService) private readonly _selectionManagerService: SelectionManagerService,
+ @Inject(SheetSkeletonManagerService) private readonly _sheetSkeletonManagerService: SheetSkeletonManagerService,
+ @IUniverInstanceService private readonly _currentUniverService: IUniverInstanceService,
+ @Inject(ISelectionRenderService) private readonly _selectionRenderService: ISelectionRenderService,
+ @Inject(IDescriptionService) private readonly _descriptionService: IDescriptionService,
+ @Inject(TextSelectionManagerService) private readonly _textSelectionManagerService: TextSelectionManagerService,
+ @IFormulaInputService private readonly _formulaInputService: IFormulaInputService
+ ) {
+ super();
+
+ this._initialize();
+ }
+
+ private _initialize(): void {
+ this._commandExecutedListener();
+
+ this._initialEditorInputChange();
+
+ this._userMouseListener();
+ }
+
+ private _initialEditorInputChange() {
+ this.disposeWithMe(
+ toDisposable(
+ this._textSelectionRenderManager.onInputBefore$.subscribe((param) => {
+ const e = param?.event as KeyboardEvent;
+ if (e == null) {
+ return;
+ }
+ if (e.which !== KeyCode.F4) {
+ this._userCursorMove = false;
+ }
+ })
+ )
+ );
+ }
+
+ private _userMouseListener() {
+ const editorObject = this._getEditorObject();
+
+ if (editorObject == null) {
+ return;
+ }
+
+ const { document: documentComponent } = editorObject;
+ this.disposeWithMe(
+ toDisposable(
+ documentComponent.onPointerDownObserver.add(() => {
+ this._userCursorMove = true;
+ })
+ )
+ );
+ }
+
+ private _changeRefString() {
+ const activeRange = this._textSelectionRenderManager.getActiveRange();
+
+ if (activeRange == null) {
+ return;
+ }
+
+ const { startOffset } = activeRange;
+
+ const strIndex = startOffset - 2;
+
+ const nodeIndex = this._formulaInputService.getCurrentSequenceNodeIndex(strIndex);
+
+ const node = this._formulaInputService.getCurrentSequenceNodeByIndex(nodeIndex);
+
+ if (node == null || typeof node === 'string' || node.nodeType !== sequenceNodeType.REFERENCE) {
+ return;
+ }
+
+ const tokenArray = node.token.split('!');
+
+ let token = node.token;
+
+ if (tokenArray.length > 1) {
+ token = tokenArray[tokenArray.length - 1];
+ }
+
+ let unitIDAndSheetName = '';
+
+ for (let i = 0, len = tokenArray.length; i < len - 1; i++) {
+ unitIDAndSheetName += tokenArray[i];
+ }
+
+ let finalToken = token;
+ if (token.indexOf(matchToken.COLON) > -1) {
+ if (!this._userCursorMove) {
+ finalToken = this._changeRangeRef(token);
+ } else {
+ const refStringSplit = token.split(matchToken.COLON);
+ const prefix = refStringSplit[0];
+ const suffix = refStringSplit[1];
+ const relativeIndex = strIndex - node.startIndex;
+
+ if (relativeIndex <= prefix.length) {
+ finalToken = this._changeSingleRef(prefix) + matchToken.COLON + suffix;
+ } else {
+ finalToken = prefix + matchToken.COLON + this._changeSingleRef(suffix);
+ }
+ }
+ } else {
+ finalToken = this._changeSingleRef(token);
+ }
+
+ finalToken = unitIDAndSheetName + finalToken;
+
+ const difference = finalToken.length - node.token.length;
+
+ this._formulaInputService.updateSequenceRef(nodeIndex, finalToken);
+
+ this._formulaInputService.syncToEditor(strIndex + difference + 1);
+ }
+
+ private _changeRangeRef(token: string) {
+ const range = deserializeRangeWithSheet(token).range;
+ const type = getAbsoluteRefTypeWitString(token);
+ let resultToken = '';
+ if (type === AbsoluteRefType.NONE) {
+ resultToken = serializeRange(range, AbsoluteRefType.ALL);
+ } else {
+ resultToken = serializeRange(range, AbsoluteRefType.NONE);
+ }
+ return resultToken;
+ }
+
+ private _changeSingleRef(token: string) {
+ const range = deserializeRangeWithSheet(token).range;
+ const type = getAbsoluteRefTypeWithSingleString(token);
+ let resultToken = '';
+ if (type === AbsoluteRefType.NONE) {
+ resultToken = serializeRange(range, AbsoluteRefType.ALL);
+ } else if (type === AbsoluteRefType.ALL) {
+ resultToken = serializeRange(range, AbsoluteRefType.ROW);
+ } else if (type === AbsoluteRefType.ROW) {
+ resultToken = serializeRange(range, AbsoluteRefType.COLUMN);
+ } else {
+ resultToken = serializeRange(range, AbsoluteRefType.NONE);
+ }
+ return resultToken;
+ }
+
+ private _commandExecutedListener() {
+ // Listen to document edits to refresh the size of the editor.
+ const updateCommandList = [ReferenceAbsoluteOperation.id];
+
+ this.disposeWithMe(
+ this._commandService.onCommandExecuted((command: ICommandInfo) => {
+ if (!updateCommandList.includes(command.id)) {
+ return;
+ }
+
+ this._changeRefString();
+ })
+ );
+ }
+
+ private _getEditorObject() {
+ return getEditorObject(this._editorBridgeService.getCurrentEditorId(), this._renderManagerService);
+ }
+}
diff --git a/packages/sheets-plugin-formula-ui/src/controllers/formula-ui.controller.ts b/packages/sheets-plugin-formula-ui/src/controllers/formula-ui.controller.ts
index d427064776..01d71c40d4 100644
--- a/packages/sheets-plugin-formula-ui/src/controllers/formula-ui.controller.ts
+++ b/packages/sheets-plugin-formula-ui/src/controllers/formula-ui.controller.ts
@@ -13,12 +13,14 @@ import { SelectEditorFormulaOperation } from '../commands/operations/editor-form
import { HelpFunctionOperation } from '../commands/operations/help-function.operation';
import { InsertFunctionOperation } from '../commands/operations/insert-function.operation';
import { MoreFunctionsOperation } from '../commands/operations/more-functions.operation';
+import { ReferenceAbsoluteOperation } from '../commands/operations/reference-absolute.operation';
import { SearchFunctionOperation } from '../commands/operations/search-function.operation';
import { RenderFormulaPromptContent } from '../views/FormulaPromptContainer';
import { MORE_FUNCTIONS_COMPONENT } from '../views/more-functions/interface';
import { MoreFunctions } from '../views/more-functions/MoreFunctions';
import { InsertFunctionMenuItemFactory, MoreFunctionsMenuItemFactory } from './menu';
import {
+ ChangeRefToAbsoluteShortcut,
promptSelectionShortcutItem,
promptSelectionShortcutItemCtrl,
promptSelectionShortcutItemCtrlAndShift,
@@ -60,6 +62,7 @@ export class FormulaUIController extends Disposable {
SearchFunctionOperation,
HelpFunctionOperation,
SelectEditorFormulaOperation,
+ ReferenceAbsoluteOperation,
].forEach((command) => this.disposeWithMe(this._commandService.registerCommand(command)));
}
@@ -69,6 +72,7 @@ export class FormulaUIController extends Disposable {
...promptSelectionShortcutItemShift(),
...promptSelectionShortcutItemCtrl(),
...promptSelectionShortcutItemCtrlAndShift(),
+ ChangeRefToAbsoluteShortcut,
].forEach((item) => {
this.disposeWithMe(this._shortcutService.registerShortcut(item));
});
diff --git a/packages/sheets-plugin-formula-ui/src/controllers/prompt.controller.ts b/packages/sheets-plugin-formula-ui/src/controllers/prompt.controller.ts
index 7556a88ed5..58a220505a 100644
--- a/packages/sheets-plugin-formula-ui/src/controllers/prompt.controller.ts
+++ b/packages/sheets-plugin-formula-ui/src/controllers/prompt.controller.ts
@@ -22,8 +22,6 @@ import {
Direction,
Disposable,
DisposableCollection,
- DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY,
- DOCS_NORMAL_EDITOR_UNIT_ID_KEY,
FOCUSING_EDITOR_INPUT_FORMULA,
ICommandInfo,
ICommandService,
@@ -66,17 +64,9 @@ import { SearchFunctionOperation } from '../commands/operations/search-function.
import { META_KEY_CTRL_AND_SHIFT } from '../common/prompt';
import { FORMULA_REF_SELECTION_PLUGIN_NAME, getFormulaRefSelectionStyle } from '../common/selection';
import { IDescriptionService } from '../services/description.service';
+import { IFormulaInputService } from '../services/formula-input.service';
import { IFormulaPromptService } from '../services/prompt.service';
-// interface IFunctionPanelParam {
-// visibleSearch: boolean;
-// visibleHelp: boolean;
-// searchText: string;
-// paramIndex: number;
-// functionInfo?: IFunctionInfo;
-// searchList?: ISearchItem[];
-// }
-
interface IRefSelection {
refIndex: number;
themeColor: string;
@@ -102,14 +92,8 @@ enum InputPanelState {
export class PromptController extends Disposable {
private _formulaRefColors: string[] = [];
- private _lastSequenceNodes: Array<string | ISequenceNode> = [];
-
private _previousSequenceNodes: Nullable<Array<string | ISequenceNode>>;
- private _isLockedOnSelectionChangeRefString: boolean = false;
-
- private _isLockedOnSelectionInsertRefString: boolean = false;
-
private _previousRangesCount: number = 0;
private _previousInsertRefStringIndex: Nullable<number>;
@@ -120,8 +104,6 @@ export class PromptController extends Disposable {
private _currentSheetId: Nullable<string>;
- private _isSelectionMoving: boolean = false;
-
private _arrowMoveActionState: ArrowMoveAction = ArrowMoveAction.InitialState;
private _isSelectionMovingRefSelections: IRefSelection[] = [];
@@ -149,7 +131,8 @@ export class PromptController extends Disposable {
@IUniverInstanceService private readonly _currentUniverService: IUniverInstanceService,
@Inject(ISelectionRenderService) private readonly _selectionRenderService: ISelectionRenderService,
@Inject(IDescriptionService) private readonly _descriptionService: IDescriptionService,
- @Inject(TextSelectionManagerService) private readonly _textSelectionManagerService: TextSelectionManagerService
+ @Inject(TextSelectionManagerService) private readonly _textSelectionManagerService: TextSelectionManagerService,
+ @IFormulaInputService private readonly _formulaInputService: IFormulaInputService
) {
super();
@@ -162,8 +145,6 @@ export class PromptController extends Disposable {
}
private _resetTemp() {
- this._lastSequenceNodes = [];
-
this._previousSequenceNodes = null;
this._previousInsertRefStringIndex = null;
@@ -174,13 +155,9 @@ export class PromptController extends Disposable {
this._isSelectionMovingRefSelections = [];
- this._isLockedOnSelectionChangeRefString = false;
-
this._previousRangesCount = 0;
this._currentInsertRefStringIndex = -1;
-
- this._isSelectionMoving = false;
}
private _initialize(): void {
@@ -201,6 +178,8 @@ export class PromptController extends Disposable {
this._commandExecutedListener();
this._cursorStateListener();
+
+ this._syncEditorListener();
}
private _initialFormulaTheme() {
@@ -230,7 +209,10 @@ export class PromptController extends Disposable {
this.disposeWithMe(
toDisposable(
this._textSelectionRenderManager.textSelection$.subscribe(() => {
- if (this._editorBridgeService.isVisible().visible === false || this._isSelectionMoving === true) {
+ if (
+ this._editorBridgeService.isVisible().visible === false ||
+ this._formulaInputService.isSelectionMoving()
+ ) {
return;
}
@@ -244,7 +226,7 @@ export class PromptController extends Disposable {
this._switchSelectionPlugin();
- if (this._isLockedOnSelectionChangeRefString) {
+ if (this._formulaInputService.isLockedSelectionChange()) {
return;
}
@@ -350,7 +332,7 @@ export class PromptController extends Disposable {
const current = this._selectionManagerService.getCurrent();
- this._isSelectionMoving = false;
+ this._formulaInputService.disableSelectionMoving();
if (current?.pluginName !== FORMULA_REF_SELECTION_PLUGIN_NAME) {
return;
@@ -381,7 +363,7 @@ export class PromptController extends Disposable {
disposableCollection.add(
toDisposable(
controlSelection.selectionMoved$.subscribe(() => {
- this._isLockedOnSelectionChangeRefString = false;
+ this._formulaInputService.disableLockedSelectionChange();
})
)
);
@@ -389,7 +371,7 @@ export class PromptController extends Disposable {
disposableCollection.add(
toDisposable(
controlSelection.selectionScaled$.subscribe(() => {
- this._isLockedOnSelectionChangeRefString = false;
+ this._formulaInputService.disableLockedSelectionChange();
})
)
);
@@ -399,41 +381,38 @@ export class PromptController extends Disposable {
);
}
- private _initialRefSelectionInsertEvent() {
+ private _syncEditorListener() {
this.disposeWithMe(
toDisposable(
- this._selectionRenderService.selectionMoving$.subscribe((ranges) => {
- if (ranges == null) {
- return;
- }
-
- if (!this._isLockedOnSelectionInsertRefString) {
- return;
- }
-
- this._isSelectionMoving = true;
-
- this._inertControlSelection(ranges);
+ this._formulaInputService.syncToEditor$.subscribe((param) => {
+ const { sequences, textSelectionOffset } = param;
+ this._syncToEditor(sequences, textSelectionOffset);
})
)
);
+ }
- this.disposeWithMe(
- toDisposable(
- this._selectionRenderService.selectionMoveStart$.subscribe((ranges) => {
- if (ranges == null) {
- return;
- }
+ private _selectionChanging(ranges: Nullable<IRange[]>) {
+ if (ranges == null) {
+ return;
+ }
- if (!this._isLockedOnSelectionInsertRefString) {
- return;
- }
+ if (!this._formulaInputService.isLockedSelectionInsert()) {
+ return;
+ }
- this._isSelectionMoving = true;
+ this._formulaInputService.enableSelectionMoving();
- this._inertControlSelection(ranges);
- })
- )
+ this._inertControlSelection(ranges);
+ }
+
+ private _initialRefSelectionInsertEvent() {
+ this.disposeWithMe(
+ toDisposable(this._selectionRenderService.selectionMoving$.subscribe(this._selectionChanging.bind(this)))
+ );
+
+ this.disposeWithMe(
+ toDisposable(this._selectionRenderService.selectionMoveStart$.subscribe(this._selectionChanging.bind(this)))
);
}
@@ -441,8 +420,6 @@ export class PromptController extends Disposable {
this.disposeWithMe(
toDisposable(
this._formulaPromptService.acceptFormulaName$.subscribe((formulaString: string) => {
- console.log(`TODO: set ${formulaString} to cell editor`);
-
const activeRange = this._textSelectionRenderManager.getActiveRange();
if (activeRange == null) {
@@ -452,8 +429,11 @@ export class PromptController extends Disposable {
const { startOffset } = activeRange;
- const nodeIndex = this._searchSequenceIndex(this._lastSequenceNodes, startOffset - 2);
- const node = this._lastSequenceNodes[nodeIndex];
+ const lastSequenceNodes = this._formulaInputService.getSequenceNodes();
+
+ const nodeIndex = this._formulaInputService.getCurrentSequenceNodeIndex(startOffset - 2);
+
+ const node = lastSequenceNodes[nodeIndex];
if (node == null || typeof node === 'string') {
this._hideFunctionPanel();
@@ -466,12 +446,12 @@ export class PromptController extends Disposable {
node.endIndex += difference;
- this._lastSequenceNodes.splice(nodeIndex + 1, 0, matchToken.OPEN_BRACKET);
+ lastSequenceNodes.splice(nodeIndex + 1, 0, matchToken.OPEN_BRACKET);
const formulaStringCount = formulaString.length + 1;
- for (let i = nodeIndex + 2, len = this._lastSequenceNodes.length; i < len; i++) {
- const node = this._lastSequenceNodes[i];
+ for (let i = nodeIndex + 2, len = lastSequenceNodes.length; i < len; i++) {
+ const node = lastSequenceNodes[i];
if (typeof node === 'string') {
continue;
}
@@ -480,7 +460,7 @@ export class PromptController extends Disposable {
node.endIndex += formulaStringCount;
}
- this._sycToEditor(this._lastSequenceNodes, node.endIndex + 2);
+ this._syncToEditor(lastSequenceNodes, node.endIndex + 2);
})
)
);
@@ -496,8 +476,7 @@ export class PromptController extends Disposable {
const { startOffset } = activeRange;
- const currentSequenceNode =
- this._lastSequenceNodes[this._searchSequenceIndex(this._lastSequenceNodes, startOffset - 2)];
+ const currentSequenceNode = this._formulaInputService.getCurrentSequenceNode(startOffset - 2);
if (currentSequenceNode == null) {
this._hideFunctionPanel();
@@ -569,61 +548,6 @@ export class PromptController extends Disposable {
});
}
- // // TODO@Dushusir: remove after use real text info
- // private _setFunctionPanel(currentInputValue: string) {
- // let param: IFunctionPanelParam = {
- // visibleSearch: false,
- // visibleHelp: false,
- // searchText: '',
- // paramIndex: 0,
- // functionInfo: {} as IFunctionInfo,
- // searchList: [],
- // };
-
- // if (this._getContextState()) {
- // currentInputValue = currentInputValue.split('\r\n')[0].toLocaleUpperCase();
-
- // const searchText = currentInputValue.substring(1);
-
- // // TODO@Dushusir: remove after use real text info
- // const matchList = ['SUM', 'AVERAGE'];
-
- // // help function
- // if (matchList.includes(searchText)) {
- // const paramIndex = Math.random() > 0.5 ? 0 : 1;
-
- // const functionInfo = this._descriptionService.getFunctionInfo(searchText);
- // param = {
- // visibleSearch: false,
- // visibleHelp: !!functionInfo,
- // searchText,
- // paramIndex,
- // functionInfo,
- // };
- // } else {
- // const searchList = this._descriptionService.getSearchListByName(searchText);
- // param = {
- // visibleSearch: searchList.length > 0,
- // visibleHelp: false,
- // searchText,
- // paramIndex: 0,
- // searchList,
- // };
- // }
- // }
-
- // this._commandService.executeCommand(SearchFunctionOperation.id, {
- // visible: param.visibleSearch,
- // searchText: param.searchText,
- // searchList: param.searchList,
- // });
- // this._commandService.executeCommand(HelpFunctionOperation.id, {
- // visible: param.visibleHelp,
- // paramIndex: param.paramIndex,
- // functionInfo: param.functionInfo,
- // });
- // }
-
/**
* If the cursor is located at a formula token,
* it is necessary to prohibit the behavior of closing the editor by clicking on the canvas,
@@ -645,7 +569,7 @@ export class PromptController extends Disposable {
if (this._matchRefDrawToken(char)) {
this._editorBridgeService.enableForceKeepVisible();
- this._isLockedOnSelectionInsertRefString = true;
+ this._formulaInputService.enableLockedSelectionInsert();
this._selectionRenderService.enableRemainLast();
@@ -704,7 +628,7 @@ export class PromptController extends Disposable {
private _disableForceKeepVisible() {
this._editorBridgeService.disableForceKeepVisible();
- this._isLockedOnSelectionInsertRefString = false;
+ this._formulaInputService.disableLockedSelectionInsert();
this._currentInsertRefStringIndex = -1;
this._selectionRenderService.disableRemainLast();
@@ -715,7 +639,11 @@ export class PromptController extends Disposable {
}
private _getCurrentBody() {
- const documentModel = this._currentUniverService.getUniverDocInstance(DOCS_NORMAL_EDITOR_UNIT_ID_KEY);
+ const editorUnitId = this._editorBridgeService.getCurrentEditorId();
+ if (editorUnitId == null) {
+ return;
+ }
+ const documentModel = this._currentUniverService.getUniverDocInstance(editorUnitId);
return documentModel?.snapshot?.body;
}
@@ -730,11 +658,13 @@ export class PromptController extends Disposable {
if (isFormulaString(currentInputValue)) {
this._contextService.setContextValue(FOCUSING_EDITOR_INPUT_FORMULA, true);
- this._lastSequenceNodes =
+ const lastSequenceNodes =
this._formulaEngineService.buildSequenceNodes(
currentInputValue.replace(/\r/g, '').replace(/\n/g, '')
) || [];
+ this._formulaInputService.setSequenceNodes(lastSequenceNodes);
+
const activeRange = this._textSelectionRenderManager.getActiveRange();
if (activeRange == null) {
@@ -746,10 +676,14 @@ export class PromptController extends Disposable {
this._currentInsertRefStringIndex = startOffset - 1;
} else {
this._contextService.setContextValue(FOCUSING_EDITOR_INPUT_FORMULA, false);
- this._isLockedOnSelectionChangeRefString = false;
- this._isLockedOnSelectionInsertRefString = false;
- this._lastSequenceNodes = [];
+ this._formulaInputService.disableLockedSelectionChange();
+
+ this._formulaInputService.disableLockedSelectionInsert();
+
+ // this._lastSequenceNodes = [];
+
+ this._formulaInputService.clearSequenceNodes();
this._hideFunctionPanel();
}
@@ -801,7 +735,7 @@ export class PromptController extends Disposable {
// dataStream.replace(/\r/g, '').replace(/\n/g, '')
// );
- const sequenceNodes = this._lastSequenceNodes;
+ const sequenceNodes = this._formulaInputService.getSequenceNodes();
this._selectionManagerService.clear();
@@ -1027,148 +961,13 @@ export class PromptController extends Disposable {
});
}
- /**
- * Synchronize the reference text based on the changes of the selection.
- * @param refIndex
- * @param rangeWithCoord
- * @returns
- */
- private _updateSequenceRef(
- sequenceNodes: Array<string | ISequenceNode>,
- refIndex: number,
- rangeWithCoord: Nullable<IRangeWithCoord>
- ) {
- if (rangeWithCoord == null) {
- return;
- }
- const { startRow, endRow, startColumn, endColumn } = rangeWithCoord;
- const refString = this._getRefString({
- startRow,
- endRow,
- startColumn,
- endColumn,
- });
-
- const node = sequenceNodes[refIndex];
-
- if (typeof node === 'string' || node.nodeType !== sequenceNodeType.REFERENCE) {
- return;
- }
-
- const difference = refString.length - node.token.length;
-
- node.token = refString;
-
- node.endIndex += difference;
-
- for (let i = refIndex + 1, len = sequenceNodes.length; i < len; i++) {
- const node = sequenceNodes[i];
- if (typeof node === 'string') {
- continue;
- }
-
- node.startIndex += difference;
- node.endIndex += difference;
- }
-
- this._sycToEditor(sequenceNodes, node.endIndex + 1);
- }
-
- /**
- * When the cursor is on the right side of a formula token,
- * you can add reference text to the formula by drawing a selection.
- * @param index
- * @param range
- */
- private _insertSequenceRef(sequenceNodes: Array<string | ISequenceNode>, index: number, range: Nullable<IRange>) {
- if (range == null) {
- return;
- }
-
- const refString = this._getRefString(range);
-
- const refStringCount = refString.length;
-
- const nodeIndex = this._searchSequenceIndex(sequenceNodes, index);
-
- sequenceNodes.splice(nodeIndex, 0, {
- token: refString,
- startIndex: index,
- endIndex: index + refStringCount - 1,
- nodeType: sequenceNodeType.REFERENCE,
- });
-
- for (let i = nodeIndex + 1, len = sequenceNodes.length; i < len; i++) {
- const node = sequenceNodes[i];
- if (typeof node === 'string') {
- continue;
- }
-
- node.startIndex += refStringCount;
- node.endIndex += refStringCount;
- }
-
- this._sycToEditor(sequenceNodes, index + refStringCount);
- }
-
- /**
- * Insert a string at the cursor position in the text corresponding to the sequenceNodes.
- * @param sequenceNodes
- * @param index
- * @param content
- */
- private _insertSequenceString(sequenceNodes: Array<string | ISequenceNode>, index: number, content: string) {
- const nodeIndex = this._searchSequenceIndex(sequenceNodes, index);
- const str = content.split('');
- sequenceNodes.splice(nodeIndex, 0, ...str);
-
- const contentCount = str.length;
-
- for (let i = nodeIndex + contentCount, len = sequenceNodes.length; i < len; i++) {
- const node = sequenceNodes[i];
- if (typeof node === 'string') {
- continue;
- }
-
- node.startIndex += contentCount;
- node.endIndex += contentCount;
- }
- }
-
- /**
- * Query the text coordinates in the sequenceNodes and determine the actual insertion index.
- * @param sequenceNodes
- * @param strIndex
- * @returns
- */
- private _searchSequenceIndex(sequenceNodes: Array<string | ISequenceNode>, strIndex: number) {
- let nodeIndex = 0;
- for (let i = 0, len = sequenceNodes.length; i < len; i++) {
- const node = sequenceNodes[i];
-
- if (typeof node === 'string') {
- nodeIndex++;
- } else {
- const { endIndex } = node;
-
- nodeIndex = endIndex;
- }
-
- if (strIndex <= nodeIndex) {
- return i;
- }
- }
-
- return sequenceNodes.length;
- }
-
/**
* Restore the sequenceNode generated by the lexer to the text in the editor, and set the cursor position.
* @param sequenceNodes
* @param textSelectionOffset
* @returns
*/
- private async _sycToEditor(sequenceNodes: Array<string | ISequenceNode>, textSelectionOffset: number) {
+ private async _syncToEditor(sequenceNodes: Array<string | ISequenceNode>, textSelectionOffset: number) {
const dataStream = this._generateStringWithSequence(sequenceNodes);
const { textRuns, refSelections } = this._buildTextRuns(sequenceNodes);
@@ -1187,9 +986,7 @@ export class PromptController extends Disposable {
this._currentInsertRefStringIndex = textSelectionOffset;
- await this._commandService.syncExecuteCommand(SetEditorResizeOperation.id, {
- unitId: DOCS_NORMAL_EDITOR_UNIT_ID_KEY,
- });
+ await this._fitEditorSize();
this._textSelectionManagerService.replaceTextRanges([
{
@@ -1201,6 +998,17 @@ export class PromptController extends Disposable {
]);
}
+ private async _fitEditorSize() {
+ const editorUnitId = this._editorBridgeService.getCurrentEditorId();
+ if (editorUnitId == null) {
+ return;
+ }
+
+ await this._commandService.syncExecuteCommand(SetEditorResizeOperation.id, {
+ unitId: editorUnitId,
+ });
+ }
+
/**
* Deserialize Sequence to text.
* @param newSequenceNodes
@@ -1225,7 +1033,11 @@ export class PromptController extends Disposable {
* @returns
*/
private _updateEditorModel(dataStream: string, textRuns: ITextRun[]) {
- const documentModel = this._currentUniverService.getUniverDocInstance(DOCS_NORMAL_EDITOR_UNIT_ID_KEY);
+ const editorUnitId = this._editorBridgeService.getCurrentEditorId();
+ if (editorUnitId == null) {
+ return;
+ }
+ const documentModel = this._currentUniverService.getUniverDocInstance(editorUnitId);
const bodyModel = documentModel?.getBodyModel();
if (bodyModel == null) {
return;
@@ -1249,7 +1061,7 @@ export class PromptController extends Disposable {
private _inertControlSelectionReplace(currentRange: IRange) {
if (this._previousSequenceNodes == null) {
- this._previousSequenceNodes = this._lastSequenceNodes;
+ this._previousSequenceNodes = this._formulaInputService.getSequenceNodes();
}
if (this._previousInsertRefStringIndex == null) {
@@ -1262,9 +1074,13 @@ export class PromptController extends Disposable {
return;
}
- this._insertSequenceRef(insertNodes, this._previousInsertRefStringIndex, currentRange);
+ const refString = this._getRefString(currentRange);
- this._lastSequenceNodes = insertNodes;
+ this._formulaInputService.setSequenceNodes(insertNodes);
+
+ this._formulaInputService.insertSequenceRef(this._previousInsertRefStringIndex, refString);
+
+ this._syncToEditor(insertNodes, this._previousInsertRefStringIndex + refString.length);
const selectionDatas = this._selectionRenderService.getSelectionDataWithStyle();
@@ -1292,7 +1108,7 @@ export class PromptController extends Disposable {
this._inertControlSelectionReplace(currentRange);
} else {
// Holding down ctrl causes an addition, requiring the ref string to be increased.
- const insertNodes = this._lastSequenceNodes;
+ const insertNodes = this._formulaInputService.getSequenceNodes();
if (insertNodes == null) {
return;
@@ -1307,16 +1123,20 @@ export class PromptController extends Disposable {
this._previousInsertRefStringIndex = this._currentInsertRefStringIndex;
if (!this._matchRefDrawToken(char)) {
- this._insertSequenceString(insertNodes, this._currentInsertRefStringIndex, matchToken.COMMA);
+ this._formulaInputService.insertSequenceString(this._currentInsertRefStringIndex, matchToken.COMMA);
this._previousInsertRefStringIndex += 1;
}
this._previousSequenceNodes = Tools.deepClone(insertNodes);
- this._insertSequenceRef(insertNodes, this._previousInsertRefStringIndex, currentRange);
+ const refString = this._getRefString(currentRange);
+
+ this._formulaInputService.setSequenceNodes(insertNodes);
- this._lastSequenceNodes = insertNodes;
+ this._formulaInputService.insertSequenceRef(this._previousInsertRefStringIndex, refString);
+
+ // this._lastSequenceNodes = insertNodes;
this._selectionRenderService.disableSkipRemainLast();
}
@@ -1379,7 +1199,7 @@ export class PromptController extends Disposable {
return;
}
- this._isLockedOnSelectionChangeRefString = true;
+ this._formulaInputService.enableLockedSelectionChange();
const id = controlSelection.selectionStyle?.id;
@@ -1387,22 +1207,32 @@ export class PromptController extends Disposable {
return;
}
- this._updateSequenceRef(this._lastSequenceNodes, Number(id), toRange);
+ const { startRow, endRow, startColumn, endColumn } = toRange;
+ const refString = this._getRefString({
+ startRow,
+ endRow,
+ startColumn,
+ endColumn,
+ });
- controlSelection.update(toRange);
- }
+ const nodeIndex = Number(id);
- private _refreshEditorObject() {
- const editorObject = this._getEditorObject();
+ this._formulaInputService.updateSequenceRef(nodeIndex, refString);
- const documentComponent = editorObject?.document;
+ const sequenceNodes = this._formulaInputService.getSequenceNodes();
- documentComponent?.getSkeleton()?.calculate();
+ const node = sequenceNodes[nodeIndex];
- documentComponent?.makeDirty();
+ if (typeof node === 'string') {
+ return;
+ }
+
+ this._syncToEditor(sequenceNodes, node.endIndex + 1);
+
+ controlSelection.update(toRange);
}
- private _refreshFormulaBarEditorObject() {
+ private _refreshEditorObject() {
const editorObject = this._getEditorObject();
const documentComponent = editorObject?.document;
@@ -1576,10 +1406,6 @@ export class PromptController extends Disposable {
}
private _getEditorObject() {
- return getEditorObject(DOCS_NORMAL_EDITOR_UNIT_ID_KEY, this._renderManagerService);
- }
-
- private _getFormulaBarEditorObject() {
- return getEditorObject(DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY, this._renderManagerService);
+ return getEditorObject(this._editorBridgeService.getCurrentEditorId(), this._renderManagerService);
}
}
diff --git a/packages/sheets-plugin-formula-ui/src/controllers/shortcuts/prompt.shortcut.ts b/packages/sheets-plugin-formula-ui/src/controllers/shortcuts/prompt.shortcut.ts
index bfebd556fa..e6f2619eb4 100644
--- a/packages/sheets-plugin-formula-ui/src/controllers/shortcuts/prompt.shortcut.ts
+++ b/packages/sheets-plugin-formula-ui/src/controllers/shortcuts/prompt.shortcut.ts
@@ -3,6 +3,7 @@ import { IShortcutItem, KeyCode, MetaKeys } from '@univerjs/base-ui';
import { whenEditorInputFormulaActivated } from '@univerjs/ui-plugin-sheets';
import { SelectEditorFormulaOperation } from '../../commands/operations/editor-formula.operation';
+import { ReferenceAbsoluteOperation } from '../../commands/operations/reference-absolute.operation';
import { META_KEY_CTRL_AND_SHIFT } from '../../common/prompt';
export const PROMPT_SELECTION_KEYCODE_ARROW_LIST = [
@@ -80,3 +81,9 @@ export function promptSelectionShortcutItemCtrlAndShift() {
}
return shortcutList;
}
+
+export const ChangeRefToAbsoluteShortcut: IShortcutItem = {
+ id: ReferenceAbsoluteOperation.id,
+ binding: KeyCode.F4,
+ preconditions: (contextService) => whenEditorInputFormulaActivated(contextService),
+};
diff --git a/packages/sheets-plugin-formula-ui/src/formula-ui-plugin.ts b/packages/sheets-plugin-formula-ui/src/formula-ui-plugin.ts
index 91e9c33b79..d81c90a1b4 100644
--- a/packages/sheets-plugin-formula-ui/src/formula-ui-plugin.ts
+++ b/packages/sheets-plugin-formula-ui/src/formula-ui-plugin.ts
@@ -3,10 +3,12 @@ import { IUniverInstanceService, LocaleService, Plugin, PluginType } from '@univ
import { Dependency, Inject, Injector } from '@wendellhu/redi';
import { FORMULA_UI_PLUGIN_NAME } from './common/plugin-name';
+import { FormulaInputController } from './controllers/formula-input.controller';
import { FormulaUIController } from './controllers/formula-ui.controller';
import { PromptController } from './controllers/prompt.controller';
import { enUS } from './locale';
import { DescriptionService, IDescriptionService } from './services/description.service';
+import { FormulaInputService, IFormulaInputService } from './services/formula-input.service';
import { FormulaPromptService, IFormulaPromptService } from './services/prompt.service';
// TODO@Dushusir: user config IFunctionInfo, we will register all function info in formula engine
@@ -36,9 +38,11 @@ export class FormulaUIPlugin extends Plugin {
// services
[IFormulaPromptService, { useClass: FormulaPromptService }],
[IDescriptionService, { useValue: descriptionService }],
+ [IFormulaInputService, { useClass: FormulaInputService }],
// controllers
[FormulaUIController],
[PromptController],
+ [FormulaInputController],
];
dependencies.forEach((dependency) => this._injector.add(dependency));
diff --git a/packages/sheets-plugin-formula-ui/src/services/formula-input.service.ts b/packages/sheets-plugin-formula-ui/src/services/formula-input.service.ts
new file mode 100644
index 0000000000..9a7e68f91d
--- /dev/null
+++ b/packages/sheets-plugin-formula-ui/src/services/formula-input.service.ts
@@ -0,0 +1,256 @@
+import { FormulaEngineService, ISequenceNode, sequenceNodeType } from '@univerjs/base-formula-engine';
+import { createIdentifier, IDisposable, Inject } from '@wendellhu/redi';
+import { Observable, Subject } from 'rxjs';
+
+export interface ISyncToEditorParam {
+ textSelectionOffset: number;
+ sequences: Array<string | ISequenceNode>;
+}
+
+export interface IFormulaInputService {
+ syncToEditor$: Observable<ISyncToEditorParam>;
+
+ changeRef$: Observable<boolean>;
+
+ syncToEditor(textSelectionOffset: number): void;
+
+ dispose(): void;
+
+ getSequenceNodes(): Array<string | ISequenceNode>;
+
+ setSequenceNodes(nodes: Array<string | ISequenceNode>): void;
+
+ clearSequenceNodes(): void;
+
+ getCurrentSequenceNodeIndex(strIndex: number): number;
+
+ getCurrentSequenceNodeByIndex(nodeIndex: number): string | ISequenceNode;
+
+ getCurrentSequenceNode(strIndex: number): string | ISequenceNode;
+
+ updateSequenceRef(nodeIndex: number, refString: string): void;
+
+ insertSequenceRef(index: number, refString: string): void;
+
+ insertSequenceString(index: number, content: string): void;
+
+ enableSelectionMoving(): void;
+
+ disableSelectionMoving(): void;
+
+ isSelectionMoving(): boolean;
+
+ enableLockedSelectionChange(): void;
+
+ disableLockedSelectionChange(): void;
+
+ isLockedSelectionChange(): boolean;
+
+ enableLockedSelectionInsert(): void;
+
+ disableLockedSelectionInsert(): void;
+
+ isLockedSelectionInsert(): boolean;
+}
+
+export class FormulaInputService implements IFormulaInputService, IDisposable {
+ private _sequenceNodes: Array<string | ISequenceNode> = [];
+
+ private _isSelectionMoving = false;
+
+ private _isLockedOnSelectionChangeRefString: boolean = false;
+
+ private _isLockedOnSelectionInsertRefString: boolean = false;
+
+ private readonly _syncToEditor$ = new Subject<ISyncToEditorParam>();
+
+ readonly syncToEditor$ = this._syncToEditor$.asObservable();
+
+ private _changeRef$ = new Subject<boolean>();
+
+ readonly changeRef$ = this._changeRef$.asObservable();
+
+ constructor(@Inject(FormulaEngineService) private readonly _formulaEngineService: FormulaEngineService) {}
+
+ dispose(): void {
+ this._sequenceNodes = [];
+ }
+
+ syncToEditor(textSelectionOffset: number) {
+ this._syncToEditor$.next({ sequences: this._sequenceNodes, textSelectionOffset });
+ }
+
+ getSequenceNodes() {
+ return this._sequenceNodes;
+ }
+
+ setSequenceNodes(nodes: Array<string | ISequenceNode>) {
+ this._sequenceNodes = nodes;
+ }
+
+ clearSequenceNodes() {
+ this._sequenceNodes = [];
+ }
+
+ getCurrentSequenceNode(strIndex: number) {
+ return this._sequenceNodes[this.getCurrentSequenceNodeIndex(strIndex)];
+ }
+
+ getCurrentSequenceNodeByIndex(nodeIndex: number) {
+ return this._sequenceNodes[nodeIndex];
+ }
+
+ /**
+ * Query the text coordinates in the sequenceNodes and determine the actual insertion index.
+ * @param sequenceNodes
+ * @param strIndex
+ * @returns
+ */
+ getCurrentSequenceNodeIndex(strIndex: number) {
+ let nodeIndex = 0;
+ for (let i = 0, len = this._sequenceNodes.length; i < len; i++) {
+ const node = this._sequenceNodes[i];
+
+ if (typeof node === 'string') {
+ nodeIndex++;
+ } else {
+ const { endIndex } = node;
+
+ nodeIndex = endIndex;
+ }
+
+ if (strIndex <= nodeIndex) {
+ return i;
+ }
+ }
+
+ return this._sequenceNodes.length;
+ }
+
+ /**
+ * Synchronize the reference text based on the changes of the selection.
+ * @param refIndex
+ * @param rangeWithCoord
+ * @returns
+ */
+ updateSequenceRef(nodeIndex: number, refString: string) {
+ const node = this._sequenceNodes[nodeIndex];
+
+ if (typeof node === 'string' || node.nodeType !== sequenceNodeType.REFERENCE) {
+ return;
+ }
+
+ const difference = refString.length - node.token.length;
+
+ node.token = refString;
+
+ node.endIndex += difference;
+
+ for (let i = nodeIndex + 1, len = this._sequenceNodes.length; i < len; i++) {
+ const node = this._sequenceNodes[i];
+ if (typeof node === 'string') {
+ continue;
+ }
+
+ node.startIndex += difference;
+ node.endIndex += difference;
+ }
+
+ this._changeRef$.next(true);
+ }
+
+ /**
+ * When the cursor is on the right side of a formula token,
+ * you can add reference text to the formula by drawing a selection.
+ * @param index
+ * @param range
+ */
+ insertSequenceRef(index: number, refString: string) {
+ const refStringCount = refString.length;
+
+ const nodeIndex = this.getCurrentSequenceNodeIndex(index);
+
+ this._sequenceNodes.splice(nodeIndex, 0, {
+ token: refString,
+ startIndex: index,
+ endIndex: index + refStringCount - 1,
+ nodeType: sequenceNodeType.REFERENCE,
+ });
+
+ for (let i = nodeIndex + 1, len = this._sequenceNodes.length; i < len; i++) {
+ const node = this._sequenceNodes[i];
+ if (typeof node === 'string') {
+ continue;
+ }
+
+ node.startIndex += refStringCount;
+ node.endIndex += refStringCount;
+ }
+
+ this._changeRef$.next(true);
+ }
+
+ /**
+ * Insert a string at the cursor position in the text corresponding to the sequenceNodes.
+ * @param sequenceNodes
+ * @param index
+ * @param content
+ */
+ insertSequenceString(index: number, content: string) {
+ const nodeIndex = this.getCurrentSequenceNodeIndex(index);
+ const str = content.split('');
+ this._sequenceNodes.splice(nodeIndex, 0, ...str);
+
+ const contentCount = str.length;
+
+ for (let i = nodeIndex + contentCount, len = this._sequenceNodes.length; i < len; i++) {
+ const node = this._sequenceNodes[i];
+ if (typeof node === 'string') {
+ continue;
+ }
+
+ node.startIndex += contentCount;
+ node.endIndex += contentCount;
+ }
+
+ this._changeRef$.next(true);
+ }
+
+ enableSelectionMoving() {
+ this._isSelectionMoving = true;
+ }
+
+ disableSelectionMoving() {
+ this._isSelectionMoving = false;
+ }
+
+ isSelectionMoving() {
+ return this._isSelectionMoving;
+ }
+
+ enableLockedSelectionChange() {
+ this._isLockedOnSelectionChangeRefString = true;
+ }
+
+ disableLockedSelectionChange() {
+ this._isLockedOnSelectionChangeRefString = false;
+ }
+
+ isLockedSelectionChange() {
+ return this._isLockedOnSelectionChangeRefString;
+ }
+
+ enableLockedSelectionInsert() {
+ this._isLockedOnSelectionInsertRefString = true;
+ }
+
+ disableLockedSelectionInsert() {
+ this._isLockedOnSelectionInsertRefString = false;
+ }
+
+ isLockedSelectionInsert() {
+ return this._isLockedOnSelectionInsertRefString;
+ }
+}
+
+export const IFormulaInputService = createIdentifier<FormulaInputService>('formula-ui.input-service');
diff --git a/packages/ui-plugin-sheets/src/basics/editor/get-editor-object.ts b/packages/ui-plugin-sheets/src/basics/editor/get-editor-object.ts
index a57ac01f0a..af8e32d8a8 100644
--- a/packages/ui-plugin-sheets/src/basics/editor/get-editor-object.ts
+++ b/packages/ui-plugin-sheets/src/basics/editor/get-editor-object.ts
@@ -8,9 +8,13 @@ export interface IDocObjectParam {
}
export function getEditorObject(
- unitId: string,
+ unitId: Nullable<string>,
renderManagerService: IRenderManagerService
): Nullable<IDocObjectParam> {
+ if (unitId == null) {
+ return;
+ }
+
const currentRender = renderManagerService.getRenderById(unitId);
if (currentRender == null) {
diff --git a/packages/ui-plugin-sheets/src/controllers/editor-bridge.controller.ts b/packages/ui-plugin-sheets/src/controllers/editor-bridge.controller.ts
index f6d71f3fd2..726aeecdda 100644
--- a/packages/ui-plugin-sheets/src/controllers/editor-bridge.controller.ts
+++ b/packages/ui-plugin-sheets/src/controllers/editor-bridge.controller.ts
@@ -7,6 +7,7 @@ import {
} from '@univerjs/base-sheets';
import {
Disposable,
+ DOCS_NORMAL_EDITOR_UNIT_ID_KEY,
ICommandInfo,
ICommandService,
IUniverInstanceService,
@@ -23,11 +24,6 @@ import { ISelectionRenderService } from '../services/selection/selection-render.
import { SheetSkeletonManagerService } from '../services/sheet-skeleton-manager.service';
import { getSheetObject } from './utils/component-tools';
-interface ISetWorksheetMutationParams {
- workbookId: string;
- worksheetId: string;
-}
-
@OnLifecycle(LifecycleStages.Rendered, EditorBridgeController)
export class EditorBridgeController extends Disposable {
constructor(
@@ -139,6 +135,7 @@ export class EditorBridgeController extends Disposable {
unitId,
sheetId,
documentLayoutObject,
+ editorUnitId: DOCS_NORMAL_EDITOR_UNIT_ID_KEY,
});
});
}
diff --git a/packages/ui-plugin-sheets/src/controllers/editor/end-edit.controller.ts b/packages/ui-plugin-sheets/src/controllers/editor/end-edit.controller.ts
index 7825cf9bc9..cbd64451ce 100644
--- a/packages/ui-plugin-sheets/src/controllers/editor/end-edit.controller.ts
+++ b/packages/ui-plugin-sheets/src/controllers/editor/end-edit.controller.ts
@@ -7,8 +7,6 @@ import {
DEFAULT_EMPTY_DOCUMENT_VALUE,
Direction,
Disposable,
- DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY,
- DOCS_NORMAL_EDITOR_UNIT_ID_KEY,
DocumentModel,
FOCUSING_EDITOR,
FOCUSING_EDITOR_BUT_HIDDEN,
@@ -195,8 +193,11 @@ export class EndEditController extends Disposable {
this._cellEditorManagerService.setState({
show: param.visible,
});
- this._undoRedoService.clearUndoRedo(DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY);
- this._undoRedoService.clearUndoRedo(DOCS_NORMAL_EDITOR_UNIT_ID_KEY);
+ const editorUnitId = this._editorBridgeService.getCurrentEditorId();
+ if (editorUnitId == null) {
+ return;
+ }
+ this._undoRedoService.clearUndoRedo(editorUnitId);
}
private _moveCursor(keycode?: KeyCode) {
@@ -307,10 +308,6 @@ export class EndEditController extends Disposable {
}
private _getEditorObject() {
- return getEditorObject(DOCS_NORMAL_EDITOR_UNIT_ID_KEY, this._renderManagerService);
- }
-
- private _getFormulaBarEditorObject() {
- return getEditorObject(DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY, this._renderManagerService);
+ return getEditorObject(this._editorBridgeService.getCurrentEditorId(), this._renderManagerService);
}
}
diff --git a/packages/ui-plugin-sheets/src/controllers/editor/start-edit.controller.ts b/packages/ui-plugin-sheets/src/controllers/editor/start-edit.controller.ts
index 825dac9459..b72cfc5c56 100644
--- a/packages/ui-plugin-sheets/src/controllers/editor/start-edit.controller.ts
+++ b/packages/ui-plugin-sheets/src/controllers/editor/start-edit.controller.ts
@@ -117,7 +117,7 @@ export class StartEditController extends Disposable {
return;
}
- const { position, documentLayoutObject, scaleX } = param;
+ const { position, documentLayoutObject, scaleX, editorUnitId } = param;
const editorObject = this._getEditorObject();
@@ -133,7 +133,7 @@ export class StartEditController extends Disposable {
const { a: angle } = textRotation as ITextRotation;
- documentModel!.updateDocumentId(DOCS_NORMAL_EDITOR_UNIT_ID_KEY);
+ documentModel!.updateDocumentId(editorUnitId);
// documentModel!.updateDocumentDataMargin(paddingData);
@@ -141,9 +141,9 @@ export class StartEditController extends Disposable {
documentModel!.updateDocumentDataPageSize((endX - startX) / scaleX);
}
- this._currentUniverService.changeDoc(DOCS_NORMAL_EDITOR_UNIT_ID_KEY, documentModel! as DocumentModel);
+ this._currentUniverService.changeDoc(editorUnitId, documentModel! as DocumentModel);
- const docParam = this._docSkeletonManagerService.updateCurrent({ unitId: DOCS_NORMAL_EDITOR_UNIT_ID_KEY });
+ const docParam = this._docSkeletonManagerService.updateCurrent({ unitId: editorUnitId });
if (docParam == null) {
return;
@@ -350,9 +350,9 @@ export class StartEditController extends Disposable {
this._addBackground(scene, editorWidth, editorHeight, fill);
// resize canvas
- setTimeout(() => {
+ requestIdleCallback(() => {
engine.resizeBySize(editorWidth, physicHeight);
- }, 0);
+ });
this._cellEditorManagerService.setState({
startX,
@@ -550,7 +550,7 @@ export class StartEditController extends Disposable {
// Listen to document edits to refresh the size of the editor.
const updateCommandList = [RichTextEditingMutation.id, SetEditorResizeOperation.id];
- const excludeUnitList = [DOCS_NORMAL_EDITOR_UNIT_ID_KEY];
+ const excludeUnitList = [DOCS_NORMAL_EDITOR_UNIT_ID_KEY, DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY];
this.disposeWithMe(
this._commandService.onCommandExecuted((command: ICommandInfo) => {
@@ -598,10 +598,6 @@ export class StartEditController extends Disposable {
}
private _getEditorObject() {
- return getEditorObject(DOCS_NORMAL_EDITOR_UNIT_ID_KEY, this._renderManagerService);
- }
-
- private _getFormulaBarEditorObject() {
- return getEditorObject(DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY, this._renderManagerService);
+ return getEditorObject(this._editorBridgeService.getCurrentEditorId(), this._renderManagerService);
}
}
diff --git a/packages/ui-plugin-sheets/src/services/editor-bridge.service.ts b/packages/ui-plugin-sheets/src/services/editor-bridge.service.ts
index bb2de31dd9..6d5b3d23db 100644
--- a/packages/ui-plugin-sheets/src/services/editor-bridge.service.ts
+++ b/packages/ui-plugin-sheets/src/services/editor-bridge.service.ts
@@ -20,6 +20,7 @@ export interface IEditorBridgeServiceParam {
documentLayoutObject: IDocumentLayoutObject;
scaleX: number;
scaleY: number;
+ editorUnitId: string;
}
export interface IEditorBridgeService {
@@ -33,6 +34,7 @@ export interface IEditorBridgeService {
enableForceKeepVisible(): void;
disableForceKeepVisible(): void;
isForceKeepVisible(): boolean;
+ getCurrentEditorId(): Nullable<string>;
}
export class EditorBridgeService implements IEditorBridgeService, IDisposable {
@@ -69,6 +71,10 @@ export class EditorBridgeService implements IEditorBridgeService, IDisposable {
return this._state;
}
+ getCurrentEditorId() {
+ return this._state?.editorUnitId;
+ }
+
changeVisible(param: IEditorBridgeServiceVisibleParam) {
this._visible = param;
diff --git a/packages/ui-plugin-sheets/src/views/editor-container/EditorContainer.tsx b/packages/ui-plugin-sheets/src/views/editor-container/EditorContainer.tsx
index 9e8478cd21..036f552984 100644
--- a/packages/ui-plugin-sheets/src/views/editor-container/EditorContainer.tsx
+++ b/packages/ui-plugin-sheets/src/views/editor-container/EditorContainer.tsx
@@ -18,6 +18,10 @@ const EDITOR_DEFAULT_POSITION = {
left: HIDDEN_EDITOR_POSITION,
};
+/**
+ * Floating editor's container.
+ * @returns
+ */
export const EditorContainer: React.FC<ICellIEditorProps> = () => {
const [state, setState] = useState({
...EDITOR_DEFAULT_POSITION,
diff --git a/packages/ui-plugin-sheets/src/views/sheet-canvas-view.ts b/packages/ui-plugin-sheets/src/views/sheet-canvas-view.ts
index 37cf8fbcfb..ec26b6463b 100644
--- a/packages/ui-plugin-sheets/src/views/sheet-canvas-view.ts
+++ b/packages/ui-plugin-sheets/src/views/sheet-canvas-view.ts
@@ -63,24 +63,6 @@ export class SheetCanvasView {
this._addNewRender();
this._loadedMap.add(unitId);
}
-
- // if (!this._isLoadedEditor) {
- // // create univer doc normal editor instance
-
- // this._currentUniverService.createDoc({
- // id: DOCS_NORMAL_EDITOR_UNIT_ID_KEY,
- // documentStyle: {},
- // });
-
- // // create univer doc formula bar editor instance
-
- // this._currentUniverService.createDoc({
- // id: DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY,
- // documentStyle: {},
- // });
-
- // this._isLoadedEditor = true;
- // }
});
}