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): selection change ref string (#466)

Univerbf7aafec6ee0
diff --git a/packages/base-formula-engine/src/analysis/lexer.ts b/packages/base-formula-engine/src/analysis/lexer.ts
index 29cff504d0..3e7f426f56 100644
--- a/packages/base-formula-engine/src/analysis/lexer.ts
+++ b/packages/base-formula-engine/src/analysis/lexer.ts
@@ -1,17 +1,16 @@
import { Disposable, Nullable, Tools } from '@univerjs/core';
import { ErrorType } from '../basics/error-type';
+import { isFormulaLexerToken } from '../basics/match-token';
import { isReferenceString, REFERENCE_SINGLE_RANGE_REGEX } from '../basics/regex';
import { ISequenceArray, ISequenceNode, sequenceNodeType } from '../basics/sequence';
import {
- compareToken,
matchToken,
OPERATOR_TOKEN_PRIORITY,
OPERATOR_TOKEN_SET,
operatorToken,
prefixToken,
SUFFIX_TOKEN_SET,
- suffixToken,
} from '../basics/token';
import {
DEFAULT_TOKEN_TYPE_LAMBDA_PARAMETER,
@@ -211,15 +210,7 @@ export class LexerTreeBuilder extends Disposable {
}
private _isLastMergeString(str: string) {
- return (
- str === matchToken.DOUBLE_QUOTATION ||
- Tools.isStringNumber(str) ||
- (!Object.values(compareToken).includes(str as compareToken) &&
- !Object.values(operatorToken).includes(str as operatorToken) &&
- !Object.values(matchToken).includes(str as matchToken) &&
- !Object.values(suffixToken).includes(str as suffixToken) &&
- !Object.values(prefixToken).includes(str as prefixToken))
- );
+ return str === matchToken.DOUBLE_QUOTATION || Tools.isStringNumber(str) || !isFormulaLexerToken(str);
}
/**
diff --git a/packages/base-formula-engine/src/basics/match-token.ts b/packages/base-formula-engine/src/basics/match-token.ts
new file mode 100644
index 0000000000..0178e8eb1b
--- /dev/null
+++ b/packages/base-formula-engine/src/basics/match-token.ts
@@ -0,0 +1,30 @@
+import { compareToken, matchToken, operatorToken, prefixToken, suffixToken } from './token';
+
+export const FORMULA_LEXER_TOKENS = [
+ ...Object.values(compareToken),
+ ...Object.values(operatorToken),
+ ...Object.values(matchToken),
+ ...Object.values(suffixToken),
+ ...Object.values(prefixToken),
+];
+
+export function isFormulaLexerToken(str: string) {
+ return FORMULA_LEXER_TOKENS.includes(str as compareToken);
+}
+
+export function includeFormulaLexerToken(str: string) {
+ for (const token of FORMULA_LEXER_TOKENS) {
+ if (str.indexOf(token) > -1) {
+ return true;
+ }
+ }
+
+ return false;
+}
+
+export function normalizeSheetName(sheetName: string) {
+ if (sheetName[0] === "'" && sheetName[sheetName.length - 1] === "'") {
+ return sheetName.substring(1, sheetName.length - 1);
+ }
+ return sheetName;
+}
diff --git a/packages/core/src/shared/reference.ts b/packages/base-formula-engine/src/basics/reference.ts
similarity index 63%
rename from packages/core/src/shared/reference.ts
rename to packages/base-formula-engine/src/basics/reference.ts
index 34008990b7..cb15c3f3cf 100644
--- a/packages/core/src/shared/reference.ts
+++ b/packages/base-formula-engine/src/basics/reference.ts
@@ -1,7 +1,7 @@
-import { IRange } from '../types/interfaces/i-range';
-import { Tools } from './tools';
+import { IRange, Tools } from '@univerjs/core';
-const COLON_SYMBOL = ':';
+import { UNIT_NAME_REGEX } from './regex';
+import { matchToken } from './token';
const $ROW_REGEX = /[^0-9]/g;
@@ -25,12 +25,19 @@ function singleReferenceToGrid(refBody: string) {
/**
* Serialize an `IRange` into a string.
- * @param sheetID ID of the Worksheet
* @param range The `IRange` to be serialized
*/
export function serializeRange(range: IRange): string {
const { startColumn, startRow, endColumn, endRow } = range;
- return `${Tools.chatAtABC(startColumn) + (startRow + 1)}:${Tools.chatAtABC(endColumn)}${endRow + 1}`;
+ const startStr = `${Tools.chatAtABC(startColumn) + (startRow + 1)}`;
+
+ const endStr = `${Tools.chatAtABC(endColumn)}${endRow + 1}`;
+
+ if (startStr === endStr) {
+ return startStr;
+ }
+
+ return `${startStr}:${endStr}`;
}
/**
@@ -43,13 +50,38 @@ export function serializeRangeWithSheet(sheetName: string, range: IRange): strin
return `${sheetName}!${serializeRange(range)}`;
}
+/**
+ * Serialize an `IRange` and a sheetID into a string.
+ * @param unit unitId or unitName
+ * @param sheetName
+ * @param range
+ * @returns
+ */
+export function serializeRangeWithSpreadsheet(unit: string, sheetName: string, range: IRange): string {
+ return `[${unit}]${sheetName}!${serializeRange(range)}`;
+}
+
+export function serializeRangeToRefString(gridRangeName: IGridRangeName) {
+ const { unitId, sheetName, range } = gridRangeName;
+
+ if (unitId != null && unitId.length > 0 && sheetName != null && sheetName.length > 0) {
+ return serializeRangeWithSpreadsheet(unitId, sheetName, range);
+ }
+
+ if (sheetName != null && sheetName.length > 0) {
+ return serializeRangeWithSheet(sheetName, range);
+ }
+
+ return serializeRange(range);
+}
+
export function deserializeRangeWithSheet(refString: string): IGridRangeName {
- const unitIdMatch = new RegExp('\'?\\[((?![\\/?:"<>|*\\\\]).)*\\]').exec(refString);
+ const unitIdMatch = new RegExp(UNIT_NAME_REGEX).exec(refString);
let unitId = '';
if (unitIdMatch != null) {
unitId = unitIdMatch[0];
- refString = refString.replace(new RegExp('\'?\\[((?![\\/?:"<>|*\\\\]).)*\\]', 'g'), '');
+ refString = refString.replace(new RegExp(UNIT_NAME_REGEX, 'g'), '');
}
const sheetNameIndex = refString.indexOf('!');
@@ -62,7 +94,7 @@ export function deserializeRangeWithSheet(refString: string): IGridRangeName {
refBody = refString;
}
- const colonIndex = refBody.indexOf(COLON_SYMBOL);
+ const colonIndex = refBody.indexOf(matchToken.COLON);
if (colonIndex === -1) {
const grid = singleReferenceToGrid(refBody);
diff --git a/packages/base-formula-engine/src/basics/regex.ts b/packages/base-formula-engine/src/basics/regex.ts
index 6e33f16094..3fb798b737 100644
--- a/packages/base-formula-engine/src/basics/regex.ts
+++ b/packages/base-formula-engine/src/basics/regex.ts
@@ -1,20 +1,18 @@
-const UNIT_NAME_REGEX = '\'?\\[((?![\\/?:"<>|*\\\\]).)*\\]';
+import { prefixToken, suffixToken } from './token';
-const SHEET_NAME_REGEX = '((?![\\[\\]\\/?*\\\\]).)*!';
+export const UNIT_NAME_REGEX = '\'?\\[((?![\\/?:"<>|*\\\\]).)*\\]';
-const ABSOLUTE_SYMBOL = '$';
+export const SHEET_NAME_REGEX = '((?![\\[\\]\\/?*\\\\]).)*!';
-const RANGE_SYMBOL = '\\s*?:\\s*?';
+export const ABSOLUTE_SYMBOL = '$';
-const PROJECTION_SYMBOL = '@';
+export const RANGE_SYMBOL = '\\s*?:\\s*?';
-const ARRAY_SYMBOL = '#';
+export const SIMPLE_SINGLE_RANGE_REGEX = `\\${ABSOLUTE_SYMBOL}?[A-Za-z]+\\${ABSOLUTE_SYMBOL}?[0-9]+`;
-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 = `^(${PROJECTION_SYMBOL})?(${UNIT_NAME_REGEX})?(${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}(${ARRAY_SYMBOL})?$`;
+export const REFERENCE_SINGLE_RANGE_REGEX = `^(${UNIT_NAME_REGEX})?(${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]+$`;
diff --git a/packages/base-formula-engine/src/index.ts b/packages/base-formula-engine/src/index.ts
index 1f947e00b3..d69507e571 100644
--- a/packages/base-formula-engine/src/index.ts
+++ b/packages/base-formula-engine/src/index.ts
@@ -9,7 +9,16 @@ export type {
IUnitSheetNameMap,
} from './basics/common';
export { FUNCTION_NAMES, FunctionType, type IFunctionInfo, type IFunctionParam } from './basics/function';
+export { includeFormulaLexerToken, isFormulaLexerToken, normalizeSheetName } from './basics/match-token';
+export {
+ deserializeRangeWithSheet,
+ serializeRange,
+ serializeRangeToRefString,
+ serializeRangeWithSheet,
+ serializeRangeWithSpreadsheet,
+} from './basics/reference';
export { type ISequenceNode, sequenceNodeType } from './basics/sequence';
+export { matchToken } from './basics/token';
export { BaseFormulaEnginePlugin } from './plugin';
export { RangeReferenceObject } from './reference-object/range-reference-object';
export { FormulaEngineService } from './services/formula-engine.service';
diff --git a/packages/base-formula-engine/src/reference-object/cell-reference-object.ts b/packages/base-formula-engine/src/reference-object/cell-reference-object.ts
index 4fac59864b..d0b7046458 100644
--- a/packages/base-formula-engine/src/reference-object/cell-reference-object.ts
+++ b/packages/base-formula-engine/src/reference-object/cell-reference-object.ts
@@ -1,6 +1,7 @@
-import { deserializeRangeWithSheet, IRange } from '@univerjs/core';
+import { IRange } from '@univerjs/core';
import { ErrorType } from '../basics/error-type';
+import { deserializeRangeWithSheet } from '../basics/reference';
import { ErrorValueObject } from '../other-object/error-value-object';
import { BaseReferenceObject } from './base-reference-object';
import { RangeReferenceObject } from './range-reference-object';
diff --git a/packages/base-formula-engine/src/reference-object/column-reference-object.ts b/packages/base-formula-engine/src/reference-object/column-reference-object.ts
index b0562d0ffb..978ebedb94 100644
--- a/packages/base-formula-engine/src/reference-object/column-reference-object.ts
+++ b/packages/base-formula-engine/src/reference-object/column-reference-object.ts
@@ -1,6 +1,7 @@
-import { deserializeRangeWithSheet, IRange } from '@univerjs/core';
+import { IRange } from '@univerjs/core';
import { ErrorType } from '../basics/error-type';
+import { deserializeRangeWithSheet } from '../basics/reference';
import { ErrorValueObject } from '../other-object/error-value-object';
import { BaseReferenceObject } from './base-reference-object';
diff --git a/packages/base-formula-engine/src/reference-object/row-reference-object.ts b/packages/base-formula-engine/src/reference-object/row-reference-object.ts
index 93cbe9c518..779e62d7d1 100644
--- a/packages/base-formula-engine/src/reference-object/row-reference-object.ts
+++ b/packages/base-formula-engine/src/reference-object/row-reference-object.ts
@@ -1,6 +1,7 @@
-import { deserializeRangeWithSheet, IRange } from '@univerjs/core';
+import { IRange } from '@univerjs/core';
import { ErrorType } from '../basics/error-type';
+import { deserializeRangeWithSheet } from '../basics/reference';
import { ErrorValueObject } from '../other-object/error-value-object';
import { BaseReferenceObject } from './base-reference-object';
diff --git a/packages/base-sheets/src/basics/selection.ts b/packages/base-sheets/src/basics/selection.ts
index 737c61a06a..554dd0dedb 100644
--- a/packages/base-sheets/src/basics/selection.ts
+++ b/packages/base-sheets/src/basics/selection.ts
@@ -3,6 +3,7 @@ import { getCellInfoInMergeData } from '@univerjs/base-render';
import {
IRange,
ISelection,
+ ISelectionCellWithCoord,
ISelectionWithCoord,
makeCellRangeToRangeData,
Nullable,
@@ -39,6 +40,11 @@ export interface ISelectionWidgetConfig {
* https://support.microsoft.com/en-us/office/select-cell-contents-in-excel-23f64223-2b6b-453a-8688-248355f10fa9
*/
export interface ISelectionStyle {
+ /**
+ * Assign an ID to a selection area.
+ * The current scenario is to identify the formula string corresponding to the selection area
+ */
+ id?: string;
/**
* The volume of the selection border determines the thickness of the selection border
*/
@@ -175,22 +181,26 @@ export function convertSelectionDataToRange(
style,
};
if (primaryWithCoord != null) {
- const { actualRow, actualColumn, isMerged, isMergedMainCell } = primaryWithCoord;
- const { startRow, startColumn, endRow, endColumn } = primaryWithCoord.mergeInfo;
- result.primary = {
- actualRow,
- actualColumn,
- isMerged,
- isMergedMainCell,
- startRow,
- startColumn,
- endRow,
- endColumn,
- };
+ result.primary = convertPrimaryWithCoordToPrimary(primaryWithCoord);
}
return result;
}
+export function convertPrimaryWithCoordToPrimary(primaryWithCoord: ISelectionCellWithCoord) {
+ const { actualRow, actualColumn, isMerged, isMergedMainCell } = primaryWithCoord;
+ const { startRow, startColumn, endRow, endColumn } = primaryWithCoord.mergeInfo;
+ return {
+ actualRow,
+ actualColumn,
+ isMerged,
+ isMergedMainCell,
+ startRow,
+ startColumn,
+ endRow,
+ endColumn,
+ };
+}
+
/**
* Convert the coordinates of a single cell into a selection data.
* @param row Specified Row Coordinate
diff --git a/packages/base-sheets/src/commands/commands/utils/selection-util.ts b/packages/base-sheets/src/commands/commands/utils/selection-util.ts
index 3fbf8aa32e..5ed3eabc1a 100644
--- a/packages/base-sheets/src/commands/commands/utils/selection-util.ts
+++ b/packages/base-sheets/src/commands/commands/utils/selection-util.ts
@@ -709,7 +709,10 @@ export function getPrimaryForRange(range: IRange, worksheet: Worksheet): ISelect
const mergedRange = worksheet.getMergedCell(range.startRow, range.startColumn);
if (!mergedRange) {
return {
- ...range,
+ startRow: range.startRow,
+ startColumn: range.startColumn,
+ endRow: range.startRow,
+ endColumn: range.startColumn,
actualRow: range.startRow,
actualColumn: range.startColumn,
rangeType: RANGE_TYPE.NORMAL,
diff --git a/packages/base-sheets/src/index.ts b/packages/base-sheets/src/index.ts
index 357f8a6668..8431e5607e 100644
--- a/packages/base-sheets/src/index.ts
+++ b/packages/base-sheets/src/index.ts
@@ -15,6 +15,7 @@ export {
type IRemoveWorksheetMergeMutationParams,
} from './basics/interfaces/mutation-interface';
export {
+ convertPrimaryWithCoordToPrimary,
convertSelectionDataToRange,
getNormalSelectionStyle,
type ISelectionStyle,
diff --git a/packages/base-sheets/src/services/selection-manager.service.ts b/packages/base-sheets/src/services/selection-manager.service.ts
index a306e90fb9..87140d6088 100644
--- a/packages/base-sheets/src/services/selection-manager.service.ts
+++ b/packages/base-sheets/src/services/selection-manager.service.ts
@@ -63,6 +63,37 @@ export class SelectionManagerService implements IDisposable {
return this._currentSelection;
}
+ getLastByPlugin(pluginName: string) {
+ if (this._currentSelection == null) {
+ return;
+ }
+ return this._getLastByParam({ ...this._currentSelection, pluginName });
+ }
+
+ changePlugin(pluginName: string) {
+ if (this._currentSelection == null) {
+ return;
+ }
+ this._currentSelection = {
+ pluginName,
+ unitId: this._currentSelection?.unitId,
+ sheetId: this._currentSelection?.sheetId,
+ };
+
+ this.refresh(this._currentSelection);
+ }
+
+ changePluginNoRefresh(pluginName: string) {
+ if (this._currentSelection == null) {
+ return;
+ }
+ this._currentSelection = {
+ pluginName,
+ unitId: this._currentSelection?.unitId,
+ sheetId: this._currentSelection?.sheetId,
+ };
+ }
+
reset() {
if (this._currentSelection == null) {
return;
@@ -148,6 +179,19 @@ export class SelectionManagerService implements IDisposable {
>;
}
+ addNoRefresh(selectionDatas: ISelectionWithStyle[]) {
+ if (this._currentSelection == null) {
+ return;
+ }
+ this._addByParam(
+ {
+ ...this._currentSelection,
+ selectionDatas,
+ },
+ false
+ );
+ }
+
add(selectionDatas: ISelectionWithStyle[]) {
if (this._currentSelection == null) {
return;
@@ -272,7 +316,7 @@ export class SelectionManagerService implements IDisposable {
return selectionData?.[selectionData.length - 1];
}
- private _addByParam(insertParam: ISelectionManagerInsertParam): void {
+ private _addByParam(insertParam: ISelectionManagerInsertParam, isRefresh = true): void {
const { pluginName, unitId, sheetId, selectionDatas } = insertParam;
if (!this._selectionInfo.has(pluginName)) {
@@ -294,7 +338,9 @@ export class SelectionManagerService implements IDisposable {
OldSelectionDatas.push(...selectionDatas);
}
- this.refresh({ pluginName, unitId, sheetId });
+ if (isRefresh) {
+ this.refresh({ pluginName, unitId, sheetId });
+ }
}
private _replaceByParam(insertParam: ISelectionManagerInsertParam) {
diff --git a/packages/core/src/shared/index.ts b/packages/core/src/shared/index.ts
index 9e551a7f36..7ab699b409 100644
--- a/packages/core/src/shared/index.ts
+++ b/packages/core/src/shared/index.ts
@@ -23,7 +23,6 @@ export * from './object-matrix';
export * from './permission';
export * from './random';
export * from './rectangle';
-export * from './reference';
export * from './row-col-iter';
export * from './sequence';
export * from './serialize/index';
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 83e9f9e1a7..6cf4ea39b7 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
@@ -1,15 +1,17 @@
// This file provides operations to change formula selection of sheets.
import { DeviceInputEventType } from '@univerjs/base-render';
-import { KeyCode } from '@univerjs/base-ui';
+import { KeyCode, MetaKeys } from '@univerjs/base-ui';
import { CommandType, Direction, IOperation } from '@univerjs/core';
import { IEditorBridgeService } from '@univerjs/ui-plugin-sheets';
+import { META_KEY_CTRL_AND_SHIFT } from '../../common/prompt';
import { IFormulaPromptService } from '../../services/prompt.service';
export interface ISelectEditorFormulaOperationParam {
eventType: DeviceInputEventType;
keycode?: KeyCode;
+ metaKey?: MetaKeys | typeof META_KEY_CTRL_AND_SHIFT;
}
export const SelectEditorFormulaOperation: IOperation<ISelectEditorFormulaOperationParam> = {
diff --git a/packages/sheets-plugin-formula-ui/src/common/prompt.ts b/packages/sheets-plugin-formula-ui/src/common/prompt.ts
new file mode 100644
index 0000000000..84d2e0a689
--- /dev/null
+++ b/packages/sheets-plugin-formula-ui/src/common/prompt.ts
@@ -0,0 +1 @@
+export const META_KEY_CTRL_AND_SHIFT = 'meta_key_ctrl_And_Shift';
diff --git a/packages/sheets-plugin-formula-ui/src/common/selection.ts b/packages/sheets-plugin-formula-ui/src/common/selection.ts
index 372c7f555d..89d1f1375b 100644
--- a/packages/sheets-plugin-formula-ui/src/common/selection.ts
+++ b/packages/sheets-plugin-formula-ui/src/common/selection.ts
@@ -4,10 +4,11 @@ import { ThemeService } from '@univerjs/core';
export const FORMULA_REF_SELECTION_PLUGIN_NAME = 'formula_reference_selection_plugin_name';
-export function getFormulaRefSelectionStyle(themeService: ThemeService, refColor: string): ISelectionStyle {
+export function getFormulaRefSelectionStyle(themeService: ThemeService, refColor: string, id: string): ISelectionStyle {
const style = themeService.getCurrentTheme();
const fill = new TinyColor(refColor).setAlpha(0.05).toString();
return {
+ id,
strokeWidth: 2,
stroke: refColor,
// strokeDash: 10,
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 94ba4b0c5d..d427064776 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
@@ -18,7 +18,12 @@ 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 { promptSelectionShortcutItem } from './shortcuts/prompt.shortcut';
+import {
+ promptSelectionShortcutItem,
+ promptSelectionShortcutItemCtrl,
+ promptSelectionShortcutItemCtrlAndShift,
+ promptSelectionShortcutItemShift,
+} from './shortcuts/prompt.shortcut';
@OnLifecycle(LifecycleStages.Ready, FormulaUIController)
export class FormulaUIController extends Disposable {
@@ -59,7 +64,12 @@ export class FormulaUIController extends Disposable {
}
private _registerShortcuts(): void {
- [...promptSelectionShortcutItem()].forEach((item) => {
+ [
+ ...promptSelectionShortcutItem(),
+ ...promptSelectionShortcutItemShift(),
+ ...promptSelectionShortcutItemCtrl(),
+ ...promptSelectionShortcutItemCtrlAndShift(),
+ ].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 764e00de54..253d0c7b24 100644
--- a/packages/sheets-plugin-formula-ui/src/controllers/prompt.controller.ts
+++ b/packages/sheets-plugin-formula-ui/src/controllers/prompt.controller.ts
@@ -1,19 +1,41 @@
-import { FormulaEngineService, IFunctionInfo, ISequenceNode, sequenceNodeType } from '@univerjs/base-formula-engine';
+import { TextSelectionManagerService } from '@univerjs/base-docs';
+import {
+ deserializeRangeWithSheet,
+ FormulaEngineService,
+ IFunctionInfo,
+ includeFormulaLexerToken,
+ ISequenceNode,
+ isFormulaLexerToken,
+ matchToken,
+ normalizeSheetName,
+ sequenceNodeType,
+ serializeRangeToRefString,
+} from '@univerjs/base-formula-engine';
import {
DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY,
DOCS_NORMAL_EDITOR_UNIT_ID_KEY,
IRenderManagerService,
ITextSelectionRenderManager,
} from '@univerjs/base-render';
-import { ISelectionWithStyle, NORMAL_SELECTION_PLUGIN_NAME, SelectionManagerService } from '@univerjs/base-sheets';
import {
- deserializeRangeWithSheet,
+ convertSelectionDataToRange,
+ getNormalSelectionStyle,
+ ISelectionWithStyle,
+ NORMAL_SELECTION_PLUGIN_NAME,
+ SelectionManagerService,
+} from '@univerjs/base-sheets';
+import { KeyCode, MetaKeys } from '@univerjs/base-ui';
+import {
+ Direction,
Disposable,
DisposableCollection,
FOCUSING_EDITOR_INPUT_FORMULA,
+ ICommandInfo,
ICommandService,
IContextService,
IDocumentBody,
+ IRange,
+ IRangeWithCoord,
isFormulaString,
ITextRun,
IUniverInstanceService,
@@ -23,18 +45,29 @@ import {
OnLifecycle,
ThemeService,
toDisposable,
+ Tools,
} from '@univerjs/core';
import {
EditorBridgeService,
+ ExpandSelectionCommand,
getEditorObject,
IEditorBridgeService,
ISelectionRenderService,
+ JumpOver,
+ MoveSelectionCommand,
+ SelectionShape,
+ SetEditorResizeOperation,
SheetSkeletonManagerService,
} from '@univerjs/ui-plugin-sheets';
import { Inject } from '@wendellhu/redi';
+import {
+ ISelectEditorFormulaOperationParam,
+ SelectEditorFormulaOperation,
+} from '../commands/operations/editor-formula.operation';
import { HelpFunctionOperation } from '../commands/operations/help-function.operation';
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 { IFormulaPromptService } from '../services/prompt.service';
@@ -58,12 +91,34 @@ interface IRefSelection {
export class PromptController extends Disposable {
private _formulaRefColors: string[] = [];
- private _currentRefIndex: number = -1;
+ 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>;
+
+ private _currentInsertRefStringIndex: number = -1;
+
+ private _currentUnitId: Nullable<string>;
+
+ private _currentSheetId: Nullable<string>;
+
+ private _isSelectionMoving: boolean = false;
+
+ private _isSelectionMovingRefSelections: IRefSelection[] = [];
private _stringColor = '';
private _numberColor = '';
+ private _insertSelections: ISelectionWithStyle[] = [];
+
constructor(
@ICommandService private readonly _commandService: ICommandService,
@Inject(LocaleService) private readonly _localeService: LocaleService,
@@ -78,7 +133,8 @@ export class PromptController extends Disposable {
@Inject(SheetSkeletonManagerService) private readonly _sheetSkeletonManagerService: SheetSkeletonManagerService,
@IUniverInstanceService private readonly _currentUniverService: IUniverInstanceService,
@Inject(ISelectionRenderService) private readonly _selectionRenderService: ISelectionRenderService,
- @Inject(IDescriptionService) private readonly _descriptionService: IDescriptionService
+ @Inject(IDescriptionService) private readonly _descriptionService: IDescriptionService,
+ @Inject(TextSelectionManagerService) private readonly _textSelectionManagerService: TextSelectionManagerService
) {
super();
@@ -87,17 +143,47 @@ export class PromptController extends Disposable {
override dispose(): void {
this._formulaRefColors = [];
+ this._resetTemp();
+ }
+
+ private _resetTemp() {
+ this._lastSequenceNodes = [];
+
+ this._previousSequenceNodes = null;
+
+ this._previousInsertRefStringIndex = null;
+
+ this._currentUnitId = null;
+
+ this._currentSheetId = null;
+
+ this._isSelectionMovingRefSelections = [];
+
+ this._isLockedOnSelectionChangeRefString = false;
+
+ this._previousRangesCount = 0;
+
+ this._currentInsertRefStringIndex = -1;
+
+ this._isSelectionMoving = false;
}
private _initialize(): void {
this._initialCursorSync();
+
this._initAcceptFormula();
this._initialFormulaTheme();
- this._initialRefSelectionEvent();
+ this._initialRefSelectionUpdateEvent();
+
+ this._initialRefSelectionInsertEvent();
this._initialExitEditor();
+
+ this._initialEditorInputChange();
+
+ this._commandExecutedListener();
}
private _initialFormulaTheme() {
@@ -127,7 +213,7 @@ export class PromptController extends Disposable {
this.disposeWithMe(
toDisposable(
this._textSelectionRenderManager.textSelection$.subscribe(() => {
- if (this._editorBridgeService.isVisible().visible === false) {
+ if (this._editorBridgeService.isVisible().visible === false || this._isSelectionMoving === true) {
return;
}
@@ -137,10 +223,34 @@ export class PromptController extends Disposable {
this._contextSwitch(dataStream);
+ this._changeKeepVisibleHideState();
+
+ this._switchSelectionPlugin();
+
+ if (this._isLockedOnSelectionChangeRefString) {
+ return;
+ }
+
+ this._highlightFormula(currentBody);
+
+ if (this._isLockedOnSelectionInsertRefString) {
+ return;
+ }
// TODO@Dushusir: use real text info
this._setFunctionPanel(dataStream);
+ })
+ )
+ );
+ }
- this._highlightFormula(currentBody);
+ private _initialEditorInputChange() {
+ this.disposeWithMe(
+ toDisposable(
+ this._textSelectionRenderManager.onInputBefore$.subscribe(() => {
+ this._previousSequenceNodes = null;
+ this._previousInsertRefStringIndex = null;
+
+ this._selectionRenderService.enableSkipRemainLast();
})
)
);
@@ -149,27 +259,238 @@ export class PromptController extends Disposable {
private _initialExitEditor() {
this.disposeWithMe(
toDisposable(
- this._editorBridgeService.visible$.subscribe((visibleParam) => {
+ this._editorBridgeService.afterVisible$.subscribe((visibleParam) => {
if (visibleParam.visible === true) {
+ const { unitId, sheetId } = this._getCurrentUnitIdAndSheetId();
+
+ if (this._currentUnitId == null) {
+ this._currentUnitId = unitId;
+ }
+
+ if (this._currentSheetId == null) {
+ this._currentSheetId = sheetId;
+ }
+
return;
}
- this._switchSelectionPlugin(NORMAL_SELECTION_PLUGIN_NAME);
+ /**
+ * Switching the selection of PluginName causes a refresh.
+ * Here, a delay is added to prevent the loss of content when pressing enter.
+ */
+ if (this._getContextState() === true) {
+ this._selectionManagerService.clear();
+ this._selectionManagerService.changePlugin(NORMAL_SELECTION_PLUGIN_NAME);
+ }
+
+ this._contextService.setContextValue(FOCUSING_EDITOR_INPUT_FORMULA, false);
+
+ this._changeKeepVisibleHideState();
+
+ this._selectionRenderService.resetStyle();
+
+ this._resetTemp();
+ })
+ )
+ );
+ }
+
+ private _initialRefSelectionUpdateEvent() {
+ const disposableCollection = new DisposableCollection();
+
+ this.disposeWithMe(
+ toDisposable(
+ this._selectionManagerService.selectionInfo$.subscribe(() => {
+ // Each range change requires re-listening
+ disposableCollection.dispose();
+
+ const current = this._selectionManagerService.getCurrent();
+
+ this._isSelectionMoving = false;
+
+ if (current?.pluginName !== FORMULA_REF_SELECTION_PLUGIN_NAME) {
+ return;
+ }
+
+ this._updateRefSelectionStyle(this._isSelectionMovingRefSelections);
+
+ const selectionControls = this._selectionRenderService.getCurrentControls();
+ selectionControls.forEach((controlSelection) => {
+ controlSelection.disableHelperSelection();
+
+ disposableCollection.add(
+ toDisposable(
+ controlSelection.selectionMoving$.subscribe((toRange) => {
+ this._changeControlSelection(toRange, controlSelection);
+ })
+ )
+ );
+
+ disposableCollection.add(
+ toDisposable(
+ controlSelection.selectionScaling$.subscribe((toRange) => {
+ this._changeControlSelection(toRange, controlSelection);
+ })
+ )
+ );
+
+ disposableCollection.add(
+ toDisposable(
+ controlSelection.selectionMoved$.subscribe(() => {
+ this._isLockedOnSelectionChangeRefString = false;
+ })
+ )
+ );
+
+ disposableCollection.add(
+ toDisposable(
+ controlSelection.selectionScaled$.subscribe(() => {
+ this._isLockedOnSelectionChangeRefString = false;
+ })
+ )
+ );
+ });
})
)
);
}
+ private _initialRefSelectionInsertEvent() {
+ this.disposeWithMe(
+ toDisposable(
+ this._selectionRenderService.selectionMoving$.subscribe((ranges) => {
+ if (ranges == null) {
+ return;
+ }
+
+ if (!this._isLockedOnSelectionInsertRefString) {
+ return;
+ }
+
+ this._isSelectionMoving = true;
+
+ this._inertControlSelection(ranges);
+ })
+ )
+ );
+
+ this.disposeWithMe(
+ toDisposable(
+ this._selectionRenderService.selectionMoveStart$.subscribe((ranges) => {
+ if (ranges == null) {
+ return;
+ }
+
+ if (!this._isLockedOnSelectionInsertRefString) {
+ return;
+ }
+
+ this._isSelectionMoving = true;
+
+ this._inertControlSelection(ranges);
+ })
+ )
+ );
+ }
+
+ /**
+ * 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,
+ * in order to generate reference text for the formula.
+ */
+ private _changeKeepVisibleHideState() {
+ if (this._getContextState() === false) {
+ this._disableForceKeepVisible();
+ return;
+ }
+
+ const char = this._getCurrentChar();
+
+ if (char == null) {
+ this._disableForceKeepVisible();
+ return;
+ }
+
+ if (this._matchRefDrawToken(char)) {
+ this._editorBridgeService.enableForceKeepVisible();
+
+ this._isLockedOnSelectionInsertRefString = true;
+
+ this._selectionRenderService.enableRemainLast();
+ } else {
+ this._disableForceKeepVisible();
+ }
+ }
+
+ private _matchRefDrawToken(char: string) {
+ return (
+ (isFormulaLexerToken(char) &&
+ char !== matchToken.CLOSE_BRACES &&
+ char !== matchToken.CLOSE_BRACKET &&
+ char !== matchToken.SINGLE_QUOTATION &&
+ char !== matchToken.DOUBLE_QUOTATION) ||
+ char === ' '
+ );
+ }
+
+ private _getCurrentChar() {
+ const activeRange = this._textSelectionRenderManager.getActiveRange();
+
+ if (activeRange == null) {
+ return;
+ }
+
+ const { startOffset } = activeRange;
+
+ const body = this._getCurrentBody();
+
+ if (body == null || startOffset == null) {
+ return;
+ }
+
+ const dataStream = body.dataStream;
+
+ return dataStream[startOffset - 1];
+ }
+
+ private _disableForceKeepVisible() {
+ this._editorBridgeService.disableForceKeepVisible();
+
+ this._isLockedOnSelectionInsertRefString = false;
+
+ this._currentInsertRefStringIndex = -1;
+ this._selectionRenderService.disableRemainLast();
+ }
+
private _getCurrentBody() {
- const state = this._editorBridgeService.getState();
- return state?.documentLayoutObject?.documentModel?.snapshot?.body;
+ const documentModel = this._currentUniverService.getUniverDocInstance(DOCS_NORMAL_EDITOR_UNIT_ID_KEY);
+ return documentModel?.snapshot?.body;
}
private _contextSwitch(currentInputValue: string) {
if (isFormulaString(currentInputValue)) {
this._contextService.setContextValue(FOCUSING_EDITOR_INPUT_FORMULA, true);
+
+ this._lastSequenceNodes =
+ this._formulaEngineService.buildSequenceNodes(
+ currentInputValue.replace(/\r/g, '').replace(/\n/g, '')
+ ) || [];
+
+ const activeRange = this._textSelectionRenderManager.getActiveRange();
+
+ if (activeRange == null) {
+ return;
+ }
+
+ const { startOffset } = activeRange;
+
+ this._currentInsertRefStringIndex = startOffset - 1;
} else {
this._contextService.setContextValue(FOCUSING_EDITOR_INPUT_FORMULA, false);
+ this._isLockedOnSelectionChangeRefString = false;
+ this._isLockedOnSelectionInsertRefString = false;
+
+ this._lastSequenceNodes = [];
}
}
@@ -238,6 +559,32 @@ export class PromptController extends Disposable {
});
}
+ /**
+ * Switch from formula selection state to regular selection state.
+ */
+ private _switchSelectionPlugin() {
+ if (this._getContextState() === true) {
+ this._selectionManagerService.changePluginNoRefresh(FORMULA_REF_SELECTION_PLUGIN_NAME);
+ // const selections = this._selectionManagerService.getSelections();
+ // if (selections == null || selections.length === 0) {
+ // const selectionData = this._selectionManagerService.getLastByPlugin(NORMAL_SELECTION_PLUGIN_NAME);
+ // if (selectionData != null) {
+ // this._selectionManagerService.add([Tools.deepClone(selectionData)]);
+ // }
+ // }
+
+ const style = getNormalSelectionStyle(this._themeService);
+ style.strokeDash = 8;
+ style.hasAutoFill = false;
+ style.hasRowHeader = false;
+ style.hasColumnHeader = false;
+ this._selectionRenderService.setStyle(style);
+ } else {
+ this._selectionManagerService.changePluginNoRefresh(NORMAL_SELECTION_PLUGIN_NAME);
+ this._selectionRenderService.resetStyle();
+ }
+ }
+
/**
*
* @param body the body object of the current input box
@@ -248,21 +595,24 @@ export class PromptController extends Disposable {
return;
}
- const dataStream = body.dataStream;
+ // const dataStream = body.dataStream;
- const sequenceNodes = this._formulaEngineService.buildSequenceNodes(
- dataStream.replace(/\r/g, '').replace(/\n/g, '')
- );
+ // const sequenceNodes = this._formulaEngineService.buildSequenceNodes(
+ // dataStream.replace(/\r/g, '').replace(/\n/g, '')
+ // );
- this._switchSelectionPlugin(FORMULA_REF_SELECTION_PLUGIN_NAME);
+ const sequenceNodes = this._lastSequenceNodes;
this._selectionManagerService.clear();
if (sequenceNodes == null || sequenceNodes.length === 0) {
body.textRuns = [];
} else {
- const textRuns: ITextRun[] = this._buildTextRuns(sequenceNodes);
+ // this._lastSequenceNodes = sequenceNodes;
+ const { textRuns, refSelections } = this._buildTextRuns(sequenceNodes);
body.textRuns = textRuns;
+
+ this._refreshSelectionForReference(refSelections);
}
this._refreshEditorObject();
@@ -271,15 +621,16 @@ export class PromptController extends Disposable {
/**
* :
* #
- *
+ * Generate styles for formula text, highlighting references, text, numbers, and arrays.
* @returns
*/
private _buildTextRuns(sequenceNodes: Array<ISequenceNode | string>) {
const textRuns: ITextRun[] = [];
const refSelections: IRefSelection[] = [];
- let refIndex = 0;
+ let refColorIndex = 0;
- for (const node of sequenceNodes) {
+ for (let i = 0, len = sequenceNodes.length; i < len; i++) {
+ const node = sequenceNodes[i];
if (typeof node === 'string') {
continue;
}
@@ -287,16 +638,16 @@ export class PromptController extends Disposable {
const { startIndex, endIndex, nodeType, token } = node;
let themeColor = '';
if (nodeType === sequenceNodeType.REFERENCE) {
- const colorIndex = refIndex % this._formulaRefColors.length;
+ const colorIndex = refColorIndex % this._formulaRefColors.length;
themeColor = this._formulaRefColors[colorIndex];
refSelections.push({
- refIndex,
+ refIndex: i,
themeColor,
token,
});
- refIndex++;
+ refColorIndex++;
} else if (nodeType === sequenceNodeType.NUMBER) {
themeColor = this._numberColor;
} else if (nodeType === sequenceNodeType.STRING) {
@@ -318,26 +669,33 @@ export class PromptController extends Disposable {
}
}
- this._refreshSelectionForReference(refSelections);
-
- console.log('sequenceNodes', sequenceNodes, textRuns);
+ // console.log('sequenceNodes', sequenceNodes, textRuns);
- return textRuns;
+ return { textRuns, refSelections };
}
+ /**
+ * Draw the referenced selection text based on the style and token.
+ * @param refSelections
+ * @returns
+ */
private _refreshSelectionForReference(refSelections: IRefSelection[]) {
- const current = this._sheetSkeletonManagerService.getCurrent();
+ const { unitId, sheetId } = this._getCurrentUnitIdAndSheetId();
- if (current == null) {
+ const selectionWithStyle: ISelectionWithStyle[] = [];
+
+ const workbook = this._currentUniverService.getUniverSheetInstance(unitId);
+ const worksheet = workbook?.getSheetBySheetId(sheetId);
+
+ if (worksheet == null) {
return;
}
- const { unitId, sheetId } = current;
-
- const selectionWithStyle: ISelectionWithStyle[] = [];
+ let lastRange: Nullable<ISelectionWithStyle> = null;
- for (const refSelection of refSelections) {
- const { themeColor, token } = refSelection;
+ for (let i = 0, len = refSelections.length; i < len; i++) {
+ const refSelection = refSelections[i];
+ const { themeColor, token, refIndex } = refSelection;
const gridRange = deserializeRangeWithSheet(token);
@@ -353,13 +711,41 @@ export class PromptController extends Disposable {
continue;
}
+ const primary = this._insertSelections.find((selection) => {
+ const { startRow, startColumn, endRow, endColumn } = selection.range;
+ if (
+ startRow === range.startRow &&
+ startColumn === range.startColumn &&
+ endRow === range.endRow &&
+ endColumn === range.endColumn
+ ) {
+ return true;
+ }
+
+ return false;
+ })?.primary;
+
+ if (primary != null) {
+ lastRange = {
+ range,
+ primary,
+ style: getFormulaRefSelectionStyle(this._themeService, themeColor, refIndex.toString()),
+ };
+
+ continue;
+ }
+
selectionWithStyle.push({
range,
- primary: null,
- style: getFormulaRefSelectionStyle(this._themeService, themeColor),
+ primary,
+ style: getFormulaRefSelectionStyle(this._themeService, themeColor, refIndex.toString()),
});
}
+ if (lastRange) {
+ selectionWithStyle.push(lastRange);
+ }
+
if (selectionWithStyle.length === 0) {
return;
}
@@ -367,72 +753,447 @@ export class PromptController extends Disposable {
this._selectionManagerService.add(selectionWithStyle);
}
- private _switchSelectionPlugin(pluginName: string) {
+ private _getSheetIdByName(unitId: string, sheetName: string) {
+ const workbook = this._currentUniverService.getUniverSheetInstance(unitId);
+
+ return workbook?.getSheetBySheetName(normalizeSheetName(sheetName))?.getSheetId();
+ }
+
+ private _getSheetNameById(unitId: string, sheetId: string) {
+ const workbook = this._currentUniverService.getUniverSheetInstance(unitId);
+
+ let sheetName = workbook?.getSheetBySheetId(sheetId)?.getName() || '';
+
+ if (sheetName.length > 0 && includeFormulaLexerToken(sheetName)) {
+ sheetName = `'${sheetName}'`;
+ }
+
+ return sheetName;
+ }
+
+ private _getCurrentUnitIdAndSheetId() {
const current = this._sheetSkeletonManagerService.getCurrent();
if (current == null) {
- return;
+ const workbook = this._currentUniverService.getCurrentUniverSheetInstance();
+ const worksheet = workbook.getActiveSheet();
+ return {
+ unitId: workbook.getUnitId(),
+ sheetId: worksheet.getSheetId(),
+ };
}
const { unitId, sheetId } = current;
- this._selectionManagerService.setCurrentSelectionNotRefresh({
- pluginName,
+ return {
unitId,
sheetId,
+ };
+ }
+
+ private _getRefString(range: IRange) {
+ 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;
+ return serializeRangeToRefString({
+ sheetName: refSheetName,
+ unitId: refUnitId,
+ range: {
+ startRow,
+ endRow,
+ startColumn,
+ endColumn,
+ },
});
}
- private _getSheetIdByName(unitId: string, sheetName: string) {
- const workbook = this._currentUniverService.getUniverSheetInstance(unitId);
+ /**
+ * 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;
- return workbook?.getSheetBySheetName(sheetName)?.getSheetId();
+ 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);
}
- private _initialRefSelectionEvent() {
- const disposableCollection = new DisposableCollection();
+ /**
+ * 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;
+ }
- this.disposeWithMe(
- toDisposable(
- this._selectionManagerService.selectionInfo$.subscribe(() => {
- // Each range change requires re-listening
- disposableCollection.dispose();
+ // 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;
+
+ const nodeIndex = this._searchSequenceIndex(sequenceNodes, index);
+
+ sequenceNodes.splice(nodeIndex, 0, {
+ token: refString,
+ startIndex: index,
+ endIndex: index + refStringCount - 1,
+ nodeType: sequenceNodeType.REFERENCE,
+ });
- const current = this._selectionManagerService.getCurrent();
+ for (let i = nodeIndex + 1, len = sequenceNodes.length; i < len; i++) {
+ const node = sequenceNodes[i];
+ if (typeof node === 'string') {
+ continue;
+ }
- if (current?.pluginName !== FORMULA_REF_SELECTION_PLUGIN_NAME) {
- return;
- }
+ node.startIndex += refStringCount;
+ node.endIndex += refStringCount;
+ }
- const selectionControls = this._selectionRenderService.getCurrentControls();
- selectionControls.forEach((controlSelection) => {
- disposableCollection.add(
- toDisposable(
- controlSelection.selectionMoving$.subscribe((toRange) => {
- if (!toRange) {
- return;
- }
+ this._sycToEditor(sequenceNodes, index + refStringCount);
+ }
- console.log('formulaRefSelections', toRange);
- })
- )
- );
+ 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);
- disposableCollection.add(
- toDisposable(
- controlSelection.selectionScaling$.subscribe((toRange) => {
- if (!toRange) {
- return;
- }
+ const contentCount = str.length;
- console.log('formulaRefSelections', toRange);
- })
- )
- );
- });
- })
- )
- );
+ 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;
+ }
+ }
+
+ 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;
+ }
+
+ private async _sycToEditor(sequenceNodes: Array<string | ISequenceNode>, textSelectionOffset: number) {
+ const dataStream = this._generateStringWithSequence(sequenceNodes);
+
+ const { textRuns, refSelections } = this._buildTextRuns(sequenceNodes);
+
+ this._isSelectionMovingRefSelections = refSelections;
+
+ this._updateEditorModel(`=${dataStream}\r\n`, textRuns);
+
+ const activeRange = this._textSelectionManagerService.getLast();
+
+ if (activeRange == null) {
+ return;
+ }
+
+ const { collapsed, style } = activeRange;
+
+ this._currentInsertRefStringIndex = textSelectionOffset;
+
+ await this._commandService.syncExecuteCommand(SetEditorResizeOperation.id, {
+ unitId: DOCS_NORMAL_EDITOR_UNIT_ID_KEY,
+ });
+
+ this._textSelectionManagerService.replaceTextRanges([
+ {
+ startOffset: textSelectionOffset + 1,
+ endOffset: textSelectionOffset + 1,
+ collapsed,
+ style,
+ },
+ ]);
+ }
+
+ /**
+ * Deserialize Sequence to text.
+ * @param newSequenceNodes
+ * @returns
+ */
+ private _generateStringWithSequence(newSequenceNodes: Array<string | ISequenceNode>) {
+ let sequenceString = '';
+ for (const node of newSequenceNodes) {
+ if (typeof node === 'string') {
+ sequenceString += node;
+ } else {
+ sequenceString += node.token;
+ }
+ }
+ return sequenceString;
+ }
+
+ /**
+ * Update the editor's model value to facilitate formula updates.
+ * @param dataStream
+ * @param textRuns
+ * @returns
+ */
+ private _updateEditorModel(dataStream: string, textRuns: ITextRun[]) {
+ const documentModel = this._currentUniverService.getUniverDocInstance(DOCS_NORMAL_EDITOR_UNIT_ID_KEY);
+ const bodyModel = documentModel?.getBodyModel();
+ if (bodyModel == null) {
+ return;
+ }
+
+ const snapshot = documentModel?.snapshot;
+
+ if (snapshot == null) {
+ return;
+ }
+
+ const newBody = {
+ dataStream,
+ textRuns,
+ };
+
+ bodyModel.reset(newBody);
+
+ snapshot.body = newBody;
+ }
+
+ private _inertControlSelectionReplace(currentRange: IRange) {
+ if (this._previousSequenceNodes == null) {
+ this._previousSequenceNodes = this._lastSequenceNodes;
+ }
+
+ if (this._previousInsertRefStringIndex == null) {
+ this._previousInsertRefStringIndex = this._currentInsertRefStringIndex;
+ }
+
+ // No new control is added, the current ref string is still modified.
+ const insertNodes = Tools.deepClone(this._previousSequenceNodes);
+ if (insertNodes == null) {
+ return;
+ }
+
+ this._insertSequenceRef(insertNodes, this._previousInsertRefStringIndex, currentRange);
+
+ this._lastSequenceNodes = insertNodes;
+
+ const selectionDatas = this._selectionRenderService.getSelectionDataWithStyle();
+
+ this._insertSelections = [];
+
+ selectionDatas.forEach((currentSelection) => {
+ const range = convertSelectionDataToRange(currentSelection);
+ this._insertSelections.push(range);
+ });
+
+ // const currentSelection = selectionDatas[selectionDatas.length - 1];
+
+ // if (currentSelection.primaryWithCoord != null) {
+ // this._lastPrimaryCell = ;
+ // }
+ }
+
+ private _inertControlSelection(ranges: IRange[]) {
+ const currentRange = ranges[ranges.length - 1];
+
+ if (
+ (ranges.length === this._previousRangesCount || this._previousRangesCount === 0) &&
+ this._previousSequenceNodes != null
+ ) {
+ this._inertControlSelectionReplace(currentRange);
+ } else {
+ // Holding down ctrl causes an addition, requiring the ref string to be increased.
+ const insertNodes = this._lastSequenceNodes;
+
+ if (insertNodes == null) {
+ return;
+ }
+
+ const char = this._getCurrentChar();
+
+ if (char == null) {
+ return;
+ }
+
+ this._previousInsertRefStringIndex = this._currentInsertRefStringIndex;
+
+ if (!this._matchRefDrawToken(char)) {
+ this._insertSequenceString(insertNodes, this._currentInsertRefStringIndex, matchToken.COMMA);
+
+ this._previousInsertRefStringIndex += 1;
+ }
+
+ this._previousSequenceNodes = Tools.deepClone(insertNodes);
+
+ this._insertSequenceRef(insertNodes, this._previousInsertRefStringIndex, currentRange);
+
+ this._lastSequenceNodes = insertNodes;
+
+ this._selectionRenderService.disableSkipRemainLast();
+ }
+
+ this._previousRangesCount = ranges.length;
+ }
+
+ private _updateRefSelectionStyle(refSelections: IRefSelection[]) {
+ const controls = this._selectionRenderService.getCurrentControls();
+
+ const { unitId, sheetId } = this._getCurrentUnitIdAndSheetId();
+
+ for (let i = 0, len = refSelections.length; i < len; i++) {
+ const refSelection = refSelections[i];
+
+ const { refIndex, themeColor, token } = refSelection;
+
+ const rangeWithSheet = deserializeRangeWithSheet(token);
+
+ const { unitId: refUnitId, sheetName, range } = rangeWithSheet;
+
+ if (refUnitId != null && refUnitId.length > 0 && unitId !== refUnitId) {
+ continue;
+ }
+
+ const refSheetId = this._getSheetIdByName(unitId, sheetName.trim());
+
+ if (refSheetId != null && refSheetId !== sheetId) {
+ continue;
+ }
+
+ const control = controls.find((c) => {
+ const { startRow, startColumn, endRow, endColumn } = c.getRange();
+ if (
+ startRow === range.startRow &&
+ startColumn === range.startColumn &&
+ endRow === range.endRow &&
+ endColumn === range.endColumn
+ ) {
+ return true;
+ }
+
+ return false;
+ });
+
+ if (control == null) {
+ continue;
+ }
+
+ const style = getFormulaRefSelectionStyle(this._themeService, themeColor, refIndex.toString());
+
+ control.updateStyle(style);
+ }
+ }
+
+ private _changeControlSelection(toRange: Nullable<IRangeWithCoord>, controlSelection: SelectionShape) {
+ if (!toRange) {
+ return;
+ }
+
+ this._isLockedOnSelectionChangeRefString = true;
+
+ const id = controlSelection.selectionStyle?.id;
+
+ if (id == null || !Tools.isStringNumber(id)) {
+ return;
+ }
+
+ this._updateSequenceRef(this._lastSequenceNodes, Number(id), toRange);
+
+ controlSelection.update(toRange);
}
private _refreshEditorObject() {
@@ -455,6 +1216,77 @@ export class PromptController extends Disposable {
documentComponent?.makeDirty();
}
+ private _commandExecutedListener() {
+ // Listen to document edits to refresh the size of the editor.
+ const updateCommandList = [SelectEditorFormulaOperation.id];
+
+ this.disposeWithMe(
+ this._commandService.onCommandExecuted((command: ICommandInfo) => {
+ if (updateCommandList.includes(command.id)) {
+ const params = command.params as ISelectEditorFormulaOperationParam;
+ const { keycode, metaKey } = params;
+
+ if (keycode === KeyCode.ENTER) {
+ console.log('ENTER');
+ return;
+ }
+ if (keycode === KeyCode.TAB) {
+ console.log('TAB');
+ return;
+ }
+
+ const previousRanges = this._selectionManagerService.getSelectionRanges() || [];
+
+ if (previousRanges.length === 0) {
+ const selectionData =
+ this._selectionManagerService.getLastByPlugin(NORMAL_SELECTION_PLUGIN_NAME);
+ if (selectionData != null) {
+ const selectionDataNew = Tools.deepClone(selectionData);
+ this._selectionManagerService.add([selectionDataNew]);
+ }
+ }
+
+ let direction = Direction.DOWN;
+ if (keycode === KeyCode.ARROW_DOWN) {
+ direction = Direction.DOWN;
+ } else if (keycode === KeyCode.ARROW_UP) {
+ direction = Direction.UP;
+ } else if (keycode === KeyCode.ARROW_LEFT) {
+ direction = Direction.LEFT;
+ } else if (keycode === KeyCode.ARROW_RIGHT) {
+ direction = Direction.RIGHT;
+ }
+
+ if (metaKey === MetaKeys.CTRL_COMMAND) {
+ this._commandService.executeCommand(MoveSelectionCommand.id, {
+ direction,
+ jumpOver: JumpOver.moveGap,
+ });
+ } else if (metaKey === MetaKeys.SHIFT) {
+ this._commandService.executeCommand(ExpandSelectionCommand.id, {
+ direction,
+ });
+ } else if (metaKey === META_KEY_CTRL_AND_SHIFT) {
+ this._commandService.executeCommand(ExpandSelectionCommand.id, {
+ direction,
+ jumpOver: JumpOver.moveGap,
+ });
+ } else {
+ this._commandService.executeCommand(MoveSelectionCommand.id, {
+ direction,
+ });
+ }
+
+ const ranges = this._selectionManagerService.getSelectionRanges() || [];
+
+ const currentRange = ranges[ranges.length - 1];
+
+ this._inertControlSelectionReplace(currentRange);
+ }
+ })
+ );
+ }
+
private _getEditorObject() {
return getEditorObject(DOCS_NORMAL_EDITOR_UNIT_ID_KEY, 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 cf261f9abb..8be92df683 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
@@ -1,10 +1,11 @@
import { DeviceInputEventType } from '@univerjs/base-render';
-import { IShortcutItem, KeyCode } from '@univerjs/base-ui';
+import { IShortcutItem, KeyCode, MetaKeys } from '@univerjs/base-ui';
import { whenEditorInputFormulaActivated } from '@univerjs/ui-plugin-sheets';
import { SelectEditorFormulaOperation } from '../../commands/operations/editor-formula.operation';
+import { META_KEY_CTRL_AND_SHIFT } from '../../common/prompt';
-export const PROMPT_SELECTION_KEYCODE_LIST = [
+export const PROMPT_SELECTION_KEYCODE_ARROW_LIST = [
KeyCode.ARROW_DOWN,
KeyCode.ARROW_UP,
KeyCode.ARROW_LEFT,
@@ -13,6 +14,8 @@ export const PROMPT_SELECTION_KEYCODE_LIST = [
KeyCode.TAB,
];
+export const PROMPT_SELECTION_KEYCODE_LIST = [...PROMPT_SELECTION_KEYCODE_ARROW_LIST, KeyCode.ENTER, KeyCode.TAB];
+
export function promptSelectionShortcutItem() {
const shortcutList: IShortcutItem[] = [];
for (const keycode of PROMPT_SELECTION_KEYCODE_LIST) {
@@ -28,3 +31,54 @@ export function promptSelectionShortcutItem() {
}
return shortcutList;
}
+
+export function promptSelectionShortcutItemShift() {
+ const shortcutList: IShortcutItem[] = [];
+ for (const keycode of PROMPT_SELECTION_KEYCODE_ARROW_LIST) {
+ shortcutList.push({
+ id: SelectEditorFormulaOperation.id,
+ binding: keycode | MetaKeys.SHIFT,
+ preconditions: (contextService) => whenEditorInputFormulaActivated(contextService),
+ staticParameters: {
+ eventType: DeviceInputEventType.Keyboard,
+ keycode,
+ metaKey: MetaKeys.SHIFT,
+ },
+ });
+ }
+ return shortcutList;
+}
+
+export function promptSelectionShortcutItemCtrl() {
+ const shortcutList: IShortcutItem[] = [];
+ for (const keycode of PROMPT_SELECTION_KEYCODE_ARROW_LIST) {
+ shortcutList.push({
+ id: SelectEditorFormulaOperation.id,
+ binding: keycode | MetaKeys.CTRL_COMMAND,
+ preconditions: (contextService) => whenEditorInputFormulaActivated(contextService),
+ staticParameters: {
+ eventType: DeviceInputEventType.Keyboard,
+ keycode,
+ metaKey: MetaKeys.CTRL_COMMAND,
+ },
+ });
+ }
+ return shortcutList;
+}
+
+export function promptSelectionShortcutItemCtrlAndShift() {
+ const shortcutList: IShortcutItem[] = [];
+ for (const keycode of PROMPT_SELECTION_KEYCODE_ARROW_LIST) {
+ shortcutList.push({
+ id: SelectEditorFormulaOperation.id,
+ binding: keycode | MetaKeys.SHIFT | MetaKeys.CTRL_COMMAND,
+ preconditions: (contextService) => whenEditorInputFormulaActivated(contextService),
+ staticParameters: {
+ eventType: DeviceInputEventType.Keyboard,
+ keycode,
+ metaKey: META_KEY_CTRL_AND_SHIFT,
+ },
+ });
+ }
+ return shortcutList;
+}
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 8f6821e2d8..0110ff46a3 100644
--- a/packages/sheets-plugin-formula-ui/src/services/prompt.service.ts
+++ b/packages/sheets-plugin-formula-ui/src/services/prompt.service.ts
@@ -124,6 +124,7 @@ export class FormulaPromptService implements IFormulaPromptService, IDisposable
private _searching: boolean = false;
private _helping: boolean = false;
+ private _isInsertRefString: boolean = false;
dispose(): void {
this._search$.complete();
diff --git a/packages/ui-plugin-sheets/src/commands/operations/cell-edit.operation.ts b/packages/ui-plugin-sheets/src/commands/operations/cell-edit.operation.ts
index 865b73dd08..43218c822f 100644
--- a/packages/ui-plugin-sheets/src/commands/operations/cell-edit.operation.ts
+++ b/packages/ui-plugin-sheets/src/commands/operations/cell-edit.operation.ts
@@ -20,6 +20,10 @@ export const SetCellEditVisibleOperation: IOperation<IEditorBridgeServiceVisible
},
};
+/**
+ * When the editor is not clicked to change the cursor,
+ * the arrow keys will exit editing and move the cell.
+ */
export const SetCellEditVisibleArrowOperation: IOperation<IEditorBridgeServiceVisibleParam> = {
id: 'sheet.operation.set-cell-edit-visible-arrow',
type: CommandType.OPERATION,
diff --git a/packages/ui-plugin-sheets/src/commands/operations/set-editor-resize.operation.ts b/packages/ui-plugin-sheets/src/commands/operations/set-editor-resize.operation.ts
new file mode 100644
index 0000000000..b2a02d3238
--- /dev/null
+++ b/packages/ui-plugin-sheets/src/commands/operations/set-editor-resize.operation.ts
@@ -0,0 +1,9 @@
+// This file provide operations to change selection of sheets.
+
+import { CommandType, IOperation } from '@univerjs/core';
+
+export const SetEditorResizeOperation: IOperation = {
+ id: 'sheet.operation.set-editor-resize',
+ type: CommandType.OPERATION,
+ handler: (accessor, params) => true,
+};
diff --git a/packages/ui-plugin-sheets/src/controllers/auto-fill.controller.ts b/packages/ui-plugin-sheets/src/controllers/auto-fill.controller.ts
index e262e10cc7..56e82ee8dd 100644
--- a/packages/ui-plugin-sheets/src/controllers/auto-fill.controller.ts
+++ b/packages/ui-plugin-sheets/src/controllers/auto-fill.controller.ts
@@ -1,5 +1,5 @@
import { getCellInfoInMergeData } from '@univerjs/base-render';
-import { SelectionManagerService } from '@univerjs/base-sheets';
+import { NORMAL_SELECTION_PLUGIN_NAME, SelectionManagerService } from '@univerjs/base-sheets';
import {
Direction,
Disposable,
@@ -95,6 +95,16 @@ export class AutoFillController extends Disposable {
// Each range change requires re-listening
disposableCollection.dispose();
+ const current = this._selectionManagerService.getCurrent();
+
+ /**
+ * Auto fill only responds to regular selections;
+ * it does not apply to selections for features like formulas or charts.
+ */
+ if (current?.pluginName !== NORMAL_SELECTION_PLUGIN_NAME) {
+ return;
+ }
+
const selectionControls = this._selectionRenderService.getCurrentControls();
selectionControls.forEach((controlSelection) => {
disposableCollection.add(
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 b9c728c436..25d086be29 100644
--- a/packages/ui-plugin-sheets/src/controllers/editor-bridge.controller.ts
+++ b/packages/ui-plugin-sheets/src/controllers/editor-bridge.controller.ts
@@ -1,5 +1,10 @@
import { DeviceInputEventType, getCanvasOffsetByEngine, IRenderManagerService } from '@univerjs/base-render';
-import { COMMAND_LISTENER_SKELETON_CHANGE, SelectionManagerService } from '@univerjs/base-sheets';
+import {
+ COMMAND_LISTENER_SKELETON_CHANGE,
+ NORMAL_SELECTION_PLUGIN_NAME,
+ SelectionManagerService,
+ SetWorksheetActivateMutation,
+} from '@univerjs/base-sheets';
import {
Disposable,
ICommandInfo,
@@ -51,6 +56,15 @@ export class EditorBridgeController extends Disposable {
private _initialSelectionListener() {
this._selectionManagerService.selectionInfo$.subscribe((params) => {
+ const current = this._selectionManagerService.getCurrent();
+
+ /**
+ * The editor only responds to regular selections.
+ */
+ if (current?.pluginName !== NORMAL_SELECTION_PLUGIN_NAME) {
+ return;
+ }
+
const currentSkeletonManager = this._sheetSkeletonManagerService.getCurrent();
const sheetObject = this._getSheetObject();
@@ -146,34 +160,47 @@ export class EditorBridgeController extends Disposable {
});
});
- spreadsheet.onPointerDownObserver.add(this._hideEditor.bind(this));
- spreadsheetColumnHeader.onPointerDownObserver.add(this._hideEditor.bind(this));
- spreadsheetLeftTopPlaceholder.onPointerDownObserver.add(this._hideEditor.bind(this));
- spreadsheetRowHeader.onPointerDownObserver.add(this._hideEditor.bind(this));
+ spreadsheet.onPointerDownObserver.add(this._keepVisibleHideEditor.bind(this));
+ spreadsheetColumnHeader.onPointerDownObserver.add(this._keepVisibleHideEditor.bind(this));
+ spreadsheetLeftTopPlaceholder.onPointerDownObserver.add(this._keepVisibleHideEditor.bind(this));
+ spreadsheetRowHeader.onPointerDownObserver.add(this._keepVisibleHideEditor.bind(this));
}
- private _hideEditor() {
- if (this._editorBridgeService.isVisible().visible === true) {
- this._selectionManagerService.makeDirty(false);
- this._commandService.executeCommand(SetCellEditVisibleOperation.id, {
- visible: false,
- eventType: DeviceInputEventType.PointerDown,
- });
+ /**
+ * In the activated state of formula editing,
+ * prohibit closing the editor according to the state to facilitate generating selection reference text.
+ */
+ private _keepVisibleHideEditor() {
+ if (this._editorBridgeService.isForceKeepVisible()) {
+ return;
+ }
+ this._hideEditor();
+ }
- /**
- * Hiding the editor triggers a SetRangeValuesMutation which saves the content.
- * This mutation, in turn, triggers a refresh of the skeleton,
- * causing the selection to update. In most scenarios,
- * this update is reasonable. However, when clicking on another cell and exiting the edit,
- * this causes the selection to be reset. Therefore,
- * a makeDirty method has been added here to block the refresh of selection.
- * The reason for using setTimeout is that it needs to wait for the process
- * to finish before allowing the refresh of the selection.
- */
- setTimeout(() => {
- this._selectionManagerService.makeDirty(true);
- }, 0);
+ private _hideEditor() {
+ if (this._editorBridgeService.isVisible().visible !== true) {
+ return;
}
+
+ this._selectionManagerService.makeDirty(false);
+ this._commandService.executeCommand(SetCellEditVisibleOperation.id, {
+ visible: false,
+ eventType: DeviceInputEventType.PointerDown,
+ });
+
+ /**
+ * Hiding the editor triggers a SetRangeValuesMutation which saves the content.
+ * This mutation, in turn, triggers a refresh of the skeleton,
+ * causing the selection to update. In most scenarios,
+ * this update is reasonable. However, when clicking on another cell and exiting the edit,
+ * this causes the selection to be reset. Therefore,
+ * a makeDirty method has been added here to block the refresh of selection.
+ * The reason for using setTimeout is that it needs to wait for the process
+ * to finish before allowing the refresh of the selection.
+ */
+ setTimeout(() => {
+ this._selectionManagerService.makeDirty(true);
+ }, 0);
}
private _getSheetObject() {
@@ -185,7 +212,9 @@ export class EditorBridgeController extends Disposable {
this.disposeWithMe(
this._commandService.onCommandExecuted((command: ICommandInfo) => {
- if (updateCommandList.includes(command.id)) {
+ if (command.id === SetWorksheetActivateMutation.id) {
+ this._keepVisibleHideEditor();
+ } else if (updateCommandList.includes(command.id)) {
this._hideEditor();
}
})
diff --git a/packages/ui-plugin-sheets/src/controllers/editor/editing.controller.ts b/packages/ui-plugin-sheets/src/controllers/editor/editing.controller.ts
index 33cecec86b..7d8267fa20 100644
--- a/packages/ui-plugin-sheets/src/controllers/editor/editing.controller.ts
+++ b/packages/ui-plugin-sheets/src/controllers/editor/editing.controller.ts
@@ -114,7 +114,7 @@ export class EditingController extends Disposable {
console.log(
'calculate',
- this._formulaEngineService.calculate('=REDUCE(1, [2sjasdfjdadsf]sheet1!A:B1, LAMBDA(a,b,a+b^2))', false)
+ this._formulaEngineService.calculate(`=REDUCE(1, 'sheeASDF%#@ASDFt-1'!A:B1, LAMBDA(a,b,a+b^2))`, false)
);
}
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 9552d9a8cc..c54dda9ddd 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
@@ -49,6 +49,7 @@ import { Subscription } from 'rxjs';
import { getEditorObject } from '../../basics/editor/get-editor-object';
import { SetCellEditVisibleOperation } from '../../commands/operations/cell-edit.operation';
+import { SetEditorResizeOperation } from '../../commands/operations/set-editor-resize.operation';
import { ICellEditorManagerService } from '../../services/editor/cell-editor-manager.service';
import { IEditorBridgeService } from '../../services/editor-bridge.service';
import styles from '../../views/sheet-container/index.module.less';
@@ -112,7 +113,7 @@ export class StartEditController extends Disposable {
private _initialEditFocusListener() {
this._onInputSubscription = this._editorBridgeService.state$.subscribe((param) => {
- if (param == null) {
+ if (param == null || this._editorBridgeService.isForceKeepVisible()) {
return;
}
@@ -348,7 +349,9 @@ export class StartEditController extends Disposable {
this._addBackground(scene, editorWidth, editorHeight, fill);
// resize canvas
- engine.resizeBySize(editorWidth, physicHeight);
+ setTimeout(() => {
+ engine.resizeBySize(editorWidth, physicHeight);
+ }, 0);
this._cellEditorManagerService.setState({
startX,
@@ -544,7 +547,7 @@ export class StartEditController extends Disposable {
private _commandExecutedListener() {
// Listen to document edits to refresh the size of the editor.
- const updateCommandList = [RichTextEditingMutation.id];
+ const updateCommandList = [RichTextEditingMutation.id, SetEditorResizeOperation.id];
const excludeUnitList = [DOCS_NORMAL_EDITOR_UNIT_ID_KEY];
diff --git a/packages/ui-plugin-sheets/src/controllers/move-range.controller.ts b/packages/ui-plugin-sheets/src/controllers/move-range.controller.ts
index 0067acdcdc..d93e3c96f1 100644
--- a/packages/ui-plugin-sheets/src/controllers/move-range.controller.ts
+++ b/packages/ui-plugin-sheets/src/controllers/move-range.controller.ts
@@ -38,6 +38,10 @@ export class MoveRangeController extends Disposable {
const current = this._selectionManagerService.getCurrent();
+ /**
+ * Moving the selection only responds to regular selections;
+ * it does not apply to selections for features like formulas or charts.
+ */
if (current?.pluginName !== NORMAL_SELECTION_PLUGIN_NAME) {
return;
}
diff --git a/packages/ui-plugin-sheets/src/controllers/selection.controller.ts b/packages/ui-plugin-sheets/src/controllers/selection.controller.ts
index c4f3757e05..fd32909131 100644
--- a/packages/ui-plugin-sheets/src/controllers/selection.controller.ts
+++ b/packages/ui-plugin-sheets/src/controllers/selection.controller.ts
@@ -254,16 +254,25 @@ export class SelectionController extends Disposable {
this._selectionRenderService.changeRuntime(skeleton, scene, viewportMain);
+ /**
+ * Features like formulas can select ranges across sub-tables.
+ * If the current pluginName is not in a normal state,
+ * the current selection will not be refreshed.
+ */
+ const current = this._selectionManagerService.getCurrent();
+ const pluginName = current?.pluginName || NORMAL_SELECTION_PLUGIN_NAME;
this._selectionManagerService.setCurrentSelection({
- pluginName: NORMAL_SELECTION_PLUGIN_NAME,
+ pluginName,
unitId,
sheetId,
});
- // If there is no initial selection, add one by default in the top left corner.
- const last = this._selectionManagerService.getLast();
- if (last == null) {
- this._selectionManagerService.add([this._getZeroRange(skeleton)]);
+ if (pluginName === NORMAL_SELECTION_PLUGIN_NAME) {
+ // If there is no initial selection, add one by default in the top left corner.
+ const last = this._selectionManagerService.getLast();
+ if (last == null) {
+ this._selectionManagerService.add([this._getZeroRange(skeleton)]);
+ }
}
});
}
diff --git a/packages/ui-plugin-sheets/src/controllers/sheet-ui.controller.ts b/packages/ui-plugin-sheets/src/controllers/sheet-ui.controller.ts
index 568b0e5a39..27e3dfe318 100644
--- a/packages/ui-plugin-sheets/src/controllers/sheet-ui.controller.ts
+++ b/packages/ui-plugin-sheets/src/controllers/sheet-ui.controller.ts
@@ -52,6 +52,7 @@ import {
} from '../commands/operations/cell-edit.operation';
import { SetScrollOperation } from '../commands/operations/scroll.operation';
import { SetCopySelectionsOperation } from '../commands/operations/selection.operation';
+import { SetEditorResizeOperation } from '../commands/operations/set-editor-resize.operation';
import { SetFormatPainterOperation } from '../commands/operations/set-format-painter.operation';
import { SetZoomRatioOperation } from '../commands/operations/set-zoom-ratio.operation';
import { BorderPanel } from '../components/border-panel/BorderPanel';
@@ -213,6 +214,7 @@ export class SheetUIController extends Disposable {
ScrollCommand,
SelectAllCommand,
SetActivateCellEditOperation,
+ SetEditorResizeOperation,
SetBoldCommand,
SetCellEditVisibleArrowOperation,
SetCellEditVisibleOperation,
diff --git a/packages/ui-plugin-sheets/src/controllers/shortcuts/utils.ts b/packages/ui-plugin-sheets/src/controllers/shortcuts/utils.ts
index 0f3eafc2f5..a08c49ab52 100644
--- a/packages/ui-plugin-sheets/src/controllers/shortcuts/utils.ts
+++ b/packages/ui-plugin-sheets/src/controllers/shortcuts/utils.ts
@@ -34,3 +34,11 @@ export function whenEditorDidNotInputFormulaActivated(contextService: IContextSe
!contextService.getContextValue(FOCUSING_EDITOR_INPUT_FORMULA)
);
}
+
+export function whenEditorNotActivatedOrFormulaActivated(contextService: IContextService) {
+ return (
+ contextService.getContextValue(FOCUSING_SHEET) &&
+ (!contextService.getContextValue(FOCUSING_EDITOR) ||
+ contextService.getContextValue(FOCUSING_EDITOR_INPUT_FORMULA))
+ );
+}
diff --git a/packages/ui-plugin-sheets/src/index.ts b/packages/ui-plugin-sheets/src/index.ts
index 4959c57c2e..3ca97f205a 100644
--- a/packages/ui-plugin-sheets/src/index.ts
+++ b/packages/ui-plugin-sheets/src/index.ts
@@ -1,7 +1,9 @@
export * from './basics';
export { getEditorObject } from './basics/editor/get-editor-object';
+export { ExpandSelectionCommand, JumpOver, MoveSelectionCommand } from './commands/commands/set-selection.command';
export { SetCellEditVisibleArrowOperation } from './commands/operations/cell-edit.operation';
export { SetScrollOperation } from './commands/operations/scroll.operation';
+export { SetEditorResizeOperation } from './commands/operations/set-editor-resize.operation';
export { SetZoomRatioOperation } from './commands/operations/set-zoom-ratio.operation';
export { RangeSelector } from './components/range-selector/RangeSelector';
export { whenEditorInputFormulaActivated } from './controllers/shortcuts/utils';
@@ -18,5 +20,6 @@ export {
type IEditorBridgeServiceVisibleParam,
} from './services/editor-bridge.service';
export { ISelectionRenderService } from './services/selection/selection-render.service';
+export { SelectionShape } from './services/selection/selection-shape';
export { SheetSkeletonManagerService } from './services/sheet-skeleton-manager.service';
export { SheetUIPlugin } from './sheet-ui-plugin';
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 7f2193a583..bb2de31dd9 100644
--- a/packages/ui-plugin-sheets/src/services/editor-bridge.service.ts
+++ b/packages/ui-plugin-sheets/src/services/editor-bridge.service.ts
@@ -30,11 +30,16 @@ export interface IEditorBridgeService {
getState(): Readonly<Nullable<IEditorBridgeServiceParam>>;
changeVisible(param: IEditorBridgeServiceVisibleParam): void;
isVisible(): IEditorBridgeServiceVisibleParam;
+ enableForceKeepVisible(): void;
+ disableForceKeepVisible(): void;
+ isForceKeepVisible(): boolean;
}
export class EditorBridgeService implements IEditorBridgeService, IDisposable {
private _state: Nullable<IEditorBridgeServiceParam> = null;
+ private _isForceKeepVisible: boolean = false;
+
private _visible: IEditorBridgeServiceVisibleParam = {
visible: false,
eventType: DeviceInputEventType.Dblclick,
@@ -46,6 +51,9 @@ export class EditorBridgeService implements IEditorBridgeService, IDisposable {
private readonly _visible$ = new BehaviorSubject<IEditorBridgeServiceVisibleParam>(this._visible);
readonly visible$ = this._visible$.asObservable();
+ private readonly _afterVisible$ = new BehaviorSubject<IEditorBridgeServiceVisibleParam>(this._visible);
+ readonly afterVisible$ = this._afterVisible$.asObservable();
+
dispose(): void {
this._state$.complete();
this._state = null;
@@ -63,12 +71,26 @@ export class EditorBridgeService implements IEditorBridgeService, IDisposable {
changeVisible(param: IEditorBridgeServiceVisibleParam) {
this._visible = param;
+
this._visible$.next(this._visible);
+ this._afterVisible$.next(this._visible);
}
isVisible() {
return this._visible;
}
+
+ enableForceKeepVisible(): void {
+ this._isForceKeepVisible = true;
+ }
+
+ disableForceKeepVisible(): void {
+ this._isForceKeepVisible = false;
+ }
+
+ isForceKeepVisible(): boolean {
+ return this._isForceKeepVisible;
+ }
}
export const IEditorBridgeService = createIdentifier<EditorBridgeService>('univer.sheet-editor-bridge.service');
diff --git a/packages/ui-plugin-sheets/src/services/selection/selection-render.service.ts b/packages/ui-plugin-sheets/src/services/selection/selection-render.service.ts
index 7b7a4c83bf..7412fcc462 100644
--- a/packages/ui-plugin-sheets/src/services/selection/selection-render.service.ts
+++ b/packages/ui-plugin-sheets/src/services/selection/selection-render.service.ts
@@ -26,7 +26,7 @@ import {
ThemeService,
} from '@univerjs/core';
import { createIdentifier, Inject } from '@wendellhu/redi';
-import { BehaviorSubject, Observable } from 'rxjs';
+import { BehaviorSubject, Observable, Subject } from 'rxjs';
import { SelectionRenderModel } from './selection-render-model';
import { SelectionShape } from './selection-shape';
@@ -40,6 +40,8 @@ export interface IControlFillConfig {
export interface ISelectionRenderService {
readonly selectionRangeWithStyle$: Observable<ISelectionWithCoordAndStyle[]>;
readonly controlFillConfig$: Observable<IControlFillConfig | null>;
+ readonly selectionMoving$: Observable<Nullable<IRange[]>>;
+ readonly selectionMoveStart$: Observable<Nullable<IRange[]>>;
enableHeaderHighlight(): void;
disableHeaderHighlight(): void;
@@ -49,6 +51,12 @@ export interface ISelectionRenderService {
resetStyle(): void;
enableSelection(): void;
disableSelection(): void;
+ enableShowPrevious(): void;
+ disableShowPrevious(): void;
+ enableRemainLast(): void;
+ disableRemainLast(): void;
+ enableSkipRemainLast(): void;
+ disableSkipRemainLast(): void;
addControlToCurrentByRangeData(data: ISelectionWithCoordAndStyle): void;
changeRuntime(skeleton: SpreadsheetSkeleton, scene: Scene, viewport?: Viewport): void;
@@ -57,6 +65,7 @@ export interface ISelectionRenderService {
getActiveRangeList(): Nullable<IRange[]>;
getActiveRange(): Nullable<IRange>;
getActiveSelection(): Nullable<SelectionShape>;
+ getSelectionDataWithStyle(): ISelectionWithCoordAndStyle[];
convertSelectionRangeToData(selectionWithStyle: ISelectionWithStyle): ISelectionWithCoordAndStyle;
convertRangeDataToSelection(range: IRange): Nullable<IRangeWithCoord>;
convertCellRangeToInfo(primary: Nullable<ISelectionCell>): Nullable<ISelectionCellWithCoord>;
@@ -129,13 +138,33 @@ export class SelectionRenderService implements ISelectionRenderService {
// Whether to enable the selection area. If set to false, the user cannot draw a selection area in the content area by clicking with the mouse.
private _isSelectionEnabled: boolean = true;
+ // Used in the format painter feature, similar to ctrl, it can retain the previous selection.
private _isShowPreviousEnable: boolean | number = 0;
+ //Used in the formula selection feature, a new selection string is added by drawing a box with the mouse.
+ private _isRemainLastEnable: boolean = true;
+
+ private _isSkipRemainLastEnable: boolean = false;
+
private readonly _selectionRangeWithStyle$ = new BehaviorSubject<ISelectionWithCoordAndStyle[]>([]);
// When the user draws a selection area in the canvas content area, this event is broadcasted when the drawing ends.
readonly selectionRangeWithStyle$ = this._selectionRangeWithStyle$.asObservable();
+ private readonly _selectionMoving$ = new Subject<Nullable<IRange[]>>();
+
+ /**
+ * Triggered during the drawing of the selection area.
+ */
+ readonly selectionMoving$ = this._selectionMoving$.asObservable();
+
+ private readonly _selectionMoveStart$ = new Subject<Nullable<IRange[]>>();
+
+ /**
+ * Triggered during the start draw the selection area.
+ */
+ readonly selectionMoveStart$ = this._selectionMoveStart$.asObservable();
+
private _activeViewport!: Viewport;
constructor(@Inject(ThemeService) private readonly _themeService: ThemeService) {
@@ -182,6 +211,22 @@ export class SelectionRenderService implements ISelectionRenderService {
this._isShowPreviousEnable = false;
}
+ enableRemainLast() {
+ this._isRemainLastEnable = true;
+ }
+
+ disableRemainLast() {
+ this._isRemainLastEnable = false;
+ }
+
+ enableSkipRemainLast() {
+ this._isSkipRemainLastEnable = true;
+ }
+
+ disableSkipRemainLast() {
+ this._isSkipRemainLastEnable = false;
+ }
+
getViewPort() {
return this._activeViewport;
}
@@ -236,7 +281,7 @@ export class SelectionRenderService implements ISelectionRenderService {
this._activeViewport = viewport || scene.getViewports()[0];
}
- getSelectionDataWithStyle() {
+ getSelectionDataWithStyle(): ISelectionWithCoordAndStyle[] {
const selectionControls = this._selectionControls;
return selectionControls.map((control) => control.getValue());
}
@@ -245,17 +290,17 @@ export class SelectionRenderService implements ISelectionRenderService {
return this._selectionControls;
}
- private _getCurrentControl() {
- const controls = this.getCurrentControls();
- if (controls && controls.length > 0) {
- for (const control of controls) {
- const currentCell = control.model.currentCell;
- if (currentCell) {
- return control;
- }
- }
- }
- }
+ // private _getCurrentControl() {
+ // const controls = this.getCurrentControls();
+ // if (controls && controls.length > 0) {
+ // for (const control of controls) {
+ // const currentCell = control.model.currentCell;
+ // if (currentCell) {
+ // return control;
+ // }
+ // }
+ // }
+ // }
private _clearSelectionControls() {
const curControls = this.getCurrentControls();
@@ -409,7 +454,7 @@ export class SelectionRenderService implements ISelectionRenderService {
this._startSelectionRange = startSelectionRange;
- let selectionControl: Nullable<SelectionShape> = this._getCurrentControl();
+ let selectionControl: Nullable<SelectionShape> = this.getActiveSelection();
const curControls = this.getCurrentControls();
@@ -436,12 +481,18 @@ export class SelectionRenderService implements ISelectionRenderService {
}
// In addition to pressing the ctrl or shift key, we must clear the previous selection
- if (curControls.length > 0 && !evt.ctrlKey && !evt.shiftKey && !this._isShowPreviousEnable) {
+ if (
+ curControls.length > 0 &&
+ !evt.ctrlKey &&
+ !evt.shiftKey &&
+ !this._isShowPreviousEnable &&
+ !this._isRemainLastEnable
+ ) {
for (const control of curControls) {
control.dispose();
}
- curControls.length = 0; // clear currentSelectionControls
+ curControls.length = 0;
}
const currentCell = selectionControl && selectionControl.model.currentCell;
@@ -464,6 +515,7 @@ export class SelectionRenderService implements ISelectionRenderService {
endX: endCell?.endX || 0,
rangeType,
};
+
selectionControl.update(
newSelectionRange,
rowHeaderWidth,
@@ -471,7 +523,29 @@ export class SelectionRenderService implements ISelectionRenderService {
this._selectionStyle,
currentCell
);
+ } else if (
+ this._isRemainLastEnable &&
+ selectionControl &&
+ !evt.ctrlKey &&
+ !evt.shiftKey &&
+ !this._isSkipRemainLastEnable
+ ) {
+ /**
+ * Supports the formula ref text selection feature,
+ * under the condition of preserving all previous selections, it modifies the position of the latest selection.
+ */
+
+ selectionControl.update(
+ startSelectionRange,
+ rowHeaderWidth,
+ columnHeaderHeight,
+ this._selectionStyle,
+ primaryWithCoord
+ );
} else {
+ /**
+ * The default behavior is to clear previous selections and always create new selections.
+ */
selectionControl = new SelectionShape(
scene,
curControls.length + zIndex,
@@ -492,6 +566,8 @@ export class SelectionRenderService implements ISelectionRenderService {
curControls.push(selectionControl);
}
+ this._selectionMoveStart$.next([...(this.getActiveRangeList() || [])]);
+
this.hasSelection = true;
this._endSelection();
@@ -717,12 +793,15 @@ export class SelectionRenderService implements ISelectionRenderService {
} = selectionControl?.model || { startRow: -1, endRow: -1, startColumn: -1, endColumn: -1 };
if (
- oldStartColumn !== finalStartColumn ||
- oldStartRow !== finalStartRow ||
- oldEndColumn !== finalEndColumn ||
- oldEndRow !== finalEndRow
+ (oldStartColumn !== finalStartColumn ||
+ oldStartRow !== finalStartRow ||
+ oldEndColumn !== finalEndColumn ||
+ oldEndRow !== finalEndRow) &&
+ selectionControl != null
) {
- selectionControl && selectionControl.update(newSelectionRange, rowHeaderWidth, columnHeaderHeight);
+ selectionControl.update(newSelectionRange, rowHeaderWidth, columnHeaderHeight);
+
+ this._selectionMoving$.next(this.getActiveRangeList());
}
}
diff --git a/packages/ui-plugin-sheets/src/services/selection/selection-shape-extension.ts b/packages/ui-plugin-sheets/src/services/selection/selection-shape-extension.ts
index 11acce0fdc..4a9a2fa543 100644
--- a/packages/ui-plugin-sheets/src/services/selection/selection-shape-extension.ts
+++ b/packages/ui-plugin-sheets/src/services/selection/selection-shape-extension.ts
@@ -41,7 +41,7 @@ export class SelectionShapeExtension {
private _upObserver: Nullable<Observer<IPointerEvent | IMouseEvent>>;
- private _helperSelection!: Rect;
+ private _helperSelection: Nullable<Rect>;
private _scrollTimer!: ScrollTimer;
@@ -77,6 +77,10 @@ export class SelectionShapeExtension {
});
}
+ get isHelperSelection() {
+ return this._control.isHelperSelection;
+ }
+
dispose() {
this._scrollTimer?.dispose();
this._fillControlColors = [];
@@ -168,7 +172,7 @@ export class SelectionShapeExtension {
const startX = startCell?.startX || 0;
const endX = endCell?.endX || 0;
- this._helperSelection.transformByState({
+ this._helperSelection?.transformByState({
left: startX,
top: startY,
width: endX - startX,
@@ -249,11 +253,14 @@ export class SelectionShapeExtension {
const style = this._control.selectionStyle!;
const scale = this._getScale();
- this._helperSelection = new Rect(HELPER_SELECTION_TEMP_NAME, {
- stroke: style.stroke,
- strokeWidth: style.strokeWidth / scale,
- });
- scene.addObject(this._helperSelection);
+
+ if (this.isHelperSelection) {
+ this._helperSelection = new Rect(HELPER_SELECTION_TEMP_NAME, {
+ stroke: style.stroke,
+ strokeWidth: style.strokeWidth / scale,
+ });
+ scene.addObject(this._helperSelection);
+ }
// const relativeCoords = scene.getRelativeCoord(Vector2.FromArray([evtOffsetX, evtOffsetY]));
@@ -284,7 +291,7 @@ export class SelectionShapeExtension {
});
this._upObserver = scene.onPointerUpObserver.add((upEvt: IPointerEvent | IMouseEvent) => {
- this._helperSelection.dispose();
+ this._helperSelection?.dispose();
const scene = this._scene;
scene.resetCursor();
this._clearObserverEvent();
@@ -642,16 +649,16 @@ export class SelectionShapeExtension {
const SELECTION_CONTROL_BORDER_BUFFER_WIDTH_SCALE = SELECTION_CONTROL_BORDER_BUFFER_WIDTH / this._getScale();
if ((startRow === endRow && isRowDropping === true) || (startColumn === endColumn && isRowDropping === false)) {
- this._helperSelection.hide();
+ this._helperSelection?.hide();
} else {
- this._helperSelection.transformByState({
+ this._helperSelection?.transformByState({
left: startX - SELECTION_CONTROL_BORDER_BUFFER_WIDTH_SCALE / 2,
top: startY - SELECTION_CONTROL_BORDER_BUFFER_WIDTH_SCALE / 2,
width: endX - startX,
height: endY - startY,
});
- this._helperSelection.show();
+ this._helperSelection?.show();
}
this._targetSelection = {
@@ -718,11 +725,13 @@ export class SelectionShapeExtension {
const darkenColor = new TinyColor(stroke).darken(2).toString();
- this._helperSelection = new Rect(HELPER_SELECTION_TEMP_NAME, {
- stroke: darkenColor,
- strokeWidth: strokeWidth + SELECTION_CONTROL_BORDER_BUFFER_WIDTH_SCALE / 2,
- });
- scene.addObject(this._helperSelection);
+ if (this.isHelperSelection) {
+ this._helperSelection = new Rect(HELPER_SELECTION_TEMP_NAME, {
+ stroke: darkenColor,
+ strokeWidth: strokeWidth + SELECTION_CONTROL_BORDER_BUFFER_WIDTH_SCALE / 2,
+ });
+ scene.addObject(this._helperSelection);
+ }
const scrollTimer = ScrollTimer.create(scene);
@@ -753,7 +762,7 @@ export class SelectionShapeExtension {
});
this._upObserver = scene.onPointerUpObserver.add((upEvt: IPointerEvent | IMouseEvent) => {
- this._helperSelection.dispose();
+ this._helperSelection?.dispose();
const scene = this._scene;
scene.resetCursor();
this._clearObserverEvent();
diff --git a/packages/ui-plugin-sheets/src/services/selection/selection-shape.ts b/packages/ui-plugin-sheets/src/services/selection/selection-shape.ts
index 0c67c3292c..9d394f080e 100644
--- a/packages/ui-plugin-sheets/src/services/selection/selection-shape.ts
+++ b/packages/ui-plugin-sheets/src/services/selection/selection-shape.ts
@@ -9,7 +9,7 @@ import {
SELECTION_CONTROL_BORDER_BUFFER_WIDTH,
} from '@univerjs/base-sheets';
import { IRangeWithCoord, ISelectionCellWithCoord, Nullable, RANGE_TYPE, ThemeService } from '@univerjs/core';
-import { BehaviorSubject } from 'rxjs';
+import { BehaviorSubject, Subject } from 'rxjs';
import { SelectionRenderModel } from './selection-render-model';
@@ -99,18 +99,20 @@ export class SelectionShape {
private _dispose$ = new BehaviorSubject<SelectionShape>(this);
readonly dispose$ = this._dispose$.asObservable();
- readonly selectionMoving$ = new BehaviorSubject<Nullable<IRangeWithCoord>>(null);
- readonly selectionMoved$ = new BehaviorSubject<Nullable<IRangeWithCoord>>(null);
- readonly selectionScaling$ = new BehaviorSubject<Nullable<IRangeWithCoord>>(null);
- readonly selectionScaled$ = new BehaviorSubject<Nullable<IRangeWithCoord>>(null);
- readonly selectionFilling$ = new BehaviorSubject<Nullable<IRangeWithCoord>>(null);
+ readonly selectionMoving$ = new Subject<Nullable<IRangeWithCoord>>();
+ readonly selectionMoved$ = new Subject<Nullable<IRangeWithCoord>>();
+ readonly selectionScaling$ = new Subject<Nullable<IRangeWithCoord>>();
+ readonly selectionScaled$ = new Subject<Nullable<IRangeWithCoord>>();
+ readonly selectionFilling$ = new Subject<Nullable<IRangeWithCoord>>();
- private readonly _selectionFilled$ = new BehaviorSubject<Nullable<IRangeWithCoord>>(null);
+ private readonly _selectionFilled$ = new Subject<Nullable<IRangeWithCoord>>();
readonly selectionFilled$ = this._selectionFilled$.asObservable();
private _defaultStyle!: ISelectionStyle;
+ private _isHelperSelection: boolean = true;
+
constructor(
private _scene: Scene,
private _zIndex: number,
@@ -208,8 +210,12 @@ export class SelectionShape {
return this._dashRect;
}
+ get isHelperSelection() {
+ return this._isHelperSelection;
+ }
+
enableHeaderHighlight() {
- this._isHeaderHighlight = true;
+ this._isHelperSelection = true;
}
disableHeaderHighlight() {
@@ -220,6 +226,131 @@ export class SelectionShape {
this._selectionFilled$.next(val);
}
+ updateStyle(style: ISelectionStyle) {
+ this._updateControl(style, this._rowHeaderWidth, this._columnHeaderHeight);
+ }
+
+ update(
+ newSelectionRange: IRangeWithCoord,
+ rowHeaderWidth: number = 0,
+ columnHeaderHeight: number = 0,
+ style?: Nullable<ISelectionStyle>,
+ highlight?: Nullable<ISelectionCellWithCoord>
+ ) {
+ this._selectionModel.setValue(newSelectionRange, highlight);
+ if (style == null) {
+ style = this._selectionStyle;
+ }
+ this._updateControl(style, rowHeaderWidth, columnHeaderHeight);
+ }
+
+ clearHighlight() {
+ this._selectionModel.clearCurrentCell();
+ this._updateControl(this._selectionStyle, this._rowHeaderWidth, this._columnHeaderHeight);
+ }
+
+ getScene() {
+ return this._scene;
+ }
+
+ dispose() {
+ this._leftControl?.dispose();
+ this._rightControl?.dispose();
+ this._topControl?.dispose();
+ this._bottomControl?.dispose();
+ this._backgroundControlTop?.dispose();
+ this._backgroundControlMiddleLeft?.dispose();
+ this._backgroundControlMiddleRight?.dispose();
+ this._backgroundControlBottom?.dispose();
+ this._fillControl?.dispose();
+ this._selectionShape?.dispose();
+
+ this._rowHeaderBackground?.dispose();
+ this._rowHeaderBorder?.dispose();
+ this._rowHeaderGroup?.dispose();
+ this._rowHeaderBackground?.dispose();
+ this._columnHeaderBackground?.dispose();
+ this._columnHeaderBorder?.dispose();
+ this._columnHeaderGroup?.dispose();
+
+ this._topLeftWidget?.dispose();
+ this._topCenterWidget?.dispose();
+ this._topRightWidget?.dispose();
+ this._middleLeftWidget?.dispose();
+ this._middleRightWidget?.dispose();
+ this._bottomLeftWidget?.dispose();
+ this._bottomCenterWidget?.dispose();
+ this._bottomRightWidget?.dispose();
+ this._dispose$.next(this);
+ this._dispose$.complete();
+ }
+
+ /**
+ * Get the cell information of the current selection, considering the case of merging cells
+ */
+ getCurrentCellInfo(): Nullable<IRangeWithCoord> {
+ const currentCell = this.model.currentCell;
+
+ if (currentCell) {
+ let currentRangeData: IRangeWithCoord;
+
+ if (currentCell.isMerged) {
+ const mergeInfo = currentCell.mergeInfo;
+
+ currentRangeData = {
+ startRow: mergeInfo.startRow,
+ endRow: mergeInfo.endRow,
+ startColumn: mergeInfo.startColumn,
+ endColumn: mergeInfo.endColumn,
+ startX: mergeInfo.startX,
+ endX: mergeInfo.endX,
+ startY: mergeInfo.startY,
+ endY: mergeInfo.endY,
+ };
+ } else {
+ const { actualRow, actualColumn, startX, endX, startY, endY } = currentCell;
+ currentRangeData = {
+ startRow: actualRow,
+ endRow: actualRow,
+ startColumn: actualColumn,
+ endColumn: actualColumn,
+ startX,
+ endX,
+ startY,
+ endY,
+ };
+ }
+
+ return currentRangeData;
+ }
+ }
+
+ getValue(): ISelectionWithCoordAndStyle {
+ return {
+ ...this._selectionModel.getValue(),
+ style: this._selectionStyle,
+ };
+ }
+
+ getRange() {
+ return this._selectionModel.getValue().rangeWithCoord;
+ }
+
+ enableHelperSelection() {
+ this._isHelperSelection = true;
+ }
+
+ disableHelperSelection() {
+ this._isHelperSelection = false;
+ }
+
+ updateStyleId(id: string) {
+ if (this._selectionStyle == null) {
+ return;
+ }
+ this._selectionStyle.id = id;
+ }
+
/**
* just handle the view
*
@@ -361,108 +492,6 @@ export class SelectionShape {
this.selectionShape.makeDirtyNoDebounce(true);
}
- update(
- newSelectionRange: IRangeWithCoord,
- rowHeaderWidth: number,
- columnHeaderHeight: number,
- style: Nullable<ISelectionStyle>,
- highlight: Nullable<ISelectionCellWithCoord>
- ) {
- this._selectionModel.setValue(newSelectionRange, highlight);
- if (style == null) {
- style = this._selectionStyle;
- }
- this._updateControl(style, rowHeaderWidth, columnHeaderHeight);
- }
-
- clearHighlight() {
- this._selectionModel.clearCurrentCell();
- this._updateControl(this._selectionStyle, this._rowHeaderWidth, this._columnHeaderHeight);
- }
-
- getScene() {
- return this._scene;
- }
-
- dispose() {
- this._leftControl?.dispose();
- this._rightControl?.dispose();
- this._topControl?.dispose();
- this._bottomControl?.dispose();
- this._backgroundControlTop?.dispose();
- this._backgroundControlMiddleLeft?.dispose();
- this._backgroundControlMiddleRight?.dispose();
- this._backgroundControlBottom?.dispose();
- this._fillControl?.dispose();
- this._selectionShape?.dispose();
-
- this._rowHeaderBackground?.dispose();
- this._rowHeaderBorder?.dispose();
- this._rowHeaderGroup?.dispose();
- this._rowHeaderBackground?.dispose();
- this._columnHeaderBackground?.dispose();
- this._columnHeaderBorder?.dispose();
- this._columnHeaderGroup?.dispose();
-
- this._topLeftWidget?.dispose();
- this._topCenterWidget?.dispose();
- this._topRightWidget?.dispose();
- this._middleLeftWidget?.dispose();
- this._middleRightWidget?.dispose();
- this._bottomLeftWidget?.dispose();
- this._bottomCenterWidget?.dispose();
- this._bottomRightWidget?.dispose();
- this._dispose$.next(this);
- this._dispose$.complete();
- }
-
- /**
- * Get the cell information of the current selection, considering the case of merging cells
- */
- getCurrentCellInfo(): Nullable<IRangeWithCoord> {
- const currentCell = this.model.currentCell;
-
- if (currentCell) {
- let currentRangeData: IRangeWithCoord;
-
- if (currentCell.isMerged) {
- const mergeInfo = currentCell.mergeInfo;
-
- currentRangeData = {
- startRow: mergeInfo.startRow,
- endRow: mergeInfo.endRow,
- startColumn: mergeInfo.startColumn,
- endColumn: mergeInfo.endColumn,
- startX: mergeInfo.startX,
- endX: mergeInfo.endX,
- startY: mergeInfo.startY,
- endY: mergeInfo.endY,
- };
- } else {
- const { actualRow, actualColumn, startX, endX, startY, endY } = currentCell;
- currentRangeData = {
- startRow: actualRow,
- endRow: actualRow,
- startColumn: actualColumn,
- endColumn: actualColumn,
- startX,
- endX,
- startY,
- endY,
- };
- }
-
- return currentRangeData;
- }
- }
-
- getValue(): ISelectionWithCoordAndStyle {
- return {
- ...this._selectionModel.getValue(),
- style: this._selectionStyle,
- };
- }
-
private _initialize() {
this._defaultStyle = getNormalSelectionStyle(this._themeService);