Skip to content

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

refactor(sheets-ui): optimize range selector behavior (#4703)

zhangwa1fa2da4420f
diff --git a/examples-node/src/locales.ts b/examples-node/src/locales.ts
new file mode 100644
index 0000000000..e52c300dc0
--- /dev/null
+++ b/examples-node/src/locales.ts
@@ -0,0 +1,82 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { Tools } from '@univerjs/core';
+
+import sheetsformulaenUS from '@univerjs/sheets-formula/locale/en-US';
+import sheetsformulafaIR from '@univerjs/sheets-formula/locale/fa-IR';
+import sheetsformulafrFR from '@univerjs/sheets-formula/locale/fr-FR';
+import sheetsformularuRU from '@univerjs/sheets-formula/locale/ru-RU';
+import sheetsformulaviVN from '@univerjs/sheets-formula/locale/vi-VN';
+import sheetsformulazhCN from '@univerjs/sheets-formula/locale/zh-CN';
+import sheetsformulazhTW from '@univerjs/sheets-formula/locale/zh-TW';
+import sheetssortenUS from '@univerjs/sheets-sort/locale/en-US';
+import sheetssortfaIR from '@univerjs/sheets-sort/locale/fa-IR';
+import sheetssortfrFR from '@univerjs/sheets-sort/locale/fr-FR';
+import sheetssortruRU from '@univerjs/sheets-sort/locale/ru-RU';
+import sheetssortviVN from '@univerjs/sheets-sort/locale/vi-VN';
+import sheetssortzhCN from '@univerjs/sheets-sort/locale/zh-CN';
+import sheetssortzhTW from '@univerjs/sheets-sort/locale/zh-TW';
+import sheetsenUS from '@univerjs/sheets/locale/en-US';
+import sheetsfaIR from '@univerjs/sheets/locale/fa-IR';
+import sheetsfrFR from '@univerjs/sheets/locale/fr-FR';
+import sheetsruRU from '@univerjs/sheets/locale/ru-RU';
+import sheetsviVN from '@univerjs/sheets/locale/vi-VN';
+import sheetszhCN from '@univerjs/sheets/locale/zh-CN';
+import sheetszhTW from '@univerjs/sheets/locale/zh-TW';
+
+export const enUS = Tools.deepMerge(
+ {},
+ sheetsenUS,
+ sheetsformulaenUS,
+ sheetssortenUS
+);
+export const frFR = Tools.deepMerge(
+ {},
+ sheetsfrFR,
+ sheetsformulafrFR,
+ sheetssortfrFR
+);
+export const ruRU = Tools.deepMerge(
+ {},
+ sheetsruRU,
+ sheetsformularuRU,
+ sheetssortruRU
+);
+export const zhCN = Tools.deepMerge(
+ {},
+ sheetszhCN,
+ sheetsformulazhCN,
+ sheetssortzhCN
+);
+export const zhTW = Tools.deepMerge(
+ {},
+ sheetszhTW,
+ sheetsformulazhTW,
+ sheetssortzhTW
+);
+export const viVN = Tools.deepMerge(
+ {},
+ sheetsviVN,
+ sheetsformulaviVN,
+ sheetssortviVN
+);
+export const faIR = Tools.deepMerge(
+ {},
+ sheetsfaIR,
+ sheetsformulafaIR,
+ sheetssortfaIR
+);
diff --git a/examples/src/sheets/button.tsx b/examples/src/sheets/button.tsx
new file mode 100644
index 0000000000..046d72248a
--- /dev/null
+++ b/examples/src/sheets/button.tsx
@@ -0,0 +1,48 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { Workbook } from '@univerjs/core';
+
+import type { IRangeSelectorInstance } from '@univerjs/sheets-formula-ui';
+import { ILogService, IUniverInstanceService, UniverInstanceType } from '@univerjs/core';
+import { Button } from '@univerjs/design';
+import { RangeSelector } from '@univerjs/sheets-formula-ui';
+import { useDependency, useObservable } from '@univerjs/ui';
+import { useMemo, useRef } from 'react';
+
+export const ButtonRangeSelector = () => {
+ const selectorRef = useRef<IRangeSelectorInstance>(null);
+ const univerInstanceService = useDependency(IUniverInstanceService);
+ const workbook = useObservable(useMemo(() => univerInstanceService.getCurrentTypeOfUnit$<Workbook>(UniverInstanceType.UNIVER_SHEET), []));
+ const worksheet = useObservable(useMemo(() => workbook?.activeSheet$, [workbook]));
+ const loggerSerive = useDependency(ILogService);
+
+ return (
+ <>
+ <Button onClick={() => selectorRef.current?.showDialog([])}>Start Select</Button>
+ <RangeSelector
+ key={workbook?.getUnitId() ?? '' + `_${worksheet?.getSheetId()}` ?? ''}
+ selectorRef={selectorRef}
+ hideEditor
+ unitId={workbook?.getUnitId() ?? ''}
+ subUnitId={worksheet?.getSheetId() ?? ''}
+ onChange={(_, str) => {
+ loggerSerive.log('==onChange', str);
+ }}
+ />
+ </>
+ );
+};
diff --git a/examples/src/sheets/main.ts b/examples/src/sheets/main.ts
index 83fb3188dd..34cfdacaa8 100644
--- a/examples/src/sheets/main.ts
+++ b/examples/src/sheets/main.ts
@@ -42,11 +42,12 @@ import { UniverSheetsThreadCommentUIPlugin } from '@univerjs/sheets-thread-comme
import { UniverSheetsUIPlugin } from '@univerjs/sheets-ui';
import { UniverSheetsZenEditorPlugin } from '@univerjs/sheets-zen-editor';
import { UniverThreadCommentUIPlugin } from '@univerjs/thread-comment-ui';
-import { UniverUIPlugin } from '@univerjs/ui';
+import { BuiltInUIPart, UniverUIPlugin } from '@univerjs/ui';
+
import { enUS, faIR, frFR, ruRU, viVN, zhCN, zhTW } from '../locales';
+import { ButtonRangeSelector } from './button';
import { UniverSheetsCustomMenuPlugin } from './custom-menu';
-
import '@univerjs/sheets/facade';
import '@univerjs/ui/facade';
import '@univerjs/docs-ui/facade';
@@ -64,8 +65,8 @@ import '@univerjs/sheets-drawing-ui/facade';
import '@univerjs/sheets-zen-editor/facade';
import '@univerjs/sheets-source-binding/facade';
import '@univerjs/sheets-crosshair-highlight/facade';
+import '@univerjs/sheets-formula-ui/facade';
import '@univerjs/sheets-sort/facade';
-
import '../global.css';
import './styles';
@@ -580,3 +581,22 @@ function initEvent() {
}
// initEvent();
+function initFacadeBtns() {
+ window.univerAPI?.registerUIPart(BuiltInUIPart.CUSTOM_HEADER, ButtonRangeSelector);
+}
+
+// setTimeout(() => {
+// const active = window.univerAPI?.getActiveSheet();
+// console.log('==active', active, window.univerAPI);
+// if (!active) {
+// return;
+// }
+
+// window.univerAPI?.showRangeSelectorDialog({
+// unitId: active.workbook.getId(),
+// subUnitId: active.worksheet.getSheetId(),
+// callback: (ranges, isCancel) => {
+// console.log('===range selector dialog result', ranges, isCancel);
+// },
+// });
+// }, 5000);
diff --git a/packages/core/src/docs/data-model/document-data-model.ts b/packages/core/src/docs/data-model/document-data-model.ts
index 9beaf14320..e6738cc7f5 100644
--- a/packages/core/src/docs/data-model/document-data-model.ts
+++ b/packages/core/src/docs/data-model/document-data-model.ts
@@ -31,6 +31,7 @@ import { Tools } from '../../shared/tools';
import { getEmptySnapshot } from './empty-snapshot';
import { JSONX } from './json-x/json-x';
import { PRESET_LIST_TYPE } from './preset-list-type';
+import { getPlainText } from './text-x/build-utils/parse';
import { getBodySlice, SliceBodyType } from './text-x/utils';
export const DEFAULT_DOC = {
@@ -356,4 +357,8 @@ export class DocumentDataModel extends DocumentDataModelSimple {
this._unitId = unitId;
}
+
+ getPlainText() {
+ return getPlainText(this.getBody()?.dataStream ?? '');
+ }
}
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index 122d91cbb4..5c07e02b51 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -17,7 +17,7 @@
import { installShims } from './common/shims';
installShims();
-
+export { getPlainText } from './docs/data-model/text-x/build-utils/parse';
export type { INumfmt } from './shared/types/numfmt.type';
export { debounce, get, merge, mergeWith, set } from 'lodash-es';
export { textDiff } from './shared/text-diff';
diff --git a/packages/design/src/components/input/Input.tsx b/packages/design/src/components/input/Input.tsx
index be2bfb7e09..5cd9a397f0 100644
--- a/packages/design/src/components/input/Input.tsx
+++ b/packages/design/src/components/input/Input.tsx
@@ -33,6 +33,7 @@ export interface IInputProps extends Pick<InputProps, 'onFocus' | 'onBlur'> {
onClick?: (e: React.MouseEvent<HTMLInputElement>) => void;
onKeyDown?: (e: React.KeyboardEvent<HTMLInputElement>) => void;
onChange?: (value: string) => void;
+ style?: React.CSSProperties;
}
export const Input = ({
diff --git a/packages/docs-ui/src/index.ts b/packages/docs-ui/src/index.ts
index ed3c66fe10..cd3cf3e317 100644
--- a/packages/docs-ui/src/index.ts
+++ b/packages/docs-ui/src/index.ts
@@ -25,7 +25,7 @@ export * from './basics/docs-view-key';
export { hasParagraphInTable } from './basics/paragraph';
export { docDrawingPositionToTransform, transformToDocDrawingPosition } from './basics/transform-position';
export { type IKeyboardEventConfig, useKeyboardEvent, useResize } from './views/rich-text-editor/hooks';
-export { RichTextEditor } from './views/rich-text-editor';
+export { type IRichTextEditorProps, RichTextEditor } from './views/rich-text-editor';
export { getCommandSkeleton, getRichTextEditPath } from './commands/util';
// export { TextEditor } from './components/editor/TextEditor';
// export { RangeSelector as DocRangeSelector } from './components/range-selector/RangeSelector';
diff --git a/packages/docs-ui/src/services/editor/editor.ts b/packages/docs-ui/src/services/editor/editor.ts
index 347f149d4a..f0645ec374 100644
--- a/packages/docs-ui/src/services/editor/editor.ts
+++ b/packages/docs-ui/src/services/editor/editor.ts
@@ -17,12 +17,14 @@
import type { DocumentDataModel, ICommandService, IDocumentData, IDocumentStyle, IPosition, IUndoRedoService, IUniverInstanceService, Nullable } from '@univerjs/core';
import type { DocSelectionManagerService } from '@univerjs/docs';
import type { IDocSelectionInnerParam, IRender, ISuccinctDocRangeParam, ITextRangeWithStyle } from '@univerjs/engine-render';
+import type { Observable } from 'rxjs';
+import type { IEditorInputConfig } from '../selection/doc-selection-render.service';
import { Disposable, isInternalEditorID, UniverInstanceType } from '@univerjs/core';
import { KeyCode } from '@univerjs/ui';
-import { merge, type Observable, Subject } from 'rxjs';
+import { merge, Subject } from 'rxjs';
import { filter } from 'rxjs/operators';
import { ReplaceSnapshotCommand } from '../../commands/commands/replace-content.command';
-import { DocSelectionRenderService, type IEditorInputConfig } from '../selection/doc-selection-render.service';
+import { DocSelectionRenderService } from '../selection/doc-selection-render.service';
interface IEditorEvent {
target: IEditor;
@@ -261,7 +263,6 @@ export class Editor extends Disposable implements IEditor {
*/
blur(): void {
const docSelectionRenderService = this._param.render.with(DocSelectionRenderService);
-
docSelectionRenderService.blur();
}
@@ -277,14 +278,14 @@ export class Editor extends Disposable implements IEditor {
}
// Selects the specified range of characters within editor.
- setSelectionRanges(ranges: ISuccinctDocRangeParam[]): void {
+ setSelectionRanges(ranges: ISuccinctDocRangeParam[], shouldFocus = true): void {
const editorUnitId = this.getEditorId();
const params = {
unitId: editorUnitId,
subUnitId: editorUnitId,
};
- return this._docSelectionManagerService.replaceDocRanges(ranges, params, false);
+ return this._docSelectionManagerService.replaceDocRanges(ranges, params, false, { shouldFocus });
}
// Get current doc ranges. include text range and rect range.
@@ -331,7 +332,7 @@ export class Editor extends Disposable implements IEditor {
});
}
- replaceText(text: string, resetCursor = true) {
+ replaceText(text: string, resetCursor: boolean | ITextRangeWithStyle[] = true) {
const data = this.getDocumentData();
this.setDocumentData(
@@ -348,13 +349,15 @@ export class Editor extends Disposable implements IEditor {
textRuns: [],
},
},
- resetCursor
- ? [{
- startOffset: text.length,
- endOffset: text.length,
- collapsed: true,
- }]
- : null
+ typeof resetCursor === 'object'
+ ? resetCursor
+ : resetCursor
+ ? [{
+ startOffset: text.length,
+ endOffset: text.length,
+ collapsed: true,
+ }]
+ : null
);
}
diff --git a/packages/docs-ui/src/services/selection/doc-selection-render.service.ts b/packages/docs-ui/src/services/selection/doc-selection-render.service.ts
index eb8a009547..89eabb0a39 100644
--- a/packages/docs-ui/src/services/selection/doc-selection-render.service.ts
+++ b/packages/docs-ui/src/services/selection/doc-selection-render.service.ts
@@ -260,7 +260,7 @@ export class DocSelectionRenderService extends RxDisposable implements IRenderMo
if (textRange) {
this._addTextRange(textRange);
}
- // eslint-disable-next-line unused-imports/no-unused-vars
+ // eslint-disable-next-line unused-imports/no-unused-vars
} catch (_e) {
generalAddRange(startOffset, endOffset);
}
@@ -279,6 +279,7 @@ export class DocSelectionRenderService extends RxDisposable implements IRenderMo
options,
});
+ if (!ranges.length || options?.shouldFocus === false) return;
this._updateInputPosition(options?.forceFocus);
}
diff --git a/packages/docs-ui/src/views/rich-text-editor/hooks/use-editor.ts b/packages/docs-ui/src/views/rich-text-editor/hooks/use-editor.ts
index 8a680eaf37..1b3a839443 100644
--- a/packages/docs-ui/src/views/rich-text-editor/hooks/use-editor.ts
+++ b/packages/docs-ui/src/views/rich-text-editor/hooks/use-editor.ts
@@ -24,7 +24,7 @@ import { IEditorService } from '../../../services/editor/editor-manager.service'
export interface IUseEditorProps {
editorId: string;
- initialValue: Nullable<IDocumentData>;
+ initialValue: Nullable<IDocumentData | string>;
container: RefObject<HTMLDivElement>;
autoFocus?: boolean;
isSingle?: boolean;
@@ -38,11 +38,10 @@ export function useEditor(opts: IUseEditorProps) {
useLayoutEffect(() => {
if (container.current) {
- const _initialValue = Tools.deepClone(initialValue);
-
+ const initialDoc = typeof initialValue === 'string' ? undefined : Tools.deepClone(initialValue);
const snapshot: IDocumentData = {
body: {
- dataStream: '\r\n',
+ dataStream: typeof initialValue === 'string' ? `${initialValue}\r\n` : '\r\n',
textRuns: [],
customBlocks: [],
customDecorations: [],
@@ -51,9 +50,9 @@ export function useEditor(opts: IUseEditorProps) {
startIndex: 0,
}],
},
- ..._initialValue,
+ ...initialDoc,
documentStyle: {
- ..._initialValue?.documentStyle,
+ ...initialDoc?.documentStyle,
pageSize: {
width: !isSingle ? container.current.clientWidth : Infinity,
height: Infinity,
diff --git a/packages/docs-ui/src/views/rich-text-editor/hooks/use-on-change.ts b/packages/docs-ui/src/views/rich-text-editor/hooks/use-on-change.ts
index 50c899919e..0c1fb1a544 100644
--- a/packages/docs-ui/src/views/rich-text-editor/hooks/use-on-change.ts
+++ b/packages/docs-ui/src/views/rich-text-editor/hooks/use-on-change.ts
@@ -17,12 +17,12 @@
import type { IDocumentData } from '@univerjs/core';
import type { IRichTextEditingMutationParams } from '@univerjs/docs';
import type { Editor } from '../../../services/editor/editor';
-import { ICommandService } from '@univerjs/core';
+import { getPlainText, ICommandService } from '@univerjs/core';
import { RichTextEditingMutation } from '@univerjs/docs';
import { useDependency } from '@univerjs/ui';
import { useEffect } from 'react';
-export function useOnChange(editor: Editor | undefined, onChange: (data: IDocumentData) => void) {
+export function useOnChange(editor: Editor | undefined, onChange: (data: IDocumentData, str: string) => void) {
const commandService = useDependency(ICommandService);
useEffect(() => {
@@ -31,7 +31,8 @@ export function useOnChange(editor: Editor | undefined, onChange: (data: IDocume
if (command.id === RichTextEditingMutation.id) {
const params = command.params as IRichTextEditingMutationParams;
if (params.unitId !== editor.getEditorId()) return;
- onChange(editor.getDocumentData());
+ const data = editor.getDocumentData();
+ onChange(data, getPlainText(data.body?.dataStream ?? ''));
}
});
diff --git a/packages/docs-ui/src/views/rich-text-editor/index.tsx b/packages/docs-ui/src/views/rich-text-editor/index.tsx
index ba6f0ee566..5860fd5422 100644
--- a/packages/docs-ui/src/views/rich-text-editor/index.tsx
+++ b/packages/docs-ui/src/views/rich-text-editor/index.tsx
@@ -15,14 +15,15 @@
*/
import type { IDocumentData } from '@univerjs/core';
+import type { ReactNode } from 'react';
import type { Editor } from '../../services/editor/editor';
import type { IKeyboardEventConfig } from './hooks';
-import { BuildTextUtils, createInternalEditorID, generateRandomId } from '@univerjs/core';
+import { BuildTextUtils, createInternalEditorID, generateRandomId, getPlainText } from '@univerjs/core';
import { DocSkeletonManagerService } from '@univerjs/docs';
import { IRenderManagerService } from '@univerjs/engine-render';
import { useDependency, useEvent, useObservable } from '@univerjs/ui';
import clsx from 'clsx';
-import React, { forwardRef, useEffect, useImperativeHandle, useMemo, useState } from 'react';
+import React, { useEffect, useLayoutEffect, useMemo, useState } from 'react';
import { IEditorService } from '../../services/editor/editor-manager.service';
import { DocSelectionRenderService } from '../../services/selection/doc-selection-render.service';
import { useKeyboardEvent, useResize } from './hooks';
@@ -34,8 +35,8 @@ import styles from './index.module.less';
export interface IRichTextEditorProps {
className?: string;
autoFocus?: boolean;
- onFocusChange?: (isFocus: boolean) => void;
- initialValue?: IDocumentData;
+ onFocusChange?: (isFocus: boolean, newValue?: string) => void;
+ initialValue?: IDocumentData | string;
onClickOutside?: () => void;
keyboardEventConfig?: IKeyboardEventConfig;
moveCursor?: boolean;
@@ -44,12 +45,14 @@ export interface IRichTextEditorProps {
placeholder?: string;
editorId?: string;
onHeightChange?: (height: number) => void;
- onChange?: (data: IDocumentData) => void;
+ onChange?: (data: IDocumentData, str: string) => void;
maxHeight?: number;
defaultHeight?: number;
+ icon?: ReactNode;
+ editorRef?: React.RefObject<Editor | null> | ((editor: Editor | null) => void);
}
-export const RichTextEditor = forwardRef<Editor, IRichTextEditorProps>((props, ref) => {
+export const RichTextEditor = (props: IRichTextEditorProps) => {
const {
className,
autoFocus,
@@ -65,6 +68,8 @@ export const RichTextEditor = forwardRef<Editor, IRichTextEditorProps>((props, r
onChange: _onChange,
defaultHeight = 32,
maxHeight = 32,
+ icon,
+ editorRef,
} = props;
const editorService = useDependency(IEditorService);
const onFocusChange = useEvent(_onFocusChange);
@@ -82,10 +87,21 @@ export const RichTextEditor = forwardRef<Editor, IRichTextEditorProps>((props, r
const renderManagerService = useDependency(IRenderManagerService);
const renderer = renderManagerService.getRenderById(editorId);
const docSelectionRenderService = renderer?.with(DocSelectionRenderService);
- const isFocusing = docSelectionRenderService?.isFocusing ?? false;
+ const selections = useObservable(docSelectionRenderService?.textSelectionInner$);
+ const isFocusing = Boolean((docSelectionRenderService?.isFocusing ?? false) && selections?.textRanges.some((r) => r.collapsed));
const sheetEmbeddingRef = React.useRef<HTMLDivElement>(null);
const [showPlaceholder, setShowPlaceholder] = useState(() => !BuildTextUtils.transform.getPlainText(editor?.getDocumentData().body?.dataStream ?? ''));
const { checkScrollBar } = useResize(editor, isSingle, true, true);
+
+ useLayoutEffect(() => {
+ if (!editorRef || !editor) return;
+ if (typeof editorRef === 'function') {
+ editorRef(editor);
+ return;
+ }
+ editorRef.current = editor;
+ }, [editor]);
+
const onChange = useEvent((data: IDocumentData) => {
const docSkeleton = renderer?.with(DocSkeletonManagerService);
const size = docSkeleton?.getSkeleton().getActualSize();
@@ -93,7 +109,7 @@ export const RichTextEditor = forwardRef<Editor, IRichTextEditorProps>((props, r
onHeightChange?.(size.actualHeight);
setHeight(Math.max(defaultHeight, Math.min(size.actualHeight + 10, maxHeight)));
}
- _onChange?.(data);
+ _onChange?.(data, getPlainText(data.body?.dataStream ?? ''));
checkScrollBar();
});
@@ -111,7 +127,8 @@ export const RichTextEditor = forwardRef<Editor, IRichTextEditorProps>((props, r
useObservable(editor?.focus$);
useEffect(() => {
- onFocusChange?.(isFocusing);
+ const data = editor?.getDocumentData();
+ onFocusChange?.(isFocusing, getPlainText(data?.body?.dataStream ?? ''));
}, [isFocusing, onFocusChange]);
useEffect(() => {
@@ -125,18 +142,18 @@ export const RichTextEditor = forwardRef<Editor, IRichTextEditorProps>((props, r
}
};
- setTimeout(() => {
+ const timer = setTimeout(() => {
document.addEventListener('click', handleClickOutside);
}, 100);
return () => {
document.removeEventListener('click', handleClickOutside);
+ clearTimeout(timer);
};
}, [editor, editorId, editorService, onClickOutside]);
useLeftAndRightArrow(isFocusing && moveCursor, false, editor);
useKeyboardEvent(isFocusing, keyboardEventConfig, editor);
- useImperativeHandle(ref, () => editor!, [editor]);
useOnChange(editor, onChange);
return (
@@ -153,6 +170,7 @@ export const RichTextEditor = forwardRef<Editor, IRichTextEditorProps>((props, r
ref={formulaEditorContainerRef}
onMouseUp={() => editor?.focus()}
/>
+ {icon}
{!showPlaceholder
? null
: (
@@ -163,4 +181,4 @@ export const RichTextEditor = forwardRef<Editor, IRichTextEditorProps>((props, r
</div>
</div>
);
-});
+};
diff --git a/packages/engine-formula/src/functions/__tests__/create-function-test-bed.ts b/packages/engine-formula/src/functions/__tests__/create-function-test-bed.ts
index ca3dcd82b7..5373943e8f 100644
--- a/packages/engine-formula/src/functions/__tests__/create-function-test-bed.ts
+++ b/packages/engine-formula/src/functions/__tests__/create-function-test-bed.ts
@@ -18,11 +18,6 @@
import type { Dependency, IWorkbookData, Workbook } from '@univerjs/core';
import type { ISheetData } from '../../basics/common';
-
-import type { BaseReferenceObject, FunctionVariantType } from '../../engine/reference-object/base-reference-object';
-import type { ArrayValueObject } from '../../engine/value-object/array-value-object';
-import type { BaseValueObject, ErrorValueObject } from '../../engine/value-object/base-value-object';
-
import {
CellValueType,
ILogService,
@@ -239,17 +234,6 @@ export function createFunctionTestBed(workbookData?: IWorkbookData, dependencies
};
}
-export function getObjectValue(result: FunctionVariantType) {
- if ((result as ErrorValueObject).isError()) {
- return (result as ErrorValueObject).getValue();
- } else if ((result as BaseReferenceObject).isReferenceObject()) {
- return (result as BaseReferenceObject).toArrayValueObject().toValue();
- } else if ((result as ArrayValueObject).isArray()) {
- return (result as ArrayValueObject).toValue();
- }
- return (result as BaseValueObject).getValue();
-}
-
export function stripArrayValue(array: (string | number | boolean | null)[][]) {
return array.map((row) => row.map((cell) => {
if (typeof cell === 'number') {
@@ -258,3 +242,5 @@ export function stripArrayValue(array: (string | number | boolean | null)[][]) {
return cell;
}));
}
+
+export { getObjectValue } from '../util';
diff --git a/packages/engine-formula/src/functions/util.ts b/packages/engine-formula/src/functions/util.ts
new file mode 100644
index 0000000000..8146a0f2cb
--- /dev/null
+++ b/packages/engine-formula/src/functions/util.ts
@@ -0,0 +1,30 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { BaseReferenceObject, FunctionVariantType } from '../engine/reference-object/base-reference-object';
+import type { ArrayValueObject } from '../engine/value-object/array-value-object';
+import type { BaseValueObject, ErrorValueObject } from '../engine/value-object/base-value-object';
+
+export function getObjectValue(result: FunctionVariantType) {
+ if ((result as ErrorValueObject).isError()) {
+ return (result as ErrorValueObject).getValue();
+ } else if ((result as BaseReferenceObject).isReferenceObject()) {
+ return (result as BaseReferenceObject).toArrayValueObject().toValue();
+ } else if ((result as ArrayValueObject).isArray()) {
+ return (result as ArrayValueObject).toValue();
+ }
+ return (result as BaseValueObject).getValue();
+}
diff --git a/packages/engine-formula/src/index.ts b/packages/engine-formula/src/index.ts
index 11a2994429..2b904a9177 100644
--- a/packages/engine-formula/src/index.ts
+++ b/packages/engine-formula/src/index.ts
@@ -14,6 +14,10 @@
* limitations under the License.
*/
+export type { BaseAstNode } from './engine/ast-node/base-ast-node.js';
+export { generateExecuteAstNodeData } from './engine/utils/ast-node-tool';
+export { getObjectValue } from './functions/util';
+
export type {
IArrayFormulaRangeType,
IArrayFormulaUnitCellType,
diff --git a/packages/sheets-conditional-formatting-ui/src/components/panel/rule-edit/index.module.less b/packages/sheets-conditional-formatting-ui/src/components/panel/rule-edit/index.module.less
index beb5122467..9a3757d3e3 100644
--- a/packages/sheets-conditional-formatting-ui/src/components/panel/rule-edit/index.module.less
+++ b/packages/sheets-conditional-formatting-ui/src/components/panel/rule-edit/index.module.less
@@ -1,4 +1,10 @@
.cf-rule-style-editor {
+ .cf-error-text {
+ color: rgb(var(--red-500));
+ font-size: var(--font-size-xxs);
+ margin-top: var(--margin-xxs);
+ }
+
.cf-preview-wrap {
margin-top: var(--margin-lg);
padding: var(--padding-xs) var(--padding-sm);
diff --git a/packages/sheets-conditional-formatting-ui/src/components/panel/rule-edit/index.tsx b/packages/sheets-conditional-formatting-ui/src/components/panel/rule-edit/index.tsx
index 40d11a6d3e..3cf0b57100 100644
--- a/packages/sheets-conditional-formatting-ui/src/components/panel/rule-edit/index.tsx
+++ b/packages/sheets-conditional-formatting-ui/src/components/panel/rule-edit/index.tsx
@@ -27,7 +27,7 @@ import { deserializeRangeWithSheet, serializeRange } from '@univerjs/engine-form
import { RemoveSheetMutation, setEndForRange, SetWorksheetActiveOperation, SheetsSelectionsService } from '@univerjs/sheets';
import { CFRuleType, CFSubRuleType, ConditionalFormattingRuleModel } from '@univerjs/sheets-conditional-formatting';
import { RangeSelector } from '@univerjs/sheets-formula-ui';
-import { useDependency, useSidebarClick } from '@univerjs/ui';
+import { useDependency } from '@univerjs/ui';
import React, { useEffect, useMemo, useRef, useState } from 'react';
import { AddCfCommand } from '../../../commands/commands/add-cf.command';
@@ -60,8 +60,6 @@ export const RuleEdit = (props: IRuleEditProps) => {
const unitId = getUnitId(univerInstanceService);
const subUnitId = getSubUnitId(univerInstanceService);
- const [isFocusRangeSelector, isFocusRangeSelectorSet] = useState(true);
- const rangeSelectorActionsRef = useRef<Parameters<typeof RangeSelector>[0]['actions']>({});
const [errorText, errorTextSet] = useState<string | undefined>(undefined);
const rangeResult = useRef<IRange[]>(props.rule?.ranges ?? []);
@@ -238,40 +236,33 @@ export const RuleEdit = (props: IRuleEditProps) => {
errorTextSet(localeService.t('sheet.cf.errorMessage.rangeError'));
}
};
-
- useSidebarClick((e: MouseEvent) => {
- const handleOutClick = rangeSelectorActionsRef.current?.handleOutClick;
- handleOutClick && handleOutClick(e, () => isFocusRangeSelectorSet(false));
- });
-
return (
<div className={styles.cfRuleStyleEditor}>
<div className={styleBase.title}>{localeService.t('sheet.cf.panel.range')}</div>
- <div className={`
- ${styleBase.mTBase}
- `}
+ <div
+ className={`
+ ${styleBase.mTBase}
+ `}
>
<RangeSelector
unitId={unitId}
- errorText={errorText}
subUnitId={subUnitId}
- initValue={rangeString}
- onChange={onRangeSelectorChange}
+ initialValue={rangeString}
+ onChange={(_, text) => onRangeSelectorChange(text)}
onVerify={handleVerify}
- onFocus={() => isFocusRangeSelectorSet(true)}
- isFocus={isFocusRangeSelector}
- actions={rangeSelectorActionsRef.current}
/>
+ {errorText && <div className={styles.cfErrorText}>{errorText}</div>}
</div>
<div className={styleBase.title}>{localeService.t('sheet.cf.panel.styleType')}</div>
<div className={styleBase.mTBase}>
<Select className={styles.width100} value={ruleType} options={options} onChange={(e) => ruleTypeSet(e)} />
</div>
<StyleEditor interceptorManager={interceptorManager} rule={props.rule?.rule as any} onChange={onStyleChange} />
- <div className={`
- ${styleBase.mTBase}
- ${styles.btnList}
- `}
+ <div
+ className={`
+ ${styleBase.mTBase}
+ ${styles.btnList}
+ `}
>
<Button size="small" onClick={handleCancel}>{localeService.t('sheet.cf.panel.cancel')}</Button>
<Button className={styleBase.mLSm} size="small" type="primary" onClick={handleSubmit}>{localeService.t('sheet.cf.panel.submit')}</Button>
diff --git a/packages/sheets-data-validation-ui/src/views/components/detail/index.tsx b/packages/sheets-data-validation-ui/src/views/components/detail/index.tsx
index 3dc310bcdf..e6c7bb4da2 100644
--- a/packages/sheets-data-validation-ui/src/views/components/detail/index.tsx
+++ b/packages/sheets-data-validation-ui/src/views/components/detail/index.tsx
@@ -16,6 +16,7 @@
import type { DataValidationOperator, DataValidationType, IDataValidationRuleBase, IDataValidationRuleOptions, IExecutionOptions, ISheetDataValidationRule, IUnitRange, Workbook } from '@univerjs/core';
import type { IUpdateSheetDataValidationRangeCommandParams } from '@univerjs/sheets-data-validation';
+import type { IRangeSelectorInstance } from '@univerjs/sheets-formula-ui';
import { debounce, ICommandService, isUnitRangesEqual, IUniverInstanceService, LocaleService, RedoCommand, shallowEqual, UndoCommand, UniverInstanceType } from '@univerjs/core';
import { DataValidationModel, DataValidatorRegistryScope, DataValidatorRegistryService, getRuleOptions, getRuleSetting, TWO_FORMULA_OPERATOR_COUNT } from '@univerjs/data-validation';
import { Button, Checkbox, FormLayout, Select } from '@univerjs/design';
@@ -23,8 +24,7 @@ import { deserializeRangeWithSheet, serializeRange } from '@univerjs/engine-form
import { SheetsSelectionsService } from '@univerjs/sheets';
import { RemoveSheetDataValidationCommand, UpdateSheetDataValidationOptionsCommand, UpdateSheetDataValidationRangeCommand, UpdateSheetDataValidationSettingCommand } from '@univerjs/sheets-data-validation';
import { RangeSelector } from '@univerjs/sheets-formula-ui';
-import { ComponentManager, useDependency, useEvent, useObservable, useSidebarClick } from '@univerjs/ui';
-
+import { ComponentManager, useDependency, useEvent, useObservable } from '@univerjs/ui';
import React, { useEffect, useMemo, useRef, useState } from 'react';
import { DataValidationPanelService } from '../../../services/data-validation-panel.service';
import { DataValidationOptions } from '../options';
@@ -55,7 +55,6 @@ export function DataValidationDetail() {
const ruleId = rule.uid;
const validatorService = useDependency(DataValidatorRegistryService);
const univerInstanceService = useDependency(IUniverInstanceService);
-
const componentManager = useDependency(ComponentManager);
const commandService = useDependency(ICommandService);
const dataValidationModel = useDependency(DataValidationModel);
@@ -67,10 +66,8 @@ export function DataValidationDetail() {
const [localRanges, setLocalRanges] = useState<IUnitRange[]>(() => localRule.ranges.map((i) => ({ unitId: '', sheetId: '', range: i })));
const debounceExecute = useMemo(() => debounceExecuteFactory(commandService), [commandService]);
const [isRangeError, setIsRangeError] = useState(false);
-
- const rangeSelectorActionsRef = useRef<Parameters<typeof RangeSelector>[0]['actions']>({});
const [isFocusRangeSelector, isFocusRangeSelectorSet] = useState(false);
-
+ const rangeSelectorInstance = useRef<IRangeSelectorInstance>(null);
const sheetSelectionService = useDependency(SheetsSelectionsService);
useEffect(() => {
@@ -106,6 +103,9 @@ export function DataValidationDetail() {
const isTwoFormula = localRule.operator ? TWO_FORMULA_OPERATOR_COUNT.includes(localRule.operator) : false;
const handleOk = () => {
+ if (rangeSelectorInstance.current?.editor?.isFocus()) {
+ handleUpdateRuleRanges(rangeSelectorInstance.current?.getValue());
+ }
if (!localRule.ranges.length || isRangeError) {
return;
}
@@ -246,11 +246,6 @@ export function DataValidationDetail() {
);
};
- useSidebarClick((e: MouseEvent) => {
- const handleOutClick = rangeSelectorActionsRef.current?.handleOutClick;
- handleOutClick && handleOutClick(e, () => isFocusRangeSelectorSet(false));
- });
-
return (
<div className={styles.dataValidationDetail}>
<FormLayout
@@ -258,13 +253,21 @@ export function DataValidationDetail() {
error={(!localRule.ranges.length || isRangeError) ? localeService.t('dataValidation.panel.rangeError') : ''}
>
<RangeSelector
+ selectorRef={rangeSelectorInstance}
unitId={unitId}
subUnitId={subUnitId}
- initValue={rangeStr}
- onChange={handleUpdateRuleRanges}
- onFocus={() => isFocusRangeSelectorSet(true)}
- isFocus={isFocusRangeSelector}
- actions={rangeSelectorActionsRef.current}
+ initialValue={rangeStr}
+ onChange={(doc, str) => {
+ if (!isFocusRangeSelector && rangeSelectorInstance.current?.verify()) {
+ handleUpdateRuleRanges(str);
+ }
+ }}
+ onFocusChange={(focusing, str) => {
+ isFocusRangeSelectorSet(focusing);
+ if (!focusing && str && rangeSelectorInstance.current?.verify()) {
+ handleUpdateRuleRanges(str);
+ }
+ }}
onVerify={(isValid) => setIsRangeError(!isValid)}
/>
</FormLayout>
diff --git a/packages/sheets-data-validation-ui/src/views/components/item/index.tsx b/packages/sheets-data-validation-ui/src/views/components/item/index.tsx
index c81e971944..d267863f08 100644
--- a/packages/sheets-data-validation-ui/src/views/components/item/index.tsx
+++ b/packages/sheets-data-validation-ui/src/views/components/item/index.tsx
@@ -15,14 +15,14 @@
*/
import type { ISheetDataValidationRule } from '@univerjs/core';
-import { ICommandService } from '@univerjs/core';
+import { ColorKit, ICommandService, ThemeService } from '@univerjs/core';
import { DataValidatorRegistryService } from '@univerjs/data-validation';
import { serializeRange } from '@univerjs/engine-formula';
import { DeleteSingle } from '@univerjs/icons';
import { RemoveSheetDataValidationCommand } from '@univerjs/sheets-data-validation';
import { IMarkSelectionService } from '@univerjs/sheets-ui';
-import { useDependency } from '@univerjs/ui';
-import React, { useEffect, useRef, useState } from 'react';
+import { useDependency, useObservable } from '@univerjs/ui';
+import React, { useEffect, useMemo, useRef, useState } from 'react';
import styles from './index.module.less';
export interface IDataValidationDetailProps {
@@ -41,6 +41,16 @@ export const DataValidationItem = (props: IDataValidationDetailProps) => {
const validator = validatorRegistry.getValidatorItem(rule.type);
const ids = useRef<(string | null)[]>(undefined);
const [isHover, setIsHover] = useState(false);
+ const themeService = useDependency(ThemeService);
+ const theme = useObservable(themeService.currentTheme$);
+ const style = useMemo(() => {
+ const color = theme?.loopColor2 ?? '#49B811';
+ const rgb = new ColorKit(color).toRgb();
+ return {
+ fill: `rgba(${rgb.r}, ${rgb.g}, ${rgb.b}, 0.1)`,
+ stroke: color,
+ };
+ }, [theme]);
const handleDelete = (e: React.MouseEvent<HTMLDivElement, MouseEvent>) => {
commandService.executeCommand(RemoveSheetDataValidationCommand.id, {
ruleId: rule.uid,
@@ -69,13 +79,7 @@ export const DataValidationItem = (props: IDataValidationDetailProps) => {
setIsHover(true);
ids.current = rule.ranges.map((range) => markSelectionService.addShape({
range,
- style: {
- // hasAutoFill: false,
- fill: 'rgba(73, 184, 17, 0.05)',
- strokeWidth: 1,
- stroke: '#49B811',
- widgets: {},
- },
+ style,
primary: null,
}));
}}
diff --git a/packages/sheets-data-validation-ui/src/views/components/list/index.tsx b/packages/sheets-data-validation-ui/src/views/components/list/index.tsx
index 422533b6fe..1a57c435b9 100644
--- a/packages/sheets-data-validation-ui/src/views/components/list/index.tsx
+++ b/packages/sheets-data-validation-ui/src/views/components/list/index.tsx
@@ -26,20 +26,7 @@ import { DataValidationPanelService } from '../../../services/data-validation-pa
import { DataValidationItem } from '../item';
import styles from './index.module.less';
-export function DataValidationList() {
- const univerInstanceService = useDependency(IUniverInstanceService);
- const workbook = useObservable(
- () => univerInstanceService.getCurrentTypeOfUnit$<Workbook>(UniverInstanceType.UNIVER_SHEET),
- undefined,
- undefined,
- []
- );
-
- if (!workbook) return null;
- return <DataValidationListWithWorkbook workbook={workbook} />;
-}
-
-function DataValidationListWithWorkbook(props: { workbook: Workbook }) {
+export function DataValidationList(props: { workbook: Workbook }) {
const sheetDataValidationModel = useDependency(SheetDataValidationModel);
const univerInstanceService = useDependency(IUniverInstanceService);
const commandService = useDependency(ICommandService);
diff --git a/packages/sheets-data-validation-ui/src/views/components/panel/index.tsx b/packages/sheets-data-validation-ui/src/views/components/panel/index.tsx
index 1cef3e1262..07c60e8a9a 100644
--- a/packages/sheets-data-validation-ui/src/views/components/panel/index.tsx
+++ b/packages/sheets-data-validation-ui/src/views/components/panel/index.tsx
@@ -14,7 +14,10 @@
* limitations under the License.
*/
+import type { Workbook } from '@univerjs/core';
+import { IUniverInstanceService, UniverInstanceType } from '@univerjs/core';
import { useDependency, useObservable } from '@univerjs/ui';
+import { of } from 'rxjs';
import { DataValidationPanelService } from '../../../services/data-validation-panel.service';
import { DataValidationDetail } from '../detail';
import { DataValidationList } from '../list';
@@ -22,10 +25,19 @@ import { DataValidationList } from '../list';
export const DataValidationPanel = () => {
const dataValidationPanelService = useDependency(DataValidationPanelService);
const activeRule = useObservable(dataValidationPanelService.activeRule$, dataValidationPanelService.activeRule);
+ const univerInstanceService = useDependency(IUniverInstanceService);
+ const workbook = useObservable(
+ () => univerInstanceService.getCurrentTypeOfUnit$<Workbook>(UniverInstanceType.UNIVER_SHEET),
+ undefined,
+ undefined,
+ []
+ );
+ const worksheet = useObservable(() => workbook?.activeSheet$ ?? of(null), undefined, undefined, []);
+ if (!workbook || !worksheet) return null;
return (
- activeRule
+ activeRule && activeRule.subUnitId === worksheet.getSheetId()
? <DataValidationDetail key={activeRule.rule.uid} />
- : <DataValidationList />
+ : <DataValidationList workbook={workbook} />
);
};
diff --git a/packages/sheets-formula-ui/package.json b/packages/sheets-formula-ui/package.json
index 65b1fc5a22..7e8b03d588 100644
--- a/packages/sheets-formula-ui/package.json
+++ b/packages/sheets-formula-ui/package.json
@@ -19,13 +19,11 @@
"keywords": [
"univer"
],
- "sideEffects": [
- "**/*.css"
- ],
"exports": {
".": "./src/index.ts",
"./*": "./src/*",
- "./locale/*": "./src/locale/*.ts"
+ "./locale/*": "./src/locale/*.ts",
+ "./facade": "./src/facade/index.ts"
},
"main": "./src/index.ts",
"types": "./lib/types/index.d.ts",
@@ -49,7 +47,12 @@
"require": "./lib/cjs/locale/*.js",
"types": "./lib/types/locale/*.d.ts"
},
- "./lib/*": "./lib/*"
+ "./lib/*": "./lib/*",
+ "./facade": {
+ "import": "./lib/es/facade.js",
+ "require": "./lib/cjs/facade.js",
+ "types": "./lib/types/facade/index.d.ts"
+ }
}
},
"directories": {
diff --git a/packages/sheets-formula-ui/src/facade/f-univer.ts b/packages/sheets-formula-ui/src/facade/f-univer.ts
new file mode 100644
index 0000000000..9c63072e34
--- /dev/null
+++ b/packages/sheets-formula-ui/src/facade/f-univer.ts
@@ -0,0 +1,57 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { IUnitRangeName } from '@univerjs/core';
+import type { IShowRangeSelectorDialogOptions } from '@univerjs/sheets-formula-ui';
+import { FUniver } from '@univerjs/core/facade';
+import { GlobalRangeSelectorService } from '@univerjs/sheets-formula-ui';
+
+export interface ISheetsFormulaUIMixin {
+ /**
+ * Shows the range selector dialog.
+ *
+ * @param {IShowRangeSelectorDialogOptions} opts The options of the range selector dialog.
+ * @returns {Promise<IUnitRangeName[]>} The selected ranges.
+ * @example
+ * ```typescript
+ * this.univer.showRangeSelectorDialog({
+ * unitId: 'unit1',
+ * subUnitId: 'subUnit1',
+ * initialValue: [{ sheetName: 'Sheet1', range: 'A1:B2' }],
+ * maxRangeCount: 2,
+ * supportAcrossSheet: true,
+ * callback: (ranges, isCancel) => {
+ * // Handle the selected ranges
+ * }
+ * })
+ * ```
+ */
+ showRangeSelectorDialog(opts: IShowRangeSelectorDialogOptions): Promise<IUnitRangeName[]>;
+}
+
+export class FSheetsFormulaUIUniver extends FUniver implements ISheetsFormulaUIMixin {
+ override showRangeSelectorDialog(opts: IShowRangeSelectorDialogOptions): Promise<IUnitRangeName[]> {
+ const globalRangeSelectorService = this._injector.get(GlobalRangeSelectorService);
+ return globalRangeSelectorService.showRangeSelectorDialog(opts);
+ }
+}
+
+FUniver.extend(FSheetsFormulaUIUniver);
+
+declare module '@univerjs/core/facade' {
+ // eslint-disable-next-line ts/naming-convention
+ interface FUniver extends ISheetsFormulaUIMixin { }
+}
diff --git a/packages/sheets-formula-ui/src/views/range-selector/hooks/use-refocus.ts b/packages/sheets-formula-ui/src/facade/index.ts
similarity index 60%
rename from packages/sheets-formula-ui/src/views/range-selector/hooks/use-refocus.ts
rename to packages/sheets-formula-ui/src/facade/index.ts
index b3bc000214..ca9d02e662 100644
--- a/packages/sheets-formula-ui/src/views/range-selector/hooks/use-refocus.ts
+++ b/packages/sheets-formula-ui/src/facade/index.ts
@@ -14,15 +14,6 @@
* limitations under the License.
*/
-// import { DOCS_NORMAL_EDITOR_UNIT_ID_KEY, IUniverInstanceService, useDependency } from '@univerjs/core';
-import { useEffect } from 'react';
+import './f-univer';
-export const useRefocus = () => {
- // const univerInstanceService = useDependency(IUniverInstanceService);
-
- useEffect(() => {
- return () => {
- // univerInstanceService.focusUnit(DOCS_NORMAL_EDITOR_UNIT_ID_KEY);
- };
- }, []);
-};
+export * from './f-univer';
diff --git a/packages/sheets-formula-ui/src/index.ts b/packages/sheets-formula-ui/src/index.ts
index a93164634e..17aca7b537 100644
--- a/packages/sheets-formula-ui/src/index.ts
+++ b/packages/sheets-formula-ui/src/index.ts
@@ -23,10 +23,10 @@ export { InsertFunctionOperation } from './commands/operations/insert-function.o
export { MoreFunctionsOperation } from './commands/operations/more-functions.operation';
export { ReferenceAbsoluteOperation } from './commands/operations/reference-absolute.operation';
export { SearchFunctionOperation } from './commands/operations/search-function.operation';
-export { RangeSelector } from './views/range-selector/index';
export { FormulaEditor } from './views/formula-editor/index';
+export { type IRangeSelectorInstance, type IRangeSelectorProps, RangeSelector } from './views/range-selector/index';
export { RefSelectionsRenderService } from './services/render-services/ref-selections.render-service';
-
+export { GlobalRangeSelectorService, type IShowRangeSelectorDialogOptions } from './services/range-selector.service';
// #region - all commands
export { FORMULA_PROMPT_ACTIVATED } from './services/prompt.service';
diff --git a/packages/sheets-formula-ui/src/services/range-selector.service.ts b/packages/sheets-formula-ui/src/services/range-selector.service.ts
new file mode 100644
index 0000000000..fa100ad625
--- /dev/null
+++ b/packages/sheets-formula-ui/src/services/range-selector.service.ts
@@ -0,0 +1,46 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { IUnitRangeName } from '@univerjs/core';
+import { BehaviorSubject } from 'rxjs';
+
+export interface IShowRangeSelectorDialogOptions {
+ unitId: string;
+ subUnitId: string;
+ initialValue?: IUnitRangeName[];
+ maxRangeCount?: number;
+ supportAcrossSheet?: boolean;
+ callback: (ranges: IUnitRangeName[], isCancel: boolean) => void;
+}
+
+export class GlobalRangeSelectorService {
+ private _currentSelector$ = new BehaviorSubject<IShowRangeSelectorDialogOptions | null>(null);
+
+ currentSelector$ = this._currentSelector$.asObservable();
+
+ showRangeSelectorDialog(opts: IShowRangeSelectorDialogOptions) {
+ const callback = opts.callback;
+ const promise = new Promise<IUnitRangeName[]>((resolve) => {
+ opts.callback = (ranges, isCancel) => {
+ resolve(ranges);
+ callback(ranges, isCancel);
+ };
+ });
+
+ this._currentSelector$.next(opts);
+ return promise;
+ }
+}
diff --git a/packages/sheets-formula-ui/src/sheets-formula-ui.plugin.ts b/packages/sheets-formula-ui/src/sheets-formula-ui.plugin.ts
index 32633d62e1..6ab4249dc6 100644
--- a/packages/sheets-formula-ui/src/sheets-formula-ui.plugin.ts
+++ b/packages/sheets-formula-ui/src/sheets-formula-ui.plugin.ts
@@ -21,7 +21,7 @@ import { UniverFormulaEnginePlugin } from '@univerjs/engine-formula';
import { IRenderManagerService } from '@univerjs/engine-render';
import { UniverSheetsFormulaPlugin } from '@univerjs/sheets-formula';
import { EMBEDDING_FORMULA_EDITOR_COMPONENT_KEY, RANGE_SELECTOR_COMPONENT_KEY } from '@univerjs/sheets-ui';
-import { ComponentManager } from '@univerjs/ui';
+import { BuiltInUIPart, ComponentManager, connectInjector, IUIPartsService } from '@univerjs/ui';
import { FORMULA_UI_PLUGIN_NAME } from './common/plugin-name';
import {
defaultPluginBaseConfig,
@@ -34,9 +34,11 @@ import { FormulaEditorShowController } from './controllers/formula-editor-show.c
import { FormulaRenderManagerController } from './controllers/formula-render.controller';
import { FormulaUIController } from './controllers/formula-ui.controller';
import { FormulaPromptService, IFormulaPromptService } from './services/prompt.service';
+import { GlobalRangeSelectorService } from './services/range-selector.service';
import { RefSelectionsRenderService } from './services/render-services/ref-selections.render-service';
import { FormulaEditor } from './views/formula-editor/index';
import { RangeSelector } from './views/range-selector';
+import { GlobalRangeSelector } from './views/range-selector/global';
/**
* The configuration of the formula UI plugin.
@@ -50,7 +52,8 @@ export class UniverSheetsFormulaUIPlugin extends Plugin {
private readonly _config: Partial<IUniverSheetsFormulaBaseConfig> = defaultPluginBaseConfig,
@Inject(Injector) override readonly _injector: Injector,
@IRenderManagerService private readonly _renderManagerService: IRenderManagerService,
- @IConfigService private readonly _configService: IConfigService
+ @IConfigService private readonly _configService: IConfigService,
+ @IUIPartsService private readonly _uiPartsService: IUIPartsService
) {
super();
@@ -69,6 +72,7 @@ export class UniverSheetsFormulaUIPlugin extends Plugin {
const j = this._injector;
const dependencies: Dependency[] = [
[IFormulaPromptService, { useClass: FormulaPromptService }],
+ [GlobalRangeSelectorService],
[FormulaUIController],
[FormulaAutoFillController],
[FormulaClipboardController],
@@ -81,6 +85,7 @@ export class UniverSheetsFormulaUIPlugin extends Plugin {
const componentManager = this._injector.get(ComponentManager);
componentManager.register(RANGE_SELECTOR_COMPONENT_KEY, RangeSelector);
componentManager.register(EMBEDDING_FORMULA_EDITOR_COMPONENT_KEY, FormulaEditor);
+ this._initUIPart();
}
override onRendered(): void {
@@ -101,4 +106,8 @@ export class UniverSheetsFormulaUIPlugin extends Plugin {
override onSteady(): void {
this._injector.get(FormulaAutoFillController);
}
+
+ private _initUIPart(): void {
+ this.disposeWithMe(this._uiPartsService.registerComponent(BuiltInUIPart.GLOBAL, () => connectInjector(GlobalRangeSelector, this._injector)));
+ }
}
diff --git a/packages/sheets-formula-ui/src/views/range-selector/hooks/use-focus.ts b/packages/sheets-formula-ui/src/views/formula-editor/hooks/use-focus.ts
similarity index 100%
rename from packages/sheets-formula-ui/src/views/range-selector/hooks/use-focus.ts
rename to packages/sheets-formula-ui/src/views/formula-editor/hooks/use-focus.ts
diff --git a/packages/sheets-formula-ui/src/views/formula-editor/hooks/use-formula-search.ts b/packages/sheets-formula-ui/src/views/formula-editor/hooks/use-formula-search.ts
index b4f4dd037d..65ba93a364 100644
--- a/packages/sheets-formula-ui/src/views/formula-editor/hooks/use-formula-search.ts
+++ b/packages/sheets-formula-ui/src/views/formula-editor/hooks/use-formula-search.ts
@@ -16,7 +16,7 @@
import type { Editor } from '@univerjs/docs-ui';
import type { ISearchItem } from '@univerjs/sheets-formula';
-import type { INode } from '../../range-selector/hooks/use-formula-token';
+import type { INode } from './use-formula-token';
import { matchToken, sequenceNodeType } from '@univerjs/engine-formula';
import { IDescriptionService } from '@univerjs/sheets-formula';
import { useDependency } from '@univerjs/ui';
diff --git a/packages/sheets-formula-ui/src/views/range-selector/hooks/use-formula-token.ts b/packages/sheets-formula-ui/src/views/formula-editor/hooks/use-formula-token.ts
similarity index 100%
rename from packages/sheets-formula-ui/src/views/range-selector/hooks/use-formula-token.ts
rename to packages/sheets-formula-ui/src/views/formula-editor/hooks/use-formula-token.ts
diff --git a/packages/sheets-formula-ui/src/views/range-selector/hooks/use-highlight.ts b/packages/sheets-formula-ui/src/views/formula-editor/hooks/use-highlight.ts
similarity index 98%
rename from packages/sheets-formula-ui/src/views/range-selector/hooks/use-highlight.ts
rename to packages/sheets-formula-ui/src/views/formula-editor/hooks/use-highlight.ts
index dbdc962a3b..77147ddb06 100644
--- a/packages/sheets-formula-ui/src/views/range-selector/hooks/use-highlight.ts
+++ b/packages/sheets-formula-ui/src/views/formula-editor/hooks/use-highlight.ts
@@ -27,7 +27,7 @@ import { IRefSelectionsService, setEndForRange } from '@univerjs/sheets';
import { IDescriptionService } from '@univerjs/sheets-formula';
import { SheetSkeletonManagerService } from '@univerjs/sheets-ui';
import { useDependency, useEvent } from '@univerjs/ui';
-import { useCallback, useEffect, useMemo } from 'react';
+import { useEffect, useMemo } from 'react';
import { genFormulaRefSelectionStyle } from '../../../common/selection';
import { RefSelectionsRenderService } from '../../../services/render-services/ref-selections.render-service';
@@ -169,7 +169,7 @@ export function useDocHight(_leadingCharacter: string = '') {
const commandService = useDependency(ICommandService);
const leadingCharacterLength = useMemo(() => _leadingCharacter.length, [_leadingCharacter]);
- const highlightDoc = useCallback((
+ const highlightDoc = useEvent((
editor: Editor,
sequenceNodes: INode[],
isNeedResetSelection = true,
@@ -228,7 +228,7 @@ export function useDocHight(_leadingCharacter: string = '') {
});
return refSelections;
}
- }, [commandService, descriptionService, colorMap, leadingCharacterLength, _leadingCharacter]);
+ });
return highlightDoc;
}
diff --git a/packages/sheets-formula-ui/src/views/range-selector/hooks/use-is-first-render.ts b/packages/sheets-formula-ui/src/views/formula-editor/hooks/use-is-first-render.ts
similarity index 100%
rename from packages/sheets-formula-ui/src/views/range-selector/hooks/use-is-first-render.ts
rename to packages/sheets-formula-ui/src/views/formula-editor/hooks/use-is-first-render.ts
diff --git a/packages/sheets-formula-ui/src/views/range-selector/hooks/use-keyboard-event.ts b/packages/sheets-formula-ui/src/views/formula-editor/hooks/use-keyboard-event.ts
similarity index 100%
rename from packages/sheets-formula-ui/src/views/range-selector/hooks/use-keyboard-event.ts
rename to packages/sheets-formula-ui/src/views/formula-editor/hooks/use-keyboard-event.ts
diff --git a/packages/sheets-formula-ui/src/views/range-selector/hooks/use-left-and-right-arrow.ts b/packages/sheets-formula-ui/src/views/formula-editor/hooks/use-left-and-right-arrow.ts
similarity index 98%
rename from packages/sheets-formula-ui/src/views/range-selector/hooks/use-left-and-right-arrow.ts
rename to packages/sheets-formula-ui/src/views/formula-editor/hooks/use-left-and-right-arrow.ts
index f121558fbf..de747ec536 100644
--- a/packages/sheets-formula-ui/src/views/range-selector/hooks/use-left-and-right-arrow.ts
+++ b/packages/sheets-formula-ui/src/views/formula-editor/hooks/use-left-and-right-arrow.ts
@@ -21,7 +21,7 @@ import { DeviceInputEventType } from '@univerjs/engine-render';
import { ExpandSelectionCommand, JumpOver, MoveSelectionCommand } from '@univerjs/sheets-ui';
import { IShortcutService, KeyCode, MetaKeys, useDependency } from '@univerjs/ui';
import { useEffect, useRef } from 'react';
-import { FormulaSelectingType } from '../../formula-editor/hooks/use-formula-selection';
+import { FormulaSelectingType } from './use-formula-selection';
// eslint-disable-next-line max-lines-per-function
export const useLeftAndRightArrow = (isNeed: boolean, shouldMoveSelection: FormulaSelectingType, editor?: Editor, onMoveInEditor?: (keyCode: KeyCode, metaKey?: MetaKeys) => void) => {
diff --git a/packages/sheets-formula-ui/src/views/range-selector/hooks/use-refactor-effect.ts b/packages/sheets-formula-ui/src/views/formula-editor/hooks/use-refactor-effect.ts
similarity index 100%
rename from packages/sheets-formula-ui/src/views/range-selector/hooks/use-refactor-effect.ts
rename to packages/sheets-formula-ui/src/views/formula-editor/hooks/use-refactor-effect.ts
diff --git a/packages/sheets-formula-ui/src/views/range-selector/hooks/use-reset-selection.ts b/packages/sheets-formula-ui/src/views/formula-editor/hooks/use-reset-selection.ts
similarity index 100%
rename from packages/sheets-formula-ui/src/views/range-selector/hooks/use-reset-selection.ts
rename to packages/sheets-formula-ui/src/views/formula-editor/hooks/use-reset-selection.ts
diff --git a/packages/sheets-formula-ui/src/views/range-selector/hooks/use-resize.ts b/packages/sheets-formula-ui/src/views/formula-editor/hooks/use-resize.ts
similarity index 100%
rename from packages/sheets-formula-ui/src/views/range-selector/hooks/use-resize.ts
rename to packages/sheets-formula-ui/src/views/formula-editor/hooks/use-resize.ts
diff --git a/packages/sheets-formula-ui/src/views/formula-editor/hooks/use-sheet-selection-change.ts b/packages/sheets-formula-ui/src/views/formula-editor/hooks/use-sheet-selection-change.ts
index 606d8544c8..84ac4a7422 100644
--- a/packages/sheets-formula-ui/src/views/formula-editor/hooks/use-sheet-selection-change.ts
+++ b/packages/sheets-formula-ui/src/views/formula-editor/hooks/use-sheet-selection-change.ts
@@ -20,7 +20,7 @@ import type { IRange, Workbook } from '@univerjs/core';
import type { Editor } from '@univerjs/docs-ui';
import type { ISelectionWithCoord, ISetSelectionsOperationParams } from '@univerjs/sheets';
import type { RefObject } from 'react';
-import type { IRefSelection } from '../../range-selector/hooks/use-highlight';
+import type { IRefSelection } from './use-highlight';
import { DisposableCollection, ICommandService, IUniverInstanceService, ThemeService } from '@univerjs/core';
import { DocSelectionManagerService } from '@univerjs/docs';
import { deserializeRangeWithSheet, generateStringWithSequence, LexerTreeBuilder, sequenceNodeType, serializeRange, serializeRangeWithSheet } from '@univerjs/engine-formula';
@@ -32,13 +32,13 @@ import { useEffect, useMemo } from 'react';
import { merge } from 'rxjs';
import { debounceTime } from 'rxjs/operators';
import { RefSelectionsRenderService } from '../../../services/render-services/ref-selections.render-service';
-import { calcHighlightRanges } from '../../range-selector/hooks/use-highlight';
import { findIndexFromSequenceNodes, findRefSequenceIndex } from '../../range-selector/utils/find-index-from-sequence-nodes';
import { getOffsetFromSequenceNodes } from '../../range-selector/utils/get-offset-from-sequence-nodes';
import { sequenceNodeToText } from '../../range-selector/utils/sequence-node-to-text';
import { unitRangesToText } from '../../range-selector/utils/unit-ranges-to-text';
import { useStateRef } from '../hooks/use-state-ref';
import { FormulaSelectingType } from './use-formula-selection';
+import { calcHighlightRanges } from './use-highlight';
const prepareSelectionChangeContext = (opts: { editor?: Editor; lexerTreeBuilder: LexerTreeBuilder }) => {
const { editor, lexerTreeBuilder } = opts;
diff --git a/packages/sheets-formula-ui/src/views/range-selector/hooks/use-switch-sheet.ts b/packages/sheets-formula-ui/src/views/formula-editor/hooks/use-switch-sheet.ts
similarity index 100%
rename from packages/sheets-formula-ui/src/views/range-selector/hooks/use-switch-sheet.ts
rename to packages/sheets-formula-ui/src/views/formula-editor/hooks/use-switch-sheet.ts
diff --git a/packages/sheets-formula-ui/src/views/formula-editor/index.tsx b/packages/sheets-formula-ui/src/views/formula-editor/index.tsx
index fae2a051ad..aa5d6a1498 100644
--- a/packages/sheets-formula-ui/src/views/formula-editor/index.tsx
+++ b/packages/sheets-formula-ui/src/views/formula-editor/index.tsx
@@ -18,8 +18,8 @@ import type { DocumentDataModel, IDisposable, ITextRange } from '@univerjs/core'
import type { Editor, IKeyboardEventConfig } from '@univerjs/docs-ui';
import type { KeyCode, MetaKeys } from '@univerjs/ui';
import type { ReactNode } from 'react';
-import type { IRefSelection } from '../range-selector/hooks/use-highlight';
import type { FormulaSelectingType } from './hooks/use-formula-selection';
+import type { IRefSelection } from './hooks/use-highlight';
import { BuildTextUtils, createInternalEditorID, generateRandomId, IUniverInstanceService, UniverInstanceType } from '@univerjs/core';
import { DocBackScrollRenderController, DocSelectionRenderService, IEditorService, useKeyboardEvent, useResize } from '@univerjs/docs-ui';
import { IRenderManagerService } from '@univerjs/engine-render';
@@ -27,18 +27,18 @@ import { EMBEDDING_FORMULA_EDITOR } from '@univerjs/sheets-ui';
import { useDependency, useEvent, useObservable, useUpdateEffect } from '@univerjs/ui';
import clsx from 'clsx';
import React, { useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';
-import { useFocus } from '../range-selector/hooks/use-focus';
-import { useFormulaToken } from '../range-selector/hooks/use-formula-token';
-import { useDocHight, useSheetHighlight } from '../range-selector/hooks/use-highlight';
-import { useLeftAndRightArrow } from '../range-selector/hooks/use-left-and-right-arrow';
-import { useRefactorEffect } from '../range-selector/hooks/use-refactor-effect';
-import { useResetSelection } from '../range-selector/hooks/use-reset-selection';
-import { useSwitchSheet } from '../range-selector/hooks/use-switch-sheet';
import { findIndexFromSequenceNodes, findRefSequenceIndex } from '../range-selector/utils/find-index-from-sequence-nodes';
import { HelpFunction } from './help-function/HelpFunction';
+import { useFocus } from './hooks/use-focus';
import { useFormulaSelecting } from './hooks/use-formula-selection';
+import { useFormulaToken } from './hooks/use-formula-token';
+import { useDocHight, useSheetHighlight } from './hooks/use-highlight';
+import { useLeftAndRightArrow } from './hooks/use-left-and-right-arrow';
+import { useRefactorEffect } from './hooks/use-refactor-effect';
+import { useResetSelection } from './hooks/use-reset-selection';
import { useSheetSelectionChange } from './hooks/use-sheet-selection-change';
import { useStateRef } from './hooks/use-state-ref';
+import { useSwitchSheet } from './hooks/use-switch-sheet';
import { useVerify } from './hooks/use-verify';
import styles from './index.module.less';
import { SearchFunction } from './search-function/SearchFunction';
diff --git a/packages/sheets-formula-ui/src/views/range-selector/global.tsx b/packages/sheets-formula-ui/src/views/range-selector/global.tsx
new file mode 100644
index 0000000000..48ff699134
--- /dev/null
+++ b/packages/sheets-formula-ui/src/views/range-selector/global.tsx
@@ -0,0 +1,45 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { IRangeSelectorInstance } from './index';
+import { useDependency, useObservable } from '@univerjs/ui';
+import { useEffect, useRef } from 'react';
+import { GlobalRangeSelectorService } from '../../services/range-selector.service';
+import { RangeSelector } from './index';
+
+export const GlobalRangeSelector = () => {
+ const rangeSelectorService = useDependency(GlobalRangeSelectorService);
+ const current = useObservable(rangeSelectorService.currentSelector$);
+ const instance = useRef<IRangeSelectorInstance | null>(null);
+
+ useEffect(() => {
+ if (current) {
+ instance.current?.showDialog(current.initialValue ?? []);
+
+ return () => {
+ instance.current?.hideDialog();
+ };
+ }
+ }, [current]);
+ return (
+ <RangeSelector
+ unitId={current?.unitId ?? ''}
+ subUnitId={current?.subUnitId ?? ''}
+ hideEditor
+ selectorRef={instance}
+ />
+ );
+};
diff --git a/packages/sheets-formula-ui/src/views/range-selector/hooks/use-editor-input.ts b/packages/sheets-formula-ui/src/views/range-selector/hooks/use-editor-input.ts
deleted file mode 100644
index 65ae4fe860..0000000000
--- a/packages/sheets-formula-ui/src/views/range-selector/hooks/use-editor-input.ts
+++ /dev/null
@@ -1,59 +0,0 @@
-/**
- * Copyright 2023-present DreamNum Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-import type { Editor } from '@univerjs/docs-ui';
-import { matchToken } from '@univerjs/engine-formula';
-import { IRenderManagerService } from '@univerjs/engine-render';
-import { useDependency } from '@univerjs/ui';
-import { useEffect } from 'react';
-import { RefSelectionsRenderService } from '../../../services/render-services/ref-selections.render-service';
-
-/**
- * add selections by inputting a `,`.
- * @param {string} unitId
- * @param {string} rangeString
- * @param {Editor} [editor]
- */
-export const useEditorInput = (unitId: string, rangeString: string, editor?: Editor) => {
- const renderManagerService = useDependency(IRenderManagerService);
- const render = renderManagerService.getRenderById(unitId);
- const refSelectionsRenderService = render?.with(RefSelectionsRenderService);
-
- useEffect(() => {
- if (editor && refSelectionsRenderService) {
- const d = editor.input$.subscribe((e) => {
- const content = e.content;
- if (content === matchToken.COMMA) {
- refSelectionsRenderService.setSkipLastEnabled(true);
- } else {
- refSelectionsRenderService.setSkipLastEnabled(false);
- }
- });
- return () => {
- d.unsubscribe();
- };
- }
- }, [editor, refSelectionsRenderService]);
-
- useEffect(() => {
- if (!refSelectionsRenderService) {
- return;
- }
- if (!rangeString.endsWith(matchToken.COMMA)) {
- refSelectionsRenderService.setSkipLastEnabled(false);
- }
- }, [rangeString, refSelectionsRenderService]);
-};
diff --git a/packages/sheets-formula-ui/src/views/range-selector/hooks/use-first-highlight-doc.ts b/packages/sheets-formula-ui/src/views/range-selector/hooks/use-first-highlight-doc.ts
deleted file mode 100644
index 3062c4a615..0000000000
--- a/packages/sheets-formula-ui/src/views/range-selector/hooks/use-first-highlight-doc.ts
+++ /dev/null
@@ -1,57 +0,0 @@
-/**
- * Copyright 2023-present DreamNum Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-import type { Editor } from '@univerjs/docs-ui';
-import type { useDocHight, useSheetHighlight } from './use-highlight';
-import { useEffect, useRef } from 'react';
-import { useFormulaToken } from './use-formula-token';
-
-export const useFirstHighlightDoc = (
- text: string,
- leadingCharacter: string,
- isNeed: boolean,
- highlightDoc: ReturnType<typeof useDocHight>,
- highlightSheet: ReturnType<typeof useSheetHighlight>,
- editor?: Editor
-) => {
- const getFormulaToken = useFormulaToken();
- const isInit = useRef(true);
- useEffect(() => {
- if (editor) {
- if (isInit.current) {
- const sequenceNodes = getFormulaToken(text);
- if (sequenceNodes.length) {
- const ranges = highlightDoc(editor, sequenceNodes);
- if (isNeed) {
- highlightSheet(ranges);
- }
- } else {
- const data = editor.getDocumentData();
- const dataStream = data.body?.dataStream ?? `${leadingCharacter}\r\n`;
- const cloneBody = { dataStream, ...data.body };
- editor.setDocumentData({ ...data, body: cloneBody });
- }
- isInit.current = false;
- } else {
- if (isNeed) {
- const sequenceNodes = getFormulaToken(text);
- const ranges = highlightDoc(editor, sequenceNodes);
- highlightSheet(ranges);
- }
- }
- }
- }, [editor, isNeed]);
-};
diff --git a/packages/sheets-formula-ui/src/views/range-selector/hooks/use-only-one-range.ts b/packages/sheets-formula-ui/src/views/range-selector/hooks/use-only-one-range.ts
deleted file mode 100644
index f056be5dd2..0000000000
--- a/packages/sheets-formula-ui/src/views/range-selector/hooks/use-only-one-range.ts
+++ /dev/null
@@ -1,37 +0,0 @@
-/**
- * Copyright 2023-present DreamNum Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-import { IRenderManagerService } from '@univerjs/engine-render';
-import { useDependency } from '@univerjs/ui';
-import { useEffect } from 'react';
-import { RefSelectionsRenderService } from '../../../services/render-services/ref-selections.render-service';
-
-export const useOnlyOneRange = (unitId: string, isOnlyOneRange: boolean) => {
- const renderManagerService = useDependency(IRenderManagerService);
-
- const render = renderManagerService.getRenderById(unitId);
- const refSelectionsRenderService = render?.with(RefSelectionsRenderService);
- useEffect(() => {
- if (!refSelectionsRenderService) {
- return;
- }
- if (isOnlyOneRange) {
- refSelectionsRenderService?.setRemainLastEnabled(false);
- } else {
- refSelectionsRenderService?.setRemainLastEnabled(true);
- }
- }, [isOnlyOneRange, refSelectionsRenderService]);
-};
diff --git a/packages/sheets-formula-ui/src/views/range-selector/hooks/use-ranges-highlight.ts b/packages/sheets-formula-ui/src/views/range-selector/hooks/use-ranges-highlight.ts
new file mode 100644
index 0000000000..c05532d697
--- /dev/null
+++ b/packages/sheets-formula-ui/src/views/range-selector/hooks/use-ranges-highlight.ts
@@ -0,0 +1,95 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { Nullable, Workbook } from '@univerjs/core';
+import type { Editor } from '@univerjs/docs-ui';
+import type { ISequenceNode } from '@univerjs/engine-formula';
+import { ColorKit, DisposableCollection, IUniverInstanceService, UniverInstanceType } from '@univerjs/core';
+import { deserializeRangeWithSheet, LexerTreeBuilder } from '@univerjs/engine-formula';
+import { IMarkSelectionService } from '@univerjs/sheets-ui';
+import { useDependency, useObservable } from '@univerjs/ui';
+import { useEffect, useRef, useState } from 'react';
+import { useDocHight } from '../../formula-editor/hooks/use-highlight';
+
+export function useRangesHighlight(editor: Nullable<Editor>, focusing: boolean, unitId: string, subUnitId: string) {
+ const lexerTreeBuilder = useDependency(LexerTreeBuilder);
+ const highlightDoc = useDocHight('');
+ const change = useObservable(editor?.getDocumentDataModel().change$);
+ const [sequenceNodes, setSequenceNodes] = useState<(string | ISequenceNode)[]>([]);
+ const markSelectionService = useDependency(IMarkSelectionService);
+ const last = useRef('');
+ const univerInstanceService = useDependency(IUniverInstanceService);
+
+ useEffect(() => {
+ if (!editor) return;
+ const text = editor.getDocumentDataModel().getPlainText();
+ if (last.current === text) {
+ return;
+ }
+ last.current = text;
+ const nodes = lexerTreeBuilder.sequenceNodesBuilder(text);
+ setSequenceNodes(nodes ?? []);
+ }, [change, editor, lexerTreeBuilder]);
+
+ useEffect(() => {
+ if (!editor) return;
+ if (!focusing) {
+ const current = editor.getDocumentData();
+ editor.setDocumentData({
+ ...current,
+ body: {
+ ...current.body,
+ dataStream: current.body?.dataStream ?? '',
+ textRuns: [],
+ },
+ });
+ return;
+ }
+ const selections = highlightDoc(editor, sequenceNodes, false);
+ const disposable = new DisposableCollection();
+ selections.forEach((selection) => {
+ // selection.token;
+ const range = deserializeRangeWithSheet(selection.token);
+ const workbook = univerInstanceService.getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET);
+ const worksheet = workbook?.getActiveSheet();
+ // range is not in the current worksheet
+ if ((!range.sheetName && subUnitId !== worksheet?.getSheetId()) || (range.sheetName && worksheet?.getName() !== range.sheetName)) {
+ return;
+ }
+
+ const rgb = new ColorKit(selection.themeColor).toRgb();
+ const id = markSelectionService.addShape({
+ range: range.range,
+ style: {
+ stroke: selection.themeColor,
+ fill: `rgba(${rgb.r}, ${rgb.g}, ${rgb.b}, 0.1)`,
+ strokeDash: 12,
+ },
+ primary: null,
+ });
+
+ if (id) {
+ disposable.add(() => markSelectionService.removeShape(id));
+ }
+ });
+
+ return () => {
+ disposable.dispose();
+ };
+ }, [editor, focusing, highlightDoc, markSelectionService, sequenceNodes]);
+
+ return { sequenceNodes };
+}
diff --git a/packages/sheets-formula-ui/src/views/range-selector/hooks/use-selection-change.ts b/packages/sheets-formula-ui/src/views/range-selector/hooks/use-selection-change.ts
new file mode 100644
index 0000000000..9dd5c126a9
--- /dev/null
+++ b/packages/sheets-formula-ui/src/views/range-selector/hooks/use-selection-change.ts
@@ -0,0 +1,63 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { IUnitRangeName, Nullable, Workbook } from '@univerjs/core';
+import type { ISelectionWithStyle } from '@univerjs/sheets';
+import { DisposableCollection, IUniverInstanceService, UniverInstanceType } from '@univerjs/core';
+import { SheetsSelectionsService } from '@univerjs/sheets';
+import { useDependency, useEvent } from '@univerjs/ui';
+import { useEffect } from 'react';
+
+export function useRangeSelectorSelectionChange(opts: { supportAcrossSheet?: boolean; unitId: string; subUnitId: string; onChange: (ranges: IUnitRangeName[], isStart: boolean) => void }) {
+ const sheetsSelectionsService = useDependency(SheetsSelectionsService);
+ const { supportAcrossSheet = false, unitId, subUnitId, onChange: _onChange } = opts;
+ const univerInstanceService = useDependency(IUniverInstanceService);
+ const workbook = univerInstanceService.getUnit<Workbook>(unitId, UniverInstanceType.UNIVER_SHEET);
+ const onChange = useEvent(_onChange);
+
+ const handleSelectionChange = useEvent((selections: Nullable<ISelectionWithStyle[]>, isStart: boolean) => {
+ const currentSheet = workbook?.getActiveSheet();
+ if (!currentSheet) return;
+ if (!supportAcrossSheet && currentSheet.getSheetId() !== subUnitId) return;
+ if (!selections?.length) return;
+ const ranges = selections.map((item) => ({
+ range: item.range,
+ unitId,
+ sheetName: currentSheet.getSheetId() === subUnitId ? '' : currentSheet.getName(),
+ }));
+
+ onChange(ranges, isStart);
+ });
+
+ useEffect(() => {
+ const disposableCollection = new DisposableCollection();
+ disposableCollection.add(sheetsSelectionsService.selectionMoveStart$.subscribe((selections) => {
+ handleSelectionChange(selections, true);
+ }));
+
+ disposableCollection.add(sheetsSelectionsService.selectionMoving$.subscribe((selections) => {
+ handleSelectionChange(selections, false);
+ }));
+
+ disposableCollection.add(sheetsSelectionsService.selectionMoveEnd$.subscribe((selections) => {
+ handleSelectionChange(selections, false);
+ }));
+
+ return () => {
+ disposableCollection.dispose();
+ };
+ }, [handleSelectionChange, sheetsSelectionsService.selectionMoveEnd$, sheetsSelectionsService.selectionMoveStart$, sheetsSelectionsService.selectionMoving$]);
+}
diff --git a/packages/sheets-formula-ui/src/views/range-selector/hooks/use-sheet-selection-change.ts b/packages/sheets-formula-ui/src/views/range-selector/hooks/use-sheet-selection-change.ts
deleted file mode 100644
index 39733c1702..0000000000
--- a/packages/sheets-formula-ui/src/views/range-selector/hooks/use-sheet-selection-change.ts
+++ /dev/null
@@ -1,224 +0,0 @@
-/**
- * Copyright 2023-present DreamNum Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-/* eslint-disable max-lines-per-function */
-
-import type { Workbook } from '@univerjs/core';
-import type { ISelectionWithCoord } from '@univerjs/sheets';
-import type { INode } from '../utils/filter-reference-node';
-
-import { DisposableCollection, IUniverInstanceService } from '@univerjs/core';
-import { deserializeRangeWithSheet, matchToken, sequenceNodeType, serializeRange, serializeRangeWithSheet } from '@univerjs/engine-formula';
-import { IRenderManagerService } from '@univerjs/engine-render';
-import { useDependency } from '@univerjs/ui';
-import { useEffect, useMemo, useRef } from 'react';
-import { distinctUntilChanged, map, merge } from 'rxjs';
-import { throttleTime } from 'rxjs/operators';
-import { RefSelectionsRenderService } from '../../../services/render-services/ref-selections.render-service';
-import { filterReferenceNode, isComma } from '../utils/filter-reference-node';
-import { rangePreProcess } from '../utils/range-pre-process';
-import { sequenceNodeToText } from '../utils/sequence-node-to-text';
-import { getSheetNameById, unitRangesToText } from '../utils/unit-ranges-to-text';
-
-export const useSheetSelectionChange = (
- isNeed: boolean,
- unitId: string,
- _subUnitId: string,
- sequenceNodes: INode[],
- isSupportAcrossSheet: boolean,
- isOnlyOneRange: boolean,
- handleRangeChange: (refString: string, offset: number, isEnd: boolean) => void) => {
- const renderManagerService = useDependency(IRenderManagerService);
- const univerInstanceService = useDependency(IUniverInstanceService);
- const isScalingRef = useRef(false);
-
- const render = renderManagerService.getRenderById(unitId);
- const refSelectionsRenderService = render?.with(RefSelectionsRenderService);
- const oldFilterReferenceNodes = useRef<INode[]>([]);
- const filterReferenceNodes = useMemo(() => {
- const newFilterReferenceNodes = filterReferenceNode(sequenceNodes);
- const old = oldFilterReferenceNodes.current;
- if (newFilterReferenceNodes.length === old.length) {
- old.splice(0);
- old.push(...newFilterReferenceNodes);
- return old;
- }
- return newFilterReferenceNodes;
- }, [sequenceNodes]);
- oldFilterReferenceNodes.current = filterReferenceNodes;
-
- const scalingOptionRef = useRef<{ result: string; offset: number }>(undefined);
-
- useEffect(() => {
- if (isNeed && refSelectionsRenderService) {
- let isFirst = true;
- const handleSelectionsChange = (selections: ISelectionWithCoord[], isEnd: boolean) => {
- if (isFirst || isScalingRef.current) {
- isFirst = false;
- return;
- }
- const cloneSelectionList = [...selections];
- const workbook = univerInstanceService.getUnit<Workbook>(unitId);
- const currentSheetName = workbook?.getActiveSheet()?.getName() || '';
- const newSequenceNodes = filterReferenceNodes.map((node, index) => {
- if (typeof node === 'string') {
- const preItem = filterReferenceNodes[index - 1];
- if (!preItem) {
- return null;
- }
- const nextItem = filterReferenceNodes[index + 1];
- if (isComma(node)) {
- if (isComma(nextItem)) {
- return null;
- }
- if (index === (filterReferenceNodes.length - 1)) {
- return null;
- }
- }
- return node;
- } else if (node.nodeType === sequenceNodeType.REFERENCE) {
- const unitRange = deserializeRangeWithSheet(node.token);
- unitRange.unitId = unitRange.unitId === '' ? unitId : unitRange.unitId;
- unitRange.sheetName = unitRange.sheetName === '' ? currentSheetName : unitRange.sheetName;
-
- const { unitId: rangeUnitId, sheetName: rangeSubName } = unitRange;
- if (isOnlyOneRange) {
- if (rangeUnitId !== unitId || currentSheetName !== rangeSubName) {
- return null;
- }
- }
- if (rangeUnitId === unitId && currentSheetName === rangeSubName) {
- const currentSelection = cloneSelectionList.shift();
- if (currentSelection && getSheetNameById(univerInstanceService, unitId, currentSelection.rangeWithCoord.sheetId || '') === rangeSubName) {
- const cloneNode = { ...node };
- rangePreProcess(currentSelection.rangeWithCoord);
- if (isSupportAcrossSheet) {
- cloneNode.token = serializeRangeWithSheet(currentSheetName, currentSelection.rangeWithCoord);
- } else {
- cloneNode.token = serializeRange(currentSelection.rangeWithCoord);
- }
- return cloneNode;
- }
- }
- return node;
- }
- return null;
- }).filter((e) => !!e) as INode[];
- const theLast = unitRangesToText(
- cloneSelectionList.map((e) => ({
- range: e.rangeWithCoord,
- unitId: e.rangeWithCoord.unitId ?? '',
- sheetName: getSheetNameById(univerInstanceService, e.rangeWithCoord.unitId ?? '', e.rangeWithCoord.sheetId ?? ''),
- })),
- isSupportAcrossSheet
- )
- .join(matchToken.COMMA);
- const thePre = sequenceNodeToText(newSequenceNodes);
- const result = `${thePre}${(thePre && theLast) ? matchToken.COMMA : ''}${theLast}`;
- const isScaling = isScalingRef.current;
- handleRangeChange(result, isScaling ? -1 : result.length, isEnd);
- };
- const d1 = refSelectionsRenderService.selectionMoveEnd$.subscribe((selections) => {
- handleSelectionsChange(selections, true);
- isScalingRef.current = false;
- if (scalingOptionRef.current) {
- const { result, offset } = scalingOptionRef.current;
- handleRangeChange(result, offset, true);
- scalingOptionRef.current = undefined;
- }
- });
-
- const d2 = refSelectionsRenderService.selectionMoving$.pipe(throttleTime(50)).subscribe((selections) => {
- handleSelectionsChange(selections, false);
- });
-
- return () => {
- d1.unsubscribe();
- d2.unsubscribe();
- };
- }
- }, [isNeed, filterReferenceNodes, refSelectionsRenderService, isSupportAcrossSheet, isOnlyOneRange, handleRangeChange, univerInstanceService, unitId]);
-
- useEffect(() => {
- if (isNeed && refSelectionsRenderService) {
- const disposableCollection = new DisposableCollection();
- const handleSequenceNodeReplace = (token: string, index: number) => {
- let currentIndex = 0;
- let offset = 0;
- let isFinish = false;
- const workbook = univerInstanceService.getUnit<Workbook>(unitId);
- const currentSheetName = workbook?.getActiveSheet()?.getName() || '';
- const newSequenceNodes = filterReferenceNodes.map((node) => {
- if (typeof node === 'string') {
- if (!isFinish) {
- offset += node.length;
- }
- return node;
- } else if (node.nodeType === sequenceNodeType.REFERENCE) {
- const unitRange = deserializeRangeWithSheet(token);
- unitRange.unitId = unitRange.unitId === '' ? unitId : unitRange.unitId;
- unitRange.sheetName = unitRange.sheetName === '' ? currentSheetName : unitRange.sheetName;
- if (currentIndex === index) {
- isFinish = true;
- const cloneNode = { ...node, token };
- if (isSupportAcrossSheet) {
- cloneNode.token = serializeRangeWithSheet(unitRange.sheetName, unitRange.range);
- } else {
- cloneNode.token = serializeRange(unitRange.range);
- }
- currentIndex++;
- offset += cloneNode.token.length;
- return cloneNode;
- }
- currentIndex++;
- if (!isFinish) {
- offset += node.token.length;
- }
- return node;
- }
- return node;
- });
- const result = sequenceNodeToText(newSequenceNodes);
- scalingOptionRef.current = { result, offset };
- handleRangeChange(result, -1, false);
- };
- let time = 0 as any;
- const dispose = refSelectionsRenderService.selectionMoveEnd$.subscribe(() => {
- time = setTimeout(() => {
- disposableCollection.dispose();
- const controls = refSelectionsRenderService.getSelectionControls();
- controls.forEach((control, index) => {
- disposableCollection.add(merge(control.selectionMoving$, control.selectionScaling$).pipe(
- map((e) => {
- return serializeRange(e);
- }),
- distinctUntilChanged()
- ).subscribe((rangeText) => {
- isScalingRef.current = true;
- handleSequenceNodeReplace(rangeText, index);
- }));
- });
- }, 30);
- });
-
- return () => {
- dispose.unsubscribe();
- disposableCollection.dispose();
- clearTimeout(time);
- };
- }
- }, [isNeed, refSelectionsRenderService, filterReferenceNodes, handleRangeChange, univerInstanceService, unitId, isSupportAcrossSheet]);
-};
diff --git a/packages/sheets-formula-ui/src/views/range-selector/hooks/use-verify.ts b/packages/sheets-formula-ui/src/views/range-selector/hooks/use-verify.ts
deleted file mode 100644
index 8467c8fe7e..0000000000
--- a/packages/sheets-formula-ui/src/views/range-selector/hooks/use-verify.ts
+++ /dev/null
@@ -1,46 +0,0 @@
-/**
- * Copyright 2023-present DreamNum Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-import type { IRangeSelectorProps } from '../';
-import type { INode } from './use-formula-token';
-import { useEffect, useRef } from 'react';
-import { sequenceNodeToText } from '../utils/sequence-node-to-text';
-import { verifyRange } from '../utils/verify-range';
-
-export const useVerify = (isNeed: boolean, onVerify: IRangeSelectorProps['onVerify'], sequenceNodes: INode[]) => {
- const isInitRender = useRef(true);
-
- // No validation is performed during the initialization phase.
- useEffect(() => {
- if (isNeed) {
- const time = setTimeout(() => {
- isInitRender.current = false;
- }, 500);
- return () => {
- clearTimeout(time);
- };
- }
- }, [isNeed]);
-
- useEffect(() => {
- if (!isInitRender.current) {
- if (onVerify) {
- const result = verifyRange(sequenceNodes);
- onVerify(result, sequenceNodeToText(sequenceNodes));
- }
- }
- }, [sequenceNodes, onVerify]);
-};
diff --git a/packages/sheets-formula-ui/src/views/range-selector/index.module.less b/packages/sheets-formula-ui/src/views/range-selector/index.module.less
index 902bd64517..ce9d95d8f7 100644
--- a/packages/sheets-formula-ui/src/views/range-selector/index.module.less
+++ b/packages/sheets-formula-ui/src/views/range-selector/index.module.less
@@ -48,6 +48,12 @@
}
&-dialog {
+ max-height: 240px;
+ overflow-y: scroll;
+ scrollbar-color: #73737366 transparent;
+ scrollbar-gutter: stable;
+ scrollbar-width: thin;
+
&-item {
display: flex;
align-items: center;
diff --git a/packages/sheets-formula-ui/src/views/range-selector/index.tsx b/packages/sheets-formula-ui/src/views/range-selector/index.tsx
index cc3b057e8e..63d1ea1f70 100644
--- a/packages/sheets-formula-ui/src/views/range-selector/index.tsx
+++ b/packages/sheets-formula-ui/src/views/range-selector/index.tsx
@@ -14,497 +14,131 @@
* limitations under the License.
*/
-import type { IDisposable, IUnitRangeName } from '@univerjs/core';
-import type { IRichTextEditingMutationParams } from '@univerjs/docs';
-import type { Editor } from '@univerjs/docs-ui';
-import type { ReactNode } from 'react';
-import type { IRefSelection } from './hooks/use-highlight';
-import { BuildTextUtils, createInternalEditorID, generateRandomId, ICommandService, IUniverInstanceService, LocaleService, UniverInstanceType } from '@univerjs/core';
+import type { IUnitRangeName, Nullable } from '@univerjs/core';
+import type { Editor, IRichTextEditorProps } from '@univerjs/docs-ui';
+import type { ISelectionWithStyle, ISetSelectionsOperationParams } from '@univerjs/sheets';
+import { ICommandService, LocaleService, RichTextBuilder } from '@univerjs/core';
import { Button, Dialog, Input, Tooltip } from '@univerjs/design';
-import { RichTextEditingMutation } from '@univerjs/docs';
-import { DocBackScrollRenderController, IEditorService } from '@univerjs/docs-ui';
-import { deserializeRangeWithSheet, LexerTreeBuilder, matchToken, sequenceNodeType } from '@univerjs/engine-formula';
-import { IRenderManagerService } from '@univerjs/engine-render';
+import { IEditorService, RichTextEditor } from '@univerjs/docs-ui';
+import { deserializeRangeWithSheet, LexerTreeBuilder, matchToken, sequenceNodeType, serializeRange, serializeRangeWithSheet } from '@univerjs/engine-formula';
import { CloseSingle, DeleteSingle, IncreaseSingle, SelectRangeSingle } from '@univerjs/icons';
-import { IDescriptionService } from '@univerjs/sheets-formula';
-import { RANGE_SELECTOR_SYMBOLS, SetCellEditVisibleOperation } from '@univerjs/sheets-ui';
-
-import { useDependency, useEvent, useObservable } from '@univerjs/ui';
-import cl from 'clsx';
-
-import React, { useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';
-import { noop, throttleTime } from 'rxjs';
-import { RefSelectionsRenderService } from '../../services/render-services/ref-selections.render-service';
-import { useEditorInput } from './hooks/use-editor-input';
-import { useFirstHighlightDoc } from './hooks/use-first-highlight-doc';
-import { useFocus } from './hooks/use-focus';
-import { useFormulaToken } from './hooks/use-formula-token';
-import { buildTextRuns, useColor, useDocHight, useSheetHighlight } from './hooks/use-highlight';
-import { useLeftAndRightArrow } from './hooks/use-left-and-right-arrow';
-import { useOnlyOneRange } from './hooks/use-only-one-range';
-import { useRefactorEffect } from './hooks/use-refactor-effect';
-import { useRefocus } from './hooks/use-refocus';
-import { useResetSelection } from './hooks/use-reset-selection';
-import { useResize } from './hooks/use-resize';
-import { useSheetSelectionChange } from './hooks/use-sheet-selection-change';
-import { useSwitchSheet } from './hooks/use-switch-sheet';
-import { useVerify } from './hooks/use-verify';
+import { SetSelectionsOperation } from '@univerjs/sheets';
+import { useDependency, useEvent } from '@univerjs/ui';
+import { useEffect, useRef, useState } from 'react';
+import { useStateRef } from '../formula-editor/hooks/use-state-ref';
+import { useRangesHighlight } from './hooks/use-ranges-highlight';
+import { useRangeSelectorSelectionChange } from './hooks/use-selection-change';
import styles from './index.module.less';
+import { verifyRange } from './util';
import { rangePreProcess } from './utils/range-pre-process';
-import { sequenceNodeToText } from './utils/sequence-node-to-text';
-import { unitRangesToText } from './utils/unit-ranges-to-text';
-import { verifyRange } from './utils/verify-range';
-export interface IRangeSelectorProps {
- initValue: string | IUnitRangeName[];
- onChange: (result: string) => void;
+export interface IRangeSelectorInstance {
+ editor: Nullable<Editor>;
+ blur: () => void;
+ focus: () => void;
+ showDialog: (ranges: IUnitRangeName[]) => void;
+ hideDialog: () => void;
+ verify: () => boolean;
+ getValue: () => string;
+}
+
+export interface IRangeSelectorProps extends IRichTextEditorProps {
unitId: string;
subUnitId: string;
- errorText?: string | ReactNode;
- onVerify?: (res: boolean, result: string) => void;
- placeholder?: string;
- isFocus?: boolean;
- onBlur?: () => void;
-
- onFocus?: () => void;
-
- actions?: {
- handleOutClick?: (e: MouseEvent, cb: () => void) => void;
- };
-
- /**
- * 是否只允许最多一个 range 区域,默认为 false。
- * @type {boolean}
- */
- isOnlyOneRange?: boolean;
-
- /**
- * 是否支持跨表选择选区.
- * 如果不支持,那么会舍弃所有的 sheetName 信息
- * @type {boolean}
- * @memberof IRangeSelectorProps
- */
- isSupportAcrossSheet?: boolean;
-
+ maxRangeCount?: number;
+ supportAcrossSheet?: boolean;
+ selectorRef?: React.RefObject<IRangeSelectorInstance | null>;
+ onVerify?: (res: boolean, rangeText: string) => void;
onRangeSelectorDialogVisibleChange?: (visible: boolean) => void;
+ hideEditor?: boolean;
+ forceShowDialogWhenSelectionChanged?: boolean;
+ resetRange?: ISelectionWithStyle[];
};
-const noopFunction = () => { };
-export function RangeSelector(props: IRangeSelectorProps) {
- const {
- initValue,
- unitId,
- subUnitId,
- errorText,
- placeholder,
- actions,
- onChange: propOnChange = noopFunction,
- onVerify = noopFunction,
- onRangeSelectorDialogVisibleChange = noopFunction,
- onBlur = noopFunction,
- onFocus = noopFunction,
- isFocus: _isFocus = true,
- isOnlyOneRange = false,
- isSupportAcrossSheet = false,
- } = props;
- const onChange = useEvent(propOnChange);
- const editorService = useDependency(IEditorService);
- const localeService = useDependency(LocaleService);
- const commandService = useDependency(ICommandService);
- const lexerTreeBuilder = useDependency(LexerTreeBuilder);
- const rangeSelectorWrapRef = useRef<HTMLDivElement>(null);
- const [rangeDialogVisible, rangeDialogVisibleSet] = useState(false);
- const [isFocus, isFocusSet] = useState(_isFocus);
- const editorId = useMemo(() => createInternalEditorID(`${RANGE_SELECTOR_SYMBOLS}-${generateRandomId(4)}`), []);
- const editorRef = useRef<Editor>(undefined);
- const editor = editorRef.current;
- const containerRef = useRef<HTMLDivElement>(null);
- const univerInstanceService = useDependency(IUniverInstanceService);
- const isNeed = useMemo(() => !rangeDialogVisible && isFocus, [rangeDialogVisible, isFocus]);
- const [rangeString, rangeStringSet] = useState(() => {
- if (typeof initValue === 'string') {
- return initValue;
- } else {
- return unitRangesToText(initValue, isSupportAcrossSheet).join(matchToken.COMMA);
- }
- });
- const currentDoc$ = useMemo(() => univerInstanceService.getCurrentTypeOfUnit$(UniverInstanceType.UNIVER_DOC), [univerInstanceService]);
- const currentDoc = useObservable(currentDoc$);
- const docFocusing = currentDoc?.getUnitId() === editorId;
- const refSelections = useRef<IRefSelection[]>([]);
-
- const clickOutside = useEvent((e: MouseEvent, cb: () => void) => {
- if (rangeSelectorWrapRef.current && !rangeDialogVisible) {
- const isContain = rangeSelectorWrapRef.current.contains(e.target as Node);
- !isContain && cb();
- }
- });
-
- // init actions
- if (actions) {
- actions.handleOutClick = clickOutside;
- }
-
- const ranges = useMemo(() => {
- return rangeString.split(matchToken.COMMA).filter((e) => !!e).map((text) => deserializeRangeWithSheet(text));
- }, [rangeString]);
-
- const isError = useMemo(() => errorText !== undefined, [errorText]);
-
- const resetSelection = useResetSelection(!rangeDialogVisible && isFocus, unitId, subUnitId);
-
- const handleInput = useMemo(() => (text: string) => {
- const nodes = lexerTreeBuilder.sequenceNodesBuilder(text);
- if (nodes) {
- const verify = verifyRange(nodes);
- if (verify) {
- const preNodes = nodes.map((node) => {
- if (typeof node === 'string') {
- return node;
- } else if (node.nodeType === sequenceNodeType.REFERENCE) {
- // The 'sequenceNodesBuilder' will cache the results.
- // You Can't modify the reference here. This will cause a cache error
- const cloneNode = { ...node };
- const unitRange = deserializeRangeWithSheet(node.token);
- unitRange.range = rangePreProcess(unitRange.range);
- if (!isSupportAcrossSheet) {
- unitRange.sheetName = '';
- unitRange.unitId = '';
- }
- cloneNode.token = unitRangesToText([unitRange], isSupportAcrossSheet)[0];
- return cloneNode;
- }
- return node;
- });
- const result = sequenceNodeToText(preNodes);
- onChange(result);
- }
- } else {
- rangeStringSet('');
- }
- }, [isSupportAcrossSheet]);
-
- const focus = useFocus(editor);
-
- const { checkScrollBar } = useResize(editor, true, true);
- const getFormulaToken = useFormulaToken();
- const sequenceNodes = useMemo(() => getFormulaToken(rangeString), [rangeString]);
-
- const highlightDoc = useDocHight();
- const highlightSheet = useSheetHighlight(unitId, subUnitId);
- const highligh = useEvent((text: string, isNeedResetSelection: boolean = true, showSelection = true) => {
- if (!editorRef.current) {
- return;
- }
- const sequenceNodes = getFormulaToken(text);
- const ranges = highlightDoc(editorRef.current, sequenceNodes, isNeedResetSelection);
- refSelections.current = ranges;
- if (showSelection) {
- highlightSheet(ranges, editorRef.current);
- }
- });
-
- useEffect(() => {
- const sub = commandService.onCommandExecuted((info) => {
- if (info.id === RichTextEditingMutation.id) {
- const params = info.params as IRichTextEditingMutationParams;
- const { unitId } = params;
- if (unitId === editorId) {
- onChange(BuildTextUtils.transform.getPlainText(editor?.getDocumentData().body?.dataStream ?? ''));
- }
- }
- });
- return () => sub.dispose();
- }, [commandService, editor, editorId, onChange]);
-
- const handleSheetSelectionChange = useEvent((text: string, offset: number, isEnd: boolean) => {
- highligh(text);
- rangeStringSet(text);
- if (isEnd) {
- focus();
- if (offset !== -1) {
- // 在渲染结束之后再设置选区
- setTimeout(() => {
- const range = { startOffset: offset, endOffset: offset };
- editor?.setSelectionRanges([range]);
- const docBackScrollRenderController = editor?.render.with(DocBackScrollRenderController);
- docBackScrollRenderController?.scrollToRange({ ...range, collapsed: true });
- }, 50);
- }
- checkScrollBar();
- }
- });
-
- useSheetSelectionChange(isNeed, unitId, subUnitId, sequenceNodes, isSupportAcrossSheet, isOnlyOneRange, handleSheetSelectionChange);
-
- useRefactorEffect(isNeed, isNeed && docFocusing, unitId);
-
- useOnlyOneRange(unitId, isOnlyOneRange);
-
- useEditorInput(unitId, rangeString, editor);
-
- useVerify(isNeed, onVerify, sequenceNodes);
-
- useLeftAndRightArrow(isNeed, 0, editor);
-
- useRefocus();
-
- useSwitchSheet(isNeed, unitId, isSupportAcrossSheet, isFocusSet, onBlur, () => {
- if (isNeed) {
- highligh(rangeString);
- }
- });
-
- useEffect(() => {
- if (editor) {
- const dispose = editor.input$.pipe(throttleTime(100)).subscribe((e) => {
- const text = (e.data.body?.dataStream ?? '').replaceAll(/\n|\r/g, '').replaceAll(/,{2,}/g, ',').replaceAll(/(^,)/g, '');
- highligh(text, false);
- rangeStringSet(text);
- });
- return () => {
- dispose.unsubscribe();
- };
- }
- }, [editor]);
-
- useEffect(() => {
- const d = commandService.onCommandExecuted((info) => {
- if (info.id === SetCellEditVisibleOperation.id) {
- rangeDialogVisibleSet(false);
- onRangeSelectorDialogVisibleChange(false);
- isFocusSet(false);
- onBlur();
- }
- });
- return () => {
- d.dispose();
- };
- }, [isSupportAcrossSheet]);
-
- useLayoutEffect(() => {
- let dispose: IDisposable;
- if (containerRef.current) {
- dispose = editorService.register({
- autofocus: true,
- editorUnitId: editorId,
- initialSnapshot: {
- id: editorId,
- body: { dataStream: `${rangeString}\r\n`, textRuns: [] },
- documentStyle: {},
- },
- }, containerRef.current);
- const editor = editorService.getEditor(editorId)! as Editor;
- editorRef.current = editor;
- highligh(rangeString, false, false);
- }
- return () => {
- dispose?.dispose();
- };
- }, []);
-
- useLayoutEffect(() => {
- if (_isFocus) {
- isFocusSet(_isFocus);
- focus();
- } else {
- editor?.blur();
- resetSelection();
- isFocusSet(_isFocus);
- }
- }, [_isFocus, focus]);
-
- useFirstHighlightDoc(rangeString, '', isFocus, highlightDoc, highlightSheet, editor);
-
- const handleClick = () => {
- onFocus();
- focus();
- isFocusSet(true);
- };
-
- const handleConfirm = (ranges: IUnitRangeName[]) => {
- const text = unitRangesToText(ranges, isSupportAcrossSheet).join(matchToken.COMMA);
- if (!text) {
- editor?.setDocumentData({ ...editor.getDocumentData(), body: { dataStream: '\r\n', textRuns: [] } });
- }
- highligh(text);
- rangeStringSet(text);
- rangeDialogVisibleSet(false);
- onRangeSelectorDialogVisibleChange(false);
- setTimeout(() => {
- isFocusSet(true);
- editor?.setSelectionRanges([{ startOffset: text.length, endOffset: text.length }]);
- focus();
- checkScrollBar();
- }, 30);
- };
-
- const handleClose = () => {
- rangeDialogVisibleSet(false);
- onRangeSelectorDialogVisibleChange(false);
- setTimeout(() => {
- isFocusSet(true);
- focus();
- }, 30);
- };
-
- const handleOpenModal = () => {
- if (!isError) {
- focus();
- // 从另一个 editor 直接打开的时候,调整下事件监听顺序,确保打开面板的逻辑在 editor 切换之后
- setTimeout(() => {
- rangeDialogVisibleSet(true);
- onRangeSelectorDialogVisibleChange(true);
- isFocusSet(false);
- }, 30);
- }
- };
-
- return (
- <div className={styles.sheetRangeSelector} ref={rangeSelectorWrapRef}>
- <div
- className={cl(styles.sheetRangeSelectorTextWrap, {
- [styles.sheetRangeSelectorActive]: isFocus && !isError,
- [styles.sheetRangeSelectorError]: isError,
- })}
- >
- <div className={styles.sheetRangeSelectorText} ref={containerRef} onMouseUp={handleClick} />
- <Tooltip title={localeService.t('rangeSelector.buttonTooltip')} placement="bottom">
- <SelectRangeSingle className={styles.sheetRangeSelectorIcon} onClick={handleOpenModal} />
- </Tooltip>
- {errorText !== undefined ? <div className={styles.sheetRangeSelectorErrorWrap}>{errorText}</div> : null}
- {(placeholder !== undefined && !rangeString) ? <div className={styles.sheetRangeSelectorPlaceholder}>{placeholder}</div> : null}
- </div>
-
- {rangeDialogVisible && (
- <RangeSelectorDialog
- editorId={editorId}
- handleConfirm={handleConfirm}
- handleClose={handleClose}
- unitId={unitId}
- subUnitId={subUnitId}
- initValue={ranges}
- visible={rangeDialogVisible}
- isOnlyOneRange={isOnlyOneRange}
- isSupportAcrossSheet={isSupportAcrossSheet}
- />
- )}
- </div>
- );
-}
-
-function RangeSelectorDialog(props: {
- editorId: string;
- handleConfirm: (ranges: IUnitRangeName[]) => void;
- handleClose: () => void;
+export interface IRangeSelectorDialogProps {
visible: boolean;
- initValue: IUnitRangeName[];
+ initialValue: IUnitRangeName[];
unitId: string;
subUnitId: string;
- isOnlyOneRange: boolean;
- isSupportAcrossSheet: boolean;
-}) {
- const { handleConfirm, handleClose: _handleClose, visible, initValue, unitId, subUnitId, isOnlyOneRange, isSupportAcrossSheet } = props;
+ maxRangeCount?: number;
+ supportAcrossSheet?: boolean;
+ onConfirm: (ranges: IUnitRangeName[]) => void;
+ onClose: () => void;
+ onShowBySelection?: (ranges: IUnitRangeName[]) => boolean;
+}
+
+export function RangeSelectorDialog(props: IRangeSelectorDialogProps) {
+ const { visible, initialValue, unitId, subUnitId, maxRangeCount = Infinity, supportAcrossSheet, onConfirm, onClose, onShowBySelection } = props;
const localeService = useDependency(LocaleService);
- const descriptionService = useDependency(IDescriptionService);
const lexerTreeBuilder = useDependency(LexerTreeBuilder);
- const renderManagerService = useDependency(IRenderManagerService);
- const render = renderManagerService.getRenderById(unitId);
- const refSelectionsRenderService = render?.with(RefSelectionsRenderService);
+ const [ranges, setRanges] = useState<string[]>([]);
+ const [focusIndex, setFocusIndex] = useState(0);
+ const scrollbarRef = useRef<HTMLDivElement>(null);
- const [ranges, rangesSet] = useState(() => {
- if (isOnlyOneRange) {
- const firstRange = initValue[0];
- if (firstRange) {
- return unitRangesToText([firstRange], isSupportAcrossSheet);
- } else {
- return [''];
- }
+ useEffect(() => {
+ if (visible && initialValue.length) {
+ const newRanges = initialValue.map((range) => range.sheetName ? serializeRangeWithSheet(range.sheetName, range.range) : serializeRange(range.range));
+ setRanges(newRanges);
+ setFocusIndex(newRanges.length - 1);
+ } else {
+ setRanges(['']);
+ setFocusIndex(0);
}
- return unitRangesToText(initValue, isSupportAcrossSheet);
- });
-
- const [focusIndex, focusIndexSet] = useState(() => ranges.length - 1);
-
- const colorMap = useColor();
-
- const rangeText = useMemo(() => ranges.join(matchToken.COMMA), [ranges]);
- const getFormulaToken = useFormulaToken();
- const sequenceNodes = useMemo(() => getFormulaToken(rangeText), [rangeText]);
-
- const refSelections = useMemo(() => buildTextRuns(descriptionService, colorMap, sequenceNodes).refSelections, [sequenceNodes]);
+ }, [visible]);
- const handleClose = () => {
- rangesSet([]);
- setTimeout(() => {
- _handleClose();
- }, 30);
- };
const handleRangeInput = (index: number, value: string) => {
- if (!value) {
- refSelectionsRenderService?.setSkipLastEnabled(true);
- } else {
- refSelectionsRenderService?.setSkipLastEnabled(false);
- }
- rangesSet((v) => {
- const result = [...v];
- result[index] = value;
- return result;
- });
+ const newRanges = [...ranges];
+ newRanges[index] = value;
+ setRanges(newRanges);
+ };
+ const handleRangeAdd = () => {
+ setRanges([...ranges, '']);
+ setFocusIndex(ranges.length);
};
const handleRangeRemove = (index: number) => {
- refSelectionsRenderService?.setSkipLastEnabled(false);
- rangesSet((v) => {
- if (v.length === 1) {
- return v;
- }
- const result: string[] = [];
- v.forEach((r, i) => {
- if (index !== i) {
- result.push(r);
- }
- });
- return result;
- });
+ ranges.splice(index, 1);
+ setRanges([...ranges]);
};
- const handleRangeAdd = () => {
- refSelectionsRenderService?.setSkipLastEnabled(true);
- rangesSet((v) => {
- v.push('');
- focusIndexSet(v.length - 1);
- return [...v];
- });
- };
+ useRangeSelectorSelectionChange({
+ unitId,
+ subUnitId,
+ supportAcrossSheet,
+ onChange: (selections, isStart) => {
+ if (!visible) {
+ if (onShowBySelection?.(selections)) {
+ return;
+ }
+ }
+ const current = new Set(ranges);
+ const addedRangesOrigin = selections.map((range) => !range.sheetName ? serializeRange(range.range) : serializeRangeWithSheet(range.sheetName, range.range));
+ const addedRanges = addedRangesOrigin.filter((item) => !current.has(item));
+ if (!addedRanges.length) return;
+ const newRanges = [...ranges];
+
+ if (addedRangesOrigin.length > 1) {
+ if (!isStart) {
+ newRanges.splice(focusIndex, 1);
+ }
- const handleSheetSelectionChange = useEvent((rangeText: string) => {
- refSelectionsRenderService?.setSkipLastEnabled(false);
- const ranges = rangeText.split(matchToken.COMMA).filter((e) => !!e);
- if (isOnlyOneRange) {
- rangesSet([ranges[0] ?? '']);
- } else {
- rangesSet(ranges);
- }
+ newRanges.push(...addedRanges);
+ const finalRanges = newRanges.slice(0, maxRangeCount);
+ setRanges(finalRanges);
+ setFocusIndex(finalRanges.length - 1);
+ requestAnimationFrame(() => {
+ scrollbarRef.current?.scrollTo({ top: scrollbarRef.current.scrollHeight });
+ });
+ } else {
+ // modify
+ newRanges.splice(focusIndex, 1, ...addedRanges);
+ const finalRanges = newRanges.slice(0, maxRangeCount);
+ setRanges(finalRanges);
+ setFocusIndex(focusIndex + addedRanges.length - 1);
+ }
+ },
});
- const highlightSheet = useSheetHighlight(unitId, subUnitId);
- useSheetSelectionChange(focusIndex >= 0, unitId, subUnitId, sequenceNodes, isSupportAcrossSheet, isOnlyOneRange, handleSheetSelectionChange);
- useRefactorEffect(focusIndex >= 0, focusIndex >= 0, unitId);
- useOnlyOneRange(unitId, isOnlyOneRange);
- useSwitchSheet(focusIndex >= 0, unitId, isSupportAcrossSheet, noop, noop, () => highlightSheet(refSelections));
-
- useEffect(() => {
- highlightSheet(refSelections);
- }, [refSelections]);
-
- // 如果只有一个空 range,那么默认自动添加 range
- useEffect(() => {
- if (ranges.length === 0 || (ranges.length === 1 && !ranges[0])) {
- refSelectionsRenderService?.setSkipLastEnabled(true);
- }
- }, [ranges]);
-
return (
<Dialog
width="328px"
@@ -514,38 +148,42 @@ function RangeSelectorDialog(props: {
closeIcon={<CloseSingle />}
footer={(
<footer>
- <Button onClick={handleClose}>{localeService.t('rangeSelector.cancel')}</Button>
+ <Button onClick={onClose}>{localeService.t('rangeSelector.cancel')}</Button>
<Button
style={{ marginLeft: 10 }}
- onClick={() => handleConfirm(ranges.filter((text) => {
- const nodes = lexerTreeBuilder.sequenceNodesBuilder(text);
- return nodes && nodes.length === 1 && typeof nodes[0] !== 'string' && nodes[0].nodeType === sequenceNodeType.REFERENCE;
- }).map((text) => deserializeRangeWithSheet(text)).map((unitRange) => ({ ...unitRange, range: rangePreProcess(unitRange.range) })))}
+ onClick={() => {
+ onConfirm(
+ ranges
+ .filter((text) => {
+ const nodes = lexerTreeBuilder.sequenceNodesBuilder(text);
+ return nodes && nodes.length === 1 && typeof nodes[0] !== 'string' && nodes[0].nodeType === sequenceNodeType.REFERENCE;
+ })
+ .map((text) => deserializeRangeWithSheet(text)).map((unitRange) => ({ ...unitRange, range: rangePreProcess(unitRange.range) }))
+ );
+ }}
type="primary"
>
{localeService.t('rangeSelector.confirm')}
</Button>
</footer>
)}
- onClose={handleClose}
+ onClose={onClose}
>
- <div className={styles.sheetRangeSelectorDialog}>
+ <div ref={scrollbarRef} className={styles.sheetRangeSelectorDialog}>
{ranges.map((text, index) => (
- <div key={`${text}_${index}`} className={styles.sheetRangeSelectorDialogItem}>
+ <div key={index} className={styles.sheetRangeSelectorDialogItem}>
<Input
affixWrapperStyle={{ width: '100%' }}
placeholder={localeService.t('rangeSelector.placeHolder')}
- key={`input_${index}`}
- onFocus={() => focusIndexSet(index)}
+ onFocus={() => setFocusIndex(index)}
value={text}
onChange={(value) => handleRangeInput(index, value)}
+ style={{ borderColor: focusIndex === index ? 'rgb(var(--primary-color))' : undefined }}
/>
- {ranges.length > 1 && !isOnlyOneRange && <DeleteSingle className={styles.sheetRangeSelectorDialogItemDelete} onClick={() => handleRangeRemove(index)} />}
-
+ {ranges.length > 1 && <DeleteSingle className={styles.sheetRangeSelectorDialogItemDelete} onClick={() => handleRangeRemove(index)} />}
</div>
))}
-
- {!isOnlyOneRange && (
+ {ranges.length < maxRangeCount && (
<div>
<Button type="link" size="small" onClick={handleRangeAdd}>
<IncreaseSingle />
@@ -554,7 +192,162 @@ function RangeSelectorDialog(props: {
</div>
)}
</div>
-
</Dialog>
);
}
+
+export function parseRanges(rangeString: string) {
+ return rangeString.split(matchToken.COMMA).filter((e) => !!e).map((text) => deserializeRangeWithSheet(text));
+}
+
+export function stringifyRanges(ranges: IUnitRangeName[]) {
+ return ranges
+ .map((range) => range.sheetName ? serializeRangeWithSheet(range.sheetName, range.range) : serializeRange(range.range))
+ .join(matchToken.COMMA);
+}
+
+export function RangeSelector(props: IRangeSelectorProps) {
+ const [editor, setEditor] = useState<Editor | null>(null);
+ const {
+ onVerify,
+ selectorRef,
+ unitId,
+ subUnitId,
+ maxRangeCount,
+ supportAcrossSheet,
+ autoFocus,
+ onChange,
+ onRangeSelectorDialogVisibleChange,
+ onClickOutside,
+ onFocusChange,
+ forceShowDialogWhenSelectionChanged,
+ hideEditor,
+ resetRange,
+ } = props;
+ const [focusing, setFocusing] = useState(autoFocus ?? false);
+ const [popupVisible, setPopupVisible] = useState(false);
+ const [rangeSelectorRanges, setRangeSelectorRanges] = useState<IUnitRangeName[]>([]);
+ const localeService = useDependency(LocaleService);
+ const editorService = useDependency(IEditorService);
+ const { sequenceNodes } = useRangesHighlight(editor, focusing, unitId, subUnitId);
+ const sequenceNodesRef = useStateRef(sequenceNodes);
+ const commandService = useDependency(ICommandService);
+
+ const blurEditor = useEvent(() => {
+ editor?.setSelectionRanges([]);
+ editor?.blur();
+ editorService.blur();
+ });
+
+ const handleOpenModal = useEvent(() => {
+ blurEditor();
+ setRangeSelectorRanges(parseRanges(editor?.getDocumentDataModel().getPlainText() ?? ''));
+ setPopupVisible(true);
+ });
+
+ useEffect(() => {
+ if (!selectorRef) return;
+ selectorRef.current = {
+ get editor() {
+ return editor;
+ },
+ focus() {
+ editorService.focus(editor!.getEditorId());
+ },
+ blur: blurEditor,
+ verify: () => verifyRange(sequenceNodesRef.current),
+ showDialog: (ranges) => {
+ blurEditor();
+ setRangeSelectorRanges(ranges);
+ setPopupVisible(true);
+ },
+ hideDialog: () => {
+ setRangeSelectorRanges([]);
+ setPopupVisible(false);
+ },
+ getValue: () => editor?.getDocumentDataModel().getPlainText() ?? '',
+ };
+ }, [blurEditor, editor, editorService, selectorRef, sequenceNodesRef]);
+
+ useEffect(() => {
+ onVerify?.(verifyRange(sequenceNodes), editor?.getDocumentDataModel().getPlainText() ?? '');
+ }, [sequenceNodes]);
+
+ useEffect(() => {
+ onRangeSelectorDialogVisibleChange?.(popupVisible);
+ }, [popupVisible]);
+
+ useEffect(() => {
+ if (popupVisible && resetRange) {
+ return () => {
+ const params: ISetSelectionsOperationParams = {
+ unitId,
+ subUnitId,
+ selections: resetRange,
+ };
+ commandService.executeCommand(SetSelectionsOperation.id, params);
+ };
+ }
+ }, [popupVisible]);
+
+ return (
+ <>
+ {!hideEditor
+ ? (
+ <RichTextEditor
+ isSingle
+ {...props}
+ onFocusChange={(focusing, newValue) => {
+ setFocusing(focusing);
+ onFocusChange?.(focusing, newValue);
+ }}
+ editorRef={setEditor}
+ onClickOutside={() => {
+ setFocusing(false);
+ blurEditor();
+ onClickOutside?.();
+ }}
+ icon={(
+ <Tooltip title={localeService.t('rangeSelector.buttonTooltip')} placement="bottom">
+ <SelectRangeSingle className={styles.sheetRangeSelectorIcon} onClick={handleOpenModal} />
+ </Tooltip>
+ )}
+ />
+ )
+ : null}
+ <RangeSelectorDialog
+ initialValue={rangeSelectorRanges}
+ unitId={unitId}
+ subUnitId={subUnitId}
+ visible={popupVisible}
+ maxRangeCount={maxRangeCount}
+ onConfirm={(ranges) => {
+ const resultStr = stringifyRanges(ranges);
+ const empty = RichTextBuilder.newEmptyData();
+ empty.body!.dataStream = resultStr;
+ editor?.replaceText(resultStr, false);
+ onChange?.(empty, resultStr);
+ setPopupVisible(false);
+ setRangeSelectorRanges([]);
+ requestAnimationFrame(() => {
+ blurEditor();
+ });
+ }}
+ onClose={() => {
+ setPopupVisible(false);
+ setRangeSelectorRanges([]);
+ }}
+ supportAcrossSheet={supportAcrossSheet}
+ onShowBySelection={(ranges: IUnitRangeName[]) => {
+ if (focusing || forceShowDialogWhenSelectionChanged) {
+ setRangeSelectorRanges(ranges);
+ setPopupVisible(true);
+ return false;
+ } else {
+ return true;
+ }
+ }}
+ />
+ </>
+ );
+}
diff --git a/packages/sheets-formula-ui/src/views/range-selector/util.ts b/packages/sheets-formula-ui/src/views/range-selector/util.ts
new file mode 100644
index 0000000000..d8961bea0a
--- /dev/null
+++ b/packages/sheets-formula-ui/src/views/range-selector/util.ts
@@ -0,0 +1,38 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { ISequenceNode } from '@univerjs/engine-formula';
+import { matchToken, sequenceNodeType } from '@univerjs/engine-formula';
+
+/**
+ * @param {((string | ISequenceNode)[])} sequenceNodes
+ * @return {*}
+ */
+export const verifyRange = (sequenceNodes: (string | ISequenceNode)[]) => {
+ const isFail = sequenceNodes.some((item) => {
+ if (typeof item === 'string') {
+ if (item !== matchToken.COMMA) {
+ return true;
+ }
+ } else {
+ if (item.nodeType !== sequenceNodeType.REFERENCE) {
+ return true;
+ }
+ }
+ return false;
+ });
+ return !isFail;
+};
diff --git a/packages/sheets-formula/src/index.ts b/packages/sheets-formula/src/index.ts
index 5c2c129308..7c2407a196 100644
--- a/packages/sheets-formula/src/index.ts
+++ b/packages/sheets-formula/src/index.ts
@@ -20,7 +20,7 @@ export { UpdateDefinedNameController } from './controllers/update-defined-name.c
export { TriggerCalculationController } from './controllers/trigger-calculation.controller';
export { CalculationMode, type IUniverSheetsFormulaBaseConfig, PLUGIN_CONFIG_KEY_BASE } from './controllers/config.schema';
export type { IRegisterAsyncFunction, IRegisterFunction, ISingleFunctionRegisterParams } from './services/register-function.service';
-
+export { calculateFormula } from './util/calculate';
// #region - all commands
export { UpdateFormulaController } from './controllers/update-formula.controller';
diff --git a/packages/sheets-formula/src/util/calculate.ts b/packages/sheets-formula/src/util/calculate.ts
new file mode 100644
index 0000000000..ab319afef9
--- /dev/null
+++ b/packages/sheets-formula/src/util/calculate.ts
@@ -0,0 +1,46 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { Injector } from '@univerjs/core';
+import type { BaseAstNode, ISheetData, LexerNode } from '@univerjs/engine-formula';
+import { AstTreeBuilder, generateExecuteAstNodeData, getObjectValue, IFormulaCurrentConfigService, Interpreter, Lexer } from '@univerjs/engine-formula';
+
+export function calculateFormula(inject: Injector, formulaString: string, unitId: string, sheetData: ISheetData) {
+ const formulaCurrentConfigService = inject.get(IFormulaCurrentConfigService);
+ const lexer = inject.get(Lexer);
+ const astTreeBuilder = inject.get(AstTreeBuilder);
+ const interpreter = inject.get(Interpreter);
+ formulaCurrentConfigService.load({
+ formulaData: {},
+ arrayFormulaCellData: {},
+ arrayFormulaRange: {},
+ forceCalculate: false,
+ dirtyRanges: [],
+ dirtyNameMap: {},
+ dirtyDefinedNameMap: {},
+ dirtyUnitFeatureMap: {},
+ excludedCell: {},
+ allUnitData: {
+ [unitId]: sheetData,
+ },
+ dirtyUnitOtherFormulaMap: {},
+ });
+
+ const lexerNode = lexer.treeBuilder(formulaString);
+ const astNode = astTreeBuilder.parse(lexerNode as LexerNode);
+ const result = interpreter.execute(generateExecuteAstNodeData(astNode as BaseAstNode));
+ return getObjectValue(result);
+}
diff --git a/packages/sheets-hyper-link-ui/src/services/popup.service.ts b/packages/sheets-hyper-link-ui/src/services/popup.service.ts
index 086612b6d0..7d101670ea 100644
--- a/packages/sheets-hyper-link-ui/src/services/popup.service.ts
+++ b/packages/sheets-hyper-link-ui/src/services/popup.service.ts
@@ -15,12 +15,13 @@
*/
import type { DocumentDataModel, ICustomRange, IDisposable, INeedCheckDisposable, ITextRange, Nullable, Workbook } from '@univerjs/core';
+import type { IBoundRectNoAngle } from '@univerjs/engine-render';
import type { ISheetLocationBase } from '@univerjs/sheets';
import type { ICanvasPopup } from '@univerjs/sheets-ui';
import { BuildTextUtils, CustomRangeType, Disposable, DOCS_NORMAL_EDITOR_UNIT_ID_KEY, DOCS_ZEN_EDITOR_UNIT_ID_KEY, Inject, Injector, IUniverInstanceService, UniverInstanceType } from '@univerjs/core';
import { DocSelectionManagerService } from '@univerjs/docs';
import { calcDocRangePositions, DocCanvasPopManagerService } from '@univerjs/docs-ui';
-import { type IBoundRectNoAngle, IRenderManagerService } from '@univerjs/engine-render';
+import { IRenderManagerService } from '@univerjs/engine-render';
import { getCustomRangePosition, getEditingCustomRangePosition, IEditorBridgeService, SheetCanvasPopManagerService } from '@univerjs/sheets-ui';
import { IZenZoneService } from '@univerjs/ui';
import { BehaviorSubject, Subject } from 'rxjs';
@@ -249,14 +250,10 @@ export class SheetsHyperLinkPopupService extends Disposable {
componentKey: CellLinkEdit.componentKey,
direction: 'vertical',
onClickOutside: () => {
- if (!this.getIsKeepVisible()) {
- this.endEditing();
- }
+ this.endEditing();
},
onContextMenu: () => {
- if (!this.getIsKeepVisible()) {
- this.endEditing();
- }
+ this.endEditing();
},
hiddenType: 'hide',
};
@@ -420,6 +417,9 @@ export class SheetsHyperLinkPopupService extends Disposable {
}
endEditing(type?: HyperLinkEditSourceType) {
+ if (this.getIsKeepVisible()) {
+ return;
+ }
const current = this._currentEditing$.getValue();
if (current && (!type || type === current.type)) {
this._currentEditingPopup?.dispose();
diff --git a/packages/sheets-hyper-link-ui/src/views/CellLinkEdit/index.tsx b/packages/sheets-hyper-link-ui/src/views/CellLinkEdit/index.tsx
index 7a515cbb2c..d242f1f624 100644
--- a/packages/sheets-hyper-link-ui/src/views/CellLinkEdit/index.tsx
+++ b/packages/sheets-hyper-link-ui/src/views/CellLinkEdit/index.tsx
@@ -15,14 +15,14 @@
*/
import type { DocumentDataModel, Nullable, Workbook } from '@univerjs/core';
-import type { ISetSelectionsOperationParams } from '@univerjs/sheets';
+import type { ISelectionWithStyle, ISetSelectionsOperationParams } from '@univerjs/sheets';
import { BuildTextUtils, ColorKit, CustomRangeType, DataStreamTreeTokenType, DisposableCollection, DOCS_ZEN_EDITOR_UNIT_ID_KEY, FOCUSING_SHEET, generateRandomId, ICommandService, IContextService, isValidRange, IUniverInstanceService, LocaleService, ThemeService, Tools, UniverInstanceType } from '@univerjs/core';
import { Button, FormLayout, Input, Select } from '@univerjs/design';
import { DocSelectionManagerService } from '@univerjs/docs';
import { DocBackScrollRenderController, DocSelectionRenderService } from '@univerjs/docs-ui';
import { deserializeRangeWithSheet, IDefinedNamesService, serializeRange, serializeRangeToRefString, serializeRangeWithSheet } from '@univerjs/engine-formula';
import { IRenderManagerService } from '@univerjs/engine-render';
-import { SetSelectionsOperation, SetWorksheetActiveOperation } from '@univerjs/sheets';
+import { SetSelectionsOperation, SetWorksheetActiveOperation, SheetsSelectionsService } from '@univerjs/sheets';
import { RangeSelector } from '@univerjs/sheets-formula-ui';
import { AddHyperLinkCommand, AddRichHyperLinkCommand, SheetHyperLinkType, SheetsHyperLinkParserService, UpdateHyperLinkCommand, UpdateRichHyperLinkCommand } from '@univerjs/sheets-hyper-link';
import { IEditorBridgeService, IMarkSelectionService, ScrollToRangeOperation } from '@univerjs/sheets-ui';
@@ -62,8 +62,9 @@ export const CellLinkEdit = () => {
const contextService = useDependency(IContextService);
const themeService = useDependency(ThemeService);
const docSelectionManagerService = useDependency(DocSelectionManagerService);
-
- const rangeSelectorActionsRef = useRef<Parameters<typeof RangeSelector>[0]['actions']>({});
+ const [selectorDialogVisible, setSelectorDialogVisible] = useState(false);
+ const sheetsSelectionService = useDependency(SheetsSelectionsService);
+ const selections = useMemo(() => sheetsSelectionService.getCurrentSelections(), []);
const customHyperLinkSidePanel = useMemo(() => {
if (sidePanelService.isBuiltInLinkType(type)) {
@@ -252,11 +253,15 @@ export const CellLinkEdit = () => {
}, [editing?.type, editorBridgeService, renderManagerService]);
useEffect(() => {
- popupService.setIsKeepVisible(isFocusRangeSelector);
+ if (isFocusRangeSelector) {
+ popupService.setIsKeepVisible(isFocusRangeSelector);
+ }
+ popupService.setIsKeepVisible(selectorDialogVisible);
+
return () => {
popupService.setIsKeepVisible(false);
};
- }, [isFocusRangeSelector, popupService]);
+ }, [isFocusRangeSelector, selectorDialogVisible, popupService]);
useEffect(() => {
return () => {
@@ -405,20 +410,13 @@ export const CellLinkEdit = () => {
commandService.executeCommand(CloseHyperLinkPopupOperation.id);
};
- const handlePanelClick = (e: React.MouseEvent<HTMLDivElement, MouseEvent>) => {
- if (type !== SheetHyperLinkType.RANGE) {
- return;
- }
- const handleOutClick = rangeSelectorActionsRef.current?.handleOutClick;
- handleOutClick && handleOutClick(e as unknown as MouseEvent, () => isFocusRangeSelectorSet(false));
- };
if (!editing) {
return null;
}
return (
- <div className={styles.cellLinkEdit} style={{ display: hide ? 'none' : 'block' }} onClick={handlePanelClick}>
+ <div className={styles.cellLinkEdit} style={{ display: hide ? 'none' : 'block' }}>
{showLabel
? (
<FormLayout
@@ -480,14 +478,13 @@ export const CellLinkEdit = () => {
<RangeSelector
unitId={workbook.getUnitId()}
subUnitId={subUnitId}
- isOnlyOneRange
- isSupportAcrossSheet
- initValue={payload}
- onChange={handleRangeChange}
- isFocus={isFocusRangeSelector}
- onFocus={() => isFocusRangeSelectorSet(true)}
- actions={rangeSelectorActionsRef.current}
+ maxRangeCount={1}
+ supportAcrossSheet
+ initialValue={payload}
+ resetRange={selections as ISelectionWithStyle[]}
+ onChange={(_, text) => handleRangeChange(text)}
onRangeSelectorDialogVisibleChange={async (visible) => {
+ setSelectorDialogVisible(visible);
if (visible) {
if (editing.type === HyperLinkEditSourceType.ZEN_EDITOR) {
zenZoneService.hide();
@@ -520,6 +517,7 @@ export const CellLinkEdit = () => {
setHide(false);
}
}}
+ onFocusChange={(focus) => isFocusRangeSelectorSet(focus)}
/>
</FormLayout>
)}
diff --git a/packages/sheets-ui/src/basics/editor/range.ts b/packages/sheets-ui/src/basics/editor/range.ts
new file mode 100644
index 0000000000..d2e469231c
--- /dev/null
+++ b/packages/sheets-ui/src/basics/editor/range.ts
@@ -0,0 +1,36 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { Nullable } from '@univerjs/core';
+import type { Editor, IRichTextEditorProps } from '@univerjs/docs-ui';
+
+export interface IRangeSelectorInstance {
+ editor: Nullable<Editor>;
+ blur: () => void;
+ focus: () => void;
+ changePopupVisible: (visible: boolean) => void;
+ verify: () => boolean;
+}
+
+export interface IRangeSelectorProps extends IRichTextEditorProps {
+ unitId: string;
+ subUnitId: string;
+ maxRangeCount?: number;
+ supportAcrossSheet?: boolean;
+ selectorRef?: React.RefObject<IRangeSelectorInstance>;
+ onVerify?: (res: boolean, rangeText: string) => void;
+ onRangeSelectorDialogVisibleChange?: (visible: boolean) => void;
+};
diff --git a/packages/sheets-ui/src/commands/commands/set-selection.command.ts b/packages/sheets-ui/src/commands/commands/set-selection.command.ts
index 70f038e472..31b54222a6 100644
--- a/packages/sheets-ui/src/commands/commands/set-selection.command.ts
+++ b/packages/sheets-ui/src/commands/commands/set-selection.command.ts
@@ -363,7 +363,7 @@ export const ExpandSelectionCommand: ICommand<IExpandSelectionCommandParams> = {
return accessor.get(ICommandService).syncExecuteCommand(SetSelectionsOperation.id, {
unitId,
subUnitId,
- type: SelectionMoveType.ONLY_SET,
+ type: SelectionMoveType.MOVE_END,
selections: [
{
range: destRange,
@@ -371,6 +371,7 @@ export const ExpandSelectionCommand: ICommand<IExpandSelectionCommandParams> = {
},
],
extra,
+ reveal: true,
});
},
};
diff --git a/packages/sheets-ui/src/views/defined-name/DefinedNameInput.tsx b/packages/sheets-ui/src/views/defined-name/DefinedNameInput.tsx
index 343ad3ec4c..ba005b5236 100644
--- a/packages/sheets-ui/src/views/defined-name/DefinedNameInput.tsx
+++ b/packages/sheets-ui/src/views/defined-name/DefinedNameInput.tsx
@@ -16,6 +16,7 @@
import type { Nullable, Workbook } from '@univerjs/core';
import type { IDefinedNamesServiceParam } from '@univerjs/engine-formula';
+import type { IRangeSelectorProps } from '../../basics/editor/range';
import { AbsoluteRefType, IUniverInstanceService, LocaleService, Tools, UniverInstanceType } from '@univerjs/core';
import { Button, Input, Radio, RadioGroup, Select } from '@univerjs/design';
import { IDefinedNamesService, IFunctionService, isReferenceStrings, isReferenceStringWithEffectiveColumn, LexerTreeBuilder, operatorToken } from '@univerjs/engine-formula';
@@ -63,7 +64,7 @@ export const DefinedNameInput = (props: IDefinedNameInputProps) => {
const lexerTreeBuilder = useDependency(LexerTreeBuilder);
const componentManager = useDependency(ComponentManager);
- const RangeSelector = useMemo(() => componentManager.get(RANGE_SELECTOR_COMPONENT_KEY), []);
+ const RangeSelector: React.ComponentType<IRangeSelectorProps> = useMemo(() => componentManager.get(RANGE_SELECTOR_COMPONENT_KEY), []) as any;
const FormulaEditor = useMemo(() => componentManager.get(EMBEDDING_FORMULA_EDITOR_COMPONENT_KEY), []);
if (workbook == null) {
return;
@@ -87,9 +88,6 @@ export const DefinedNameInput = (props: IDefinedNameInputProps) => {
const [validFormulaOrRange, setValidFormulaOrRange] = useState(true);
- const rangeSelectorActionsRef = useRef<any>({});
- const [isFocusRangeSelector, isFocusRangeSelectorSet] = useState(false);
-
const options = [{
label: localeService.t('definedName.scopeWorkbook'),
value: SCOPE_WORKBOOK_VALUE_DEFINED_NAME,
@@ -99,10 +97,6 @@ export const DefinedNameInput = (props: IDefinedNameInputProps) => {
return !isReferenceStrings(token);
};
- useEffect(() => {
- isFocusRangeSelectorSet(false);
- }, [subUnitId]);
-
useEffect(() => {
setValidFormulaOrRange(true);
setNameValue(name);
@@ -210,11 +204,6 @@ export const DefinedNameInput = (props: IDefinedNameInputProps) => {
const formulaEditorActionsRef = useRef<any>({});
const [isFocusFormulaEditor, isFocusFormulaEditorSet] = useState(false);
- useSidebarClick((e: MouseEvent) => {
- const handleOutClick = rangeSelectorActionsRef.current?.handleOutClick;
- handleOutClick && handleOutClick(e, () => isFocusRangeSelectorSet(false));
- });
-
useSidebarClick((e: MouseEvent) => {
const handleOutClick = formulaEditorActionsRef.current?.handleOutClick;
handleOutClick && handleOutClick(e, () => isFocusFormulaEditorSet(false));
@@ -237,12 +226,10 @@ export const DefinedNameInput = (props: IDefinedNameInputProps) => {
<RangeSelector
unitId={unitId}
subUnitId={subUnitId}
- initValue={formulaOrRefStringValue}
- onChange={rangeSelectorChange}
- isFocus={isFocusRangeSelector}
- onFocus={() => isFocusRangeSelectorSet(true)}
- actions={rangeSelectorActionsRef.current}
- isSupportAcrossSheet
+ initialValue={formulaOrRefStringValue}
+ onChange={(_, text) => rangeSelectorChange(text)}
+
+ supportAcrossSheet
/>
)
)
@@ -278,9 +265,10 @@ export const DefinedNameInput = (props: IDefinedNameInputProps) => {
<ErrorSingle />
</div>
<div>
- <Button onClick={() => {
- cancel && cancel();
- }}
+ <Button
+ onClick={() => {
+ cancel && cancel();
+ }}
>
{localeService.t('definedName.cancel')}
</Button>
diff --git a/packages/sheets-ui/src/views/permission/panel-detail/PermissionDetailMainPart.tsx b/packages/sheets-ui/src/views/permission/panel-detail/PermissionDetailMainPart.tsx
index 4fabc89582..711a8f3c8d 100644
--- a/packages/sheets-ui/src/views/permission/panel-detail/PermissionDetailMainPart.tsx
+++ b/packages/sheets-ui/src/views/permission/panel-detail/PermissionDetailMainPart.tsx
@@ -15,6 +15,7 @@
*/
import type { IRange, Workbook } from '@univerjs/core';
+import type { IRangeSelectorProps } from '../../../basics/editor/range';
import { Injector, isValidRange, IUniverInstanceService, LocaleService, UniverInstanceType } from '@univerjs/core';
import { FormLayout, Input } from '@univerjs/design';
import { deserializeRangeWithSheet, serializeRange } from '@univerjs/engine-formula';
@@ -29,18 +30,15 @@ interface IPermissionDetailMainPartProps {
permissionId: string;
ranges: IRange[];
onRangesChange: (ranges: IRange[], err?: string) => void;
- isFocusRangeSelector: boolean;
rangesErrMsg?: string;
desc?: string;
onDescChange: (desc: string) => void;
- rangeSelectorRef: React.MutableRefObject<any>;
- onFocus: () => void;
}
export const PermissionDetailMainPart = (props: IPermissionDetailMainPartProps) => {
- const { ranges, onRangesChange, rangeSelectorRef, desc, onDescChange, rangesErrMsg, isFocusRangeSelector, permissionId, onFocus } = props;
+ const { ranges, onRangesChange, desc, onDescChange, rangesErrMsg, permissionId } = props;
const componentManager = useDependency(ComponentManager);
- const RangeSelector = useMemo(() => componentManager.get(RANGE_SELECTOR_COMPONENT_KEY), []);
+ const RangeSelector: React.ComponentType<IRangeSelectorProps> = useMemo(() => componentManager.get(RANGE_SELECTOR_COMPONENT_KEY), []) as any;
const univerInstanceService = useDependency(IUniverInstanceService);
const localeService = useDependency(LocaleService);
const injector = useDependency(Injector);
@@ -78,17 +76,17 @@ export const PermissionDetailMainPart = (props: IPermissionDetailMainPartProps)
return (
<>
- <FormLayout className={styles.sheetPermissionPanelTitle} label={localeService.t('permission.panel.protectedRange')}>
+ <FormLayout
+ className={styles.sheetPermissionPanelTitle}
+ label={localeService.t('permission.panel.protectedRange')}
+ error={rangesErrMsg}
+ >
{RangeSelector && (
<RangeSelector
unitId={unitId}
- errorText={rangesErrMsg}
subUnitId={subUnitId}
- initValue={ranges?.map((i) => serializeRange(i)).join(',')}
- onChange={handleRangeChange}
- onFocus={onFocus}
- isFocus={isFocusRangeSelector}
- actions={rangeSelectorRef.current}
+ initialValue={ranges?.map((i) => serializeRange(i)).join(',')}
+ onChange={(_, text) => handleRangeChange(text)}
/>
)}
</FormLayout>
diff --git a/packages/sheets-ui/src/views/permission/panel-detail/PermissionDetailPanel.tsx b/packages/sheets-ui/src/views/permission/panel-detail/PermissionDetailPanel.tsx
index 1d2cf77ccf..198e5d1dfd 100644
--- a/packages/sheets-ui/src/views/permission/panel-detail/PermissionDetailPanel.tsx
+++ b/packages/sheets-ui/src/views/permission/panel-detail/PermissionDetailPanel.tsx
@@ -18,8 +18,8 @@ import type { IRange, Workbook } from '@univerjs/core';
import type { IPermissionPanelRule } from '../../../services/permission/sheet-permission-panel.model';
import { Injector, IUniverInstanceService, UniverInstanceType } from '@univerjs/core';
import { EditStateEnum, ViewStateEnum } from '@univerjs/sheets';
-import { ComponentContainer, ISidebarService, useComponentsOfPart, useDependency, useSidebarClick } from '@univerjs/ui';
-import React, { useEffect, useRef, useState } from 'react';
+import { ComponentContainer, ISidebarService, useComponentsOfPart, useDependency } from '@univerjs/ui';
+import React, { useEffect, useState } from 'react';
import { UNIVER_SHEET_PERMISSION_USER_PART } from '../../../consts/permission';
import { checkRangeValid, generateDefaultRule, generateRuleByUnitType } from '../util';
import styles from './index.module.less';
@@ -44,14 +44,6 @@ export const SheetPermissionPanelDetail = (props: ISheetPermissionPanelDetailPro
const [desc, setDesc] = useState<string | undefined>(activeRule.description);
const [editState, setEditState] = useState<EditStateEnum>(activeRule.editState ?? EditStateEnum.OnlyMe);
const [viewState, setViewState] = useState<ViewStateEnum>(activeRule.viewState ?? ViewStateEnum.OthersCanView);
- const rangeSelectorActionsRef = useRef<any>({});
- const [isFocusRangeSelector, isFocusRangeSelectorSet] = useState(false);
-
- useSidebarClick((e: MouseEvent) => {
- const handleOutClick = rangeSelectorActionsRef.current?.handleOutClick;
- handleOutClick && handleOutClick(e, () => isFocusRangeSelectorSet(false));
- });
-
const PermissionDetailUserPart = useComponentsOfPart(UNIVER_SHEET_PERMISSION_USER_PART);
useEffect(() => {
@@ -73,18 +65,15 @@ export const SheetPermissionPanelDetail = (props: ISheetPermissionPanelDetailPro
return (
<div className={styles.permissionPanelDetailWrapper}>
<PermissionDetailMainPart
- onFocus={() => isFocusRangeSelectorSet(true)}
permissionId={activeRule.permissionId}
ranges={ranges}
onRangesChange={(v: IRange[], err?: string) => {
setRanges(v);
setRangesErrMsg(err);
}}
- isFocusRangeSelector={isFocusRangeSelector}
rangesErrMsg={rangesErrMsg}
desc={desc}
onDescChange={(v) => setDesc(v)}
- rangeSelectorRef={rangeSelectorActionsRef}
/>
<ComponentContainer
key="user-part"
diff --git a/packages/thread-comment-ui/src/views/thread-comment-editor/index.tsx b/packages/thread-comment-ui/src/views/thread-comment-editor/index.tsx
index 8910c94a71..c34f4e48ab 100644
--- a/packages/thread-comment-ui/src/views/thread-comment-editor/index.tsx
+++ b/packages/thread-comment-ui/src/views/thread-comment-editor/index.tsx
@@ -106,7 +106,7 @@ export const ThreadCommentEditor = forwardRef<IThreadCommentEditorInstance, IThr
return (
<div className={styles.threadCommentEditor} onClick={(e) => e.preventDefault()}>
<RichTextEditor
- ref={editor}
+ editorRef={editor}
autoFocus={autoFocus}
style={{ width: '100%' }}
keyboardEventConfig={keyboardEventConfig}