@univerjs/sheets-formula-ui 1.0.0-alpha.2 → 1.0.0-alpha.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/es/index.js CHANGED
@@ -1,5 +1,5 @@
1
- import { AbsoluteRefType, BuildTextUtils, CellValueType, ColorKit, CommandType, DEFAULT_EMPTY_DOCUMENT_VALUE, DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY, DOCS_NORMAL_EDITOR_UNIT_ID_KEY, DependentOn, Direction, Disposable, DisposableCollection, DocumentFlavor, EDITOR_ACTIVATED, HorizontalAlign, ICommandService, IConfigService, IContextService, ILogService, IUniverInstanceService, Inject, Injector, InterceptorEffectEnum, LocaleService, ObjectMatrix, Plugin, RANGE_TYPE, Range, Rectangle, RichTextBuilder, RxDisposable, ThemeService, Tools, UniverInstanceType, VerticalAlign, createIdentifier, createInternalEditorID, generateRandomId, getBodySlice, getCellValueType, getEmptyCell, isFormulaId, isFormulaString, isICellData, isRealNum, merge, noop, registerDependencies, toDisposable, touchDependencies } from "@univerjs/core";
2
- import { BaseSelectionRenderService, COPY_SPECIAL_MENU_ID, COPY_TYPE, CellAlertManagerService, CellAlertType, EMBEDDING_FORMULA_EDITOR, EMBEDDING_FORMULA_EDITOR_COMPONENT_KEY, ExpandSelectionCommand, HoverManagerService, IEditorBridgeService, IMarkSelectionService, ISheetClipboardService, JumpOver, MoveSelectionCommand, PASTE_SPECIAL_MENU_ID, PREDEFINED_HOOK_NAME_COPY, PREDEFINED_HOOK_NAME_PASTE, RANGE_SELECTOR_COMPONENT_KEY, SELECTION_SHAPE_DEPTH, SelectionControl, SetCellEditVisibleOperation, SheetPasteCommand, SheetSkeletonManagerService, SheetsUIPart, checkInHeaderRanges, genNormalSelectionStyle, getAllSelection, getCoordByOffset, getCurrentRangeDisable$, getSheetObject, menuClipboardDisabledObservable, useActiveWorkbook, whenSheetEditorActivated, whenSheetEditorFocused } from "@univerjs/sheets-ui";
1
+ import { AbsoluteRefType, BuildTextUtils, CellValueType, ColorKit, CommandType, DEFAULT_EMPTY_DOCUMENT_VALUE, DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY, DOCS_NORMAL_EDITOR_UNIT_ID_KEY, DependentOn, Direction, Disposable, DisposableCollection, DocumentFlavor, EDITOR_ACTIVATED, FOCUSING_FX_BAR_EDITOR, HorizontalAlign, ICommandService, IConfigService, IContextService, ILogService, IUniverInstanceService, Inject, Injector, InterceptorEffectEnum, LocaleService, ObjectMatrix, Plugin, RANGE_TYPE, Range, Rectangle, RichTextBuilder, RxDisposable, ThemeService, Tools, UniverInstanceType, VerticalAlign, createIdentifier, createInternalEditorID, generateRandomId, getCellValueType, getEmptyCell, isFormulaId, isFormulaString, isICellData, isRealNum, merge, noop, registerDependencies, toDisposable, touchDependencies } from "@univerjs/core";
2
+ import { BaseSelectionRenderService, COPY_SPECIAL_MENU_ID, COPY_TYPE, CellAlertManagerService, CellAlertType, EMBEDDING_FORMULA_EDITOR, EMBEDDING_FORMULA_EDITOR_COMPONENT_KEY, ExpandSelectionCommand, HoverManagerService, IEditorBridgeService, IMarkSelectionService, ISheetClipboardService, ISheetSelectionRenderService, JumpOver, MoveSelectionCommand, PASTE_SPECIAL_MENU_ID, PREDEFINED_HOOK_NAME_COPY, PREDEFINED_HOOK_NAME_PASTE, RANGE_SELECTOR_COMPONENT_KEY, SELECTION_SHAPE_DEPTH, SelectionControl, SetCellEditVisibleOperation, SheetPasteCommand, SheetSkeletonManagerService, SheetsUIPart, checkInHeaderRanges, genNormalSelectionStyle, getAllSelection, getCoordByOffset, getCurrentRangeDisable$, getSheetObject, menuClipboardDisabledObservable, useActiveWorkbook, whenSheetEditorActivated, whenSheetEditorFocused } from "@univerjs/sheets-ui";
3
3
  import { ErrorType, FormulaDataModel, FunctionType, LexerTreeBuilder, SetArrayFormulaDataMutation, SetFormulaCalculationResultMutation, SetFormulaCalculationStopMutation, deserializeRangeWithSheet, deserializeRangeWithSheetWithCache, extractFormulaError, generateStringWithSequence, getAbsoluteRefTypeWithSingleString, handleRefStringInfo, isFormulaLexerToken, matchRefDrawToken, matchToken, operatorToken, sequenceNodeType, serializeRange, serializeRangeToRefString, serializeRangeWithSheet, serializeRangeWithSpreadsheet } from "@univerjs/engine-formula";
4
4
  import { BehaviorSubject, Subject, combineLatestWith, debounceTime, distinctUntilChanged, filter, map, merge as merge$1, throttleTime } from "rxjs";
5
5
  import { DocBackScrollRenderController, DocSelectionRenderService, IEditorService, MoveCursorOperation, MoveSelectionOperation, ReplaceTextRunsCommand, RichTextEditor, createEditorUndoRedoKeyboardConfig, useKeyboardEvent, useResize } from "@univerjs/docs-ui";
@@ -8,8 +8,8 @@ import { BEFORE_CELL_EDIT, INTERCEPTOR_POINT, IRefSelectionsService, REF_SELECTI
8
8
  import { IDescriptionService, ImageFormulaCellInterceptorController, InsertFunctionCommand, PLUGIN_CONFIG_KEY_BASE, QuickSumCommand, TriggerCalculationController, UniverSheetsFormulaPlugin } from "@univerjs/sheets-formula";
9
9
  import { BuiltInUIPart, ComponentManager, IContextMenuService, IMenuManagerService, IShortcutService, ISidebarService, IUIPartsService, IconManager, KeyCode, MenuItemType, MetaKeys, ProgressBar, RectPopup, RibbonFormulasGroup, connectInjector, getMenuHiddenObservable, useDependency, useEvent, useObservable, useUpdateEffect } from "@univerjs/ui";
10
10
  import { DocSelectionManagerService } from "@univerjs/docs";
11
- import { CheckMarkIcon, CloseIcon, DeleteIcon, FunctionIcon, IncreaseIcon, MoreRightIcon, SelectRangeIcon } from "@univerjs/icons";
12
- import { Button, Dialog, Input, Select, Tooltip, borderClassName, borderLeftClassName, borderTopClassName, clsx, scrollbarClassName } from "@univerjs/design";
11
+ import { CheckMarkIcon, CloseIcon, DatabaseFunctionIcon, DateFunctionIcon, DeleteIcon, EngineeringFunctionIcon, FinancialFunctionIcon, FunctionIcon, IncreaseIcon, InformationFunctionIcon, LogicalFunctionIcon, LookupFunctionIcon, MathFunctionIcon, MoreRightIcon, SelectRangeIcon, StatisticalFunctionIcon, TextFunctionIcon } from "@univerjs/icons";
12
+ import { Button, Dialog, Input, Select, Tooltip, borderClassName, borderLeftClassName, borderTopClassName, clsx, divideYClassName, scrollbarClassName } from "@univerjs/design";
13
13
  import { forwardRef, useCallback, useEffect, useImperativeHandle, useLayoutEffect, useMemo, useRef, useState } from "react";
14
14
  import { Fragment, jsx, jsxs } from "react/jsx-runtime";
15
15
  import { debounceTime as debounceTime$1 } from "rxjs/operators";
@@ -777,10 +777,192 @@ FormulaReorderController = __decorate([
777
777
  __decorateParam(3, Inject(LexerTreeBuilder))
778
778
  ], FormulaReorderController);
779
779
 
780
+ //#endregion
781
+ //#region src/menu/menu.ts
782
+ function InsertCommonFunctionMenuItemFactory(accessor) {
783
+ const commonFunctions = [
784
+ "SUMIF",
785
+ "SUM",
786
+ "AVERAGE",
787
+ "IF",
788
+ "COUNT",
789
+ "SIN",
790
+ "MAX"
791
+ ];
792
+ let selections = commonFunctions.map((name) => ({
793
+ label: {
794
+ name,
795
+ selectable: false
796
+ },
797
+ value: name
798
+ }));
799
+ try {
800
+ const descriptionService = accessor.get(IDescriptionService);
801
+ const filtered = commonFunctions.filter((name) => Boolean(descriptionService.getFunctionInfo(name)));
802
+ if (filtered.length > 0) selections = filtered.map((name) => ({
803
+ label: {
804
+ name,
805
+ selectable: false
806
+ },
807
+ value: name
808
+ }));
809
+ } catch {}
810
+ return {
811
+ id: `${InsertFunctionOperation.id}.common`,
812
+ commandId: InsertFunctionOperation.id,
813
+ title: "sheets-formula-ui.insert.common",
814
+ tooltip: "sheets-formula-ui.insert.tooltip",
815
+ icon: "FunctionIcon",
816
+ type: MenuItemType.SELECTOR,
817
+ selections,
818
+ hidden$: getMenuHiddenObservable(accessor, UniverInstanceType.UNIVER_SHEET)
819
+ };
820
+ }
821
+ function createInsertFunctionCategoryMenuItemFactory(functionType, categoryKey, icon) {
822
+ return function insertFunctionCategoryMenuItemFactory(accessor) {
823
+ let selections = [];
824
+ try {
825
+ selections = accessor.get(IDescriptionService).getSearchListByType(functionType).map(({ name }) => ({
826
+ label: {
827
+ name,
828
+ selectable: false
829
+ },
830
+ value: name
831
+ }));
832
+ } catch {
833
+ selections = [];
834
+ }
835
+ const localeKey = `sheets-formula-ui.functionType.${categoryKey}`;
836
+ return {
837
+ id: `${InsertFunctionOperation.id}.${categoryKey}`,
838
+ commandId: InsertFunctionOperation.id,
839
+ title: localeKey,
840
+ tooltip: localeKey,
841
+ icon,
842
+ type: MenuItemType.SELECTOR,
843
+ selections,
844
+ hidden$: getMenuHiddenObservable(accessor, UniverInstanceType.UNIVER_SHEET)
845
+ };
846
+ };
847
+ }
848
+ const InsertFinancialFunctionMenuItemFactory = createInsertFunctionCategoryMenuItemFactory(FunctionType.Financial, "financial", "FinancialFunctionIcon");
849
+ const InsertLogicalFunctionMenuItemFactory = createInsertFunctionCategoryMenuItemFactory(FunctionType.Logical, "logical", "LogicalFunctionIcon");
850
+ const InsertTextFunctionMenuItemFactory = createInsertFunctionCategoryMenuItemFactory(FunctionType.Text, "text", "TextFunctionIcon");
851
+ const InsertDateFunctionMenuItemFactory = createInsertFunctionCategoryMenuItemFactory(FunctionType.Date, "date", "DateFunctionIcon");
852
+ const InsertLookupFunctionMenuItemFactory = createInsertFunctionCategoryMenuItemFactory(FunctionType.Lookup, "lookup", "LookupFunctionIcon");
853
+ const InsertMathFunctionMenuItemFactory = createInsertFunctionCategoryMenuItemFactory(FunctionType.Math, "math", "MathFunctionIcon");
854
+ const InsertStatisticalFunctionMenuItemFactory = createInsertFunctionCategoryMenuItemFactory(FunctionType.Statistical, "statistical", "StatisticalFunctionIcon");
855
+ const InsertEngineeringFunctionMenuItemFactory = createInsertFunctionCategoryMenuItemFactory(FunctionType.Engineering, "engineering", "EngineeringFunctionIcon");
856
+ const InsertInformationFunctionMenuItemFactory = createInsertFunctionCategoryMenuItemFactory(FunctionType.Information, "information", "InformationFunctionIcon");
857
+ const InsertDatabaseFunctionMenuItemFactory = createInsertFunctionCategoryMenuItemFactory(FunctionType.Database, "database", "DatabaseFunctionIcon");
858
+ function AllFunctionsMenuItemFactory(accessor) {
859
+ return {
860
+ id: MoreFunctionsOperation.id,
861
+ title: "sheets-formula-ui.moreFunctions.allFunctions",
862
+ tooltip: "sheets-formula-ui.insert.tooltip",
863
+ type: MenuItemType.BUTTON,
864
+ hidden$: getMenuHiddenObservable(accessor, UniverInstanceType.UNIVER_SHEET),
865
+ disabled$: getCurrentRangeDisable$(accessor, {
866
+ workbookTypes: [WorkbookEditablePermission],
867
+ worksheetTypes: [WorksheetEditPermission, WorksheetSetCellValuePermission],
868
+ rangeTypes: [RangeProtectionPermissionEditPoint]
869
+ })
870
+ };
871
+ }
872
+ function CopyFormulaOnlyMenuItemFactory(accessor) {
873
+ return {
874
+ id: SheetCopyFormulaOnlyCommand.id,
875
+ type: MenuItemType.BUTTON,
876
+ title: "sheets-formula-ui.operation.copyFormulaOnly",
877
+ disabled$: getCurrentRangeDisable$(accessor, {
878
+ workbookTypes: [WorkbookCopyPermission],
879
+ worksheetTypes: [WorksheetCopyPermission],
880
+ rangeTypes: [RangeProtectionPermissionViewPoint]
881
+ }),
882
+ hidden$: getMenuHiddenObservable(accessor, UniverInstanceType.UNIVER_SHEET)
883
+ };
884
+ }
885
+ function PasteFormulaMenuItemFactory(accessor) {
886
+ return {
887
+ id: SheetOnlyPasteFormulaCommand.id,
888
+ type: MenuItemType.BUTTON,
889
+ title: "sheets-formula-ui.operation.pasteFormula",
890
+ disabled$: menuClipboardDisabledObservable(accessor).pipe(combineLatestWith(getCurrentRangeDisable$(accessor, {
891
+ workbookTypes: [WorkbookEditablePermission],
892
+ rangeTypes: [RangeProtectionPermissionEditPoint],
893
+ worksheetTypes: [WorksheetSetCellValuePermission, WorksheetEditPermission]
894
+ })), map(([d1, d2]) => d1 || d2)),
895
+ hidden$: getMenuHiddenObservable(accessor, UniverInstanceType.UNIVER_SHEET)
896
+ };
897
+ }
898
+
899
+ //#endregion
900
+ //#region src/menu/schema.ts
901
+ const menuSchema = {
902
+ [RibbonFormulasGroup.BASIC]: {
903
+ [`${InsertFunctionOperation.id}.common`]: {
904
+ order: 0,
905
+ menuItemFactory: InsertCommonFunctionMenuItemFactory,
906
+ [MoreFunctionsOperation.id]: {
907
+ order: 0,
908
+ menuItemFactory: AllFunctionsMenuItemFactory
909
+ }
910
+ },
911
+ [`${InsertFunctionOperation.id}.financial`]: {
912
+ order: 1,
913
+ menuItemFactory: InsertFinancialFunctionMenuItemFactory
914
+ },
915
+ [`${InsertFunctionOperation.id}.logical`]: {
916
+ order: 2,
917
+ menuItemFactory: InsertLogicalFunctionMenuItemFactory
918
+ },
919
+ [`${InsertFunctionOperation.id}.text`]: {
920
+ order: 3,
921
+ menuItemFactory: InsertTextFunctionMenuItemFactory
922
+ },
923
+ [`${InsertFunctionOperation.id}.date`]: {
924
+ order: 4,
925
+ menuItemFactory: InsertDateFunctionMenuItemFactory
926
+ },
927
+ [`${InsertFunctionOperation.id}.lookup`]: {
928
+ order: 5,
929
+ menuItemFactory: InsertLookupFunctionMenuItemFactory
930
+ },
931
+ [`${InsertFunctionOperation.id}.math`]: {
932
+ order: 6,
933
+ menuItemFactory: InsertMathFunctionMenuItemFactory
934
+ },
935
+ [`${InsertFunctionOperation.id}.statistical`]: {
936
+ order: 7,
937
+ menuItemFactory: InsertStatisticalFunctionMenuItemFactory
938
+ },
939
+ [`${InsertFunctionOperation.id}.engineering`]: {
940
+ order: 8,
941
+ menuItemFactory: InsertEngineeringFunctionMenuItemFactory
942
+ },
943
+ [`${InsertFunctionOperation.id}.information`]: {
944
+ order: 9,
945
+ menuItemFactory: InsertInformationFunctionMenuItemFactory
946
+ },
947
+ [`${InsertFunctionOperation.id}.database`]: {
948
+ order: 10,
949
+ menuItemFactory: InsertDatabaseFunctionMenuItemFactory
950
+ }
951
+ },
952
+ [COPY_SPECIAL_MENU_ID]: { [SheetCopyFormulaOnlyCommand.id]: {
953
+ order: 0,
954
+ menuItemFactory: CopyFormulaOnlyMenuItemFactory
955
+ } },
956
+ [PASTE_SPECIAL_MENU_ID]: { [SheetOnlyPasteFormulaCommand.id]: {
957
+ order: 4,
958
+ menuItemFactory: PasteFormulaMenuItemFactory
959
+ } }
960
+ };
961
+
780
962
  //#endregion
781
963
  //#region package.json
782
964
  var name = "@univerjs/sheets-formula-ui";
783
- var version = "1.0.0-alpha.2";
965
+ var version = "1.0.0-alpha.4";
784
966
 
785
967
  //#endregion
786
968
  //#region src/config/config.ts
@@ -825,6 +1007,112 @@ const findRefSequenceIndex = (sequenceNode, targetIndex) => {
825
1007
  return result;
826
1008
  };
827
1009
 
1010
+ //#endregion
1011
+ //#region src/views/formula-editor/formula-embed-integration.service.ts
1012
+ const FORMULA_EMBED_INTERACTION_BOUNDARY_OWNER_ATTRIBUTE = "data-embed-interaction-boundary-owner";
1013
+ const FORMULA_EMBED_ID_ATTRIBUTE = "data-embed-id";
1014
+ const FORMULA_EMBED_HOST_UNIT_ID_ATTRIBUTE = "data-embed-host-unit-id";
1015
+ const FORMULA_EMBED_CHILD_UNIT_ID_ATTRIBUTE = "data-embed-child-unit-id";
1016
+ const IFormulaEmbedRuntimeFocusCoordinator = createIdentifier("sheets-formula-ui.embed-runtime-focus-coordinator");
1017
+ const IFormulaEmbedInteractionBoundaryService = createIdentifier("sheets-formula-ui.embed-interaction-boundary.service");
1018
+ function registerFormulaEditorRuntimePortal(options) {
1019
+ var _options$ownerDocumen;
1020
+ const ownerDocument = (_options$ownerDocumen = options.ownerDocument) !== null && _options$ownerDocumen !== void 0 ? _options$ownerDocumen : typeof document === "undefined" ? void 0 : document;
1021
+ if (!ownerDocument) return toDisposable(() => {});
1022
+ const collection = new DisposableCollection();
1023
+ const view = ownerDocument.defaultView;
1024
+ const frameHandles = [];
1025
+ let observer;
1026
+ let portalRegistration;
1027
+ let registeredPortalRoot = null;
1028
+ let disposed = false;
1029
+ const tryRegister = () => {
1030
+ if (disposed) return;
1031
+ const portalRoot = resolveFormulaEditorPortalRoot(options.editorId, ownerDocument);
1032
+ if (portalRoot === registeredPortalRoot) return;
1033
+ portalRegistration === null || portalRegistration === void 0 || portalRegistration.dispose();
1034
+ portalRegistration = void 0;
1035
+ registeredPortalRoot = null;
1036
+ if (!portalRoot) return;
1037
+ registeredPortalRoot = portalRoot;
1038
+ portalRegistration = registerFormulaEditorPortalRoot(options, ownerDocument, portalRoot);
1039
+ };
1040
+ const scheduleRetry = (remaining) => {
1041
+ if (remaining <= 0 || !(view === null || view === void 0 ? void 0 : view.requestAnimationFrame)) return;
1042
+ const handle = view.requestAnimationFrame(() => {
1043
+ const index = frameHandles.indexOf(handle);
1044
+ if (index >= 0) frameHandles.splice(index, 1);
1045
+ tryRegister();
1046
+ if (!registeredPortalRoot) scheduleRetry(remaining - 1);
1047
+ });
1048
+ frameHandles.push(handle);
1049
+ };
1050
+ tryRegister();
1051
+ if (!registeredPortalRoot) scheduleRetry(2);
1052
+ if ((view === null || view === void 0 ? void 0 : view.MutationObserver) && ownerDocument.body) {
1053
+ observer = new view.MutationObserver(() => tryRegister());
1054
+ observer.observe(ownerDocument.body, {
1055
+ childList: true,
1056
+ subtree: true
1057
+ });
1058
+ }
1059
+ collection.add(toDisposable(() => {
1060
+ disposed = true;
1061
+ frameHandles.forEach((handle) => {
1062
+ var _view$cancelAnimation;
1063
+ return view === null || view === void 0 || (_view$cancelAnimation = view.cancelAnimationFrame) === null || _view$cancelAnimation === void 0 ? void 0 : _view$cancelAnimation.call(view, handle);
1064
+ });
1065
+ frameHandles.length = 0;
1066
+ observer === null || observer === void 0 || observer.disconnect();
1067
+ observer = void 0;
1068
+ portalRegistration === null || portalRegistration === void 0 || portalRegistration.dispose();
1069
+ portalRegistration = void 0;
1070
+ registeredPortalRoot = null;
1071
+ }));
1072
+ return collection;
1073
+ }
1074
+ function resolveFormulaEditorPortalRoot(editorId, ownerDocument) {
1075
+ var _ref;
1076
+ return (_ref = ownerDocument.getElementById(`univer-doc-selection-container-${editorId}`)) !== null && _ref !== void 0 ? _ref : ownerDocument.getElementById(`__editor_${editorId}`);
1077
+ }
1078
+ function registerFormulaEditorPortalRoot(options, ownerDocument, portalRoot) {
1079
+ const collection = new DisposableCollection();
1080
+ const editorElement = ownerDocument.getElementById(`__editor_${options.editorId}`);
1081
+ (editorElement && editorElement !== portalRoot ? [portalRoot, editorElement] : [portalRoot]).forEach((element) => {
1082
+ if (options.interactionBoundaryService) collection.add(options.interactionBoundaryService.registerOwnedElement(options.embedId, element));
1083
+ if (options.focusCoordinator) collection.add(options.focusCoordinator.registerElement({
1084
+ embedId: options.embedId,
1085
+ role: "child-editor",
1086
+ element
1087
+ }));
1088
+ });
1089
+ return collection;
1090
+ }
1091
+ function resolveFormulaEmbedRuntimeDomScope(root) {
1092
+ var _scopeElement$getAttr, _scopeElement$getAttr2;
1093
+ const scopeElement = root === null || root === void 0 ? void 0 : root.closest(`[${FORMULA_EMBED_ID_ATTRIBUTE}]`);
1094
+ const embedId = scopeElement === null || scopeElement === void 0 ? void 0 : scopeElement.getAttribute(FORMULA_EMBED_ID_ATTRIBUTE);
1095
+ if (!scopeElement || !embedId) return;
1096
+ return {
1097
+ embedId,
1098
+ hostUnitId: (_scopeElement$getAttr = scopeElement.getAttribute("data-embed-host-unit-id")) !== null && _scopeElement$getAttr !== void 0 ? _scopeElement$getAttr : void 0,
1099
+ childUnitId: (_scopeElement$getAttr2 = scopeElement.getAttribute("data-embed-child-unit-id")) !== null && _scopeElement$getAttr2 !== void 0 ? _scopeElement$getAttr2 : void 0
1100
+ };
1101
+ }
1102
+ function resolveActiveFormulaEmbedRuntimeDomScope(ownerDocument) {
1103
+ const activeElement = ownerDocument === null || ownerDocument === void 0 ? void 0 : ownerDocument.activeElement;
1104
+ return activeElement instanceof HTMLElement ? resolveFormulaEmbedRuntimeDomScope(activeElement) : void 0;
1105
+ }
1106
+ function isEventTargetInSameFormulaEmbedInteractionBoundary(left, right) {
1107
+ const leftOwner = resolveFormulaEmbedInteractionOwnerId(left);
1108
+ return Boolean(leftOwner && leftOwner === resolveFormulaEmbedInteractionOwnerId(right));
1109
+ }
1110
+ function resolveFormulaEmbedInteractionOwnerId(target) {
1111
+ var _target$closest$getAt, _target$closest;
1112
+ if (!(target instanceof Element)) return;
1113
+ return (_target$closest$getAt = (_target$closest = target.closest(`[${"data-embed-interaction-boundary-owner"}]`)) === null || _target$closest === void 0 ? void 0 : _target$closest.getAttribute("data-embed-interaction-boundary-owner")) !== null && _target$closest$getAt !== void 0 ? _target$closest$getAt : void 0;
1114
+ }
1115
+
828
1116
  //#endregion
829
1117
  //#region src/services/utils.ts
830
1118
  function getFunctionTypeValues(localeService, customFormula) {
@@ -1064,16 +1352,19 @@ const HelpHiddenTip = ({ onClick }) => {
1064
1352
 
1065
1353
  //#endregion
1066
1354
  //#region src/views/formula-editor/help-function/HelpFunction.tsx
1067
- const Params = ({ className, title, value }) => /* @__PURE__ */ jsxs("div", {
1068
- className: "univer-my-2",
1069
- children: [/* @__PURE__ */ jsx("div", {
1070
- className: clsx("univer-mb-2 univer-text-sm univer-font-medium univer-text-gray-900 dark:!univer-text-white", className),
1071
- children: title
1072
- }), /* @__PURE__ */ jsx("div", {
1073
- className: "univer-whitespace-pre-wrap univer-break-words univer-text-xs univer-text-gray-500",
1074
- children: value
1075
- })]
1076
- });
1355
+ const Params = ({ className, title, titleKey, value }) => {
1356
+ const localeService = useDependency(LocaleService);
1357
+ return /* @__PURE__ */ jsxs("div", {
1358
+ className: "univer-my-2",
1359
+ children: [/* @__PURE__ */ jsx("div", {
1360
+ className: clsx("univer-mb-2 univer-text-sm univer-font-medium univer-text-gray-900 dark:!univer-text-white", className),
1361
+ children: titleKey ? localeService.t(titleKey) : title
1362
+ }), /* @__PURE__ */ jsx("div", {
1363
+ className: "univer-whitespace-pre-wrap univer-break-words univer-text-xs univer-text-gray-500",
1364
+ children: value
1365
+ })]
1366
+ });
1367
+ };
1077
1368
  const Help = (props) => {
1078
1369
  const { prefix, value, active, onClick } = props;
1079
1370
  return /* @__PURE__ */ jsxs("div", { children: [
@@ -1149,11 +1440,11 @@ function HelpFunction(props) {
1149
1440
  className: "univer-mt-3",
1150
1441
  children: [
1151
1442
  /* @__PURE__ */ jsx(Params, {
1152
- title: localeService.t("sheets-formula-ui.prompt.helpExample"),
1443
+ titleKey: "sheets-formula-ui.prompt.helpExample",
1153
1444
  value: `${functionInfo.functionName}(${functionInfo.functionParameter.map((item) => item.example).join(",")})`
1154
1445
  }),
1155
1446
  /* @__PURE__ */ jsx(Params, {
1156
- title: localeService.t("sheets-formula-ui.prompt.helpAbstract"),
1447
+ titleKey: "sheets-formula-ui.prompt.helpAbstract",
1157
1448
  value: functionInfo.description
1158
1449
  }),
1159
1450
  functionInfo && functionInfo.functionParameter && functionInfo.functionParameter.map((item, i) => /* @__PURE__ */ jsx(Params, {
@@ -1170,26 +1461,47 @@ function HelpFunction(props) {
1170
1461
 
1171
1462
  //#endregion
1172
1463
  //#region src/views/formula-editor/hooks/use-focus.ts
1464
+ function focusFormulaEditor(editorService, editor, offset) {
1465
+ if (!editor) return;
1466
+ editorService.focus(editor.getEditorId());
1467
+ focusFormulaEditorElement(editor);
1468
+ if (editor.docSelectionRenderService.isOnPointerEvent) return;
1469
+ const selections = [...editor.getSelectionRanges()];
1470
+ if (Tools.isDefine(offset)) editor.setSelectionRanges([{
1471
+ startOffset: offset,
1472
+ endOffset: offset
1473
+ }]);
1474
+ else if (!selections.length) {
1475
+ var _editor$getDocumentDa, _editor$getDocumentDa2;
1476
+ const body = (_editor$getDocumentDa = (_editor$getDocumentDa2 = editor.getDocumentData().body) === null || _editor$getDocumentDa2 === void 0 ? void 0 : _editor$getDocumentDa2.dataStream) !== null && _editor$getDocumentDa !== void 0 ? _editor$getDocumentDa : "\r\n";
1477
+ const offset = Math.max(body.length - 2, 0);
1478
+ editor.setSelectionRanges([{
1479
+ startOffset: offset,
1480
+ endOffset: offset
1481
+ }]);
1482
+ } else editor.setSelectionRanges(selections);
1483
+ }
1484
+ function focusFormulaEditorElement(editor) {
1485
+ var _editor$editorDOM$own, _editor$editorDOM;
1486
+ const editorElement = ((_editor$editorDOM$own = (_editor$editorDOM = editor.editorDOM) === null || _editor$editorDOM === void 0 ? void 0 : _editor$editorDOM.ownerDocument) !== null && _editor$editorDOM$own !== void 0 ? _editor$editorDOM$own : document).getElementById(`__editor_${editor.getEditorId()}`);
1487
+ editorElement === null || editorElement === void 0 || editorElement.focus({ preventScroll: true });
1488
+ }
1489
+ function shouldSkipFormulaEditorMouseUpFocus(_target) {
1490
+ return false;
1491
+ }
1492
+ function shouldRefocusFormulaEditorOnMouseUp(options) {
1493
+ if (shouldSkipFormulaEditorMouseUpFocus(options.target)) return false;
1494
+ if (options.isPointerSelecting || options.isFocusing) return false;
1495
+ return true;
1496
+ }
1497
+ function hasActiveFormulaEmbedInteraction(scopeElement) {
1498
+ const ownerDocument = scopeElement === null || scopeElement === void 0 ? void 0 : scopeElement.ownerDocument;
1499
+ return isEventTargetInSameFormulaEmbedInteractionBoundary(scopeElement, ownerDocument === null || ownerDocument === void 0 ? void 0 : ownerDocument.activeElement);
1500
+ }
1173
1501
  const useFocus = (editor) => {
1174
1502
  const editorService = useDependency(IEditorService);
1175
1503
  return useEvent((offset) => {
1176
- if (editor) {
1177
- editorService.focus(editor.getEditorId());
1178
- const selections = [...editor.getSelectionRanges()];
1179
- if (Tools.isDefine(offset)) editor.setSelectionRanges([{
1180
- startOffset: offset,
1181
- endOffset: offset
1182
- }]);
1183
- else if (!selections.length && !editor.docSelectionRenderService.isOnPointerEvent) {
1184
- var _editor$getDocumentDa, _editor$getDocumentDa2;
1185
- const body = (_editor$getDocumentDa = (_editor$getDocumentDa2 = editor.getDocumentData().body) === null || _editor$getDocumentDa2 === void 0 ? void 0 : _editor$getDocumentDa2.dataStream) !== null && _editor$getDocumentDa !== void 0 ? _editor$getDocumentDa : "\r\n";
1186
- const offset = Math.max(body.length - 2, 0);
1187
- editor.setSelectionRanges([{
1188
- startOffset: offset,
1189
- endOffset: offset
1190
- }]);
1191
- } else editor.setSelectionRanges(selections);
1192
- }
1504
+ focusFormulaEditor(editorService, editor, offset);
1193
1505
  });
1194
1506
  };
1195
1507
 
@@ -1538,9 +1850,16 @@ function getDefaultRefSelectionStyle(themeService) {
1538
1850
 
1539
1851
  //#endregion
1540
1852
  //#region src/views/formula-editor/hooks/use-formula-selection.ts
1541
- function getCurrentBodyDataStreamAndOffset(accssor) {
1542
- var _documentModel$getBod, _documentModel$getBod2;
1543
- const documentModel = accssor.get(IUniverInstanceService).getCurrentUnitOfType(UniverInstanceType.UNIVER_DOC);
1853
+ function resolveFormulaSelectionDataStream(accssor, editor, editorId) {
1854
+ var _editor$getDocumentDa, _documentModel$getBod, _documentModel$getBod2;
1855
+ const editorDataStream = editor === null || editor === void 0 || (_editor$getDocumentDa = editor.getDocumentData().body) === null || _editor$getDocumentDa === void 0 ? void 0 : _editor$getDocumentDa.dataStream;
1856
+ if (editorDataStream != null) return {
1857
+ dataStream: editorDataStream,
1858
+ offset: 0
1859
+ };
1860
+ const univerInstanceService = accssor.get(IUniverInstanceService);
1861
+ const editorDocumentModel = editorId ? univerInstanceService.getUnit(editorId, UniverInstanceType.UNIVER_DOC) : void 0;
1862
+ const documentModel = editorDocumentModel !== null && editorDocumentModel !== void 0 ? editorDocumentModel : univerInstanceService.getCurrentUnitOfType(UniverInstanceType.UNIVER_DOC);
1544
1863
  if (!(documentModel === null || documentModel === void 0 ? void 0 : documentModel.getBody())) return;
1545
1864
  return {
1546
1865
  dataStream: (_documentModel$getBod = (_documentModel$getBod2 = documentModel.getBody()) === null || _documentModel$getBod2 === void 0 ? void 0 : _documentModel$getBod2.dataStream) !== null && _documentModel$getBod !== void 0 ? _documentModel$getBod : "",
@@ -1550,9 +1869,36 @@ function getCurrentBodyDataStreamAndOffset(accssor) {
1550
1869
  function shouldSkipReferenceEditingByPointer(isDisabledByPointer, disableOnClick) {
1551
1870
  return isDisabledByPointer && !disableOnClick;
1552
1871
  }
1872
+ function resolveFormulaSelectionWorkbook(currentWorkbook, fallbackWorkbook) {
1873
+ var _ref;
1874
+ return (_ref = currentWorkbook !== null && currentWorkbook !== void 0 ? currentWorkbook : fallbackWorkbook) !== null && _ref !== void 0 ? _ref : void 0;
1875
+ }
1876
+ function resolveFormulaSelectionCursorIndex(activeRange, dataStream) {
1877
+ const index = (activeRange === null || activeRange === void 0 ? void 0 : activeRange.collapsed) ? activeRange.startOffset : -1;
1878
+ if (index <= 0 && dataStream.startsWith("=") && dataStream.length > 0) return dataStream.length;
1879
+ return index;
1880
+ }
1881
+ function getSelectionAfterLaggingFormulaInput(dataStream, selection, content) {
1882
+ if (!content || content.includes("\r") || content.includes("\n") || !dataStream.startsWith("=") || !(selection === null || selection === void 0 ? void 0 : selection.collapsed)) return;
1883
+ const startOffset = selection.startOffset;
1884
+ if (startOffset == null) return;
1885
+ if (selection.endOffset !== startOffset) return;
1886
+ if (dataStream.slice(startOffset, startOffset + content.length) !== content) return;
1887
+ const nextOffset = startOffset + content.length;
1888
+ return {
1889
+ startOffset: nextOffset,
1890
+ endOffset: nextOffset,
1891
+ collapsed: true
1892
+ };
1893
+ }
1894
+ function resolveFormulaSelectingIntent(adding, editing) {
1895
+ if (adding) return 1;
1896
+ if (editing) return 2;
1897
+ return 0;
1898
+ }
1553
1899
  function useFormulaSelecting(opts) {
1554
1900
  var _renderer$mainCompone2;
1555
- const { editorId, isFocus, disableOnClick, unitId, subUnitId } = opts;
1901
+ const { editor, editorId, isFocus, disableOnClick, unitId, subUnitId } = opts;
1556
1902
  const renderManagerService = useDependency(IRenderManagerService);
1557
1903
  const univerInstanceService = useDependency(IUniverInstanceService);
1558
1904
  const sheetRenderer = renderManagerService.getRenderById(unitId);
@@ -1563,6 +1909,7 @@ function useFormulaSelecting(opts) {
1563
1909
  const [isSelecting, innerSetIsSelecting] = useState(0);
1564
1910
  const lexerTreeBuilder = useDependency(LexerTreeBuilder);
1565
1911
  const isDisabledByPointer = useRef(true);
1912
+ const lastInputContentRef = useRef("");
1566
1913
  const refSelectionsRenderService = sheetRenderer === null || sheetRenderer === void 0 ? void 0 : sheetRenderer.with(RefSelectionsRenderService);
1567
1914
  const isSelectingRef = useStateRef(isSelecting);
1568
1915
  const workbook = univerInstanceService.getUnit(unitId, UniverInstanceType.UNIVER_SHEET);
@@ -1573,15 +1920,15 @@ function useFormulaSelecting(opts) {
1573
1920
  innerSetIsSelecting(v);
1574
1921
  });
1575
1922
  const calculateSelectingType = useEvent(() => {
1576
- var _config$dataStream, _lexerTreeBuilder$seq;
1577
- const currentWorkbook = univerInstanceService.getCurrentUnitOfType(UniverInstanceType.UNIVER_SHEET);
1923
+ var _editor$getSelectionR, _editor$getSelectionR2, _config$dataStream, _getSelectionAfterLag, _lexerTreeBuilder$seq;
1924
+ const currentWorkbook = resolveFormulaSelectionWorkbook(univerInstanceService.getCurrentUnitOfType(UniverInstanceType.UNIVER_SHEET), workbook);
1578
1925
  if (!currentWorkbook) return;
1579
1926
  const currentSheet = currentWorkbook.getActiveSheet();
1580
- const activeRange = docSelectionRenderService === null || docSelectionRenderService === void 0 ? void 0 : docSelectionRenderService.getActiveTextRange();
1581
- const index = (activeRange === null || activeRange === void 0 ? void 0 : activeRange.collapsed) ? activeRange.startOffset : -1;
1582
- const config = getCurrentBodyDataStreamAndOffset(injector);
1927
+ const activeRange = (_editor$getSelectionR = editor === null || editor === void 0 || (_editor$getSelectionR2 = editor.getSelectionRanges()) === null || _editor$getSelectionR2 === void 0 ? void 0 : _editor$getSelectionR2[0]) !== null && _editor$getSelectionR !== void 0 ? _editor$getSelectionR : docSelectionRenderService === null || docSelectionRenderService === void 0 ? void 0 : docSelectionRenderService.getActiveTextRange();
1928
+ const config = resolveFormulaSelectionDataStream(injector, editor, editorId);
1583
1929
  if (!config) return;
1584
1930
  const dataStream = config === null || config === void 0 || (_config$dataStream = config.dataStream) === null || _config$dataStream === void 0 ? void 0 : _config$dataStream.slice(0, -2);
1931
+ const index = resolveFormulaSelectionCursorIndex((_getSelectionAfterLag = getSelectionAfterLaggingFormulaInput(dataStream, activeRange, lastInputContentRef.current)) !== null && _getSelectionAfterLag !== void 0 ? _getSelectionAfterLag : activeRange, dataStream);
1585
1932
  const nodes = ((_lexerTreeBuilder$seq = lexerTreeBuilder.sequenceNodesBuilder(dataStream)) !== null && _lexerTreeBuilder$seq !== void 0 ? _lexerTreeBuilder$seq : []).map((node) => {
1586
1933
  if (typeof node === "object") {
1587
1934
  if (node.nodeType === sequenceNodeType.REFERENCE) return {
@@ -1599,21 +1946,22 @@ function useFormulaSelecting(opts) {
1599
1946
  const nextChar = dataStream[index];
1600
1947
  const focusingNode = nodes.find((node) => typeof node === "object" && node.nodeType === sequenceNodeType.REFERENCE && index === node.endIndex + 2);
1601
1948
  const adding = char && matchRefDrawToken(char) && (!nextChar || isFormulaLexerToken(nextChar) && nextChar !== matchToken.OPEN_BRACKET);
1602
- const editing = Boolean(focusingNode);
1603
- if ((dataStream === null || dataStream === void 0 ? void 0 : dataStream.substring(0, 1)) === "=" && (adding || editing)) if (editing) {
1604
- var _univerInstanceServic;
1605
- if (shouldSkipReferenceEditingByPointer(isDisabledByPointer.current, disableOnClick)) return;
1606
- isDisabledByPointer.current = false;
1607
- const { sheetName, unitId } = focusingNode.range;
1608
- const currentUnitId = (_univerInstanceServic = univerInstanceService.getCurrentUnitOfType(UniverInstanceType.UNIVER_SHEET)) === null || _univerInstanceServic === void 0 ? void 0 : _univerInstanceServic.getUnitId();
1609
- if (unitId && unitId !== currentUnitId) setIsSelecting(4);
1610
- else if (!sheetName && currentSheet.getSheetId() === (sourceSheet === null || sourceSheet === void 0 ? void 0 : sourceSheet.getSheetId()) || sheetName === currentSheet.getName()) setIsSelecting(2);
1611
- else setIsSelecting(3);
1612
- } else {
1613
- isDisabledByPointer.current = false;
1614
- setIsSelecting(1);
1615
- }
1616
- else setIsSelecting(0);
1949
+ const selectingIntent = resolveFormulaSelectingIntent(Boolean(adding), Boolean(focusingNode));
1950
+ if ((dataStream === null || dataStream === void 0 ? void 0 : dataStream.substring(0, 1)) === "=" && selectingIntent !== 0) {
1951
+ if (selectingIntent === 1) {
1952
+ isDisabledByPointer.current = false;
1953
+ setIsSelecting(1);
1954
+ } else if (focusingNode) {
1955
+ var _resolveFormulaSelect;
1956
+ if (shouldSkipReferenceEditingByPointer(isDisabledByPointer.current, disableOnClick)) return;
1957
+ isDisabledByPointer.current = false;
1958
+ const { sheetName, unitId } = focusingNode.range;
1959
+ const currentUnitId = (_resolveFormulaSelect = resolveFormulaSelectionWorkbook(univerInstanceService.getCurrentUnitOfType(UniverInstanceType.UNIVER_SHEET), workbook)) === null || _resolveFormulaSelect === void 0 ? void 0 : _resolveFormulaSelect.getUnitId();
1960
+ if (unitId && unitId !== currentUnitId) setIsSelecting(4);
1961
+ else if (!sheetName && currentSheet.getSheetId() === (sourceSheet === null || sourceSheet === void 0 ? void 0 : sourceSheet.getSheetId()) || sheetName === currentSheet.getName()) setIsSelecting(2);
1962
+ else setIsSelecting(3);
1963
+ }
1964
+ } else setIsSelecting(0);
1617
1965
  });
1618
1966
  useEffect(() => {
1619
1967
  const sub = docSelectionManagerService.textSelection$.pipe(filter((param) => param.unitId === editorId)).subscribe(() => {
@@ -1625,6 +1973,43 @@ function useFormulaSelecting(opts) {
1625
1973
  docSelectionManagerService.textSelection$,
1626
1974
  editorId
1627
1975
  ]);
1976
+ useEffect(() => {
1977
+ if (!isFocus || !editor) return;
1978
+ let timeout;
1979
+ const sub = editor.input$.subscribe(({ content, isComposing }) => {
1980
+ if (!isComposing) lastInputContentRef.current = content;
1981
+ queueMicrotask(() => {
1982
+ calculateSelectingType();
1983
+ });
1984
+ if (timeout) clearTimeout(timeout);
1985
+ timeout = setTimeout(() => {
1986
+ calculateSelectingType();
1987
+ lastInputContentRef.current = "";
1988
+ }, 0);
1989
+ });
1990
+ return () => {
1991
+ if (timeout) clearTimeout(timeout);
1992
+ sub.unsubscribe();
1993
+ };
1994
+ }, [
1995
+ calculateSelectingType,
1996
+ editor,
1997
+ isFocus
1998
+ ]);
1999
+ useEffect(() => {
2000
+ var _editorDocumentModel$;
2001
+ if (!isFocus) return;
2002
+ const editorDocumentModel = univerInstanceService.getUnit(editorId, UniverInstanceType.UNIVER_DOC);
2003
+ const sub = editorDocumentModel === null || editorDocumentModel === void 0 || (_editorDocumentModel$ = editorDocumentModel.change$) === null || _editorDocumentModel$ === void 0 ? void 0 : _editorDocumentModel$.subscribe(() => {
2004
+ queueMicrotask(calculateSelectingType);
2005
+ });
2006
+ return () => sub === null || sub === void 0 ? void 0 : sub.unsubscribe();
2007
+ }, [
2008
+ calculateSelectingType,
2009
+ editorId,
2010
+ isFocus,
2011
+ univerInstanceService
2012
+ ]);
1628
2013
  useEffect(() => {
1629
2014
  if (!isFocus) {
1630
2015
  setIsSelecting(0);
@@ -1710,10 +2095,7 @@ function calcHighlightRanges(opts) {
1710
2095
  const workbook = univerInstanceService.getUnit(unitId, UniverInstanceType.UNIVER_SHEET);
1711
2096
  const worksheet = workbook === null || workbook === void 0 ? void 0 : workbook.getActiveSheet();
1712
2097
  const selectionWithStyle = [];
1713
- if (!workbook || !worksheet) {
1714
- refSelectionsService.setSelections(selectionWithStyle);
1715
- return;
1716
- }
2098
+ if (!workbook || !worksheet) return selectionWithStyle;
1717
2099
  const currentSheetId = worksheet.getSheetId();
1718
2100
  const getSheetIdByName = (name) => {
1719
2101
  var _workbook$getSheetByS;
@@ -1758,6 +2140,7 @@ function calcHighlightRanges(opts) {
1758
2140
  const cursor = (_editor$getSelectionR = editor.getSelectionRanges()) === null || _editor$getSelectionR === void 0 || (_editor$getSelectionR = _editor$getSelectionR[0]) === null || _editor$getSelectionR === void 0 ? void 0 : _editor$getSelectionR.startOffset;
1759
2141
  const activeIndex = endIndexes.findIndex((end) => end + 2 === cursor);
1760
2142
  if (activeIndex !== -1) refSelectionsRenderService === null || refSelectionsRenderService === void 0 || refSelectionsRenderService.setActiveSelectionIndex(activeIndex);
2143
+ else if (selectionWithStyle.length) refSelectionsRenderService === null || refSelectionsRenderService === void 0 || refSelectionsRenderService.setActiveSelectionIndex(selectionWithStyle.length - 1);
1761
2144
  else refSelectionsRenderService === null || refSelectionsRenderService === void 0 || refSelectionsRenderService.resetActiveSelectionIndex();
1762
2145
  }
1763
2146
  return selectionWithStyle;
@@ -1772,14 +2155,25 @@ function useSheetHighlight(unitId, subUnitId) {
1772
2155
  const themeService = useDependency(ThemeService);
1773
2156
  const refSelectionsService = useDependency(IRefSelectionsService);
1774
2157
  const renderManagerService = useDependency(IRenderManagerService);
1775
- const currentWorkbook = useObservable(useMemo(() => univerInstanceService.getCurrentTypeOfUnit$(UniverInstanceType.UNIVER_SHEET), [univerInstanceService]));
1776
- const currentRender = currentWorkbook ? renderManagerService.getRenderById(currentWorkbook.getUnitId()) : null;
1777
- const refSelectionsRenderService = currentRender === null || currentRender === void 0 ? void 0 : currentRender.with(RefSelectionsRenderService);
1778
- const sheetSkeletonManagerService = currentRender === null || currentRender === void 0 ? void 0 : currentRender.with(SheetSkeletonManagerService);
1779
- const highlightSheet = useEvent((refSelections, editor) => {
2158
+ const ownerRender = renderManagerService.getRenderById(unitId);
2159
+ const ownerRefSelectionsRenderService = ownerRender === null || ownerRender === void 0 ? void 0 : ownerRender.with(RefSelectionsRenderService);
2160
+ const getHighlightWorkbook = useEvent((refSelections) => {
2161
+ const ownerWorkbook = univerInstanceService.getUnit(unitId, UniverInstanceType.UNIVER_SHEET);
1780
2162
  const currentWorkbook = univerInstanceService.getCurrentUnitOfType(UniverInstanceType.UNIVER_SHEET);
2163
+ const currentUnitId = currentWorkbook === null || currentWorkbook === void 0 ? void 0 : currentWorkbook.getUnitId();
2164
+ return Boolean(currentUnitId) && refSelections.some((refSelection) => deserializeRangeWithSheet(refSelection.token).unitId === currentUnitId) ? currentWorkbook : ownerWorkbook !== null && ownerWorkbook !== void 0 ? ownerWorkbook : currentWorkbook;
2165
+ });
2166
+ const highlightSheet = useEvent((refSelections, editor, isEnd = false) => {
2167
+ var _currentWorkbook$getA;
2168
+ const currentWorkbook = getHighlightWorkbook(refSelections);
1781
2169
  if (!currentWorkbook) return;
1782
- if (refSelectionsRenderService === null || refSelectionsRenderService === void 0 ? void 0 : refSelectionsRenderService.selectionMoving) return;
2170
+ const currentRender = renderManagerService.getRenderById(currentWorkbook.getUnitId());
2171
+ const refSelectionsRenderService = currentRender === null || currentRender === void 0 ? void 0 : currentRender.with(RefSelectionsRenderService);
2172
+ const sheetSelectionRenderService = currentRender === null || currentRender === void 0 ? void 0 : currentRender.with(ISheetSelectionRenderService);
2173
+ const sheetSkeletonManagerService = currentRender === null || currentRender === void 0 ? void 0 : currentRender.with(SheetSkeletonManagerService);
2174
+ if (!isEnd && (refSelectionsRenderService === null || refSelectionsRenderService === void 0 ? void 0 : refSelectionsRenderService.selectionMoving)) return;
2175
+ const currentSheetId = (_currentWorkbook$getA = currentWorkbook.getActiveSheet()) === null || _currentWorkbook$getA === void 0 ? void 0 : _currentWorkbook$getA.getSheetId();
2176
+ if (!currentSheetId) return;
1783
2177
  const selectionWithStyle = calcHighlightRanges({
1784
2178
  unitId,
1785
2179
  subUnitId,
@@ -1794,13 +2188,14 @@ function useSheetHighlight(unitId, subUnitId) {
1794
2188
  });
1795
2189
  if (!selectionWithStyle) return;
1796
2190
  if (((refSelectionsRenderService === null || refSelectionsRenderService === void 0 ? void 0 : refSelectionsRenderService.getSelectionControls()) || []).length === selectionWithStyle.length) refSelectionsRenderService === null || refSelectionsRenderService === void 0 || refSelectionsRenderService.resetSelectionsByModelData(selectionWithStyle);
1797
- else refSelectionsService.setSelections(selectionWithStyle);
2191
+ else refSelectionsService.setSelections(currentWorkbook.getUnitId(), currentSheetId, selectionWithStyle);
2192
+ if (isEnd && selectionWithStyle.length) sheetSelectionRenderService === null || sheetSelectionRenderService === void 0 || sheetSelectionRenderService.resetSelectionsByModelData([]);
1798
2193
  });
1799
2194
  useEffect(() => {
1800
2195
  return () => {
1801
- refSelectionsRenderService === null || refSelectionsRenderService === void 0 || refSelectionsRenderService.resetActiveSelectionIndex();
2196
+ ownerRefSelectionsRenderService === null || ownerRefSelectionsRenderService === void 0 || ownerRefSelectionsRenderService.resetActiveSelectionIndex();
1802
2197
  };
1803
- }, [refSelectionsRenderService]);
2198
+ }, [ownerRefSelectionsRenderService]);
1804
2199
  return highlightSheet;
1805
2200
  }
1806
2201
  function useDocHight(_leadingCharacter = "") {
@@ -1808,23 +2203,18 @@ function useDocHight(_leadingCharacter = "") {
1808
2203
  const colorMap = useColor();
1809
2204
  const commandService = useDependency(ICommandService);
1810
2205
  const leadingCharacterLength = useMemo(() => _leadingCharacter.length, [_leadingCharacter]);
1811
- return useEvent((editor, sequenceNodes, isNeedResetSelection = true, newSelections) => {
2206
+ return useEvent((editor, sequenceNodes, isNeedResetSelection = true, newSelections, sourceText) => {
1812
2207
  const data = editor.getDocumentData();
1813
2208
  const editorId = editor.getEditorId();
1814
2209
  if (!data) return [];
1815
2210
  const body = data.body;
1816
2211
  if (!body) return [];
1817
2212
  const str = body.dataStream.slice(0, body.dataStream.length - 2);
1818
- const cloneBody = {
1819
- dataStream: "",
1820
- ...data.body
1821
- };
1822
2213
  if (!str.startsWith(_leadingCharacter)) return [];
1823
2214
  if (sequenceNodes == null || sequenceNodes.length === 0) {
1824
- cloneBody.textRuns = [];
1825
2215
  commandService.syncExecuteCommand(ReplaceTextRunsCommand.id, {
1826
2216
  unitId: editorId,
1827
- body: getBodySlice(cloneBody, 0, cloneBody.dataStream.length - 2)
2217
+ body: createFormulaHighlightBody(str, [])
1828
2218
  });
1829
2219
  return [];
1830
2220
  } else {
@@ -1833,19 +2223,16 @@ function useDocHight(_leadingCharacter = "") {
1833
2223
  e.ed = e.ed + leadingCharacterLength;
1834
2224
  e.st = e.st + leadingCharacterLength;
1835
2225
  });
1836
- cloneBody.textRuns = [{
2226
+ const highlightDataStream = getFormulaHighlightDataStream(_leadingCharacter, sequenceNodes, sourceText);
2227
+ const highlightTextRuns = [{
1837
2228
  st: 0,
1838
2229
  ed: 1,
1839
2230
  ts: { fs: 11 }
1840
2231
  }, ...textRuns];
1841
- cloneBody.dataStream = `${_leadingCharacter}${sequenceNodes.reduce((pre, cur) => {
1842
- if (typeof cur === "string") return `${pre}${cur}`;
1843
- return `${pre}${cur.token}`;
1844
- }, "")}\r\n`;
1845
2232
  let selections;
1846
2233
  if (isNeedResetSelection) {
1847
2234
  selections = editor.getSelectionRanges();
1848
- const maxOffset = cloneBody.dataStream.length - 2 + leadingCharacterLength;
2235
+ const maxOffset = highlightDataStream.length - 2 + leadingCharacterLength;
1849
2236
  selections.forEach((selection) => {
1850
2237
  selection.startOffset = Math.max(0, Math.min(selection.startOffset, maxOffset));
1851
2238
  selection.endOffset = Math.max(0, Math.min(selection.endOffset, maxOffset));
@@ -1853,13 +2240,30 @@ function useDocHight(_leadingCharacter = "") {
1853
2240
  }
1854
2241
  commandService.syncExecuteCommand(ReplaceTextRunsCommand.id, {
1855
2242
  unitId: editorId,
1856
- body: getBodySlice(cloneBody, 0, cloneBody.dataStream.length - 2),
2243
+ body: createFormulaHighlightBody(highlightDataStream.slice(0, -2), highlightTextRuns),
1857
2244
  textRanges: newSelections !== null && newSelections !== void 0 ? newSelections : selections
1858
2245
  });
1859
2246
  return refSelections;
1860
2247
  }
1861
2248
  });
1862
2249
  }
2250
+ /**
2251
+ * ReplaceTextRunsCommand shifts the editor's existing structural metadata when text changes.
2252
+ * Its replacement body must therefore contain only inline formula data; carrying paragraphs
2253
+ * or section breaks copied from the old snapshot would leave their indexes stale.
2254
+ */
2255
+ function createFormulaHighlightBody(dataStream, textRuns) {
2256
+ return {
2257
+ dataStream,
2258
+ textRuns
2259
+ };
2260
+ }
2261
+ function getFormulaHighlightDataStream(leadingCharacter, sequenceNodes, sourceText) {
2262
+ return `${leadingCharacter}${sourceText !== null && sourceText !== void 0 ? sourceText : sequenceNodes.reduce((pre, cur) => {
2263
+ if (typeof cur === "string") return `${pre}${cur}`;
2264
+ return `${pre}${cur.token}`;
2265
+ }, "")}\r\n`;
2266
+ }
1863
2267
  function useColor() {
1864
2268
  const themeService = useDependency(ThemeService);
1865
2269
  return useMemo(() => {
@@ -1962,17 +2366,41 @@ function buildTextRuns(descriptionService, colorMap, sequenceNodes) {
1962
2366
 
1963
2367
  //#endregion
1964
2368
  //#region src/views/formula-editor/hooks/use-left-and-right-arrow.ts
1965
- const useLeftAndRightArrow = (isNeed, shouldMoveSelection, editor, onMoveInEditor) => {
2369
+ function shouldMoveFormulaSelectionFromCurrentSelection(selectingType, refSelectionCount) {
2370
+ if (selectingType === 1) return refSelectionCount === 0;
2371
+ return selectingType === 3;
2372
+ }
2373
+ function isFormulaEditorInteractionOwner(focusEditorId, editorId, options) {
2374
+ var _options$formulaBarEd, _options$normalEditor;
2375
+ if (focusEditorId === editorId) return true;
2376
+ if (!(options === null || options === void 0 ? void 0 : options.fxBarFocused)) return false;
2377
+ return editorId === ((_options$formulaBarEd = options.formulaBarEditorId) !== null && _options$formulaBarEd !== void 0 ? _options$formulaBarEd : DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY) && focusEditorId === ((_options$normalEditor = options.normalEditorId) !== null && _options$normalEditor !== void 0 ? _options$normalEditor : DOCS_NORMAL_EDITOR_UNIT_ID_KEY);
2378
+ }
2379
+ const useLeftAndRightArrow = (isNeed, shouldMoveSelection, editor, onMoveInEditor, getRefSelectionCount) => {
1966
2380
  const commandService = useDependency(ICommandService);
1967
2381
  const shortcutService = useDependency(IShortcutService);
2382
+ const editorService = useDependency(IEditorService);
2383
+ const contextService = useDependency(IContextService);
2384
+ const operationNamespace = useMemo(() => generateRandomId(4), []);
1968
2385
  const shouldMoveSelectionRef = useRef(shouldMoveSelection);
1969
2386
  shouldMoveSelectionRef.current = shouldMoveSelection;
1970
2387
  const onMoveInEditorRef = useRef(onMoveInEditor);
1971
2388
  onMoveInEditorRef.current = onMoveInEditor;
2389
+ const getRefSelectionCountRef = useRef(getRefSelectionCount);
2390
+ getRefSelectionCountRef.current = getRefSelectionCount;
1972
2391
  useEffect(() => {
1973
2392
  if (!editor || !isNeed) return;
1974
- const operationId = `sheet.formula-embedding-editor.${editor.getEditorId()}`;
2393
+ const editorId = editor.getEditorId();
2394
+ const operationId = `sheet.formula-embedding-editor.${editorId}.${operationNamespace}`;
1975
2395
  const d = new DisposableCollection();
2396
+ const shouldHandleShortcut = () => {
2397
+ try {
2398
+ const fxBarFocused = contextService.getContextValue(FOCUSING_FX_BAR_EDITOR);
2399
+ return isFormulaEditorInteractionOwner(editorService.getFocusId(), editorId, { fxBarFocused }) && (editor.docSelectionRenderService.isFocusing || fxBarFocused);
2400
+ } catch {
2401
+ return false;
2402
+ }
2403
+ };
1976
2404
  const handleMoveInEditor = (keycode, metaKey) => {
1977
2405
  if (onMoveInEditorRef.current) {
1978
2406
  onMoveInEditorRef.current(keycode, metaKey);
@@ -1991,27 +2419,30 @@ const useLeftAndRightArrow = (isNeed, shouldMoveSelection, editor, onMoveInEdito
1991
2419
  else if (keycode === KeyCode.ARROW_UP) direction = Direction.UP;
1992
2420
  else if (keycode === KeyCode.ARROW_LEFT) direction = Direction.LEFT;
1993
2421
  else if (keycode === KeyCode.ARROW_RIGHT) direction = Direction.RIGHT;
1994
- if (shouldMoveSelectionRef.current) if (metaKey === MetaKeys.CTRL_COMMAND) commandService.executeCommand(MoveSelectionCommand.id, {
1995
- direction,
1996
- jumpOver: JumpOver.moveGap,
1997
- extra: "formula-editor",
1998
- fromCurrentSelection: shouldMoveSelectionRef.current === 1 || shouldMoveSelectionRef.current === 3
1999
- });
2000
- else if (metaKey === MetaKeys.SHIFT) commandService.executeCommand(ExpandSelectionCommand.id, {
2001
- direction,
2002
- extra: "formula-editor"
2003
- });
2004
- else if (metaKey === (MetaKeys.CTRL_COMMAND | MetaKeys.SHIFT)) commandService.executeCommand(ExpandSelectionCommand.id, {
2005
- direction,
2006
- jumpOver: JumpOver.moveGap,
2007
- extra: "formula-editor"
2008
- });
2009
- else commandService.executeCommand(MoveSelectionCommand.id, {
2010
- direction,
2011
- extra: "formula-editor",
2012
- fromCurrentSelection: shouldMoveSelectionRef.current === 1 || shouldMoveSelectionRef.current === 3
2013
- });
2014
- else handleMoveInEditor(keycode, metaKey);
2422
+ if (shouldMoveSelectionRef.current) {
2423
+ var _getRefSelectionCount, _getRefSelectionCount2;
2424
+ const fromCurrentSelection = shouldMoveFormulaSelectionFromCurrentSelection(shouldMoveSelectionRef.current, (_getRefSelectionCount = (_getRefSelectionCount2 = getRefSelectionCountRef.current) === null || _getRefSelectionCount2 === void 0 ? void 0 : _getRefSelectionCount2.call(getRefSelectionCountRef)) !== null && _getRefSelectionCount !== void 0 ? _getRefSelectionCount : 0);
2425
+ if (metaKey === MetaKeys.CTRL_COMMAND) commandService.executeCommand(MoveSelectionCommand.id, {
2426
+ direction,
2427
+ jumpOver: JumpOver.moveGap,
2428
+ extra: "formula-editor",
2429
+ fromCurrentSelection
2430
+ });
2431
+ else if (metaKey === MetaKeys.SHIFT) commandService.executeCommand(ExpandSelectionCommand.id, {
2432
+ direction,
2433
+ extra: "formula-editor"
2434
+ });
2435
+ else if (metaKey === (MetaKeys.CTRL_COMMAND | MetaKeys.SHIFT)) commandService.executeCommand(ExpandSelectionCommand.id, {
2436
+ direction,
2437
+ jumpOver: JumpOver.moveGap,
2438
+ extra: "formula-editor"
2439
+ });
2440
+ else commandService.executeCommand(MoveSelectionCommand.id, {
2441
+ direction,
2442
+ extra: "formula-editor",
2443
+ fromCurrentSelection
2444
+ });
2445
+ } else handleMoveInEditor(keycode, metaKey);
2015
2446
  };
2016
2447
  d.add(commandService.registerCommand({
2017
2448
  id: operationId,
@@ -2078,7 +2509,7 @@ const useLeftAndRightArrow = (isNeed, shouldMoveSelection, editor, onMoveInEdito
2078
2509
  return {
2079
2510
  id: operationId,
2080
2511
  binding: metaKey ? keyCode | metaKey : keyCode,
2081
- preconditions: () => true,
2512
+ preconditions: shouldHandleShortcut,
2082
2513
  priority: 900,
2083
2514
  staticParameters: {
2084
2515
  eventType: DeviceInputEventType.Keyboard,
@@ -2094,8 +2525,11 @@ const useLeftAndRightArrow = (isNeed, shouldMoveSelection, editor, onMoveInEdito
2094
2525
  };
2095
2526
  }, [
2096
2527
  commandService,
2528
+ contextService,
2097
2529
  editor,
2530
+ editorService,
2098
2531
  isNeed,
2532
+ operationNamespace,
2099
2533
  shortcutService
2100
2534
  ]);
2101
2535
  };
@@ -2131,7 +2565,7 @@ const useRefactorEffect = (isNeed, selecting, unitId, editorId, disableContextMe
2131
2565
  editorId
2132
2566
  ]);
2133
2567
  useLayoutEffect(() => {
2134
- if (isNeed && selecting) {
2568
+ if (isNeed && Boolean(selecting)) {
2135
2569
  const d1 = refSelectionsRenderService === null || refSelectionsRenderService === void 0 ? void 0 : refSelectionsRenderService.enableSelectionChanging();
2136
2570
  contextService.setContextValue(REF_SELECTIONS_ENABLED, true);
2137
2571
  return () => {
@@ -2202,18 +2636,45 @@ const prepareSelectionChangeContext = (opts) => {
2202
2636
  var _editor$getDocumentDa, _editor$getDocumentDa2, _lexerTreeBuilder$seq;
2203
2637
  const { editor, lexerTreeBuilder } = opts;
2204
2638
  const currentDocSelections = editor === null || editor === void 0 ? void 0 : editor.getSelectionRanges();
2205
- if ((currentDocSelections === null || currentDocSelections === void 0 ? void 0 : currentDocSelections.length) !== 1) return;
2206
- const offset = currentDocSelections[0].startOffset - 1;
2207
2639
  const dataStream = ((_editor$getDocumentDa = editor === null || editor === void 0 || (_editor$getDocumentDa2 = editor.getDocumentData().body) === null || _editor$getDocumentDa2 === void 0 ? void 0 : _editor$getDocumentDa2.dataStream) !== null && _editor$getDocumentDa !== void 0 ? _editor$getDocumentDa : "\r\n").slice(0, -2);
2208
2640
  const sequenceNodes = (_lexerTreeBuilder$seq = lexerTreeBuilder.sequenceNodesBuilder(dataStream.slice(1))) !== null && _lexerTreeBuilder$seq !== void 0 ? _lexerTreeBuilder$seq : [];
2641
+ let offset;
2642
+ if ((currentDocSelections === null || currentDocSelections === void 0 ? void 0 : currentDocSelections.length) === 1) offset = currentDocSelections[0].startOffset - 1;
2643
+ else if (dataStream.startsWith("=")) offset = Math.max(dataStream.length - 1, 0);
2644
+ else return;
2209
2645
  const nodeIndex = findIndexFromSequenceNodes(sequenceNodes, offset, false);
2210
2646
  return {
2211
2647
  nodeIndex,
2212
2648
  updatingRefIndex: findRefSequenceIndex(sequenceNodes, nodeIndex),
2649
+ formulaText: dataStream.slice(1),
2213
2650
  sequenceNodes,
2214
2651
  offset
2215
2652
  };
2216
2653
  };
2654
+ function getSequenceNodeCharAtOffset(sequenceNodes, offset) {
2655
+ let currentOffset = 0;
2656
+ for (const node of sequenceNodes) {
2657
+ const text = typeof node === "string" ? node : node.token;
2658
+ const nextOffset = currentOffset + text.length;
2659
+ if (offset > currentOffset && offset <= nextOffset) return text[offset - currentOffset - 1];
2660
+ currentOffset = nextOffset;
2661
+ }
2662
+ }
2663
+ function isFormulaReferenceAddingContext(sequenceNodes, offset) {
2664
+ const char = getSequenceNodeCharAtOffset(sequenceNodes, offset);
2665
+ return Boolean(char && matchRefDrawToken(char));
2666
+ }
2667
+ function isFormulaReferenceAddingTextContext(formulaText, offset) {
2668
+ const char = formulaText[offset - 1];
2669
+ const nextChar = formulaText[offset];
2670
+ return Boolean(char && matchRefDrawToken(char) && (!nextChar || isFormulaLexerToken(nextChar) && nextChar !== matchToken.OPEN_BRACKET));
2671
+ }
2672
+ function insertFormulaReferenceText(formulaText, refText, offset) {
2673
+ return `${formulaText.slice(0, offset)}${refText}${formulaText.slice(offset)}`;
2674
+ }
2675
+ function shouldSkipFormulaReferenceUpdate(isAdd, selectionCount) {
2676
+ return !isAdd && selectionCount === 0;
2677
+ }
2217
2678
  function getSelectionsForFormulaRefUpdate(selections, updatingRefIndex, isCtrlAddMode) {
2218
2679
  const orderedSelections = [...selections];
2219
2680
  if (updatingRefIndex === -1) return { orderedSelections };
@@ -2225,17 +2686,78 @@ function getSelectionsForFormulaRefUpdate(selections, updatingRefIndex, isCtrlAd
2225
2686
  insertedSelection
2226
2687
  };
2227
2688
  }
2689
+ function getLastFormulaSelection(selections) {
2690
+ return selections[selections.length - 1];
2691
+ }
2692
+ function getFormulaSelectionIdentityKey(selection) {
2693
+ var _ref, _item$rangeWithCoord, _range$startRow, _range$endRow, _range$startColumn, _range$endColumn;
2694
+ const item = selection;
2695
+ const range = (_ref = (_item$rangeWithCoord = item.rangeWithCoord) !== null && _item$rangeWithCoord !== void 0 ? _item$rangeWithCoord : item.range) !== null && _ref !== void 0 ? _ref : item;
2696
+ return [
2697
+ (_range$startRow = range.startRow) !== null && _range$startRow !== void 0 ? _range$startRow : "",
2698
+ (_range$endRow = range.endRow) !== null && _range$endRow !== void 0 ? _range$endRow : "",
2699
+ (_range$startColumn = range.startColumn) !== null && _range$startColumn !== void 0 ? _range$startColumn : "",
2700
+ (_range$endColumn = range.endColumn) !== null && _range$endColumn !== void 0 ? _range$endColumn : ""
2701
+ ].join(":");
2702
+ }
2703
+ function isSameFormulaSelection(first, second) {
2704
+ return getFormulaSelectionIdentityKey(first) === getFormulaSelectionIdentityKey(second);
2705
+ }
2706
+ const SHARED_SELECTION_CHANGE_DUPLICATE_END_GUARDS = /* @__PURE__ */ new Map();
2707
+ function getSharedSelectionChangeDuplicateEndGuard(key) {
2708
+ let guard = SHARED_SELECTION_CHANGE_DUPLICATE_END_GUARDS.get(key);
2709
+ if (!guard) {
2710
+ guard = createSelectionChangeDuplicateEndGuard();
2711
+ SHARED_SELECTION_CHANGE_DUPLICATE_END_GUARDS.set(key, guard);
2712
+ }
2713
+ return guard;
2714
+ }
2715
+ function createSelectionChangeDuplicateEndGuard() {
2716
+ let lastTransientSelectionsKey;
2717
+ const getSelectionsKey = (selections) => selections.map(getFormulaSelectionIdentityKey).join("|");
2718
+ return {
2719
+ shouldSkip(selections, isEnd) {
2720
+ const selectionsKey = getSelectionsKey(selections);
2721
+ if (selectionsKey === lastTransientSelectionsKey) return true;
2722
+ if (isEnd) {
2723
+ lastTransientSelectionsKey = void 0;
2724
+ return false;
2725
+ }
2726
+ lastTransientSelectionsKey = selectionsKey;
2727
+ return false;
2728
+ },
2729
+ reset() {
2730
+ lastTransientSelectionsKey = void 0;
2731
+ }
2732
+ };
2733
+ }
2228
2734
  function createSelectionChangeHandler(opts) {
2735
+ var _opts$duplicateEndGua;
2229
2736
  let prevSelectionsCount = opts.initialSelectionsCount;
2230
2737
  let pendingCtrlAddCount = 0;
2738
+ const duplicateEndGuard = (_opts$duplicateEndGua = opts.duplicateEndGuard) !== null && _opts$duplicateEndGua !== void 0 ? _opts$duplicateEndGua : createSelectionChangeDuplicateEndGuard();
2231
2739
  return (selections, isEnd, options) => {
2232
2740
  if (options === null || options === void 0 ? void 0 : options.initial) return;
2233
- const isCtrlAddMode = selections.length > prevSelectionsCount;
2741
+ if (selections.length === 0) return;
2742
+ const isCtrlAddMode = !(options === null || options === void 0 ? void 0 : options.initial) && prevSelectionsCount > 0 && selections.length > prevSelectionsCount;
2234
2743
  if (isCtrlAddMode && !isEnd) {
2235
2744
  pendingCtrlAddCount = selections.length;
2745
+ if (duplicateEndGuard.shouldSkip(selections, false)) return;
2746
+ opts.onSelectionsChange(selections, false, true);
2747
+ prevSelectionsCount = selections.length;
2748
+ pendingCtrlAddCount = 0;
2749
+ return;
2750
+ }
2751
+ const shouldApplyPendingCtrlAdd = isEnd && selections.length === pendingCtrlAddCount;
2752
+ if (duplicateEndGuard.shouldSkip(selections, isEnd)) {
2753
+ if (isEnd) {
2754
+ var _opts$onDuplicateEnd;
2755
+ (_opts$onDuplicateEnd = opts.onDuplicateEnd) === null || _opts$onDuplicateEnd === void 0 || _opts$onDuplicateEnd.call(opts, selections);
2756
+ }
2757
+ prevSelectionsCount = selections.length;
2758
+ pendingCtrlAddCount = 0;
2236
2759
  return;
2237
2760
  }
2238
- const shouldApplyPendingCtrlAdd = isEnd && selections.length === pendingCtrlAddCount;
2239
2761
  if (isEnd) {
2240
2762
  prevSelectionsCount = selections.length;
2241
2763
  pendingCtrlAddCount = 0;
@@ -2243,12 +2765,29 @@ function createSelectionChangeHandler(opts) {
2243
2765
  opts.onSelectionsChange(selections, isEnd, isCtrlAddMode || shouldApplyPendingCtrlAdd);
2244
2766
  };
2245
2767
  }
2768
+ function replaceFormulaControlSelection(selections, index, newRange) {
2769
+ const current = selections[index];
2770
+ if (!current) return;
2771
+ const nextRange = {
2772
+ ...newRange,
2773
+ sheetId: current.sheetId,
2774
+ unitId: current.unitId
2775
+ };
2776
+ const nextSelections = [...selections];
2777
+ nextSelections[index] = nextRange;
2778
+ return nextSelections;
2779
+ }
2780
+ function getInitialFormulaReferenceSelectionCount(renderSelectionCount, formulaReferenceCount, selectingType) {
2781
+ return Math.max(renderSelectionCount, formulaReferenceCount);
2782
+ }
2246
2783
  const useSheetSelectionChange = (isNeed, isFocus, isSelectingRef, unitId, subUnitId, getRefSelections, isSupportAcrossSheet, listenSelectionSet, editor, handleRangeChange = noop) => {
2247
- var _currentUnit$getUnitI;
2784
+ var _activeWorkbook$getUn;
2248
2785
  const renderManagerService = useDependency(IRenderManagerService);
2249
2786
  const univerInstanceService = useDependency(IUniverInstanceService);
2250
2787
  const commandService = useDependency(ICommandService);
2788
+ const contextService = useDependency(IContextService);
2251
2789
  const docSelectionManagerService = useDependency(DocSelectionManagerService);
2790
+ const editorService = useDependency(IEditorService);
2252
2791
  const themeService = useDependency(ThemeService);
2253
2792
  const lexerTreeBuilder = useDependency(LexerTreeBuilder);
2254
2793
  const workbook = univerInstanceService.getUnit(unitId);
@@ -2266,32 +2805,39 @@ const useSheetSelectionChange = (isNeed, isFocus, isSelectingRef, unitId, subUni
2266
2805
  activeSheet,
2267
2806
  sheetName
2268
2807
  });
2269
- const currentUnit = useObservable(useMemo(() => univerInstanceService.getCurrentTypeOfUnit$(UniverInstanceType.UNIVER_SHEET), [univerInstanceService]));
2270
- const render = renderManagerService.getRenderById((_currentUnit$getUnitI = currentUnit === null || currentUnit === void 0 ? void 0 : currentUnit.getUnitId()) !== null && _currentUnit$getUnitI !== void 0 ? _currentUnit$getUnitI : "");
2808
+ const activeWorkbook = resolveFormulaSelectionWorkbook(useObservable(useMemo(() => univerInstanceService.getCurrentTypeOfUnit$(UniverInstanceType.UNIVER_SHEET), [univerInstanceService])), workbook);
2809
+ const render = renderManagerService.getRenderById((_activeWorkbook$getUn = activeWorkbook === null || activeWorkbook === void 0 ? void 0 : activeWorkbook.getUnitId()) !== null && _activeWorkbook$getUn !== void 0 ? _activeWorkbook$getUn : unitId);
2271
2810
  const refSelectionsRenderService = render === null || render === void 0 ? void 0 : render.with(RefSelectionsRenderService);
2272
2811
  const sheetSkeletonManagerService = render === null || render === void 0 ? void 0 : render.with(SheetSkeletonManagerService);
2273
2812
  const refSelectionsService = useDependency(IRefSelectionsService);
2813
+ const duplicateEndGuard = useMemo(() => getSharedSelectionChangeDuplicateEndGuard(`${unitId}:${subUnitId}`), [subUnitId, unitId]);
2274
2814
  const onSelectionsChange = useEvent((selections, isEnd, isCtrlAddMode) => {
2815
+ if (!editor || !isFormulaEditorInteractionOwner(editorService.getFocusId(), editor.getEditorId(), { fxBarFocused: contextService.getContextValue(FOCUSING_FX_BAR_EDITOR) })) return;
2275
2816
  const ctx = prepareSelectionChangeContext({
2276
2817
  editor,
2277
2818
  lexerTreeBuilder
2278
2819
  });
2279
2820
  if (!ctx) return;
2280
- const { nodeIndex, updatingRefIndex, sequenceNodes, offset } = ctx;
2281
- if (isSelectingRef.current === 1) if (offset !== 0) {
2821
+ const { nodeIndex, updatingRefIndex, formulaText, sequenceNodes, offset } = ctx;
2822
+ if (isSelectingRef.current === 1 || isFormulaReferenceAddingContext(sequenceNodes, offset) || isFormulaReferenceAddingTextContext(formulaText, offset)) if (offset !== 0) {
2282
2823
  var _range$sheetId, _range$unitId, _range$unitId2;
2283
2824
  if (nodeIndex === -1 && sequenceNodes.length) return;
2284
- const range = selections[selections.length - 1];
2825
+ const range = getLastFormulaSelection(selections);
2826
+ if (!range) return;
2285
2827
  const lastNodes = sequenceNodes.splice(nodeIndex + 1);
2286
2828
  const rangeSheetId = (_range$sheetId = range.sheetId) !== null && _range$sheetId !== void 0 ? _range$sheetId : subUnitId;
2287
2829
  const unitRangeName = {
2288
2830
  range,
2289
- unitId: (_range$unitId = range.unitId) !== null && _range$unitId !== void 0 ? _range$unitId : currentUnit.getUnitId(),
2290
- sheetName: getSheetNameById((_range$unitId2 = range.unitId) !== null && _range$unitId2 !== void 0 ? _range$unitId2 : currentUnit.getUnitId(), rangeSheetId)
2831
+ unitId: (_range$unitId = range.unitId) !== null && _range$unitId !== void 0 ? _range$unitId : activeWorkbook.getUnitId(),
2832
+ sheetName: getSheetNameById((_range$unitId2 = range.unitId) !== null && _range$unitId2 !== void 0 ? _range$unitId2 : activeWorkbook.getUnitId(), rangeSheetId)
2291
2833
  };
2292
2834
  const isAcrossSheet = rangeSheetId !== subUnitId;
2293
- const isAcrossWorkbook = (currentUnit === null || currentUnit === void 0 ? void 0 : currentUnit.getUnitId()) !== unitId;
2835
+ const isAcrossWorkbook = (activeWorkbook === null || activeWorkbook === void 0 ? void 0 : activeWorkbook.getUnitId()) !== unitId;
2294
2836
  const refRanges = unitRangesToText([unitRangeName], isSupportAcrossSheet && (isAcrossSheet || isAcrossWorkbook), sheetName, isAcrossWorkbook);
2837
+ if (isFormulaReferenceAddingTextContext(formulaText, offset)) {
2838
+ handleRangeChange(insertFormulaReferenceText(formulaText, refRanges[0], offset), offset + refRanges[0].length, isEnd);
2839
+ return;
2840
+ }
2295
2841
  sequenceNodes.push({
2296
2842
  token: refRanges[0],
2297
2843
  nodeType: sequenceNodeType.REFERENCE
@@ -2299,15 +2845,16 @@ const useSheetSelectionChange = (isNeed, isFocus, isSelectingRef, unitId, subUni
2299
2845
  handleRangeChange(sequenceNodeToText([...sequenceNodes, ...lastNodes]), getOffsetFromSequenceNodes(sequenceNodes), isEnd);
2300
2846
  } else {
2301
2847
  var _range$sheetId2, _range$unitId3, _range$unitId4;
2302
- const range = selections[selections.length - 1];
2848
+ const range = getLastFormulaSelection(selections);
2849
+ if (!range) return;
2303
2850
  const rangeSheetId = (_range$sheetId2 = range.sheetId) !== null && _range$sheetId2 !== void 0 ? _range$sheetId2 : subUnitId;
2304
2851
  const unitRangeName = {
2305
2852
  range,
2306
- unitId: (_range$unitId3 = range.unitId) !== null && _range$unitId3 !== void 0 ? _range$unitId3 : currentUnit.getUnitId(),
2307
- sheetName: getSheetNameById((_range$unitId4 = range.unitId) !== null && _range$unitId4 !== void 0 ? _range$unitId4 : currentUnit.getUnitId(), rangeSheetId)
2853
+ unitId: (_range$unitId3 = range.unitId) !== null && _range$unitId3 !== void 0 ? _range$unitId3 : activeWorkbook.getUnitId(),
2854
+ sheetName: getSheetNameById((_range$unitId4 = range.unitId) !== null && _range$unitId4 !== void 0 ? _range$unitId4 : activeWorkbook.getUnitId(), rangeSheetId)
2308
2855
  };
2309
2856
  const isAcrossSheet = rangeSheetId !== subUnitId;
2310
- const isAcrossWorkbook = (currentUnit === null || currentUnit === void 0 ? void 0 : currentUnit.getUnitId()) !== unitId;
2857
+ const isAcrossWorkbook = (activeWorkbook === null || activeWorkbook === void 0 ? void 0 : activeWorkbook.getUnitId()) !== unitId;
2311
2858
  const refRanges = unitRangesToText([unitRangeName], isSupportAcrossSheet && (isAcrossSheet || isAcrossWorkbook), sheetName, isAcrossWorkbook);
2312
2859
  sequenceNodes.unshift({
2313
2860
  token: refRanges[0],
@@ -2321,9 +2868,9 @@ const useSheetSelectionChange = (isNeed, isFocus, isSelectingRef, unitId, subUni
2321
2868
  const node = sequenceNodes[nodeIndex];
2322
2869
  if (typeof node === "object" && node.nodeType === sequenceNodeType.REFERENCE) {
2323
2870
  const oldToken = node.token;
2324
- if ((currentUnit === null || currentUnit === void 0 ? void 0 : currentUnit.getUnitId()) !== unitId) {
2325
- var _currentUnit$getUnitI2;
2326
- node.token = serializeRangeWithSpreadsheet((_currentUnit$getUnitI2 = currentUnit === null || currentUnit === void 0 ? void 0 : currentUnit.getUnitId()) !== null && _currentUnit$getUnitI2 !== void 0 ? _currentUnit$getUnitI2 : "", sheetName, last);
2871
+ if ((activeWorkbook === null || activeWorkbook === void 0 ? void 0 : activeWorkbook.getUnitId()) !== unitId) {
2872
+ var _activeWorkbook$getUn2;
2873
+ node.token = serializeRangeWithSpreadsheet((_activeWorkbook$getUn2 = activeWorkbook === null || activeWorkbook === void 0 ? void 0 : activeWorkbook.getUnitId()) !== null && _activeWorkbook$getUn2 !== void 0 ? _activeWorkbook$getUn2 : "", sheetName, last);
2327
2874
  } else node.token = sheetName === (activeSheet === null || activeSheet === void 0 ? void 0 : activeSheet.getName()) ? serializeRange(last) : serializeRangeWithSheet(activeSheet.getName(), last);
2328
2875
  const newOffset = offset + (node.token.length - oldToken.length);
2329
2876
  handleRangeChange(generateStringWithSequence(sequenceNodes), newOffset, isEnd);
@@ -2335,10 +2882,10 @@ const useSheetSelectionChange = (isNeed, isFocus, isSelectingRef, unitId, subUni
2335
2882
  const rangeSheetId = (_range$sheetId3 = range.sheetId) !== null && _range$sheetId3 !== void 0 ? _range$sheetId3 : subUnitId;
2336
2883
  const unitRangeName = {
2337
2884
  range,
2338
- unitId: (_range$unitId5 = range.unitId) !== null && _range$unitId5 !== void 0 ? _range$unitId5 : currentUnit.getUnitId(),
2339
- sheetName: getSheetNameById((_range$unitId6 = range.unitId) !== null && _range$unitId6 !== void 0 ? _range$unitId6 : currentUnit.getUnitId(), rangeSheetId)
2885
+ unitId: (_range$unitId5 = range.unitId) !== null && _range$unitId5 !== void 0 ? _range$unitId5 : activeWorkbook.getUnitId(),
2886
+ sheetName: getSheetNameById((_range$unitId6 = range.unitId) !== null && _range$unitId6 !== void 0 ? _range$unitId6 : activeWorkbook.getUnitId(), rangeSheetId)
2340
2887
  };
2341
- const isAcrossWorkbook = (currentUnit === null || currentUnit === void 0 ? void 0 : currentUnit.getUnitId()) !== unitId;
2888
+ const isAcrossWorkbook = (activeWorkbook === null || activeWorkbook === void 0 ? void 0 : activeWorkbook.getUnitId()) !== unitId;
2342
2889
  return unitRangesToText([unitRangeName], isSupportAcrossSheet && (rangeSheetId !== subUnitId || isAcrossWorkbook), sheetName, isAcrossWorkbook)[0];
2343
2890
  };
2344
2891
  let currentRefIndex = 0;
@@ -2347,7 +2894,7 @@ const useSheetSelectionChange = (isNeed, isFocus, isSelectingRef, unitId, subUni
2347
2894
  if (item.nodeType === sequenceNodeType.REFERENCE) {
2348
2895
  const nodeRange = deserializeRangeWithSheet(item.token);
2349
2896
  if (!nodeRange.sheetName) nodeRange.sheetName = sheetName;
2350
- if ((nodeRange.unitId || unitId) !== (currentUnit === null || currentUnit === void 0 ? void 0 : currentUnit.getUnitId())) return item.token;
2897
+ if ((nodeRange.unitId || unitId) !== (activeWorkbook === null || activeWorkbook === void 0 ? void 0 : activeWorkbook.getUnitId())) return item.token;
2351
2898
  if (isSupportAcrossSheet) {
2352
2899
  var _contextRef$current$a;
2353
2900
  if (((_contextRef$current$a = contextRef.current.activeSheet) === null || _contextRef$current$a === void 0 ? void 0 : _contextRef$current$a.getName()) !== nodeRange.sheetName) return item.token;
@@ -2382,13 +2929,28 @@ const useSheetSelectionChange = (isNeed, isFocus, isSelectingRef, unitId, subUni
2382
2929
  useEffect(() => {
2383
2930
  if (refSelectionsRenderService && isNeed) {
2384
2931
  const handleSelectionsChange = createSelectionChangeHandler({
2385
- initialSelectionsCount: Math.max(refSelectionsRenderService.getSelectionDataWithStyle().length, refSelectionsService.getCurrentSelections().length, getRefSelections().length),
2932
+ initialSelectionsCount: getInitialFormulaReferenceSelectionCount(refSelectionsRenderService.getSelectionDataWithStyle().length, getRefSelections().length, isSelectingRef.current),
2933
+ duplicateEndGuard: {
2934
+ shouldSkip: (selections, isEnd) => duplicateEndGuard.shouldSkip(selections.map((i) => i.rangeWithCoord), isEnd),
2935
+ reset: duplicateEndGuard.reset
2936
+ },
2386
2937
  onSelectionsChange: (selections, isEnd, isCtrlAddMode) => {
2387
2938
  onSelectionsChange(selections.map((i) => i.rangeWithCoord), isEnd, isCtrlAddMode);
2939
+ },
2940
+ onDuplicateEnd: () => {
2941
+ const ctx = prepareSelectionChangeContext({
2942
+ editor,
2943
+ lexerTreeBuilder
2944
+ });
2945
+ if (!ctx) return;
2946
+ handleRangeChange(ctx.formulaText, ctx.offset, true);
2388
2947
  }
2389
2948
  });
2390
2949
  let isInitialMoveEnd = true;
2391
2950
  const disposableCollection = new DisposableCollection();
2951
+ disposableCollection.add(refSelectionsRenderService.selectionMoveStart$.subscribe((selections) => {
2952
+ handleSelectionsChange(selections, false);
2953
+ }));
2392
2954
  disposableCollection.add(refSelectionsRenderService.selectionMoving$.subscribe((selections) => {
2393
2955
  handleSelectionsChange(selections, false);
2394
2956
  }));
@@ -2414,20 +2976,12 @@ const useSheetSelectionChange = (isNeed, isFocus, isSelectingRef, unitId, subUni
2414
2976
  disposableCollection.dispose();
2415
2977
  refSelectionsRenderService.getSelectionControls().forEach((control, index) => {
2416
2978
  disposableCollection.add(control.selectionScaling$.subscribe((newRange) => {
2417
- const selections = refSelectionsRenderService.getSelectionDataWithStyle().map((i) => i.rangeWithCoord);
2418
- const current = selections[index];
2419
- newRange.sheetId = current.sheetId;
2420
- newRange.unitId = current.unitId;
2421
- selections[index] = newRange;
2422
- onSelectionsChange(selections, false);
2979
+ const nextSelections = replaceFormulaControlSelection(refSelectionsRenderService.getSelectionDataWithStyle().map((i) => i.rangeWithCoord), index, newRange);
2980
+ if (nextSelections) onSelectionsChange(nextSelections, false);
2423
2981
  }));
2424
2982
  disposableCollection.add(control.selectionMoving$.subscribe((newRange) => {
2425
- const selections = refSelectionsRenderService.getSelectionDataWithStyle().map((i) => i.rangeWithCoord);
2426
- const current = selections[index];
2427
- newRange.sheetId = current.sheetId;
2428
- newRange.unitId = current.unitId;
2429
- selections[index] = newRange;
2430
- onSelectionsChange(selections, true);
2983
+ const nextSelections = replaceFormulaControlSelection(refSelectionsRenderService.getSelectionDataWithStyle().map((i) => i.rangeWithCoord), index, newRange);
2984
+ if (nextSelections) onSelectionsChange(nextSelections, true);
2431
2985
  }));
2432
2986
  });
2433
2987
  };
@@ -2451,6 +3005,7 @@ const useSheetSelectionChange = (isNeed, isFocus, isSelectingRef, unitId, subUni
2451
3005
  if (listenSelectionSet) {
2452
3006
  const d = commandService.onCommandExecuted((commandInfo) => {
2453
3007
  if (commandInfo.id !== SetSelectionsOperation.id) return;
3008
+ if (!editor || !isFormulaEditorInteractionOwner(editorService.getFocusId(), editor.getEditorId(), { fxBarFocused: contextService.getContextValue(FOCUSING_FX_BAR_EDITOR) })) return;
2454
3009
  const params = commandInfo.params;
2455
3010
  if (params.extra !== "formula-editor") return;
2456
3011
  if (params.selections.length) {
@@ -2466,10 +3021,20 @@ const useSheetSelectionChange = (isNeed, isFocus, isSelectingRef, unitId, subUni
2466
3021
  }
2467
3022
  range.unitId = params.unitId;
2468
3023
  range.sheetId = params.subUnitId;
2469
- const isAdd = isSelectingRef.current === 1;
3024
+ const ctx = prepareSelectionChangeContext({
3025
+ editor,
3026
+ lexerTreeBuilder
3027
+ });
3028
+ const isAdd = isSelectingRef.current === 1 || Boolean(ctx && (isFormulaReferenceAddingContext(ctx.sequenceNodes, ctx.offset) || isFormulaReferenceAddingTextContext(ctx.formulaText, ctx.offset)));
2470
3029
  const selections = ((_refSelectionsRenderS = refSelectionsRenderService === null || refSelectionsRenderService === void 0 ? void 0 : refSelectionsRenderService.getSelectionDataWithStyle()) !== null && _refSelectionsRenderS !== void 0 ? _refSelectionsRenderS : []).map((i) => i.rangeWithCoord);
2471
- if (isAdd) selections.push(range);
2472
- else selections[selections.length - 1] = range;
3030
+ if (isAdd) {
3031
+ if (selections.length > 0 && isSameFormulaSelection(selections[selections.length - 1], range)) return;
3032
+ selections.push(range);
3033
+ } else {
3034
+ if (shouldSkipFormulaReferenceUpdate(isAdd, selections.length)) return;
3035
+ selections[selections.length - 1] = range;
3036
+ }
3037
+ if (duplicateEndGuard.shouldSkip(selections, true)) return;
2473
3038
  onSelectionsChange(selections, true);
2474
3039
  }
2475
3040
  }
@@ -2480,7 +3045,10 @@ const useSheetSelectionChange = (isNeed, isFocus, isSelectingRef, unitId, subUni
2480
3045
  }
2481
3046
  }, [
2482
3047
  commandService,
3048
+ contextService,
3049
+ duplicateEndGuard,
2483
3050
  editor,
3051
+ editorService,
2484
3052
  isSelectingRef,
2485
3053
  lexerTreeBuilder,
2486
3054
  listenSelectionSet,
@@ -2501,7 +3069,7 @@ const useSheetSelectionChange = (isNeed, isFocus, isSelectingRef, unitId, subUni
2501
3069
  sheetSkeletonManagerService,
2502
3070
  themeService,
2503
3071
  univerInstanceService,
2504
- currentWorkbook: currentUnit
3072
+ currentWorkbook: activeWorkbook
2505
3073
  });
2506
3074
  });
2507
3075
  return () => sub.unsubscribe();
@@ -2688,7 +3256,7 @@ function SearchFunctionFactory(props, ref) {
2688
3256
  const shortcutService = useDependency(IShortcutService);
2689
3257
  const commandService = useDependency(ICommandService);
2690
3258
  const { searchList, searchText, handlerFormulaReplace, reset: resetFormulaSearch } = useFormulaSearch(isFocus, sequenceNodes, editor);
2691
- const visible = useMemo(() => !!searchList.length, [searchList]);
3259
+ const visible = searchList.length > 0;
2692
3260
  const ulRef = useRef(void 0);
2693
3261
  const [active, setActive] = useState(0);
2694
3262
  const isEnableMouseEnterOrOut = useRef(false);
@@ -2863,18 +3431,22 @@ const getFormulaText = (formula) => {
2863
3431
 
2864
3432
  //#endregion
2865
3433
  //#region src/views/formula-editor/index.tsx
3434
+ function shouldApplyFormulaSelectionChange(selectingMode, isFocusing, hasActiveInteraction) {
3435
+ return Boolean(selectingMode) || Boolean(isFocusing) || hasActiveInteraction;
3436
+ }
2866
3437
  function syncCounterpartFormulaEditorSelection(editorService, editorId, selections) {
2867
3438
  var _editorService$getEdi;
2868
3439
  if (!(selections === null || selections === void 0 ? void 0 : selections.length)) return;
2869
3440
  const syncEditorId = editorId === DOCS_NORMAL_EDITOR_UNIT_ID_KEY ? DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY : editorId === DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY ? DOCS_NORMAL_EDITOR_UNIT_ID_KEY : null;
2870
3441
  if (!syncEditorId) return;
2871
- (_editorService$getEdi = editorService.getEditor(syncEditorId)) === null || _editorService$getEdi === void 0 || _editorService$getEdi.setSelectionRanges(selections);
3442
+ (_editorService$getEdi = editorService.getEditor(syncEditorId)) === null || _editorService$getEdi === void 0 || _editorService$getEdi.setSelectionRanges(selections, false);
2872
3443
  }
2873
3444
  const FormulaEditor = forwardRef((props, ref) => {
2874
- var _document$getBody$dat, _document$getBody, _configService$getCon, _configService$getCon2;
3445
+ var _document$getBody$dat2, _document$getBody2, _configService$getCon, _configService$getCon2;
2875
3446
  const { errorText, initValue, unitId, subUnitId, isFocus: _isFocus = true, isSupportAcrossSheet = false, onFocus = noop, onBlur = noop, onChange: propOnChange, onVerify, className, editorId: propEditorId, moveCursor = true, onFormulaSelectingChange: propOnFormulaSelectingChange, keyboardEventConfig, onMoveInEditor, resetSelectionOnBlur = true, autoScrollbar = true, isSingle = true, disableSelectionOnClick = false, autofocus = true, disableContextMenu, style, borderless = false, canvasStyle } = props;
2876
3447
  const editorService = useDependency(IEditorService);
2877
3448
  const commandService = useDependency(ICommandService);
3449
+ const injector = useDependency(Injector);
2878
3450
  const sheetEmbeddingRef = useRef(null);
2879
3451
  const onChange = useEvent(propOnChange);
2880
3452
  useImperativeHandle(ref, () => ({ isClickOutSide: (e) => {
@@ -2884,22 +3456,25 @@ const FormulaEditor = forwardRef((props, ref) => {
2884
3456
  const onFormulaSelectingChange = useEvent(propOnFormulaSelectingChange);
2885
3457
  const searchFunctionRef = useRef(null);
2886
3458
  const editorRef = useRef(void 0);
2887
- const editor = editorRef.current;
3459
+ const [editor, setEditor] = useState();
2888
3460
  const [isFocus, setIsFocus] = useState(_isFocus);
2889
3461
  const formulaEditorContainerRef = useRef(null);
2890
3462
  const editorId = useMemo(() => propEditorId !== null && propEditorId !== void 0 ? propEditorId : createInternalEditorID(`${EMBEDDING_FORMULA_EDITOR}-${generateRandomId(4)}`), []);
2891
- const isError = useMemo(() => errorText !== void 0, [errorText]);
3463
+ const isError = errorText !== void 0;
2892
3464
  const univerInstanceService = useDependency(IUniverInstanceService);
2893
3465
  const document = univerInstanceService.getUnit(editorId);
2894
- useObservable(document === null || document === void 0 ? void 0 : document.change$);
2895
3466
  const getFormulaToken = useFormulaToken();
2896
- const formulaText = BuildTextUtils.transform.getPlainText((_document$getBody$dat = document === null || document === void 0 || (_document$getBody = document.getBody()) === null || _document$getBody === void 0 ? void 0 : _document$getBody.dataStream) !== null && _document$getBody$dat !== void 0 ? _document$getBody$dat : "");
3467
+ const formulaText = useObservable(document ? () => document.change$.pipe(map(() => {
3468
+ var _document$getBody$dat, _document$getBody;
3469
+ return BuildTextUtils.transform.getPlainText((_document$getBody$dat = (_document$getBody = document.getBody()) === null || _document$getBody === void 0 ? void 0 : _document$getBody.dataStream) !== null && _document$getBody$dat !== void 0 ? _document$getBody$dat : "");
3470
+ })) : null, BuildTextUtils.transform.getPlainText((_document$getBody$dat2 = document === null || document === void 0 || (_document$getBody2 = document.getBody()) === null || _document$getBody2 === void 0 ? void 0 : _document$getBody2.dataStream) !== null && _document$getBody$dat2 !== void 0 ? _document$getBody$dat2 : ""), false, [document]);
2897
3471
  const formulaTextRef = useStateRef(formulaText);
2898
3472
  const formulaWithoutEqualSymbol = useMemo(() => getFormulaText(formulaText), [formulaText]);
2899
3473
  const sequenceNodes = useMemo(() => getFormulaToken(formulaWithoutEqualSymbol), [formulaWithoutEqualSymbol, getFormulaToken]);
2900
3474
  const { isSelecting, isSelectingRef } = useFormulaSelecting({
2901
3475
  unitId,
2902
3476
  subUnitId,
3477
+ editor,
2903
3478
  editorId,
2904
3479
  isFocus,
2905
3480
  disableOnClick: disableSelectionOnClick
@@ -2910,13 +3485,35 @@ const FormulaEditor = forwardRef((props, ref) => {
2910
3485
  const isFocusing = docSelectionRenderService === null || docSelectionRenderService === void 0 ? void 0 : docSelectionRenderService.isFocusing;
2911
3486
  const currentDoc = useObservable(useMemo(() => univerInstanceService.getCurrentTypeOfUnit$(UniverInstanceType.UNIVER_DOC), [univerInstanceService]));
2912
3487
  const docFocusing = (currentDoc === null || currentDoc === void 0 ? void 0 : currentDoc.getUnitId()) === editorId;
2913
- const refSelections = useRef([]);
2914
- const getRefSelections = useEvent(() => refSelections.current);
3488
+ const refSelectionsRef = useRef([]);
3489
+ const getRefSelections = useEvent(() => refSelectionsRef.current);
3490
+ const getRefSelectionCount = useEvent(() => getRefSelections().length);
2915
3491
  const selectingMode = isSelecting;
2916
3492
  const functionScreenTips = (_configService$getCon = (_configService$getCon2 = useDependency(IConfigService).getConfig("sheets-formula-ui.base.config")) === null || _configService$getCon2 === void 0 ? void 0 : _configService$getCon2.functionScreenTips) !== null && _configService$getCon !== void 0 ? _configService$getCon : true;
2917
3493
  useUpdateEffect(() => {
2918
3494
  onChange(formulaText);
2919
3495
  }, [formulaText, onChange]);
3496
+ useEffect(() => {
3497
+ if (!isFocus || !editor) return;
3498
+ const subscription = editor.input$.subscribe(({ content, isComposing }) => {
3499
+ if (isComposing) return;
3500
+ queueMicrotask(() => {
3501
+ var _editor$getSelectionR, _editor$getDocumentDa, _editor$getDocumentDa2;
3502
+ const selection = (_editor$getSelectionR = editor.getSelectionRanges()) === null || _editor$getSelectionR === void 0 ? void 0 : _editor$getSelectionR[0];
3503
+ const normalizedSelection = getSelectionAfterLaggingFormulaInput((_editor$getDocumentDa = (_editor$getDocumentDa2 = editor.getDocumentData().body) === null || _editor$getDocumentDa2 === void 0 ? void 0 : _editor$getDocumentDa2.dataStream) !== null && _editor$getDocumentDa !== void 0 ? _editor$getDocumentDa : "", selection, content);
3504
+ if (!normalizedSelection) return;
3505
+ const selections = [normalizedSelection];
3506
+ editor.setSelectionRanges(selections, false);
3507
+ syncCounterpartFormulaEditorSelection(editorService, editorId, selections);
3508
+ });
3509
+ });
3510
+ return () => subscription.unsubscribe();
3511
+ }, [
3512
+ editor,
3513
+ editorId,
3514
+ editorService,
3515
+ isFocus
3516
+ ]);
2920
3517
  const highlightDoc = useDocHight("=");
2921
3518
  const highlightSheet = useSheetHighlight(unitId, subUnitId);
2922
3519
  const highlight = useEvent((text, isNeedResetSelection = true, isEnd, newSelections) => {
@@ -2924,18 +3521,18 @@ const FormulaEditor = forwardRef((props, ref) => {
2924
3521
  highTextRef.current = text;
2925
3522
  const formulaStr = text[0] === "=" ? text.slice(1) : "";
2926
3523
  const sequenceNodes = getFormulaToken(formulaStr);
2927
- const parsedFormula = sequenceNodes.reduce((pre, cur) => typeof cur === "object" ? `${pre}${cur.token}` : `${pre}${cur}`, "");
2928
- const ranges = highlightDoc(editorRef.current, parsedFormula === formulaStr ? sequenceNodes : [], isNeedResetSelection, newSelections);
2929
- refSelections.current = ranges;
3524
+ const ranges = highlightDoc(editorRef.current, sequenceNodes, isNeedResetSelection, newSelections, formulaStr);
3525
+ refSelectionsRef.current = ranges;
2930
3526
  if (isEnd) {
2931
3527
  const currentDocSelections = newSelections !== null && newSelections !== void 0 ? newSelections : editor === null || editor === void 0 ? void 0 : editor.getSelectionRanges();
2932
- if ((currentDocSelections === null || currentDocSelections === void 0 ? void 0 : currentDocSelections.length) !== 1) return;
2933
- const refIndex = findRefSequenceIndex(sequenceNodes, findIndexFromSequenceNodes(sequenceNodes, currentDocSelections[0].startOffset - 1, false));
2934
- if (refIndex >= 0) {
2935
- const target = ranges.splice(refIndex, 1)[0];
2936
- target && ranges.push(target);
3528
+ if ((currentDocSelections === null || currentDocSelections === void 0 ? void 0 : currentDocSelections.length) === 1) {
3529
+ const refIndex = findRefSequenceIndex(sequenceNodes, findIndexFromSequenceNodes(sequenceNodes, currentDocSelections[0].startOffset - 1, false));
3530
+ if (refIndex >= 0) {
3531
+ const target = ranges.splice(refIndex, 1)[0];
3532
+ target && ranges.push(target);
3533
+ }
2937
3534
  }
2938
- highlightSheet(isFocus ? ranges : [], editorRef.current);
3535
+ highlightSheet(isFocus ? ranges : [], editorRef.current, isEnd);
2939
3536
  }
2940
3537
  });
2941
3538
  useEffect(() => {
@@ -3000,13 +3597,52 @@ const FormulaEditor = forwardRef((props, ref) => {
3000
3597
  },
3001
3598
  canvasStyle
3002
3599
  }, formulaEditorContainerRef.current);
3003
- editorRef.current = editorService.getEditor(editorId);
3600
+ const registeredEditor = editorService.getEditor(editorId);
3601
+ editorRef.current = registeredEditor;
3602
+ setEditor(registeredEditor);
3004
3603
  highlight(initValue, false, true);
3005
3604
  }
3006
3605
  return () => {
3606
+ editorRef.current = void 0;
3007
3607
  dispose === null || dispose === void 0 || dispose.dispose();
3008
3608
  };
3009
3609
  }, []);
3610
+ useEffect(() => {
3611
+ var _ref, _resolveFormulaEmbedR;
3612
+ const formulaEditorContainer = formulaEditorContainerRef.current;
3613
+ if (!isFocus || !formulaEditorContainer || !injector.has(IFormulaEmbedRuntimeFocusCoordinator)) return;
3614
+ const focusCoordinator = injector.get(IFormulaEmbedRuntimeFocusCoordinator);
3615
+ const scope = (_ref = (_resolveFormulaEmbedR = resolveFormulaEmbedRuntimeDomScope(formulaEditorContainer)) !== null && _resolveFormulaEmbedR !== void 0 ? _resolveFormulaEmbedR : focusCoordinator.resolveRuntimeScopeByChildUnitId(editorId)) !== null && _ref !== void 0 ? _ref : resolveActiveFormulaEmbedRuntimeDomScope(formulaEditorContainer.ownerDocument);
3616
+ if (!scope) return;
3617
+ const collection = new DisposableCollection();
3618
+ const interactionBoundaryService = injector.has(IFormulaEmbedInteractionBoundaryService) ? injector.get(IFormulaEmbedInteractionBoundaryService) : void 0;
3619
+ collection.add(focusCoordinator.acquireLease({
3620
+ embedId: scope.embedId,
3621
+ role: "child-editor",
3622
+ owner: "sheet-formula-editor",
3623
+ hostUnitId: scope.hostUnitId,
3624
+ childUnitId: scope.childUnitId,
3625
+ associatedChildUnitIds: [editorId]
3626
+ }));
3627
+ if (interactionBoundaryService) collection.add(interactionBoundaryService.registerOwnedElement(scope.embedId, formulaEditorContainer));
3628
+ collection.add(focusCoordinator.registerElement({
3629
+ embedId: scope.embedId,
3630
+ role: "child-editor",
3631
+ element: formulaEditorContainer
3632
+ }));
3633
+ collection.add(registerFormulaEditorRuntimePortal({
3634
+ embedId: scope.embedId,
3635
+ editorId,
3636
+ ownerDocument: formulaEditorContainer.ownerDocument,
3637
+ interactionBoundaryService,
3638
+ focusCoordinator
3639
+ }));
3640
+ return () => collection.dispose();
3641
+ }, [
3642
+ editorId,
3643
+ injector,
3644
+ isFocus
3645
+ ]);
3010
3646
  useLayoutEffect(() => {
3011
3647
  let focusRetryFrame = 0;
3012
3648
  let finalFocusRetryFrame = 0;
@@ -3040,10 +3676,10 @@ const FormulaEditor = forwardRef((props, ref) => {
3040
3676
  resetSelectionOnBlur
3041
3677
  ]);
3042
3678
  const { checkScrollBar } = useResize(editor, isSingle, autoScrollbar);
3043
- useRefactorEffect(isFocus, Boolean(isSelecting && docFocusing), unitId, editorId, disableContextMenu);
3044
- useLeftAndRightArrow(Boolean(isFocus && isFocusing && moveCursor), selectingMode, editor, onMoveInEditor);
3679
+ useRefactorEffect(isFocus, isSelecting, unitId, editorId, disableContextMenu);
3680
+ useLeftAndRightArrow(Boolean(isFocus && isFocusing && moveCursor), selectingMode, editor, onMoveInEditor, getRefSelectionCount);
3045
3681
  const handleSelectionChange = useEvent((refString, offset, isEnd) => {
3046
- if (!isFocusing) return;
3682
+ if (!shouldApplyFormulaSelectionChange(selectingMode, isFocusing, hasActiveFormulaEmbedInteraction(formulaEditorContainerRef.current))) return;
3047
3683
  const newSelections = offset !== -1 ? [{
3048
3684
  startOffset: offset + 1,
3049
3685
  endOffset: offset + 1,
@@ -3067,7 +3703,7 @@ const FormulaEditor = forwardRef((props, ref) => {
3067
3703
  checkScrollBar();
3068
3704
  }
3069
3705
  });
3070
- useSheetSelectionChange(isFocus && Boolean(isSelecting && docFocusing), isFocus, isSelectingRef, unitId, subUnitId, getRefSelections, isSupportAcrossSheet, Boolean(selectingMode), editor, handleSelectionChange);
3706
+ useSheetSelectionChange(isFocus && Boolean(isSelecting), isFocus, isSelectingRef, unitId, subUnitId, getRefSelections, isSupportAcrossSheet, Boolean(selectingMode), editor, handleSelectionChange);
3071
3707
  useSwitchSheet(isFocus && Boolean(isSelecting && docFocusing), unitId, isSupportAcrossSheet, setIsFocus, onBlur, () => {
3072
3708
  highlight(formulaTextRef.current, false, true);
3073
3709
  });
@@ -3090,7 +3726,13 @@ const FormulaEditor = forwardRef((props, ref) => {
3090
3726
  highlight(`=${res.text}`);
3091
3727
  }
3092
3728
  };
3093
- const handleMouseUp = () => {
3729
+ const handleMouseUp = (event) => {
3730
+ if (hasActiveFormulaEmbedInteraction(formulaEditorContainerRef.current)) return;
3731
+ if (!shouldRefocusFormulaEditorOnMouseUp({
3732
+ target: event.target,
3733
+ isFocusing,
3734
+ isPointerSelecting: docSelectionRenderService === null || docSelectionRenderService === void 0 ? void 0 : docSelectionRenderService.isOnPointerEvent
3735
+ })) return;
3094
3736
  setIsFocus(true);
3095
3737
  onFocus();
3096
3738
  focus();
@@ -3107,6 +3749,7 @@ const FormulaEditor = forwardRef((props, ref) => {
3107
3749
  }),
3108
3750
  children: /* @__PURE__ */ jsx("div", {
3109
3751
  ref: formulaEditorContainerRef,
3752
+ "data-u-comp": "formula-editor",
3110
3753
  className: "univer-relative univer-size-full",
3111
3754
  onMouseUp: handleMouseUp
3112
3755
  })
@@ -3178,6 +3821,13 @@ function FunctionParams(props) {
3178
3821
  function InputParams(props) {
3179
3822
  const { functionInfo, onChange } = props;
3180
3823
  if (!functionInfo) return null;
3824
+ return /* @__PURE__ */ jsx(InputParamsInner, {
3825
+ functionInfo,
3826
+ onChange
3827
+ });
3828
+ }
3829
+ function InputParamsInner(props) {
3830
+ const { functionInfo, onChange } = props;
3181
3831
  const [params, setParams] = useState([]);
3182
3832
  const [functionParameter, setFunctionParameter] = useState(functionInfo.functionParameter);
3183
3833
  const [activeIndex, setActiveIndex] = useState(-1);
@@ -3322,27 +3972,60 @@ function SelectFunction(props) {
3322
3972
  }, index))
3323
3973
  }),
3324
3974
  functionInfo && /* @__PURE__ */ jsxs("div", {
3325
- className: clsx("univer-mx-0 univer-my-2 univer-overflow-y-auto", scrollbarClassName),
3975
+ "data-u-comp": "formula-function-details",
3976
+ className: clsx("univer-mx-0 univer-my-3 univer-overflow-y-auto", scrollbarClassName),
3326
3977
  children: [
3327
- /* @__PURE__ */ jsx(FunctionParams, {
3328
- title: functionInfo.functionName,
3329
- value: functionInfo.description
3330
- }),
3331
- /* @__PURE__ */ jsx(FunctionParams, {
3332
- title: localeService.t("sheets-formula-ui.moreFunctions.syntax"),
3333
- value: /* @__PURE__ */ jsx(FunctionHelp, {
3334
- prefix: functionInfo.functionName,
3335
- value: functionInfo.functionParameter
3336
- })
3978
+ /* @__PURE__ */ jsxs("div", {
3979
+ className: "univer-rounded-lg univer-bg-gray-50 univer-p-3 dark:!univer-bg-gray-800",
3980
+ children: [/* @__PURE__ */ jsx("div", {
3981
+ className: "univer-text-sm univer-font-semibold univer-text-gray-900 dark:!univer-text-white",
3982
+ children: functionInfo.functionName
3983
+ }), /* @__PURE__ */ jsx("div", {
3984
+ className: "univer-mt-1 univer-text-xs univer-leading-5 univer-text-gray-600 dark:!univer-text-gray-300",
3985
+ children: functionInfo.description
3986
+ })]
3337
3987
  }),
3338
- /* @__PURE__ */ jsx(FunctionParams, {
3339
- title: localeService.t("sheets-formula-ui.prompt.helpExample"),
3340
- value: `${functionInfo.functionName}(${functionInfo.functionParameter.map((item) => item.example).join(",")})`
3988
+ /* @__PURE__ */ jsxs("div", {
3989
+ className: "univer-mt-4 univer-flex univer-flex-col univer-gap-3",
3990
+ children: [/* @__PURE__ */ jsxs("div", { children: [/* @__PURE__ */ jsx("div", {
3991
+ className: "univer-text-xs univer-font-medium univer-text-gray-500 dark:!univer-text-gray-300",
3992
+ children: localeService.t("sheets-formula-ui.moreFunctions.syntax")
3993
+ }), /* @__PURE__ */ jsx("div", {
3994
+ "data-u-comp": "formula-function-syntax",
3995
+ className: clsx("univer-mt-1.5 univer-break-words univer-rounded-md univer-bg-gray-50 univer-px-3 univer-py-2 univer-font-mono univer-text-xs univer-leading-5 univer-text-gray-900 dark:!univer-bg-gray-800 dark:!univer-text-white", borderClassName),
3996
+ children: /* @__PURE__ */ jsx(FunctionHelp, {
3997
+ prefix: functionInfo.functionName,
3998
+ value: functionInfo.functionParameter
3999
+ })
4000
+ })] }), /* @__PURE__ */ jsxs("div", { children: [/* @__PURE__ */ jsx("div", {
4001
+ className: "univer-text-xs univer-font-medium univer-text-gray-500 dark:!univer-text-gray-300",
4002
+ children: localeService.t("sheets-formula-ui.prompt.helpExample")
4003
+ }), /* @__PURE__ */ jsx("div", {
4004
+ "data-u-comp": "formula-function-example",
4005
+ className: clsx("univer-mt-1.5 univer-break-words univer-rounded-md univer-bg-gray-50 univer-px-3 univer-py-2 univer-font-mono univer-text-xs univer-leading-5 univer-text-gray-900 dark:!univer-bg-gray-800 dark:!univer-text-white", borderClassName),
4006
+ children: `${functionInfo.functionName}(${functionInfo.functionParameter.map((item) => item.example).join(",")})`
4007
+ })] })]
3341
4008
  }),
3342
- functionInfo.functionParameter && functionInfo.functionParameter.map((item) => /* @__PURE__ */ jsx(FunctionParams, {
3343
- title: item.name,
3344
- value: `${item.require ? required : optional} ${item.detail}`
3345
- }, item.name))
4009
+ functionInfo.functionParameter.length > 0 && /* @__PURE__ */ jsx("div", {
4010
+ className: clsx("univer-mt-4 univer-rounded-lg univer-px-3", borderClassName, divideYClassName),
4011
+ children: functionInfo.functionParameter.map((item) => /* @__PURE__ */ jsxs("div", {
4012
+ "data-u-comp": "formula-function-parameter",
4013
+ className: "univer-py-3",
4014
+ children: [/* @__PURE__ */ jsxs("div", {
4015
+ className: "univer-flex univer-items-center univer-gap-2",
4016
+ children: [/* @__PURE__ */ jsx("span", {
4017
+ className: "univer-text-xs univer-font-medium univer-text-gray-900 dark:!univer-text-white",
4018
+ children: item.name
4019
+ }), /* @__PURE__ */ jsx("span", {
4020
+ className: clsx("univer-rounded-full univer-px-2 univer-py-0.5 univer-text-xs univer-leading-4", item.require ? "univer-bg-primary-50 univer-text-primary-600 dark:!univer-bg-primary-900 dark:!univer-text-primary-200" : "univer-bg-gray-100 univer-text-gray-600 dark:!univer-bg-gray-700 dark:!univer-text-gray-200"),
4021
+ children: item.require ? required : optional
4022
+ })]
4023
+ }), /* @__PURE__ */ jsx("div", {
4024
+ className: "univer-mt-1 univer-text-xs univer-leading-5 univer-text-gray-600 dark:!univer-text-gray-300",
4025
+ children: item.detail
4026
+ })]
4027
+ }, item.name))
4028
+ })
3346
4029
  ]
3347
4030
  })
3348
4031
  ] });
@@ -3828,7 +4511,19 @@ let ComponentsController = class ComponentsController extends Disposable {
3828
4511
  this._registerComponents();
3829
4512
  }
3830
4513
  _registerIcons() {
3831
- this.disposeWithMe(this._iconManager.register({ FunctionIcon }));
4514
+ this.disposeWithMe(this._iconManager.register({
4515
+ DatabaseFunctionIcon,
4516
+ DateFunctionIcon,
4517
+ EngineeringFunctionIcon,
4518
+ FinancialFunctionIcon,
4519
+ FunctionIcon,
4520
+ InformationFunctionIcon,
4521
+ LogicalFunctionIcon,
4522
+ LookupFunctionIcon,
4523
+ MathFunctionIcon,
4524
+ StatisticalFunctionIcon,
4525
+ TextFunctionIcon
4526
+ }));
3832
4527
  }
3833
4528
  _registerComponents() {
3834
4529
  this.disposeWithMe(this._componentManager.register(MORE_FUNCTIONS_COMPONENT, MoreFunctions));
@@ -4549,227 +5244,6 @@ ImageFormulaRenderController = __decorate([
4549
5244
  __decorateParam(2, IUniverInstanceService)
4550
5245
  ], ImageFormulaRenderController);
4551
5246
 
4552
- //#endregion
4553
- //#region src/menu/menu.ts
4554
- function InsertCommonFunctionMenuItemFactory(accessor) {
4555
- const commonFunctions = [
4556
- "SUMIF",
4557
- "SUM",
4558
- "AVERAGE",
4559
- "IF",
4560
- "COUNT",
4561
- "SIN",
4562
- "MAX"
4563
- ];
4564
- let selections = commonFunctions.map((name) => ({
4565
- label: {
4566
- name,
4567
- selectable: false
4568
- },
4569
- value: name
4570
- }));
4571
- try {
4572
- const descriptionService = accessor.get(IDescriptionService);
4573
- const filtered = commonFunctions.filter((name) => Boolean(descriptionService.getFunctionInfo(name)));
4574
- if (filtered.length > 0) selections = filtered.map((name) => ({
4575
- label: {
4576
- name,
4577
- selectable: false
4578
- },
4579
- value: name
4580
- }));
4581
- } catch {}
4582
- return {
4583
- id: `${InsertFunctionOperation.id}.common`,
4584
- commandId: InsertFunctionOperation.id,
4585
- title: "sheets-formula-ui.insert.common",
4586
- tooltip: "sheets-formula-ui.insert.tooltip",
4587
- icon: "FunctionIcon",
4588
- type: MenuItemType.SELECTOR,
4589
- selections,
4590
- hidden$: getMenuHiddenObservable(accessor, UniverInstanceType.UNIVER_SHEET)
4591
- };
4592
- }
4593
- function createInsertFunctionCategoryMenuItemFactory(functionType, categoryKey, icon) {
4594
- return function insertFunctionCategoryMenuItemFactory(accessor) {
4595
- let selections = [];
4596
- try {
4597
- selections = accessor.get(IDescriptionService).getSearchListByType(functionType).map(({ name }) => ({
4598
- label: {
4599
- name,
4600
- selectable: false
4601
- },
4602
- value: name
4603
- }));
4604
- } catch {
4605
- selections = [];
4606
- }
4607
- return {
4608
- id: `${InsertFunctionOperation.id}.${categoryKey}`,
4609
- commandId: InsertFunctionOperation.id,
4610
- title: `sheets-formula-ui.functionType.${categoryKey}`,
4611
- tooltip: "sheets-formula-ui.insert.tooltip",
4612
- icon,
4613
- type: MenuItemType.SELECTOR,
4614
- selections,
4615
- hidden$: getMenuHiddenObservable(accessor, UniverInstanceType.UNIVER_SHEET)
4616
- };
4617
- };
4618
- }
4619
- const InsertFinancialFunctionMenuItemFactory = createInsertFunctionCategoryMenuItemFactory(FunctionType.Financial, "financial");
4620
- const InsertLogicalFunctionMenuItemFactory = createInsertFunctionCategoryMenuItemFactory(FunctionType.Logical, "logical");
4621
- const InsertTextFunctionMenuItemFactory = createInsertFunctionCategoryMenuItemFactory(FunctionType.Text, "text");
4622
- const InsertDateFunctionMenuItemFactory = createInsertFunctionCategoryMenuItemFactory(FunctionType.Date, "date");
4623
- const InsertLookupFunctionMenuItemFactory = createInsertFunctionCategoryMenuItemFactory(FunctionType.Lookup, "lookup");
4624
- const InsertMathFunctionMenuItemFactory = createInsertFunctionCategoryMenuItemFactory(FunctionType.Math, "math");
4625
- const InsertStatisticalFunctionMenuItemFactory = createInsertFunctionCategoryMenuItemFactory(FunctionType.Statistical, "statistical");
4626
- const InsertEngineeringFunctionMenuItemFactory = createInsertFunctionCategoryMenuItemFactory(FunctionType.Engineering, "engineering");
4627
- const InsertInformationFunctionMenuItemFactory = createInsertFunctionCategoryMenuItemFactory(FunctionType.Information, "information");
4628
- const InsertDatabaseFunctionMenuItemFactory = createInsertFunctionCategoryMenuItemFactory(FunctionType.Database, "database");
4629
- function AllFunctionsMenuItemFactory(accessor) {
4630
- return {
4631
- id: MoreFunctionsOperation.id,
4632
- title: "sheets-formula-ui.moreFunctions.allFunctions",
4633
- tooltip: "sheets-formula-ui.insert.tooltip",
4634
- type: MenuItemType.BUTTON,
4635
- hidden$: getMenuHiddenObservable(accessor, UniverInstanceType.UNIVER_SHEET),
4636
- disabled$: getCurrentRangeDisable$(accessor, {
4637
- workbookTypes: [WorkbookEditablePermission],
4638
- worksheetTypes: [WorksheetEditPermission, WorksheetSetCellValuePermission],
4639
- rangeTypes: [RangeProtectionPermissionEditPoint]
4640
- })
4641
- };
4642
- }
4643
- function CopyFormulaOnlyMenuItemFactory(accessor) {
4644
- return {
4645
- id: SheetCopyFormulaOnlyCommand.id,
4646
- type: MenuItemType.BUTTON,
4647
- title: "sheets-formula-ui.operation.copyFormulaOnly",
4648
- disabled$: getCurrentRangeDisable$(accessor, {
4649
- workbookTypes: [WorkbookCopyPermission],
4650
- worksheetTypes: [WorksheetCopyPermission],
4651
- rangeTypes: [RangeProtectionPermissionViewPoint]
4652
- }),
4653
- hidden$: getMenuHiddenObservable(accessor, UniverInstanceType.UNIVER_SHEET)
4654
- };
4655
- }
4656
- function PasteFormulaMenuItemFactory(accessor) {
4657
- return {
4658
- id: SheetOnlyPasteFormulaCommand.id,
4659
- type: MenuItemType.BUTTON,
4660
- title: "sheets-formula-ui.operation.pasteFormula",
4661
- disabled$: menuClipboardDisabledObservable(accessor).pipe(combineLatestWith(getCurrentRangeDisable$(accessor, {
4662
- workbookTypes: [WorkbookEditablePermission],
4663
- rangeTypes: [RangeProtectionPermissionEditPoint],
4664
- worksheetTypes: [WorksheetSetCellValuePermission, WorksheetEditPermission]
4665
- })), map(([d1, d2]) => d1 || d2)),
4666
- hidden$: getMenuHiddenObservable(accessor, UniverInstanceType.UNIVER_SHEET)
4667
- };
4668
- }
4669
-
4670
- //#endregion
4671
- //#region src/menu/schema.ts
4672
- const menuSchema = {
4673
- [RibbonFormulasGroup.BASIC]: {
4674
- [`${InsertFunctionOperation.id}.common`]: {
4675
- order: 0,
4676
- menuItemFactory: InsertCommonFunctionMenuItemFactory,
4677
- [MoreFunctionsOperation.id]: {
4678
- order: 0,
4679
- menuItemFactory: AllFunctionsMenuItemFactory
4680
- }
4681
- },
4682
- [`${InsertFunctionOperation.id}.financial`]: {
4683
- order: 1,
4684
- menuItemFactory: InsertFinancialFunctionMenuItemFactory,
4685
- [MoreFunctionsOperation.id]: {
4686
- order: 0,
4687
- menuItemFactory: AllFunctionsMenuItemFactory
4688
- }
4689
- },
4690
- [`${InsertFunctionOperation.id}.logical`]: {
4691
- order: 2,
4692
- menuItemFactory: InsertLogicalFunctionMenuItemFactory,
4693
- [MoreFunctionsOperation.id]: {
4694
- order: 0,
4695
- menuItemFactory: AllFunctionsMenuItemFactory
4696
- }
4697
- },
4698
- [`${InsertFunctionOperation.id}.text`]: {
4699
- order: 3,
4700
- menuItemFactory: InsertTextFunctionMenuItemFactory,
4701
- [MoreFunctionsOperation.id]: {
4702
- order: 0,
4703
- menuItemFactory: AllFunctionsMenuItemFactory
4704
- }
4705
- },
4706
- [`${InsertFunctionOperation.id}.date`]: {
4707
- order: 4,
4708
- menuItemFactory: InsertDateFunctionMenuItemFactory,
4709
- [MoreFunctionsOperation.id]: {
4710
- order: 0,
4711
- menuItemFactory: AllFunctionsMenuItemFactory
4712
- }
4713
- },
4714
- [`${InsertFunctionOperation.id}.lookup`]: {
4715
- order: 5,
4716
- menuItemFactory: InsertLookupFunctionMenuItemFactory,
4717
- [MoreFunctionsOperation.id]: {
4718
- order: 0,
4719
- menuItemFactory: AllFunctionsMenuItemFactory
4720
- }
4721
- },
4722
- [`${InsertFunctionOperation.id}.math`]: {
4723
- order: 6,
4724
- menuItemFactory: InsertMathFunctionMenuItemFactory,
4725
- [MoreFunctionsOperation.id]: {
4726
- order: 0,
4727
- menuItemFactory: AllFunctionsMenuItemFactory
4728
- }
4729
- },
4730
- [`${InsertFunctionOperation.id}.statistical`]: {
4731
- order: 7,
4732
- menuItemFactory: InsertStatisticalFunctionMenuItemFactory,
4733
- [MoreFunctionsOperation.id]: {
4734
- order: 0,
4735
- menuItemFactory: AllFunctionsMenuItemFactory
4736
- }
4737
- },
4738
- [`${InsertFunctionOperation.id}.engineering`]: {
4739
- order: 8,
4740
- menuItemFactory: InsertEngineeringFunctionMenuItemFactory,
4741
- [MoreFunctionsOperation.id]: {
4742
- order: 0,
4743
- menuItemFactory: AllFunctionsMenuItemFactory
4744
- }
4745
- },
4746
- [`${InsertFunctionOperation.id}.information`]: {
4747
- order: 9,
4748
- menuItemFactory: InsertInformationFunctionMenuItemFactory,
4749
- [MoreFunctionsOperation.id]: {
4750
- order: 0,
4751
- menuItemFactory: AllFunctionsMenuItemFactory
4752
- }
4753
- },
4754
- [`${InsertFunctionOperation.id}.database`]: {
4755
- order: 10,
4756
- menuItemFactory: InsertDatabaseFunctionMenuItemFactory,
4757
- [MoreFunctionsOperation.id]: {
4758
- order: 0,
4759
- menuItemFactory: AllFunctionsMenuItemFactory
4760
- }
4761
- }
4762
- },
4763
- [COPY_SPECIAL_MENU_ID]: { [SheetCopyFormulaOnlyCommand.id]: {
4764
- order: 0,
4765
- menuItemFactory: CopyFormulaOnlyMenuItemFactory
4766
- } },
4767
- [PASTE_SPECIAL_MENU_ID]: { [SheetOnlyPasteFormulaCommand.id]: {
4768
- order: 4,
4769
- menuItemFactory: PasteFormulaMenuItemFactory
4770
- } }
4771
- };
4772
-
4773
5247
  //#endregion
4774
5248
  //#region src/views/formula-progress/FormulaProgress.tsx
4775
5249
  /**
@@ -4989,4 +5463,4 @@ UniverSheetsFormulaUIPlugin = __decorate([
4989
5463
  ], UniverSheetsFormulaUIPlugin);
4990
5464
 
4991
5465
  //#endregion
4992
- export { FORMULA_PROMPT_ACTIVATED, FormulaEditor, FormulaReorderController, GlobalRangeSelectorService, HelpFunctionOperation, InsertFunctionOperation, MoreFunctionsOperation, RangeSelector, RefSelectionsRenderService, ReferenceAbsoluteOperation, SearchFunctionOperation, SheetCopyFormulaOnlyCommand, SheetOnlyPasteFormulaCommand, UniverSheetsFormulaUIPlugin };
5466
+ export { FORMULA_PROMPT_ACTIVATED, FormulaEditor, FormulaReorderController, GlobalRangeSelectorService, HelpFunctionOperation, InsertFunctionOperation, MoreFunctionsOperation, RangeSelector, RefSelectionsRenderService, ReferenceAbsoluteOperation, SearchFunctionOperation, SheetCopyFormulaOnlyCommand, SheetOnlyPasteFormulaCommand, menuSchema as SheetsFormulaUIMenuSchema, UniverSheetsFormulaUIPlugin };