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