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.

fix(sheet): formula input (#504)

Univerb05ecc9082cf
diff --git a/packages/base-formula-engine/src/analysis/lexer.ts b/packages/base-formula-engine/src/analysis/lexer.ts
index 75560932b4..b0cfc15267 100644
--- a/packages/base-formula-engine/src/analysis/lexer.ts
+++ b/packages/base-formula-engine/src/analysis/lexer.ts
@@ -89,37 +89,96 @@ export class LexerTreeBuilder extends Disposable {
return this._currentLexerNode;
}
- checkIfAddBracket(formulaString: string) {
- const lastString = formulaString[formulaString.length - 1];
+ getFunctionAndParameter(formulaString: string, strIndex: number) {
+ const current = this._getCurrentParamIndex(formulaString, strIndex);
+
+ if (current == null || current === ErrorType.VALUE) {
+ return;
+ }
+
+ const lexerNode = current[0];
+
+ if (typeof lexerNode === 'string') {
+ return;
+ }
+
+ let parent = lexerNode.getParent();
+
+ let children = lexerNode;
+
+ while (parent) {
+ const token = parent.getToken();
+ if (
+ token !== DEFAULT_TOKEN_TYPE_PARAMETER &&
+ !isFormulaLexerToken(token) &&
+ parent.getStartIndex() !== -1
+ ) {
+ const paramIndex = parent.getChildren().indexOf(children);
+
+ return {
+ functionName: token,
+ paramIndex,
+ };
+ }
+
+ children = parent;
+ parent = parent.getParent();
+ }
+ }
- if (lastString === matchToken.CLOSE_BRACKET) {
- return false;
+ /**
+ * Estimate the number of right brackets that need to be automatically added to the end of the formula.
+ * @param formulaString
+ * @returns
+ */
+ checkIfAddBracket(formulaString: string) {
+ let lastBracketCount = 0;
+ let lastIndex = formulaString.length - 1;
+ let lastString = formulaString[lastIndex];
+ /**
+ * Determine how many close brackets are at the end, and estimate how many functions need to automatically add close brackets.
+ */
+ while (lastString === matchToken.CLOSE_BRACKET || lastString === ' ') {
+ if (lastString === matchToken.CLOSE_BRACKET) {
+ lastBracketCount++;
+ }
+ lastString = formulaString[--lastIndex];
}
const current = this._getCurrentParamIndex(formulaString, formulaString.length - 2);
if (current == null || current === ErrorType.VALUE) {
- return false;
+ return 0;
}
const lexerNode = current[0];
if (typeof lexerNode === 'string') {
- return false;
+ return 0;
}
let parent = lexerNode.getParent();
+ let bracketCount = 0;
+ /**
+ * Perform an upward search on the syntax tree to see how many layers the function is nested.
+ * For each layer passed, subtract the estimated number of right brackets,
+ * ultimately obtaining the number of right brackets that need to be completed.
+ */
while (parent) {
const token = parent.getToken();
if (token !== DEFAULT_TOKEN_TYPE_PARAMETER && token !== matchToken.COLON && parent.getStartIndex() !== -1) {
- return true;
+ if (lastBracketCount === 0) {
+ bracketCount += 1;
+ } else {
+ lastBracketCount--;
+ }
}
parent = parent.getParent();
}
- return false;
+ return bracketCount;
}
sequenceNodesBuilder(formulaString: string) {
diff --git a/packages/base-formula-engine/src/services/formula-engine.service.ts b/packages/base-formula-engine/src/services/formula-engine.service.ts
index 497b6495ab..11f2861fbe 100644
--- a/packages/base-formula-engine/src/services/formula-engine.service.ts
+++ b/packages/base-formula-engine/src/services/formula-engine.service.ts
@@ -151,6 +151,10 @@ export class FormulaEngineService extends Disposable {
return this.lexerTreeBuilder.checkIfAddBracket(formulaString);
}
+ getFunctionAndParameter(formulaString: string, strIndex: number) {
+ return this.lexerTreeBuilder.getFunctionAndParameter(formulaString, strIndex);
+ }
+
/**
*
* @param unitId
diff --git a/packages/base-render/src/components/docs/document.ts b/packages/base-render/src/components/docs/document.ts
index 5eee2e4b1a..937297b50f 100644
--- a/packages/base-render/src/components/docs/document.ts
+++ b/packages/base-render/src/components/docs/document.ts
@@ -27,13 +27,13 @@ import { DocComponent } from './doc-component';
import { DOCS_EXTENSION_TYPE } from './doc-extension';
import { DocumentSkeleton } from './doc-skeleton';
-interface PageMarginLayout {
+interface IPageMarginLayout {
pageMarginLeft: number;
pageMarginTop: number;
pageLayoutType?: PageLayoutType;
}
-export interface IDocumentsConfig extends PageMarginLayout {
+export interface IDocumentsConfig extends IPageMarginLayout {
allowCache?: boolean;
hasEditor?: boolean;
}
@@ -45,7 +45,7 @@ export interface IPageRenderConfig {
ctx: CanvasRenderingContext2D;
}
-export interface IDocumentOffsetConfig extends PageMarginLayout {
+export interface IDocumentOffsetConfig extends IPageMarginLayout {
docsLeft: number;
docsTop: number;
documentTransform: Transform;
diff --git a/packages/core/src/shared/common.ts b/packages/core/src/shared/common.ts
index b52f67b921..6bc7daeeef 100644
--- a/packages/core/src/shared/common.ts
+++ b/packages/core/src/shared/common.ts
@@ -127,7 +127,7 @@ export function getColorStyle(color: Nullable<IColorStyle>): Nullable<string> {
}
export function isFormulaString(value: any): boolean {
- return Tools.isString(value) && value.indexOf('=') === 0 && value.length > 1;
+ return Tools.isString(value) && value.substring(0, 1) === '=' && value.length > 1;
}
export function isFormulaId(value: any): boolean {
diff --git a/packages/sheets-plugin-formula-ui/src/commands/operations/editor-formula.operation.ts b/packages/sheets-plugin-formula-ui/src/commands/operations/editor-formula.operation.ts
index 6cf4ea39b7..2eff05a4bd 100644
--- a/packages/sheets-plugin-formula-ui/src/commands/operations/editor-formula.operation.ts
+++ b/packages/sheets-plugin-formula-ui/src/commands/operations/editor-formula.operation.ts
@@ -2,11 +2,9 @@
import { DeviceInputEventType } from '@univerjs/base-render';
import { KeyCode, MetaKeys } from '@univerjs/base-ui';
-import { CommandType, Direction, IOperation } from '@univerjs/core';
-import { IEditorBridgeService } from '@univerjs/ui-plugin-sheets';
+import { CommandType, IOperation } from '@univerjs/core';
import { META_KEY_CTRL_AND_SHIFT } from '../../common/prompt';
-import { IFormulaPromptService } from '../../services/prompt.service';
export interface ISelectEditorFormulaOperationParam {
eventType: DeviceInputEventType;
@@ -17,36 +15,35 @@ export interface ISelectEditorFormulaOperationParam {
export const SelectEditorFormulaOperation: IOperation<ISelectEditorFormulaOperationParam> = {
id: 'formula-ui.operation.select-editor-formula',
type: CommandType.OPERATION,
- handler: (accessor, params) => {
- const { eventType, keycode } = params;
- const formulaPromptService = accessor.get(IFormulaPromptService);
- const editorBridgeService = accessor.get(IEditorBridgeService);
+ handler: (accessor, params) =>
+ // const { eventType, keycode } = params;
+ // const formulaPromptService = accessor.get(IFormulaPromptService);
+ // const editorBridgeService = accessor.get(IEditorBridgeService);
- switch (keycode) {
- case KeyCode.ARROW_DOWN:
- formulaPromptService.navigate({ direction: Direction.DOWN });
- break;
- case KeyCode.ARROW_UP:
- formulaPromptService.navigate({ direction: Direction.UP });
- break;
- case KeyCode.ENTER:
- case KeyCode.TAB:
- if (formulaPromptService.isSearching()) {
- formulaPromptService.accept(true);
- } else {
- const editorBridgeParameters = {
- visible: false,
- eventType,
- keycode,
- };
+ // switch (keycode) {
+ // case KeyCode.ARROW_DOWN:
+ // formulaPromptService.navigate({ direction: Direction.DOWN });
+ // break;
+ // case KeyCode.ARROW_UP:
+ // formulaPromptService.navigate({ direction: Direction.UP });
+ // break;
+ // // case KeyCode.ENTER:
+ // // case KeyCode.TAB:
+ // // if (formulaPromptService.isSearching()) {
+ // // formulaPromptService.accept(true);
+ // // } else {
+ // // const editorBridgeParameters = {
+ // // visible: false,
+ // // eventType,
+ // // keycode,
+ // // };
- editorBridgeService.changeVisible(editorBridgeParameters);
- }
- break;
- default:
- break;
- }
+ // // editorBridgeService.changeVisible(editorBridgeParameters);
+ // // }
+ // // break;
+ // default:
+ // break;
+ // }
- return true;
- },
+ true,
};
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 7ac286640f..7556a88ed5 100644
--- a/packages/sheets-plugin-formula-ui/src/controllers/prompt.controller.ts
+++ b/packages/sheets-plugin-formula-ui/src/controllers/prompt.controller.ts
@@ -1,7 +1,6 @@
import { MoveCursorOperation, TextSelectionManagerService } from '@univerjs/base-docs';
import {
FormulaEngineService,
- IFunctionInfo,
includeFormulaLexerToken,
ISequenceNode,
isFormulaLexerToken,
@@ -66,17 +65,17 @@ import { HelpFunctionOperation } from '../commands/operations/help-function.oper
import { SearchFunctionOperation } from '../commands/operations/search-function.operation';
import { META_KEY_CTRL_AND_SHIFT } from '../common/prompt';
import { FORMULA_REF_SELECTION_PLUGIN_NAME, getFormulaRefSelectionStyle } from '../common/selection';
-import { IDescriptionService, ISearchItem } from '../services/description.service';
+import { IDescriptionService } from '../services/description.service';
import { IFormulaPromptService } from '../services/prompt.service';
-interface IFunctionPanelParam {
- visibleSearch: boolean;
- visibleHelp: boolean;
- searchText: string;
- paramIndex: number;
- functionInfo?: IFunctionInfo;
- searchList?: ISearchItem[];
-}
+// interface IFunctionPanelParam {
+// visibleSearch: boolean;
+// visibleHelp: boolean;
+// searchText: string;
+// paramIndex: number;
+// functionInfo?: IFunctionInfo;
+// searchList?: ISearchItem[];
+// }
interface IRefSelection {
refIndex: number;
@@ -92,6 +91,13 @@ enum ArrowMoveAction {
exitInput,
}
+enum InputPanelState {
+ InitialState,
+ keyNormal,
+ keyArrow,
+ mouse,
+}
+
@OnLifecycle(LifecycleStages.Steady, PromptController)
export class PromptController extends Disposable {
private _formulaRefColors: string[] = [];
@@ -126,6 +132,8 @@ export class PromptController extends Disposable {
private _insertSelections: ISelectionWithStyle[] = [];
+ private _inputPanelState: InputPanelState = InputPanelState.InitialState;
+
constructor(
@ICommandService private readonly _commandService: ICommandService,
@Inject(LocaleService) private readonly _localeService: LocaleService,
@@ -242,11 +250,11 @@ export class PromptController extends Disposable {
this._highlightFormula(currentBody);
- if (this._isLockedOnSelectionInsertRefString) {
- return;
- }
+ // if (this._isLockedOnSelectionInsertRefString) {
+ // return;
+ // }
// TODO@Dushusir: use real text info
- this._setFunctionPanel(dataStream);
+ this._changeFunctionPanelState();
})
)
);
@@ -268,10 +276,14 @@ export class PromptController extends Disposable {
if (
![KeyCode.ARROW_DOWN, KeyCode.ARROW_UP, KeyCode.ARROW_LEFT, KeyCode.ARROW_RIGHT].includes(
e.which
- ) &&
- this._arrowMoveActionState !== ArrowMoveAction.moveCursor
+ )
) {
- this._arrowMoveActionState = ArrowMoveAction.moveRefReady;
+ if (this._arrowMoveActionState !== ArrowMoveAction.moveCursor) {
+ this._arrowMoveActionState = ArrowMoveAction.moveRefReady;
+ }
+ this._inputPanelState = InputPanelState.keyNormal;
+ } else {
+ this._inputPanelState = InputPanelState.keyArrow;
}
})
)
@@ -320,6 +332,8 @@ export class PromptController extends Disposable {
this._selectionRenderService.resetStyle();
this._resetTemp();
+
+ this._hideFunctionPanel();
})
)
);
@@ -423,6 +437,193 @@ export class PromptController extends Disposable {
);
}
+ private _initAcceptFormula() {
+ 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) {
+ this._hideFunctionPanel();
+ return;
+ }
+
+ const { startOffset } = activeRange;
+
+ const nodeIndex = this._searchSequenceIndex(this._lastSequenceNodes, startOffset - 2);
+ const node = this._lastSequenceNodes[nodeIndex];
+
+ if (node == null || typeof node === 'string') {
+ this._hideFunctionPanel();
+ return;
+ }
+
+ const difference = formulaString.length - node.token.length;
+
+ node.token = formulaString;
+
+ node.endIndex += difference;
+
+ this._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];
+ if (typeof node === 'string') {
+ continue;
+ }
+
+ node.startIndex += formulaStringCount;
+ node.endIndex += formulaStringCount;
+ }
+
+ this._sycToEditor(this._lastSequenceNodes, node.endIndex + 2);
+ })
+ )
+ );
+ }
+
+ private _changeFunctionPanelState() {
+ const activeRange = this._textSelectionRenderManager.getActiveRange();
+
+ if (activeRange == null) {
+ this._hideFunctionPanel();
+ return;
+ }
+
+ const { startOffset } = activeRange;
+
+ const currentSequenceNode =
+ this._lastSequenceNodes[this._searchSequenceIndex(this._lastSequenceNodes, startOffset - 2)];
+
+ if (currentSequenceNode == null) {
+ this._hideFunctionPanel();
+ return;
+ }
+
+ if (typeof currentSequenceNode !== 'string' && currentSequenceNode.nodeType === sequenceNodeType.FUNCTION) {
+ const token = currentSequenceNode.token.toUpperCase();
+
+ if (this._inputPanelState === InputPanelState.keyNormal) {
+ // show search function panel
+ const searchList = this._descriptionService.getSearchListByName(token);
+ this._hideFunctionPanel();
+ if (searchList == null || searchList.length === 0) {
+ return;
+ }
+ this._commandService.executeCommand(SearchFunctionOperation.id, {
+ visible: true,
+ searchText: token,
+ searchList,
+ });
+ } else if (this._descriptionService.hasFunction(token)) {
+ // show help function panel
+ this._changeHelpFunctionPanelState(token, -1);
+ }
+
+ return;
+ }
+
+ const currentBody = this._getCurrentBody();
+
+ const dataStream = currentBody?.dataStream || '';
+
+ const functionAndParameter = this._formulaEngineService.getFunctionAndParameter(dataStream, startOffset - 1);
+
+ if (functionAndParameter == null) {
+ this._hideFunctionPanel();
+ return;
+ }
+
+ const { functionName, paramIndex } = functionAndParameter;
+
+ this._changeHelpFunctionPanelState(functionName.toUpperCase(), paramIndex);
+ }
+
+ private _changeHelpFunctionPanelState(token: string, paramIndex: number) {
+ const functionInfo = this._descriptionService.getFunctionInfo(token);
+ this._hideFunctionPanel();
+ if (functionInfo == null) {
+ return;
+ }
+
+ // show help function panel
+ this._commandService.executeCommand(HelpFunctionOperation.id, {
+ visible: true,
+ paramIndex,
+ functionInfo,
+ });
+ }
+
+ private _hideFunctionPanel() {
+ this._commandService.executeCommand(SearchFunctionOperation.id, {
+ visible: false,
+ searchText: '',
+ });
+ this._commandService.executeCommand(HelpFunctionOperation.id, {
+ visible: false,
+ paramIndex: -1,
+ });
+ }
+
+ // // 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,
@@ -456,6 +657,11 @@ export class PromptController extends Disposable {
}
}
+ /**
+ * Determine whether the character is a token keyword for the formula engine.
+ * @param char
+ * @returns
+ */
private _matchRefDrawToken(char: string) {
return (
(isFormulaLexerToken(char) &&
@@ -467,6 +673,10 @@ export class PromptController extends Disposable {
);
}
+ /**
+ *
+ * @returns Return the character under the current cursor in the editor.
+ */
private _getCurrentChar() {
const activeRange = this._textSelectionRenderManager.getActiveRange();
@@ -487,6 +697,10 @@ export class PromptController extends Disposable {
return dataStream[startOffset - 1];
}
+ /**
+ * Disable the ref string generation mode. In the ref string generation mode,
+ * users can select a certain area using the mouse and arrow keys, and convert the area into a ref string.
+ */
private _disableForceKeepVisible() {
this._editorBridgeService.disableForceKeepVisible();
@@ -505,6 +719,13 @@ export class PromptController extends Disposable {
return documentModel?.snapshot?.body;
}
+ /**
+ * Detect whether the user's input content is a formula. If it is a formula,
+ * serialize the current input content into a sequenceNode;
+ * otherwise, close the formula panel.
+ * @param currentInputValue The text content entered by the user in the editor.
+ * @returns
+ */
private _contextSwitch(currentInputValue: string) {
if (isFormulaString(currentInputValue)) {
this._contextService.setContextValue(FOCUSING_EDITOR_INPUT_FORMULA, true);
@@ -529,6 +750,8 @@ export class PromptController extends Disposable {
this._isLockedOnSelectionInsertRefString = false;
this._lastSequenceNodes = [];
+
+ this._hideFunctionPanel();
}
}
@@ -536,67 +759,6 @@ export class PromptController extends Disposable {
return this._contextService.getContextValue(FOCUSING_EDITOR_INPUT_FORMULA);
}
- // 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,
- });
- }
-
- private _initAcceptFormula() {
- this._formulaPromptService.acceptFormulaName$.subscribe((name: string) => {
- console.log(`TODO: set ${name} to cell editor`);
- });
- }
-
/**
* Switch from formula selection state to regular selection state.
*/
@@ -829,6 +991,11 @@ export class PromptController extends Disposable {
};
}
+ /**
+ * Convert the selection range to a ref string for the formula engine, such as A1:B1
+ * @param range
+ * @returns
+ */
private _getRefString(range: IRange) {
const { unitId, sheetId } = this._getCurrentUnitIdAndSheetId();
@@ -918,35 +1085,6 @@ export class PromptController extends Disposable {
return;
}
- // const { unitId, sheetId } = this._getCurrentUnitIdAndSheetId();
-
- // let refUnitId = '';
- // let refSheetName = '';
-
- // if (unitId === this._currentUnitId) {
- // refUnitId = '';
- // } else {
- // refUnitId = unitId;
- // }
-
- // if (sheetId === this._currentSheetId) {
- // refSheetName = '';
- // } else {
- // refSheetName = this._getSheetNameById(unitId, sheetId);
- // }
-
- // const { startRow, endRow, startColumn, endColumn } = range;
- // const refString = serializeRangeToRefString({
- // sheetName: refSheetName,
- // unitId: refUnitId,
- // range: {
- // startRow,
- // endRow,
- // startColumn,
- // endColumn,
- // },
- // });
-
const refString = this._getRefString(range);
const refStringCount = refString.length;
@@ -973,6 +1111,12 @@ export class PromptController extends Disposable {
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('');
@@ -991,6 +1135,12 @@ export class PromptController extends Disposable {
}
}
+ /**
+ * 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++) {
@@ -1012,6 +1162,12 @@ export class PromptController extends Disposable {
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) {
const dataStream = this._generateStringWithSequence(sequenceNodes);
@@ -1273,6 +1429,8 @@ export class PromptController extends Disposable {
toDisposable(
documentComponent.onPointerDownObserver.add(() => {
this._arrowMoveActionState = ArrowMoveAction.moveCursor;
+
+ this._inputPanelState = InputPanelState.mouse;
})
)
);
@@ -1289,6 +1447,10 @@ export class PromptController extends Disposable {
const { keycode, metaKey } = params;
if (keycode === KeyCode.ENTER) {
+ if (this._formulaPromptService.isSearching()) {
+ this._formulaPromptService.accept(true);
+ return;
+ }
this._editorBridgeService.changeVisible({
visible: false,
eventType: DeviceInputEventType.Keyboard,
@@ -1300,6 +1462,10 @@ export class PromptController extends Disposable {
return;
}
if (keycode === KeyCode.TAB) {
+ if (this._formulaPromptService.isSearching()) {
+ this._formulaPromptService.accept(true);
+ return;
+ }
this._editorBridgeService.changeVisible({
visible: false,
eventType: DeviceInputEventType.Keyboard,
@@ -1311,6 +1477,17 @@ export class PromptController extends Disposable {
return;
}
+ if (this._formulaPromptService.isSearching()) {
+ if (keycode === KeyCode.ARROW_DOWN) {
+ this._formulaPromptService.navigate({ direction: Direction.DOWN });
+ return;
+ }
+ if (keycode === KeyCode.ARROW_UP) {
+ this._formulaPromptService.navigate({ direction: Direction.UP });
+ return;
+ }
+ }
+
if (this._arrowMoveActionState === ArrowMoveAction.moveCursor) {
this._moveInEditor(keycode);
return;
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 8be92df683..bfebd556fa 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
@@ -10,8 +10,6 @@ export const PROMPT_SELECTION_KEYCODE_ARROW_LIST = [
KeyCode.ARROW_UP,
KeyCode.ARROW_LEFT,
KeyCode.ARROW_RIGHT,
- KeyCode.ENTER,
- KeyCode.TAB,
];
export const PROMPT_SELECTION_KEYCODE_LIST = [...PROMPT_SELECTION_KEYCODE_ARROW_LIST, KeyCode.ENTER, KeyCode.TAB];
diff --git a/packages/sheets-plugin-formula-ui/src/services/description.service.ts b/packages/sheets-plugin-formula-ui/src/services/description.service.ts
index 29c180cf86..1ab1540f8b 100644
--- a/packages/sheets-plugin-formula-ui/src/services/description.service.ts
+++ b/packages/sheets-plugin-formula-ui/src/services/description.service.ts
@@ -16,6 +16,8 @@ export interface IDescriptionService {
*/
getDescriptions(): Map<string, IFunctionInfo>;
+ hasFunction(searchText: string): boolean;
+
/**
* get function info by name
* @param searchText
@@ -57,6 +59,11 @@ export class DescriptionService implements IDescriptionService, IDisposable {
return this._formulaEngineService.getDescriptions();
}
+ hasFunction(searchText: string) {
+ const functionList = this._formulaEngineService.getDescriptions();
+ return functionList.get(searchText.toLocaleUpperCase()) !== undefined;
+ }
+
getFunctionInfo(searchText: string) {
const functionList = this._formulaEngineService.getDescriptions();
return functionList.get(searchText.toLocaleUpperCase());
diff --git a/packages/sheets-plugin-formula-ui/src/services/prompt.service.ts b/packages/sheets-plugin-formula-ui/src/services/prompt.service.ts
index 0110ff46a3..fe1848162c 100644
--- a/packages/sheets-plugin-formula-ui/src/services/prompt.service.ts
+++ b/packages/sheets-plugin-formula-ui/src/services/prompt.service.ts
@@ -95,6 +95,10 @@ export interface IFormulaPromptService {
*/
acceptFormulaName(param: string): void;
+ isSearching(): boolean;
+
+ isHelping(): boolean;
+
dispose(): void;
}
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 918d3a3795..73db848f2b 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
@@ -148,33 +148,30 @@ export class EndEditController extends Disposable {
return;
}
- if (body.textRuns && body.textRuns.length > 1) {
+ const data = body.dataStream;
+ const lastString = data.substring(data.length - 2, data.length);
+ let newDataStream = lastString === DEFAULT_EMPTY_DOCUMENT_VALUE ? data.substring(0, data.length - 2) : data;
+
+ if (isFormulaString(newDataStream)) {
+ const bracketCount = this._formulaEngineService.checkIfAddBracket(newDataStream);
+ for (let i = 0; i < bracketCount; i++) {
+ newDataStream += matchToken.CLOSE_BRACKET;
+ }
+
+ cellData.f = newDataStream;
+ cellData.v = null;
+ cellData.p = null;
+ } else if (body.textRuns && body.textRuns.length > 1) {
cellData.p = snapshot;
cellData.v = null;
cellData.f = null;
} else {
- const data = body.dataStream;
- const lastString = data.substring(data.length - 2, data.length);
- let newDataStream =
- lastString === DEFAULT_EMPTY_DOCUMENT_VALUE ? data.substring(0, data.length - 2) : data;
-
if (newDataStream === cellData.v) {
return;
}
-
- if (isFormulaString(newDataStream)) {
- if (this._formulaEngineService.checkIfAddBracket(newDataStream)) {
- newDataStream += matchToken.CLOSE_BRACKET;
- }
-
- cellData.f = newDataStream;
- cellData.v = null;
- cellData.p = null;
- } else {
- cellData.v = newDataStream;
- cellData.f = null;
- cellData.p = null;
- }
+ cellData.v = newDataStream;
+ cellData.f = null;
+ cellData.p = null;
}
this._commandService.executeCommand(SetRangeValuesCommand.id, {
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 3da678941b..825dac9459 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
@@ -309,8 +309,6 @@ export class StartEditController extends Disposable {
const viewportMain = scene.getViewport(VIEWPORT_KEY.VIEW_MAIN);
- const scrollBar = viewportMain?.getScrollBar() as Nullable<ScrollBar>;
-
const clientHeight =
document.body.clientHeight -
startY -
@@ -320,20 +318,9 @@ export class StartEditController extends Disposable {
const clientWidth = document.body.clientWidth - startX - canvasOffset.left;
- editorWidth += scrollBar?.barSize || 0;
-
- if (editorWidth > clientWidth) {
- editorWidth = clientWidth;
- }
-
let physicHeight = editorHeight;
- scene.transformByState({
- width: editorWidth,
- height: editorHeight,
- });
-
- documentComponent.resize(editorWidth, editorHeight);
+ let scrollBar = viewportMain?.getScrollBar() as Nullable<ScrollBar>;
if (physicHeight > clientHeight) {
physicHeight = clientHeight;
@@ -343,9 +330,23 @@ export class StartEditController extends Disposable {
viewportMain?.resetSizeAndScrollBar();
}
} else {
+ scrollBar = null;
viewportMain?.getScrollBar()?.dispose();
}
+ editorWidth += scrollBar?.barSize || 0;
+
+ if (editorWidth > clientWidth) {
+ editorWidth = clientWidth;
+ }
+
+ scene.transformByState({
+ width: editorWidth,
+ height: editorHeight,
+ });
+
+ documentComponent.resize(editorWidth, editorHeight);
+
this._addBackground(scene, editorWidth, editorHeight, fill);
// resize canvas