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(formula-editor): init (#3833)

Gpound.liu063fd290659e
diff --git a/packages/docs-ui/src/controllers/render-controllers/doc-editor-bridge.controller.ts b/packages/docs-ui/src/controllers/render-controllers/doc-editor-bridge.controller.ts
index 1081db4cd9..a4d8584162 100644
--- a/packages/docs-ui/src/controllers/render-controllers/doc-editor-bridge.controller.ts
+++ b/packages/docs-ui/src/controllers/render-controllers/doc-editor-bridge.controller.ts
@@ -194,6 +194,11 @@ export class DocEditorBridgeController extends Disposable implements IRenderModu
return;
}
+ // TODO:@ggg: Docs-ui should not rely on sheet-ui stuff, and the code needs to be removed after the editor is refactored.
+ if (unitId.includes('range_selector') || unitId.includes('embedding_formula_editor')) {
+ return;
+ }
+
this._editorService.blur();
})
);
diff --git a/packages/docs-ui/src/services/editor/editor-manager.service.ts b/packages/docs-ui/src/services/editor/editor-manager.service.ts
index 4166919f4c..ec65a3bb0d 100644
--- a/packages/docs-ui/src/services/editor/editor-manager.service.ts
+++ b/packages/docs-ui/src/services/editor/editor-manager.service.ts
@@ -18,7 +18,7 @@ import type { DocumentDataModel, IDisposable, IDocumentBody, IDocumentData, Null
import type { ISuccinctDocRangeParam, Scene } from '@univerjs/engine-render';
import type { Observable } from 'rxjs';
import type { IEditorConfigParams, IEditorStateParams } from './editor';
-import { createIdentifier, DEFAULT_EMPTY_DOCUMENT_VALUE, Disposable, EDITOR_ACTIVATED, FOCUSING_EDITOR_INPUT_FORMULA, FOCUSING_EDITOR_STANDALONE, FOCUSING_UNIVER_EDITOR_STANDALONE_SINGLE_MODE, HorizontalAlign, ICommandService, IContextService, Inject, IUndoRedoService, IUniverInstanceService, toDisposable, UniverInstanceType, VerticalAlign } from '@univerjs/core';
+import { createIdentifier, DEFAULT_EMPTY_DOCUMENT_VALUE, Disposable, EDITOR_ACTIVATED, FOCUSING_EDITOR_INPUT_FORMULA, FOCUSING_EDITOR_STANDALONE, FOCUSING_UNIVER_EDITOR_STANDALONE_SINGLE_MODE, HorizontalAlign, ICommandService, IContextService, Inject, isInternalEditorID, IUndoRedoService, IUniverInstanceService, toDisposable, UniverInstanceType, VerticalAlign } from '@univerjs/core';
import { DocSelectionManagerService } from '@univerjs/docs';
import { isReferenceStrings, LexerTreeBuilder, operatorToken } from '@univerjs/engine-formula';
import { IRenderManagerService } from '@univerjs/engine-render';
@@ -46,20 +46,35 @@ export interface IEditorInputFormulaParam {
formulaString: string;
}
+/**
+ * @deprecated
+ */
export interface IEditorService {
getEditor(id?: string): Readonly<Nullable<Editor>>;
register(config: IEditorConfigParams, container: HTMLDivElement): IDisposable;
+ /**
+ * @deprecated
+ */
isVisible(id: string): Nullable<boolean>;
inputFormula$: Observable<IEditorInputFormulaParam>;
+ /**
+ * @deprecated
+ */
setFormula(formulaString: string): void;
resize$: Observable<string>;
+ /**
+ * @deprecated
+ */
resize(id: string): void;
+ /**
+ * @deprecated
+ */
getAllEditor(): Map<string, Editor>;
/**
@@ -80,43 +95,91 @@ export interface IEditorService {
isSheetEditor(editorUnitId: string): boolean;
closeRangePrompt$: Observable<unknown>;
+ /**
+ * @deprecated
+ */
closeRangePrompt(): void;
blur$: Observable<unknown>;
+ /**
+ * @deprecated
+ */
blur(): void;
focus$: Observable<ISuccinctDocRangeParam>;
+ /**
+ * @deprecated
+ */
focus(editorUnitId?: string): void;
setValue$: Observable<IEditorSetValueParam>;
valueChange$: Observable<Readonly<Editor>>;
+ /**
+ * @deprecated
+ */
setValue(val: string, editorUnitId?: string): void;
+ /**
+ * @deprecated
+ */
setValueNoRefresh(val: string, editorUnitId?: string): void;
+ /**
+ * @deprecated
+ */
setRichValue(body: IDocumentBody, editorUnitId?: string): void;
+ /**
+ * @deprecated
+ */
getFirstEditor(): Editor;
focusStyle$: Observable<Nullable<string>>;
+ /**
+ * @deprecated
+ */
focusStyle(editorUnitId: Nullable<string>): void;
+ /**
+ * @deprecated
+ */
refreshValueChange(editorId: string): void;
+ /**
+ * @deprecated
+ */
checkValueLegality(editorId: string): boolean;
+ /**
+ * @deprecated
+ */
getValue(id: string): Nullable<string>;
+ /**
+ * @deprecated
+ */
getRichValue(id: string): Nullable<IDocumentBody>;
+ /**
+ * @deprecated
+ */
changeSpreadsheetFocusState(state: boolean): void;
+ /**
+ * @deprecated
+ */
getSpreadsheetFocusState(): boolean;
+ /**
+ * @deprecated
+ */
selectionChangingState(): boolean;
singleSelection$: Observable<boolean>;
+ /**
+ * @deprecated
+ */
singleSelection(state: boolean): void;
setFocusId(id: Nullable<string>): void;
@@ -273,9 +336,11 @@ export class EditorService extends Disposable implements IEditorService, IDispos
editor.setFocus(true);
this._contextService.setContextValue(EDITOR_ACTIVATED, true);
- this._contextService.setContextValue(FOCUSING_EDITOR_STANDALONE, true);
- this._contextService.setContextValue(FOCUSING_UNIVER_EDITOR_STANDALONE_SINGLE_MODE, editor.isSingle());
+ if (!isInternalEditorID(editorUnitId)) {
+ this._contextService.setContextValue(FOCUSING_EDITOR_STANDALONE, true);
+ this._contextService.setContextValue(FOCUSING_UNIVER_EDITOR_STANDALONE_SINGLE_MODE, editor.isSingle());
+ }
if (!this._spreadsheetFocusState) {
this.singleSelection(!!editor.isSingleChoice());
@@ -353,8 +418,8 @@ export class EditorService extends Disposable implements IEditorService, IDispos
this.focusStyle(editorUnitId);
this._focus$.next({
- startOffset: valueCount - 2,
- endOffset: valueCount - 2,
+ startOffset: valueCount,
+ endOffset: valueCount,
});
}
diff --git a/packages/sheets-conditional-formatting-ui/src/components/panel/rule-edit/colorScale.tsx b/packages/sheets-conditional-formatting-ui/src/components/panel/rule-edit/colorScale.tsx
index 81ad9b0c73..04777dd51b 100644
--- a/packages/sheets-conditional-formatting-ui/src/components/panel/rule-edit/colorScale.tsx
+++ b/packages/sheets-conditional-formatting-ui/src/components/panel/rule-edit/colorScale.tsx
@@ -14,22 +14,24 @@
* limitations under the License.
*/
-import { createInternalEditorID, IUniverInstanceService, LocaleService, UniverInstanceType, useDependency } from '@univerjs/core';
-import { InputNumber, Select } from '@univerjs/design';
-import { TextEditor } from '@univerjs/docs-ui';
-import { CFRuleType, CFValueType, createDefaultValueByValueType, SHEET_CONDITIONAL_FORMATTING_PLUGIN } from '@univerjs/sheets-conditional-formatting';
-import React, { useEffect, useMemo, useState } from 'react';
import type { Workbook } from '@univerjs/core';
import type { IColorScale, IConditionalFormattingRuleConfig } from '@univerjs/sheets-conditional-formatting';
+import type { IStyleEditorProps } from './type';
+
+import { IUniverInstanceService, LocaleService, UniverInstanceType, useDependency } from '@univerjs/core';
+import { InputNumber, Select } from '@univerjs/design';
+import { CFRuleType, CFValueType, createDefaultValueByValueType } from '@univerjs/sheets-conditional-formatting';
+import { FormulaEditor } from '@univerjs/sheets-formula-ui';
+import { useSidebarClick } from '@univerjs/ui';
+import React, { useEffect, useMemo, useRef, useState } from 'react';
import { ColorPicker } from '../../color-picker';
import { Preview } from '../../preview';
import stylesBase from '../index.module.less';
import styles from './index.module.less';
-import type { IStyleEditorProps } from './type';
const createOptionItem = (text: string, localeService: LocaleService) => ({ label: localeService.t(`sheet.cf.valueType.${text}`), value: text });
-const TextInput = (props: { id: string; type: CFValueType | 'none';value: number | string;onChange: (v: number | string) => void; className: string }) => {
+const TextInput = (props: { id: string; type: CFValueType | 'none'; value: number | string; onChange: (v: number | string) => void; className: string }) => {
const { type, className, onChange, id, value } = props;
const univerInstanceService = useDependency(IUniverInstanceService);
const unitId = univerInstanceService.getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET)!.getUnitId();
@@ -50,21 +52,31 @@ const TextInput = (props: { id: string; type: CFValueType | 'none';value: number
min: Number.MIN_SAFE_INTEGER, max: Number.MAX_SAFE_INTEGER,
};
}, [type]);
+
+ const formulaEditorActionsRef = useRef<Parameters<typeof FormulaEditor>[0]['actions']>({});
+ const [isFocusFormulaEditor, isFocusFormulaEditorSet] = useState(false);
+
+ useSidebarClick((e: MouseEvent) => {
+ const handleOutClick = formulaEditorActionsRef.current?.handleOutClick;
+ handleOutClick && handleOutClick(e, () => isFocusFormulaEditorSet(false));
+ });
+
if (type === CFValueType.formula) {
return (
- <TextEditor
- openForSheetSubUnitId={subUnitId}
- openForSheetUnitId={unitId}
- id={createInternalEditorID(`${SHEET_CONDITIONAL_FORMATTING_PLUGIN}_colo_scale_${id}`)}
- value={formulaInitValue}
- style={{ maxWidth: '50%', marginLeft: 4 }}
- canvasStyle={{ fontSize: 10 }}
- onlyInputFormula={true}
- onChange={(v = '') => {
- const formula = v || '';
- onChange(formula);
- }}
- />
+ <div style={{ width: '100%', marginLeft: 4 }}>
+ <FormulaEditor
+ initValue={formulaInitValue as any}
+ unitId={unitId}
+ subUnitId={subUnitId}
+ isFocus={isFocusFormulaEditor}
+ onChange={(v = '') => {
+ const formula = v || '';
+ onChange(formula);
+ }}
+ onFocus={() => isFocusFormulaEditorSet(true)}
+ actions={formulaEditorActionsRef.current}
+ />
+ </div>
);
} else {
return <InputNumber className={className} value={Number(props.value) || 0} onChange={(v) => props.onChange(v || 0)} {...config} />;
@@ -217,6 +229,7 @@ export const ColorScaleStyleEditor = (props: IStyleEditorProps) => {
<div className={stylesBase.label}>{localeService.t('sheet.cf.valueType.min')}</div>
<div className={`${stylesBase.labelContainer} ${stylesBase.mTSm}`}>
<Select
+ style={{ flexShrink: 0 }}
options={minOptions}
value={minType}
onChange={(v) => {
@@ -248,6 +261,7 @@ export const ColorScaleStyleEditor = (props: IStyleEditorProps) => {
<div className={stylesBase.label}>{localeService.t('sheet.cf.panel.medianValue')}</div>
<div className={`${stylesBase.labelContainer} ${stylesBase.mTSm}`}>
<Select
+ style={{ flexShrink: 0 }}
options={medianOptions}
value={medianType}
onChange={(v) => {
@@ -283,6 +297,7 @@ export const ColorScaleStyleEditor = (props: IStyleEditorProps) => {
<div className={stylesBase.label}>{localeService.t('sheet.cf.valueType.max')}</div>
<div className={`${stylesBase.labelContainer} ${stylesBase.mTSm}`}>
<Select
+ style={{ flexShrink: 0 }}
options={maxOptions}
value={maxType}
onChange={(v) => {
diff --git a/packages/sheets-conditional-formatting-ui/src/components/panel/rule-edit/dataBar.tsx b/packages/sheets-conditional-formatting-ui/src/components/panel/rule-edit/dataBar.tsx
index 13ab223ea1..9cffd564cf 100644
--- a/packages/sheets-conditional-formatting-ui/src/components/panel/rule-edit/dataBar.tsx
+++ b/packages/sheets-conditional-formatting-ui/src/components/panel/rule-edit/dataBar.tsx
@@ -14,18 +14,20 @@
* limitations under the License.
*/
-import { createInternalEditorID, IUniverInstanceService, LocaleService, UniverInstanceType, useDependency } from '@univerjs/core';
-import { Checkbox, InputNumber, Radio, RadioGroup, Select } from '@univerjs/design';
-import { TextEditor } from '@univerjs/docs-ui';
-import { CFRuleType, CFValueType, createDefaultValueByValueType, defaultDataBarNativeColor, defaultDataBarPositiveColor, SHEET_CONDITIONAL_FORMATTING_PLUGIN } from '@univerjs/sheets-conditional-formatting';
-import React, { useEffect, useMemo, useRef, useState } from 'react';
import type { Workbook } from '@univerjs/core';
import type { IConditionalFormattingRuleConfig, IValueConfig } from '@univerjs/sheets-conditional-formatting';
+import type { IStyleEditorProps } from './type';
+import { IUniverInstanceService, LocaleService, UniverInstanceType, useDependency } from '@univerjs/core';
+import { Checkbox, InputNumber, Radio, RadioGroup, Select } from '@univerjs/design';
+
+import { CFRuleType, CFValueType, createDefaultValueByValueType, defaultDataBarNativeColor, defaultDataBarPositiveColor } from '@univerjs/sheets-conditional-formatting';
+import { FormulaEditor } from '@univerjs/sheets-formula-ui';
+import { useSidebarClick } from '@univerjs/ui';
+import React, { useEffect, useMemo, useRef, useState } from 'react';
import { ColorPicker } from '../../color-picker';
import { Preview } from '../../preview';
import stylesBase from '../index.module.less';
import styles from './index.module.less';
-import type { IStyleEditorProps } from './type';
const createOptionItem = (text: CFValueType, localeService: LocaleService) => ({ label: localeService.t(`sheet.cf.valueType.${text}`), value: text });
@@ -34,6 +36,15 @@ const InputText = (props: { disabled?: boolean; id: string; className: string; t
const univerInstanceService = useDependency(IUniverInstanceService);
const unitId = univerInstanceService.getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET)!.getUnitId();
const subUnitId = univerInstanceService.getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET)!.getActiveSheet()?.getSheetId();
+
+ const formulaEditorActionsRef = useRef<Parameters<typeof FormulaEditor>[0]['actions']>({});
+ const [isFocusFormulaEditor, isFocusFormulaEditorSet] = useState(false);
+
+ useSidebarClick((e: MouseEvent) => {
+ const handleOutClick = formulaEditorActionsRef.current?.handleOutClick;
+ handleOutClick && handleOutClick(e, () => isFocusFormulaEditorSet(false));
+ });
+
const _value = useRef(value);
const config = useMemo(() => {
if ([CFValueType.percentile, CFValueType.percent].includes(type)) {
@@ -49,19 +60,20 @@ const InputText = (props: { disabled?: boolean; id: string; className: string; t
if (type === CFValueType.formula) {
const v = String(_value.current).startsWith('=') ? String(_value.current) || '' : '=';
return (
- <TextEditor
- id={createInternalEditorID(`${SHEET_CONDITIONAL_FORMATTING_PLUGIN}_data_bar_${id}`)}
- value={v}
- openForSheetSubUnitId={subUnitId}
- openForSheetUnitId={unitId}
- style={{ width: '47%', marginLeft: 14 }}
- canvasStyle={{ fontSize: 10 }}
- onlyInputFormula={true}
- onChange={(v = '') => {
- const formula = v || '';
- onChange(formula);
- }}
- />
+ <div style={{ width: '100%', marginLeft: 12 }}>
+ <FormulaEditor
+ initValue={v as any}
+ unitId={unitId}
+ subUnitId={subUnitId}
+ isFocus={isFocusFormulaEditor}
+ onChange={(v = '') => {
+ const formula = v || '';
+ onChange(formula);
+ }}
+ onFocus={() => isFocusFormulaEditorSet(true)}
+ actions={formulaEditorActionsRef.current}
+ />
+ </div>
);
}
return (
@@ -273,6 +285,7 @@ export const DataBarStyleEditor = (props: IStyleEditorProps) => {
<div className={stylesBase.label}>{localeService.t('sheet.cf.valueType.min')}</div>
<div className={`${stylesBase.mTSm} ${stylesBase.labelContainer}`}>
<Select
+ style={{ width: '50%', flexShrink: 0 }}
options={minOptions}
value={minValueType}
onChange={(v) => {
@@ -298,6 +311,7 @@ export const DataBarStyleEditor = (props: IStyleEditorProps) => {
<div className={stylesBase.label}>{localeService.t('sheet.cf.valueType.max')}</div>
<div className={`${stylesBase.mTSm} ${stylesBase.labelContainer}`}>
<Select
+ style={{ width: '50%', flexShrink: 0 }}
options={maxOptions}
value={maxValueType}
onChange={(v) => {
diff --git a/packages/sheets-conditional-formatting-ui/src/components/panel/rule-edit/formula.tsx b/packages/sheets-conditional-formatting-ui/src/components/panel/rule-edit/formula.tsx
index de856e3d6a..4f5bd0752d 100644
--- a/packages/sheets-conditional-formatting-ui/src/components/panel/rule-edit/formula.tsx
+++ b/packages/sheets-conditional-formatting-ui/src/components/panel/rule-edit/formula.tsx
@@ -14,18 +14,18 @@
* limitations under the License.
*/
-import { createInternalEditorID, IUniverInstanceService, LocaleService, UniverInstanceType, useDependency } from '@univerjs/core';
-import { TextEditor } from '@univerjs/docs-ui';
-import { CFRuleType, CFSubRuleType, SHEET_CONDITIONAL_FORMATTING_PLUGIN } from '@univerjs/sheets-conditional-formatting';
-import React, { useEffect, useState } from 'react';
import type { Workbook } from '@univerjs/core';
import type { IAverageHighlightCell, IConditionalFormattingRuleConfig, IHighlightCell, IRankHighlightCell } from '@univerjs/sheets-conditional-formatting';
+import type { IStyleEditorProps } from './type';
+import { IUniverInstanceService, LocaleService, UniverInstanceType, useDependency } from '@univerjs/core';
+import { CFRuleType, CFSubRuleType } from '@univerjs/sheets-conditional-formatting';
+import { FormulaEditor } from '@univerjs/sheets-formula-ui';
+import { useSidebarClick } from '@univerjs/ui';
+import React, { useEffect, useRef, useState } from 'react';
import { ConditionalStyleEditor } from '../../conditional-style-editor';
import { Preview } from '../../preview';
-import { WrapperError } from '../../wrapper-error/WrapperError';
import stylesBase from '../index.module.less';
import styles from './index.module.less';
-import type { IStyleEditorProps } from './type';
export const FormulaStyleEditor = (props: IStyleEditorProps) => {
const { onChange, interceptorManager } = props;
@@ -36,6 +36,9 @@ export const FormulaStyleEditor = (props: IStyleEditorProps) => {
const rule = props.rule?.type === CFRuleType.highlightCell ? props.rule : undefined as IRankHighlightCell | IAverageHighlightCell | undefined;
+ const divEleRef = useRef<HTMLDivElement>(null);
+ const [isFocusFormulaEditor, isFocusFormulaEditorSet] = useState(false);
+ const formulaEditorActionsRef = useRef<Parameters<typeof FormulaEditor>[0]['actions']>({});
const [style, styleSet] = useState<IHighlightCell['style']>({});
const [formula, formulaSet] = useState(() => {
if (rule?.subType === CFSubRuleType.formula) {
@@ -43,7 +46,7 @@ export const FormulaStyleEditor = (props: IStyleEditorProps) => {
}
return '=';
});
- const [formulaError, formulaErrorSet] = useState('');
+ const [formulaError, formulaErrorSet] = useState<string | undefined>(undefined);
const getResult = (config: {
style: IHighlightCell['style'];
@@ -68,7 +71,7 @@ export const FormulaStyleEditor = (props: IStyleEditorProps) => {
useEffect(() => {
const dispose = interceptorManager.intercept(interceptorManager.getInterceptPoints().beforeSubmit, {
handler: (v, _c, next) => {
- if (!formula || formula.length === 1 || !formula.startsWith('=')) {
+ if (formulaError || formula.length === 1 || !formula.startsWith('=')) {
formulaErrorSet(localeService.t('sheet.cf.errorMessage.formulaError'));
return false;
}
@@ -76,7 +79,7 @@ export const FormulaStyleEditor = (props: IStyleEditorProps) => {
},
});
return dispose as () => void;
- }, [formula]);
+ }, [formulaError, formula]);
const _onChange = (config: {
formula: string;
@@ -84,26 +87,38 @@ export const FormulaStyleEditor = (props: IStyleEditorProps) => {
}) => {
onChange(getResult(config));
};
+
+ useSidebarClick((e: MouseEvent) => {
+ const handleOutClick = formulaEditorActionsRef.current?.handleOutClick;
+ handleOutClick && handleOutClick(e, () => isFocusFormulaEditorSet(false));
+ });
+
return (
- <div>
+ <div ref={divEleRef}>
<div className={`${stylesBase.title} ${stylesBase.mTBase}`}>{localeService.t('sheet.cf.panel.styleRule')}</div>
<div className={`${stylesBase.mTSm}`}>
- <WrapperError errorText={formulaError}>
- <TextEditor
- id={createInternalEditorID(`${SHEET_CONDITIONAL_FORMATTING_PLUGIN}_formula`)}
- openForSheetSubUnitId={worksheet?.getSheetId()}
- openForSheetUnitId={workbook.getUnitId()}
- value={formula}
- canvasStyle={{ fontSize: 10 }}
- onlyInputFormula={true}
- onChange={(v = '') => {
- const formula = v || '';
- formulaSet(formula);
- _onChange({ style, formula });
- formulaErrorSet('');
- }}
- />
- </WrapperError>
+
+ <FormulaEditor
+ onChange={(formula) => {
+ formulaSet(formula);
+ _onChange({ style, formula });
+ }}
+ onVerify={(result, formula) => {
+ if (!result || formula.length === 1) {
+ formulaErrorSet(localeService.t('sheet.cf.errorMessage.formulaError'));
+ } else {
+ formulaErrorSet(undefined);
+ }
+ }}
+ errorText={formulaError}
+ onFocus={() => { isFocusFormulaEditorSet(true); }}
+ actions={formulaEditorActionsRef.current}
+ isFocus={isFocusFormulaEditor}
+ initValue={formula as any}
+ unitId={workbook.getUnitId()}
+ subUnitId={worksheet?.getSheetId()}
+ >
+ </FormulaEditor>
</div>
diff --git a/packages/sheets-conditional-formatting-ui/src/components/panel/rule-edit/iconSet.tsx b/packages/sheets-conditional-formatting-ui/src/components/panel/rule-edit/iconSet.tsx
index e984910bc8..85959199d5 100644
--- a/packages/sheets-conditional-formatting-ui/src/components/panel/rule-edit/iconSet.tsx
+++ b/packages/sheets-conditional-formatting-ui/src/components/panel/rule-edit/iconSet.tsx
@@ -17,15 +17,16 @@
import type { Workbook } from '@univerjs/core';
import type { IIconSet, IIconType } from '@univerjs/sheets-conditional-formatting';
import type { IStyleEditorProps } from './type';
-import { createInternalEditorID, get, IUniverInstanceService, LocaleService, set, Tools, UniverInstanceType, useDependency } from '@univerjs/core';
+import { get, IUniverInstanceService, LocaleService, set, Tools, UniverInstanceType, useDependency } from '@univerjs/core';
import { Checkbox, Dropdown, InputNumber, Select } from '@univerjs/design';
-import { TextEditor } from '@univerjs/docs-ui';
-
import { MoreDownSingle, SlashSingle } from '@univerjs/icons';
-import { CFNumberOperator, CFRuleType, CFSubRuleType, CFValueType, compareWithNumber, createDefaultValue, EMPTY_ICON_TYPE, getOppositeOperator, iconGroup, iconMap, SHEET_CONDITIONAL_FORMATTING_PLUGIN } from '@univerjs/sheets-conditional-formatting';
-import { ILayoutService, useScrollYOverContainer } from '@univerjs/ui';
-import React, { forwardRef, useEffect, useMemo, useState } from 'react';
+
+import { CFNumberOperator, CFRuleType, CFSubRuleType, CFValueType, compareWithNumber, createDefaultValue, EMPTY_ICON_TYPE, getOppositeOperator, iconGroup, iconMap } from '@univerjs/sheets-conditional-formatting';
+import { FormulaEditor } from '@univerjs/sheets-formula-ui';
+import { ILayoutService, useScrollYOverContainer, useSidebarClick } from '@univerjs/ui';
+
+import React, { forwardRef, useEffect, useMemo, useRef, useState } from 'react';
import stylesBase from '../index.module.less';
import styles from './index.module.less';
@@ -35,7 +36,7 @@ const getIcon = (iconType: string, iconId: string | number) => {
return arr[Number(iconId)] || '';
};
-const TextInput = (props: { id: number; type: CFValueType; value: number | string;onChange: (v: number | string) => void; error?: string }) => {
+const TextInput = (props: { id: number; type: CFValueType; value: number | string; onChange: (v: number | string) => void; error?: string }) => {
const univerInstanceService = useDependency(IUniverInstanceService);
const unitId = univerInstanceService.getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET)!.getUnitId();
const subUnitId = univerInstanceService.getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET)!.getActiveSheet()?.getSheetId();
@@ -45,6 +46,14 @@ const TextInput = (props: { id: number; type: CFValueType; value: number | strin
}
return '';
}, [props.error]);
+
+ const formulaEditorActionsRef = useRef<Parameters<typeof FormulaEditor>[0]['actions']>({});
+ const [isFocusFormulaEditor, isFocusFormulaEditorSet] = useState(false);
+
+ useSidebarClick((e: MouseEvent) => {
+ const handleOutClick = formulaEditorActionsRef.current?.handleOutClick;
+ handleOutClick && handleOutClick(e, () => isFocusFormulaEditorSet(false));
+ });
return (
<div className={styles.positionRelative}>
{props.type !== CFValueType.formula
@@ -59,18 +68,20 @@ const TextInput = (props: { id: number; type: CFValueType; value: number | strin
</>
)
: (
- <TextEditor
- id={createInternalEditorID(`${SHEET_CONDITIONAL_FORMATTING_PLUGIN}_icon_set_${props.id}`)}
- value={String(props.value).startsWith('=') ? String(props.value) : '='}
- openForSheetSubUnitId={subUnitId}
- openForSheetUnitId={unitId}
- canvasStyle={{ fontSize: 10 }}
- onlyInputFormula={true}
- onChange={(v = '') => {
- const formula = v || '';
- props.onChange(formula);
- }}
- />
+ <div style={{ width: '100%' }}>
+ <FormulaEditor
+ initValue={String(props.value) as any}
+ unitId={unitId}
+ subUnitId={subUnitId}
+ isFocus={isFocusFormulaEditor}
+ onChange={(v = '') => {
+ const formula = v || '';
+ props.onChange(formula);
+ }}
+ onFocus={() => isFocusFormulaEditorSet(true)}
+ actions={formulaEditorActionsRef.current}
+ />
+ </div>
)}
</div>
);
@@ -117,9 +128,9 @@ const IconGroupList = forwardRef<HTMLDivElement | null, IconGroupListProps>((pro
);
});
-const IconItemList = (props: { onClick: (iconType: IIconType, iconId: string) => void;iconType?: IIconType; iconId: string }) => {
+const IconItemList = (props: { onClick: (iconType: IIconType, iconId: string) => void; iconType?: IIconType; iconId: string }) => {
const list = useMemo(() => {
- const result: { iconType: IIconType;iconId: string; base64: string }[] = [];
+ const result: { iconType: IIconType; iconId: string; base64: string }[] = [];
for (const key in iconMap) {
const list = iconMap[key as IIconType];
const iconType = key as IIconType;
@@ -183,6 +194,9 @@ const IconSetRuleEdit = (props: {
const handleValueTypeChange = (v: string, index: number) => {
onChange([String(index), 'value', 'type'], v);
+ const item = configList[index];
+ const defaultValue = createDefaultValue(CFSubRuleType.number, item.operator) as number;
+ handleValueValueChange(defaultValue, index);
};
const render = useMemo(() => {
return configList.map((item, index) => {
@@ -262,7 +276,13 @@ const IconSetRuleEdit = (props: {
</div>
</div>
<div className={`${stylesBase.mTSm} ${styles.flex}`}>
- <Select className={`${styles.width45} ${stylesBase.mL0}`} options={valueTypeOptions} value={item.value.type} onChange={(v) => { handleValueTypeChange(v as CFNumberOperator, index); }} />
+ <Select
+ style={{ flexShrink: 0 }}
+ className={`${styles.width45} ${stylesBase.mL0}`}
+ options={valueTypeOptions}
+ value={item.value.type}
+ onChange={(v) => { handleValueTypeChange(v as CFNumberOperator, index); }}
+ />
<div className={`${stylesBase.mL0} ${styles.width45}`}>
<TextInput id={index} type={item.value.type} error={error} value={item.value.value || ''} onChange={(v) => handleValueValueChange(v, index)} />
</div>
@@ -304,10 +324,12 @@ export const IconSet = (props: IStyleEditorProps<unknown, IIconSet>) => {
if (index === list.length - 1) {
// The last condition is actually the complement of the above conditions,
// packages/sheets-conditional-formatting/src/services/calculate-unit/icon-set.ts
- return { operator: CFNumberOperator.lessThanOrEqual,
- value: { type: CFValueType.num, value: Number.MAX_SAFE_INTEGER },
- iconType: currentIconType,
- iconId: String(index) };
+ return {
+ operator: CFNumberOperator.lessThanOrEqual,
+ value: { type: CFValueType.num, value: Number.MAX_SAFE_INTEGER },
+ iconType: currentIconType,
+ iconId: String(index),
+ };
}
return createDefaultConfigItem(currentIconType, index, list);
});
@@ -389,20 +411,24 @@ export const IconSet = (props: IStyleEditorProps<unknown, IIconSet>) => {
};
useEffect(() => {
- const dispose = interceptorManager.intercept(interceptorManager.getInterceptPoints().submit, { handler() {
- const result: IIconSet = { type: CFRuleType.iconSet, isShowValue, config: configList } as IIconSet;
- return result;
- } });
+ const dispose = interceptorManager.intercept(interceptorManager.getInterceptPoints().submit, {
+ handler() {
+ const result: IIconSet = { type: CFRuleType.iconSet, isShowValue, config: configList } as IIconSet;
+ return result;
+ },
+ });
return () => {
dispose();
};
}, [isShowValue, configList, interceptorManager]);
useEffect(() => {
- const dispose = interceptorManager.intercept(interceptorManager.getInterceptPoints().beforeSubmit, { handler() {
- const keys = Object.keys(errorMap);
- return keys.length === 0;
- } });
+ const dispose = interceptorManager.intercept(interceptorManager.getInterceptPoints().beforeSubmit, {
+ handler() {
+ const keys = Object.keys(errorMap);
+ return keys.length === 0;
+ },
+ });
return () => {
dispose();
};
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 878ccf9391..beb5122467 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,6 +1,6 @@
.cf-rule-style-editor {
.cf-preview-wrap {
- margin-top: var(--margin-sm);
+ margin-top: var(--margin-lg);
padding: var(--padding-xs) var(--padding-sm);
border: 1px solid rgb(var(--border-color));
border-radius: var(--border-radius-base);
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 4afb9622fc..63f4aee44f 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,6 +27,8 @@ 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 { useSidebarClick } from '@univerjs/ui';
+
import React, { useEffect, useMemo, useRef, useState } from 'react';
import { AddCfCommand } from '../../../commands/commands/add-cf.command';
@@ -58,14 +60,7 @@ export const RuleEdit = (props: IRuleEditProps) => {
const unitId = getUnitId(univerInstanceService);
const subUnitId = getSubUnitId(univerInstanceService);
- const [isFocusRangeSelector, isFocusRangeSelectorSet] = useState(() => {
- // 如果是自定义公式的话,则不自动聚焦在选区.
- const { rule } = props;
- if (rule?.rule.type === CFRuleType.highlightCell) {
- return rule.rule.subType !== CFSubRuleType.formula;
- }
- return true;
- });
+ 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 ?? []);
@@ -185,7 +180,7 @@ export const RuleEdit = (props: IRuleEditProps) => {
};
const onRangeSelectorChange = (rangeString: string) => {
- const result = rangeString.split(',').map(deserializeRangeWithSheet).map((item) => item.range);
+ const result = rangeString.split(',').filter((e) => !!e).map(deserializeRangeWithSheet).map((item) => item.range);
rangeResult.current = result;
};
@@ -244,13 +239,13 @@ export const RuleEdit = (props: IRuleEditProps) => {
}
};
- const handlePanelClick = (e: React.MouseEvent<HTMLDivElement, MouseEvent>) => {
+ useSidebarClick((e: MouseEvent) => {
const handleOutClick = rangeSelectorActionsRef.current?.handleOutClick;
- handleOutClick && handleOutClick(e, isFocusRangeSelectorSet);
- };
+ handleOutClick && handleOutClick(e, () => isFocusRangeSelectorSet(false));
+ });
return (
- <div className={styles.cfRuleStyleEditor} onClick={handlePanelClick}>
+ <div className={styles.cfRuleStyleEditor}>
<div className={styleBase.title}>{localeService.t('sheet.cf.panel.range')}</div>
<div className={`${styleBase.mTBase}`}>
<RangeSelector
@@ -260,6 +255,7 @@ export const RuleEdit = (props: IRuleEditProps) => {
initValue={rangeString}
onChange={onRangeSelectorChange}
onVerify={handleVerify}
+ onFocus={() => isFocusRangeSelectorSet(true)}
isFocus={isFocusRangeSelector}
actions={rangeSelectorActionsRef.current}
/>
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 34ac520811..62bca6e8fa 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
@@ -23,7 +23,8 @@ 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, useEvent, useObservable } from '@univerjs/ui';
+
+import { ComponentManager, useEvent, useObservable, useSidebarClick } from '@univerjs/ui';
import React, { useEffect, useMemo, useRef, useState } from 'react';
import { DataValidationPanelService } from '../../../services/data-validation-panel.service';
import { DataValidationOptions } from '../options';
@@ -246,13 +247,13 @@ export function DataValidationDetail() {
);
};
- const handlePanelClick = (e: React.MouseEvent<HTMLDivElement, MouseEvent>) => {
+ useSidebarClick((e: MouseEvent) => {
const handleOutClick = rangeSelectorActionsRef.current?.handleOutClick;
- handleOutClick && handleOutClick(e, isFocusRangeSelectorSet);
- };
+ handleOutClick && handleOutClick(e, () => isFocusRangeSelectorSet(false));
+ });
return (
- <div className={styles.dataValidationDetail} onClick={handlePanelClick}>
+ <div className={styles.dataValidationDetail}>
<FormLayout
label={localeService.t('dataValidation.panel.range')}
error={(!localRule.ranges.length || isRangeError) ? localeService.t('dataValidation.panel.rangeError') : ''}
@@ -262,6 +263,7 @@ export function DataValidationDetail() {
subUnitId={subUnitId}
initValue={rangeStr}
onChange={handleUpdateRuleRanges}
+ onFocus={() => isFocusRangeSelectorSet(true)}
isFocus={isFocusRangeSelector}
actions={rangeSelectorActionsRef.current}
onVerify={(isValid) => setIsRangeError(!isValid)}
diff --git a/packages/sheets-data-validation-ui/src/views/components/formula-input/custom-formula-input.tsx b/packages/sheets-data-validation-ui/src/views/components/formula-input/custom-formula-input.tsx
index 0a64295a9f..04c64ba209 100644
--- a/packages/sheets-data-validation-ui/src/views/components/formula-input/custom-formula-input.tsx
+++ b/packages/sheets-data-validation-ui/src/views/components/formula-input/custom-formula-input.tsx
@@ -15,31 +15,36 @@
*/
import type { IFormulaInputProps } from '@univerjs/data-validation';
-import { createInternalEditorID } from '@univerjs/core';
-
-import { FormLayout } from '@univerjs/design';
-import { TextEditor } from '@univerjs/docs-ui';
-import React from 'react';
+import { FormulaEditor } from '@univerjs/sheets-formula-ui';
+import { useSidebarClick } from '@univerjs/ui';
+import React, { useRef, useState } from 'react';
export function CustomFormulaInput(props: IFormulaInputProps) {
const { unitId, subUnitId, value, onChange, showError, validResult } = props;
- const formula1Res = showError ? validResult?.formula1 : '';
+ const formula1Res = showError ? validResult?.formula1 : undefined;
+ const formulaEditorActionsRef = useRef<Parameters<typeof FormulaEditor>[0]['actions']>({});
+ const [isFocusFormulaEditor, isFocusFormulaEditorSet] = useState(false);
+ useSidebarClick((e: MouseEvent) => {
+ const handleOutClick = formulaEditorActionsRef.current?.handleOutClick;
+ handleOutClick && handleOutClick(e, () => isFocusFormulaEditorSet(false));
+ });
return (
- <FormLayout error={formula1Res}>
- <TextEditor
- value={value?.formula1 ?? ''}
- id={createInternalEditorID(`dataValidation-custom-formula-${unitId}-${subUnitId}`)}
- onChange={(newValue) => {
- onChange?.({
- ...value,
- formula1: (newValue ?? '').trim(),
- });
- }}
- onlyInputFormula
- openForSheetUnitId={unitId}
- openForSheetSubUnitId={subUnitId}
- />
- </FormLayout>
+ <FormulaEditor
+ initValue={value?.formula1 ?? '' as any}
+ unitId={unitId}
+ subUnitId={subUnitId}
+ isFocus={isFocusFormulaEditor}
+ onChange={(v = '') => {
+ const formula = v || '';
+ onChange?.({
+ ...value,
+ formula1: (formula).trim(),
+ });
+ }}
+ errorText={formula1Res}
+ onFocus={() => isFocusFormulaEditorSet(true)}
+ actions={formulaEditorActionsRef.current}
+ />
);
}
diff --git a/packages/sheets-data-validation-ui/src/views/components/formula-input/list-formula-input.tsx b/packages/sheets-data-validation-ui/src/views/components/formula-input/list-formula-input.tsx
index ca0cd7f356..e512c99ffd 100644
--- a/packages/sheets-data-validation-ui/src/views/components/formula-input/list-formula-input.tsx
+++ b/packages/sheets-data-validation-ui/src/views/components/formula-input/list-formula-input.tsx
@@ -15,13 +15,14 @@
*/
import type { ListValidator } from '@univerjs/sheets-data-validation';
-import { createInternalEditorID, DataValidationType, isFormulaString, LocaleService, Tools, useDependency } from '@univerjs/core';
+import { DataValidationType, isFormulaString, LocaleService, Tools, useDependency } from '@univerjs/core';
import { DataValidationModel, DataValidatorRegistryService, type IFormulaInputProps } from '@univerjs/data-validation';
import { DraggableList, FormLayout, Input, Radio, RadioGroup, Select } from '@univerjs/design';
-import { TextEditor } from '@univerjs/docs-ui';
import { DeleteSingle, IncreaseSingle, SequenceSingle } from '@univerjs/icons';
import { DataValidationFormulaController, deserializeListOptions, serializeListOptions } from '@univerjs/sheets-data-validation';
-import { useEvent, useObservable } from '@univerjs/ui';
+import { FormulaEditor } from '@univerjs/sheets-formula-ui';
+
+import { useEvent, useObservable, useSidebarClick } from '@univerjs/ui';
import cs from 'clsx';
import React, { useEffect, useMemo, useRef, useState } from 'react';
import { debounceTime } from 'rxjs';
@@ -311,6 +312,14 @@ export function ListFormulaInput(props: IFormulaInputProps) {
[formula2, onChange]
);
+ const formulaEditorActionsRef = useRef<Parameters<typeof FormulaEditor>[0]['actions']>({});
+ const [isFocusFormulaEditor, isFocusFormulaEditorSet] = useState(false);
+
+ useSidebarClick((e: MouseEvent) => {
+ const handleOutClick = formulaEditorActionsRef.current?.handleOutClick;
+ handleOutClick && handleOutClick(e, () => isFocusFormulaEditorSet(false));
+ });
+
return (
<>
<FormLayout label={localeService.t('dataValidation.list.options')}>
@@ -334,20 +343,20 @@ export function ListFormulaInput(props: IFormulaInputProps) {
{isFormulaStr === '1'
? (
<>
- <FormLayout error={formula1Res || localError}>
- <TextEditor
- id={createInternalEditorID(`list-ref-range-${unitId}-${subUnitId}`)}
- value={formulaStr}
- openForSheetUnitId={unitId}
- openForSheetSubUnitId={subUnitId}
- onlyInputFormula
- onChange={async (newString) => {
- const str = (newString ?? '').trim();
- setFormulaStrCopy(str);
- updateFormula(str);
- }}
- />
- </FormLayout>
+ <FormulaEditor
+ initValue={formulaStr as any}
+ unitId={unitId}
+ subUnitId={subUnitId}
+ isFocus={isFocusFormulaEditor}
+ onChange={(v = '') => {
+ const str = (v ?? '').trim();
+ setFormulaStrCopy(str);
+ updateFormula(str);
+ }}
+ errorText={(formula1Res || localError) || undefined}
+ onFocus={() => isFocusFormulaEditorSet(true)}
+ actions={formulaEditorActionsRef.current}
+ />
<FormLayout>
<div ref={containerRef}>
{refFinalList.map((item) => {
diff --git a/packages/sheets-formula-ui/src/controllers/prompt.controller.ts b/packages/sheets-formula-ui/src/controllers/prompt.controller.ts
index c487befd1f..89cde6e2e5 100644
--- a/packages/sheets-formula-ui/src/controllers/prompt.controller.ts
+++ b/packages/sheets-formula-ui/src/controllers/prompt.controller.ts
@@ -33,13 +33,13 @@ import type {
} from '@univerjs/sheets';
import type { EditorBridgeService, SelectionShape } from '@univerjs/sheets-ui';
import type { ISelectEditorFormulaOperationParam } from '../commands/operations/editor-formula.operation';
-import {
- AbsoluteRefType,
+import { AbsoluteRefType,
Direction,
Disposable,
DisposableCollection,
DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY,
DOCS_NORMAL_EDITOR_UNIT_ID_KEY,
+ DOCS_ZEN_EDITOR_UNIT_ID_KEY,
FOCUSING_EDITOR_INPUT_FORMULA,
FORMULA_EDITOR_ACTIVATED,
ICommandService,
@@ -90,13 +90,14 @@ import {
ExpandSelectionCommand,
getEditorObject,
IEditorBridgeService,
+ isEmbeddingFormulaEditor,
isRangeSelector,
JumpOver,
MoveSelectionCommand,
SheetSkeletonManagerService,
} from '@univerjs/sheets-ui';
import { IContextMenuService, ILayoutService, KeyCode, MetaKeys, SetEditorResizeOperation, UNI_DISABLE_CHANGING_FOCUS_KEY } from '@univerjs/ui';
-import { distinctUntilChanged, distinctUntilKeyChanged, filter } from 'rxjs';
+import { debounceTime, distinctUntilChanged, distinctUntilKeyChanged, filter, merge } from 'rxjs';
import { SelectEditorFormulaOperation } from '../commands/operations/editor-formula.operation';
import { HelpFunctionOperation } from '../commands/operations/help-function.operation';
import { ReferenceAbsoluteOperation } from '../commands/operations/reference-absolute.operation';
@@ -255,7 +256,7 @@ export class PromptController extends Disposable {
this._docSelectionManagerService.textSelection$
.pipe(
filter((item) => {
- return !isRangeSelector(item.unitId);
+ return !isRangeSelector(item.unitId) && !isEmbeddingFormulaEditor(item.unitId);
})
)
.subscribe((params) => {
@@ -303,59 +304,60 @@ export class PromptController extends Disposable {
private _initialEditorInputChange() {
const arrows = [KeyCode.ARROW_DOWN, KeyCode.ARROW_UP, KeyCode.ARROW_LEFT, KeyCode.ARROW_RIGHT, KeyCode.CTRL, KeyCode.SHIFT];
// TODO: @runzhe Should there be a registration mechanism, rather than a unified process here?
- this._univerInstanceService.getCurrentTypeOfUnit$<DocumentDataModel>(UniverInstanceType.UNIVER_DOC).subscribe((documentDataModel) => {
- const unitId = documentDataModel?.getUnitId();
-
- if (unitId == null) {
- return;
- }
+ this._univerInstanceService.getCurrentTypeOfUnit$<DocumentDataModel>(UniverInstanceType.UNIVER_DOC)
+ .pipe(filter((documentDataModel) => {
+ const unitId = documentDataModel?.getUnitId() || '';
+ return !isRangeSelector(unitId) && !isEmbeddingFormulaEditor(unitId);
+ }))
+ .subscribe((documentDataModel) => {
+ const unitId = documentDataModel?.getUnitId();
+
+ if (unitId == null) {
+ return;
+ }
- if (isRangeSelector(unitId)) {
- return;
- }
+ if (this._listenInputCache.has(unitId)) {
+ return;
+ }
- if (this._listenInputCache.has(unitId)) {
- return;
- }
+ const editor = this._editorService.getEditor(unitId);
- const editor = this._editorService.getEditor(unitId);
+ if (editor == null) {
+ return;
+ }
- if (editor == null) {
- return;
- }
+ const docSelectionRenderService = this._renderManagerService.getRenderById(unitId)?.with(DocSelectionRenderService);
- const docSelectionRenderService = this._renderManagerService.getRenderById(unitId)?.with(DocSelectionRenderService);
+ if (docSelectionRenderService) {
+ this.disposeWithMe(
+ docSelectionRenderService.onInputBefore$.subscribe((param) => {
+ this._previousSequenceNodes = null;
+ this._previousInsertRefStringIndex = null;
- if (docSelectionRenderService) {
- this.disposeWithMe(
- docSelectionRenderService.onInputBefore$.subscribe((param) => {
- this._previousSequenceNodes = null;
- this._previousInsertRefStringIndex = null;
+ this._selectionRenderService.setSkipLastEnabled(true);
- this._selectionRenderService.setSkipLastEnabled(true);
+ const event = param?.event as KeyboardEvent;
+ if (!event) return;
- const event = param?.event as KeyboardEvent;
- if (!event) return;
+ if (!arrows.includes(event.which)) {
+ if (this._arrowMoveActionState !== ArrowMoveAction.moveCursor) {
+ this._arrowMoveActionState = ArrowMoveAction.moveRefReady;
+ }
- if (!arrows.includes(event.which)) {
- if (this._arrowMoveActionState !== ArrowMoveAction.moveCursor) {
- this._arrowMoveActionState = ArrowMoveAction.moveRefReady;
+ this._inputPanelState = InputPanelState.keyNormal;
+ } else {
+ this._inputPanelState = InputPanelState.keyArrow;
}
- this._inputPanelState = InputPanelState.keyNormal;
- } else {
- this._inputPanelState = InputPanelState.keyArrow;
- }
-
- if (event.which !== KeyCode.F4) {
- this._userCursorMove = false;
- }
- })
- );
- }
+ if (event.which !== KeyCode.F4) {
+ this._userCursorMove = false;
+ }
+ })
+ );
+ }
- this._listenInputCache.add(unitId);
- });
+ this._listenInputCache.add(unitId);
+ });
}
private _closeRangePromptWhenEditorInvisible() {
@@ -378,25 +380,27 @@ export class PromptController extends Disposable {
private _initialChangeEditor() {
this.disposeWithMe(
- this._univerInstanceService.getCurrentTypeOfUnit$<DocumentDataModel>(UniverInstanceType.UNIVER_DOC).subscribe((documentDataModel) => {
- if (documentDataModel == null) {
- return;
- }
+ this._univerInstanceService.getCurrentTypeOfUnit$<DocumentDataModel>(UniverInstanceType.UNIVER_DOC)
+ .pipe(filter((documentDataModel) => {
+ const editorId = documentDataModel?.getUnitId() || '';
+ return !isRangeSelector(editorId) && !isEmbeddingFormulaEditor(editorId);
+ }))
+ .subscribe((documentDataModel) => {
+ if (documentDataModel == null) {
+ return;
+ }
- const editorId = documentDataModel.getUnitId();
+ const editorId = documentDataModel.getUnitId();
- if (isRangeSelector(editorId)) {
- return;
- }
- if (!this._editorService.isEditor(editorId) || this._previousEditorUnitId === editorId) {
- return;
- }
+ if (!this._editorService.isEditor(editorId) || this._previousEditorUnitId === editorId) {
+ return;
+ }
- if (!this._editorService.isSheetEditor(editorId)) {
- this._closeRangePrompt(editorId);
- this._previousEditorUnitId = editorId;
- }
- })
+ if (!this._editorService.isSheetEditor(editorId)) {
+ this._closeRangePrompt(editorId);
+ this._previousEditorUnitId = editorId;
+ }
+ })
);
this.disposeWithMe(
@@ -409,6 +413,10 @@ export class PromptController extends Disposable {
}
private _closeRangePrompt(editorId: Nullable<string>) {
+ const docId = editorId || this._univerInstanceService.getCurrentUnitForType(UniverInstanceType.UNIVER_DOC)?.getUnitId() || '';
+ if (isRangeSelector(docId) || isEmbeddingFormulaEditor(docId) || docId === DOCS_ZEN_EDITOR_UNIT_ID_KEY) {
+ return;
+ }
this._insertSelections = [];
this._refSelectionsService.clear();
@@ -437,14 +445,25 @@ export class PromptController extends Disposable {
// Theme color should be set when SelectionControl is created, it's too late to set theme color at selecitonEnd(pointerup).
// The logic below has been moved to syncToEditor.
// this._allSelectionRenderServices.forEach((r) => this._updateRefSelectionStyle(r, this._isSelectionMovingRefSelections));
-
+ const docID = this._univerInstanceService.getCurrentUnitForType(UniverInstanceType.UNIVER_DOC)?.getUnitId() || '';
+ if (isRangeSelector(docID) || isEmbeddingFormulaEditor(docID)) {
+ return;
+ }
const selectionControls = this._allSelectionRenderServices.map((s) => s.getSelectionControls()).flat();
selectionControls.forEach((c) => {
c.disableHelperSelection();
- d.add(c.selectionMoving$.subscribe((toRange) => this._onSelectionControlChange(toRange, c)));
- d.add(c.selectionScaling$.subscribe((toRange) => this._onSelectionControlChange(toRange, c)));
- d.add(c.selectionMoved$.subscribe(() => this._formulaPromptService.disableLockedSelectionChange()));
- d.add(c.selectionScaled$.subscribe(() => this._formulaPromptService.disableLockedSelectionChange()));
+ d.add(merge(c.selectionMoving$, c.selectionScaling$).pipe(debounceTime(30)).subscribe((toRange) => {
+ const docID = this._univerInstanceService.getCurrentUnitForType(UniverInstanceType.UNIVER_DOC)?.getUnitId() || '';
+ if (isRangeSelector(docID) || isEmbeddingFormulaEditor(docID)) {
+ d.dispose();
+ this._formulaPromptService.disableLockedSelectionChange();
+ return;
+ }
+ this._onSelectionControlChange(toRange, c);
+ }));
+ d.add(merge(c.selectionMoved$, c.selectionScaled$).subscribe(() => {
+ this._formulaPromptService.disableLockedSelectionChange();
+ }));
});
}));
}
@@ -1736,6 +1755,11 @@ export class PromptController extends Disposable {
this.disposeWithMe(
this._commandService.onCommandExecuted((command: ICommandInfo) => {
+ const instance = this._univerInstanceService.getCurrentUnitForType(UniverInstanceType.UNIVER_DOC);
+ const unitId = instance?.getUnitId() || '';
+ if (isRangeSelector(unitId) || isEmbeddingFormulaEditor(unitId)) {
+ return;
+ }
if (command.id === ReferenceAbsoluteOperation.id) {
this._changeRefString();
} else if (updateCommandList.includes(command.id)) {
diff --git a/packages/sheets-formula-ui/src/index.ts b/packages/sheets-formula-ui/src/index.ts
index dd5d38dd98..c0ed9c111b 100644
--- a/packages/sheets-formula-ui/src/index.ts
+++ b/packages/sheets-formula-ui/src/index.ts
@@ -22,6 +22,7 @@ export { MoreFunctionsOperation } from './commands/operations/more-functions.ope
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 { RefSelectionsRenderService } from './services/render-services/ref-selections.render-service';
// #region - all commands
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 fe86d5f37a..6ad59284bb 100644
--- a/packages/sheets-formula-ui/src/sheets-formula-ui.plugin.ts
+++ b/packages/sheets-formula-ui/src/sheets-formula-ui.plugin.ts
@@ -20,7 +20,7 @@ import { DependentOn, IConfigService, Inject, Injector, Plugin, UniverInstanceTy
import { UniverFormulaEnginePlugin } from '@univerjs/engine-formula';
import { IRenderManagerService } from '@univerjs/engine-render';
import { UniverSheetsFormulaPlugin } from '@univerjs/sheets-formula';
-import { RANGE_SELECTOR_COMPONENT_KEY } from '@univerjs/sheets-ui';
+import { EMBEDDING_FORMULA_EDITOR_COMPONENT_KEY, RANGE_SELECTOR_COMPONENT_KEY } from '@univerjs/sheets-ui';
import { ComponentManager } from '@univerjs/ui';
import { FORMULA_UI_PLUGIN_NAME } from './common/plugin-name';
import {
@@ -36,6 +36,7 @@ import { FormulaUIController } from './controllers/formula-ui.controller';
import { PromptController } from './controllers/prompt.controller';
import { FormulaPromptService, IFormulaPromptService } from './services/prompt.service';
import { RefSelectionsRenderService } from './services/render-services/ref-selections.render-service';
+import { FormulaEditor } from './views/formula-editor/index';
import { RangeSelector } from './views/range-selector';
/**
@@ -95,6 +96,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);
}
override onSteady(): void {
diff --git a/packages/sheets-formula-ui/src/views/formula-editor/help-function/HelpFunction.tsx b/packages/sheets-formula-ui/src/views/formula-editor/help-function/HelpFunction.tsx
new file mode 100644
index 0000000000..2a2e5f49a8
--- /dev/null
+++ b/packages/sheets-formula-ui/src/views/formula-editor/help-function/HelpFunction.tsx
@@ -0,0 +1,198 @@
+/**
+ * Copyright 2023-present DreamNum Inc.
+ *
+ * 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 { IFunctionInfo, IFunctionParam } from '@univerjs/engine-formula';
+import { LocaleService, useDependency } from '@univerjs/core';
+import { Popup } from '@univerjs/design';
+import { IEditorService } from '@univerjs/docs-ui';
+import { CloseSingle, MoreSingle } from '@univerjs/icons';
+import { ISidebarService } from '@univerjs/ui';
+
+import React, { useEffect, useMemo, useState } from 'react';
+import { throttleTime } from 'rxjs';
+import { generateParam } from '../../../services/utils';
+import { useResizeScrollObserver } from '../hooks/useResizeScrollObserver';
+import styles from './index.module.less';
+
+interface IHelpFunctionProps {
+ functionInfo?: IFunctionInfo;
+ paramIndex: number;
+ editorId: string;
+ onParamsSwitch?: (index: number) => void;
+ onClose?: () => void;
+};
+const noop = () => { };
+export function HelpFunction(props: IHelpFunctionProps) {
+ const { functionInfo, paramIndex, editorId, onParamsSwitch = noop, onClose = noop } = props;
+
+ const editorService = useDependency(IEditorService);
+ const sidebarService = useDependency(ISidebarService);
+
+ const visible = useMemo(() => !!functionInfo && paramIndex >= 0, [functionInfo, paramIndex]);
+
+ const [contentVisible, setContentVisible] = useState(true);
+ const [offset, setOffset] = useState<[number, number]>([0, 0]);
+ const localeService = useDependency(LocaleService);
+ const required = localeService.t('formula.prompt.required');
+ const optional = localeService.t('formula.prompt.optional');
+
+ useResizeScrollObserver(updatePosition);
+
+ useEffect(() => {
+ const sidebarSubscription = sidebarService.scrollEvent$.pipe(throttleTime(100)).subscribe(updatePosition);
+
+ return () => {
+ sidebarSubscription.unsubscribe();
+ };
+ }, []);
+ useEffect(() => {
+ const doc = editorService.getEditor(editorId);
+ if (!doc) {
+ return;
+ }
+ const position = doc.getBoundingClientRect();
+ const { left, top, height } = position;
+ setOffset([left, top + height]);
+ }, [functionInfo, paramIndex, editorId]);
+
+ function updatePosition() {
+ const doc = editorService.getEditor(editorId);
+ if (!doc) {
+ return;
+ }
+ const position = doc.getBoundingClientRect();
+ const { left, top, height } = position;
+ setOffset([left, top + height]);
+ return position;
+ }
+
+ function handleSwitchActive(paramIndex: number) {
+ onParamsSwitch && onParamsSwitch(paramIndex);
+ }
+
+ return (
+ <Popup visible={visible} offset={offset}>
+ {functionInfo
+ ? (
+ <div className={styles.formulaHelpFunction}>
+ <div className={styles.formulaHelpFunctionTitle}>
+ <Help
+ prefix={functionInfo.functionName}
+ value={functionInfo.functionParameter}
+ active={paramIndex}
+ onClick={handleSwitchActive}
+ />
+ <div className={styles.formulaHelpFunctionTitleIcons}>
+ <div
+ className={styles.formulaHelpFunctionTitleIcon}
+ style={{ transform: contentVisible ? 'rotateZ(-90deg)' : 'rotateZ(90deg)' }}
+ onClick={() => setContentVisible(!contentVisible)}
+ >
+ <MoreSingle />
+ </div>
+ <div
+ className={styles.formulaHelpFunctionTitleIcon}
+ onClick={onClose}
+ >
+ <CloseSingle />
+ </div>
+ </div>
+ </div>
+
+ <div
+ className={styles.formulaHelpFunctionContent}
+ style={{
+ height: contentVisible ? 'unset' : 0,
+ padding: contentVisible ? 'revert-layer' : 0,
+ }}
+ >
+ <div className={styles.formulaHelpFunctionContentInner}>
+ <Params
+ title={localeService.t('formula.prompt.helpExample')}
+ value={`${functionInfo.functionName}(${functionInfo.functionParameter
+ .map((item) => item.example)
+ .join(',')})`}
+ />
+ <Params
+ title={localeService.t('formula.prompt.helpAbstract')}
+ value={functionInfo.description}
+ />
+ {functionInfo &&
+ functionInfo.functionParameter &&
+ functionInfo.functionParameter.map((item: IFunctionParam, i: number) => (
+ <Params
+ key={i}
+ className={paramIndex === i ? styles.formulaHelpFunctionActive : ''}
+ title={item.name}
+ value={`${item.require ? required : optional} ${item.detail}`}
+ />
+ ))}
+ </div>
+ </div>
+ </div>
+ )
+ : (
+ <></>
+ )}
+ </Popup>
+ );
+}
+
+interface IParamsProps {
+ className?: string;
+ title?: string;
+ value?: string;
+}
+
+const Params = (props: IParamsProps) => (
+ <div className={styles.formulaHelpFunctionContentParams}>
+ <div className={`${styles.formulaHelpFunctionContentParamsTitle} ${props.className}`}>{props.title}</div>
+ <div className={styles.formulaHelpFunctionContentParamsDetail}>{props.value}</div>
+ </div>
+);
+
+interface IHelpProps {
+ prefix?: string;
+ value?: IFunctionParam[];
+ active: number;
+ onClick: (paramIndex: number) => void;
+}
+
+const Help = (props: IHelpProps) => {
+ const { prefix, value, active, onClick } = props;
+ return (
+ <div className={styles.formulaHelpParam}>
+ <span className={styles.formulaHelpParamPrefix}>
+ {prefix}
+ (
+ </span>
+ {value &&
+ value.map((item: IFunctionParam, i: number) => (
+ // TODO@Dushusir: more params needs to be active
+ <span key={i} className={styles.formulaHelpParamItem}>
+ <span
+ className={active === i ? styles.formulaHelpFunctionActive : styles.formulaHelpParamActive}
+ onClick={() => onClick(i)}
+ >
+ {generateParam(item)}
+ </span>
+ {i === value.length - 1 ? '' : ','}
+ </span>
+ ))}
+ )
+ </div>
+ );
+};
diff --git a/packages/sheets-formula-ui/src/views/formula-editor/help-function/index.module.less b/packages/sheets-formula-ui/src/views/formula-editor/help-function/index.module.less
new file mode 100644
index 0000000000..bfe186d777
--- /dev/null
+++ b/packages/sheets-formula-ui/src/views/formula-editor/help-function/index.module.less
@@ -0,0 +1,129 @@
+@width: 250px;
+@max-height: 350px;
+@icon-size: 24px;
+
+.formula-help-function {
+ user-select: none;
+
+ box-sizing: border-box;
+ width: @width;
+ margin: 0;
+
+ line-height: 20px;
+ list-style: none;
+
+ background-color: rgb(var(--bg-color-secondary));
+ border: 1px solid rgb(var(--border-color));
+ border-radius: var(--border-radius-lg);
+ outline: none;
+ box-shadow: var(--box-shadow-base);
+
+ &-title {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+
+ box-sizing: border-box;
+ padding: var(--padding-base) var(--padding-lg);
+
+ font-size: var(--font-size-xxs);
+ font-weight: 500;
+ color: rgb(var(--text-color));
+ overflow-wrap: anywhere;
+
+ border-bottom: 1px solid rgb(var(--border-color));
+
+ &-icons {
+ display: flex;
+ }
+
+ &-icon {
+ cursor: pointer;
+
+ display: flex;
+ align-items: center;
+ justify-content: center;
+
+ width: @icon-size;
+ height: @icon-size;
+ margin-left: var(--margin-xs);
+ padding: 0;
+
+ font-size: var(--font-size-xs);
+ color: rgb(var(--text-color-secondary));
+
+ background-color: transparent;
+ border: none;
+ border-radius: var(--border-radius-base);
+ outline: none;
+
+ transition: background-color 0.2s;
+
+ &:hover {
+ background-color: rgb(var(--bg-color-hover));
+ }
+ }
+ }
+
+ &-content {
+ overflow-y: auto;
+ box-sizing: border-box;
+ max-height: @max-height;
+ padding: 0 var(--padding-lg) var(--padding-base) var(--padding-lg);
+
+ &-inner {
+ margin-top: var(--margin-sm);
+ }
+
+ &-params {
+ margin: var(--margin-xs) 0;
+
+ &-title {
+ margin-bottom: var(--margin-xs);
+ font-size: var(--font-size-xs);
+ font-weight: 500;
+ color: rgb(var(--text-color));
+ }
+
+ &-detail {
+ font-size: var(--font-size-xxs);
+ font-weight: 400;
+ white-space: pre-wrap;
+ word-wrap: break-word;
+ color: rgb(var(--text-color-secondary));
+ }
+ }
+ }
+
+ &-active {
+ color: rgb(var(--primary-color));
+ }
+}
+
+.formula-help-decorator {
+ cursor: pointer;
+
+ position: fixed;
+ z-index: 10;
+
+ display: flex;
+ align-items: center;
+ justify-content: center;
+
+ padding: var(--padding-xs);
+}
+
+.formula-help-param {
+ z-index: 1;
+ &-prefix {
+ z-index: 1;
+ }
+
+ &-item {
+ z-index: 1;
+ }
+
+ &-active {
+ z-index: 1;
+ }
+}
diff --git a/packages/sheets-formula-ui/src/views/formula-editor/hooks/useFormulaDescribe.ts b/packages/sheets-formula-ui/src/views/formula-editor/hooks/useFormulaDescribe.ts
new file mode 100644
index 0000000000..fac5faa176
--- /dev/null
+++ b/packages/sheets-formula-ui/src/views/formula-editor/hooks/useFormulaDescribe.ts
@@ -0,0 +1,87 @@
+/**
+ * Copyright 2023-present DreamNum Inc.
+ *
+ * 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 { IFunctionInfo } from '@univerjs/engine-formula';
+import { useDependency } from '@univerjs/core';
+import { LexerTreeBuilder } from '@univerjs/engine-formula';
+import { IDescriptionService } from '@univerjs/sheets-formula';
+import { useEffect, useRef, useState } from 'react';
+import { debounceTime, distinctUntilChanged, filter, map } from 'rxjs';
+import { useStateRef } from './useStateRef';
+
+export const useFormulaDescribe = (isNeed: boolean, formulaText: string, editor?: Editor) => {
+ const descriptionService = useDependency(IDescriptionService);
+ const lexerTreeBuilder = useDependency(LexerTreeBuilder);
+
+ const [functionInfo, functionInfoSet] = useState<IFunctionInfo | undefined>();
+ const [paramIndex, paramIndexSet] = useState<number>(-1);
+ const [isShow, isShowSet] = useState(true);
+ const isShowRef = useStateRef(isShow);
+
+ const formulaTextRef = useRef(formulaText);
+ formulaTextRef.current = formulaText;
+
+ const reset = () => {
+ functionInfoSet(undefined);
+ paramIndexSet(-1);
+ isShowSet(false);
+ };
+
+ useEffect(() => {
+ if (editor && isNeed) {
+ const d = editor.selectionChange$.pipe(debounceTime(50)).subscribe((e) => {
+ if (e.textRanges.length === 1) {
+ const [range] = e.textRanges;
+ if (range.collapsed && isShowRef.current) {
+ // 为什么减1,因为nodes是不包含初始 ‘=’ 字符的,但是 selection 会包含 '='
+ const res = lexerTreeBuilder.getFunctionAndParameter(formulaTextRef.current, range.startOffset - 1);
+ if (res) {
+ const { functionName, paramIndex } = res;
+ const info = descriptionService.getFunctionInfo(functionName);
+ functionInfoSet(info);
+ paramIndexSet(paramIndex);
+ return;
+ }
+ }
+ }
+ functionInfoSet(undefined);
+ paramIndexSet(-1);
+ });
+ const d2 = editor.selectionChange$.pipe(
+ filter((e) => e.textRanges.length === 1),
+ map((e) => e.textRanges[0].startOffset),
+ distinctUntilChanged()
+ ).subscribe(() => {
+ isShowSet(true);
+ });
+ return () => {
+ d.unsubscribe();
+ d2.unsubscribe();
+ };
+ }
+ }, [editor, isNeed]);
+
+ useEffect(() => {
+ if (!isNeed) {
+ reset();
+ }
+ }, [isNeed]);
+
+ return {
+ functionInfo, paramIndex, reset,
+ };
+};
diff --git a/packages/sheets-formula-ui/src/views/formula-editor/hooks/useFormulaSearch.ts b/packages/sheets-formula-ui/src/views/formula-editor/hooks/useFormulaSearch.ts
new file mode 100644
index 0000000000..4357d43ef5
--- /dev/null
+++ b/packages/sheets-formula-ui/src/views/formula-editor/hooks/useFormulaSearch.ts
@@ -0,0 +1,107 @@
+/**
+ * Copyright 2023-present DreamNum Inc.
+ *
+ * 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 { ISearchItem } from '@univerjs/sheets-formula';
+import type { INode } from '../../range-selector/hooks/useFormulaToken';
+import { useDependency } from '@univerjs/core';
+import { matchToken, sequenceNodeType } from '@univerjs/engine-formula';
+import { IDescriptionService } from '@univerjs/sheets-formula';
+import { useEffect, useRef, useState } from 'react';
+import { debounceTime } from 'rxjs';
+import { findIndexFromSequenceNodes } from '../../range-selector/utils/findIndexFromSequenceNodes';
+import { sequenceNodeToText } from '../../range-selector/utils/sequenceNodeToText';
+import { useStateRef } from '../hooks/useStateRef';
+
+export const useFormulaSearch = (isNeed: boolean, nodes: INode[] = [], editor?: Editor) => {
+ const descriptionService = useDependency(IDescriptionService);
+
+ const [searchList, searchListSet] = useState<ISearchItem[]>([]);
+ const [searchText, searchTextSet] = useState<string>('');
+ const indexRef = useRef(-1);
+ const stateRef = useStateRef({ nodes });
+
+ const reset = () => {
+ searchListSet([]);
+ searchTextSet('');
+ indexRef.current = -1;
+ };
+
+ useEffect(() => {
+ if (editor && isNeed) {
+ const d = editor.input$.pipe(debounceTime(300)).subscribe(() => {
+ const selections = editor.getSelectionRanges();
+ if (selections.length === 1) {
+ const nodes = stateRef.current.nodes;
+ const range = selections[0];
+ if (range.collapsed) {
+ // 为什么减1,因为nodes是不包含初始 ‘=’ 字符的,但是 selection 会包含 '='
+ const currentNodeIndex = findIndexFromSequenceNodes(nodes, range.startOffset - 1, false);
+ indexRef.current = currentNodeIndex;
+ const currentNode = nodes[currentNodeIndex];
+ if (currentNode && typeof currentNode !== 'string' && currentNode.nodeType === sequenceNodeType.FUNCTION) {
+ indexRef.current = currentNodeIndex;
+ const token = currentNode.token;
+ const list = descriptionService.getSearchListByNameFirstLetter(token);
+ searchListSet(list);
+ searchTextSet(token);
+ return;
+ }
+ }
+ }
+ indexRef.current = -1;
+ searchTextSet('');
+ searchListSet((pre) => {
+ if (!pre?.length) {
+ return pre;
+ }
+ return [];
+ });
+ });
+ return () => {
+ d.unsubscribe();
+ };
+ };
+ }, [editor, isNeed]);
+
+ useEffect(() => {
+ if (!isNeed) {
+ reset();
+ }
+ }, [isNeed]);
+
+ const handlerFormulaReplace = (formulaName: string) => {
+ const cloneNodes = [...stateRef.current.nodes];
+ if (indexRef.current !== -1) {
+ const lastNodes = cloneNodes.splice(indexRef.current + 1);
+ const oldNode = cloneNodes.pop() || '';
+ let offset = (typeof oldNode === 'string' ? oldNode.length : oldNode.token.length) - formulaName.length;
+ cloneNodes.push(formulaName);
+ if (lastNodes[0] !== matchToken.OPEN_BRACKET) {
+ cloneNodes.push(matchToken.OPEN_BRACKET);
+ offset--;
+ }
+ const text = sequenceNodeToText([...cloneNodes, ...lastNodes]);
+ return { text, offset };
+ }
+ };
+ return {
+ searchList,
+ searchText,
+ handlerFormulaReplace,
+ reset,
+ };
+};
diff --git a/packages/sheets-formula-ui/src/views/formula-editor/hooks/useHighlight.ts b/packages/sheets-formula-ui/src/views/formula-editor/hooks/useHighlight.ts
new file mode 100644
index 0000000000..26d90e02b5
--- /dev/null
+++ b/packages/sheets-formula-ui/src/views/formula-editor/hooks/useHighlight.ts
@@ -0,0 +1,176 @@
+/**
+ * Copyright 2023-present DreamNum Inc.
+ *
+ * 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 { ISequenceNode } from '@univerjs/engine-formula';
+import type { ISelectionStyle, ISelectionWithStyle } from '@univerjs/sheets';
+import { ColorKit, IUniverInstanceService, ThemeService, useDependency } from '@univerjs/core';
+import { IEditorService } from '@univerjs/docs-ui';
+import { deserializeRangeWithSheet } from '@univerjs/engine-formula';
+import { IRenderManagerService } from '@univerjs/engine-render';
+import { IRefSelectionsService, setEndForRange } from '@univerjs/sheets';
+import { IDescriptionService } from '@univerjs/sheets-formula';
+import { attachRangeWithCoord, SheetSkeletonManagerService } from '@univerjs/sheets-ui';
+import { useEffect, useState } from 'react';
+import { RefSelectionsRenderService } from '../../../services/render-services/ref-selections.render-service';
+import { buildTextRuns, useColor } from '../../range-selector/hooks/useHighlight';
+
+interface IRefSelection {
+ refIndex: number;
+ themeColor: string;
+ token: string;
+}
+
+/**
+ * @param {string} unitId
+ * @param {string} subUnitId 打开面板的时候传入的 sheetId
+ * @param {IRefSelection[]} refSelections
+ */
+
+export function useSheetHighlight(isNeed: boolean, unitId: string, subUnitId: string, refSelections: IRefSelection[]) {
+ const univerInstanceService = useDependency(IUniverInstanceService);
+ const themeService = useDependency(ThemeService);
+ const refSelectionsService = useDependency(IRefSelectionsService);
+ const renderManagerService = useDependency(IRenderManagerService);
+ const render = renderManagerService.getRenderById(unitId);
+ const refSelectionsRenderService = render?.with(RefSelectionsRenderService);
+ const sheetSkeletonManagerService = render?.with(SheetSkeletonManagerService);
+
+ const [ranges, rangesSet] = useState<ISelectionWithStyle[]>([]);
+
+ useEffect(() => {
+ const workbook = univerInstanceService.getUnit<Workbook>(unitId);
+ const worksheet = workbook?.getActiveSheet();
+ const selectionWithStyle: ISelectionWithStyle[] = [];
+ if (!workbook || !worksheet || !isNeed) {
+ rangesSet(selectionWithStyle);
+ return;
+ }
+ const currentSheetId = worksheet?.getSheetId();
+ const getSheetIdByName = (name: string) => workbook?.getSheetBySheetName(name)?.getSheetId();
+
+ for (let i = 0, len = refSelections.length; i < len; i++) {
+ const refSelection = refSelections[i];
+ const { themeColor, token, refIndex } = refSelection;
+
+ const unitRangeName = deserializeRangeWithSheet(token);
+ const { unitId: refUnitId, sheetName, range: rawRange } = unitRangeName;
+ if (refUnitId && unitId !== refUnitId) {
+ continue;
+ }
+
+ const refSheetId = getSheetIdByName(sheetName);
+
+ if (refSheetId && refSheetId !== currentSheetId) {
+ continue;
+ }
+
+ const range = setEndForRange(rawRange, worksheet.getRowCount(), worksheet.getColumnCount());
+
+ selectionWithStyle.push({
+ range,
+ primary: null,
+ style: getFormulaRefSelectionStyle(themeService, themeColor, refIndex.toString()),
+ });
+ }
+ rangesSet(selectionWithStyle);
+ }, [unitId, subUnitId, refSelections, isNeed]);
+
+ useEffect(() => {
+ const skeleton = sheetSkeletonManagerService?.getCurrentSkeleton();
+ if (skeleton && isNeed) {
+ const allControls = refSelectionsRenderService?.getSelectionControls() || [];
+ if (allControls.length === ranges.length) {
+ allControls.forEach((control, index) => {
+ const selection = ranges[index];
+ control.updateRange(attachRangeWithCoord(skeleton, selection.range), null);
+ control.updateStyle(selection.style!);
+ });
+ } else {
+ refSelectionsService.setSelections(ranges);
+ }
+ }
+ }, [ranges, isNeed]);
+}
+
+export function useDocHight(editorId: string, sequenceNodes: (string | ISequenceNode)[]) {
+ const editorService = useDependency(IEditorService);
+ const descriptionService = useDependency(IDescriptionService);
+ const colorMap = useColor();
+ const [ranges, rangesSet] = useState<IRefSelection[]>([]);
+
+ useEffect(() => {
+ const editor = editorService.getEditor(editorId);
+ if (!editor) {
+ return;
+ }
+ const data = editor.getDocumentData();
+ if (!data) {
+ return;
+ }
+ const body = data.body;
+ if (!body) {
+ return;
+ }
+ const cloneBody = { dataStream: '', ...data.body };
+
+ if (sequenceNodes == null || sequenceNodes.length === 0) {
+ cloneBody.textRuns = [];
+ cloneBody.dataStream = data.body?.dataStream || '\r\n';
+ rangesSet([]);
+ } else {
+ const { textRuns, refSelections } = buildTextRuns(descriptionService, colorMap, sequenceNodes);
+ // 公式前面需要加1
+ textRuns.forEach((e) => {
+ e.ed++;
+ e.st++;
+ });
+ cloneBody.textRuns = textRuns;
+ const text = sequenceNodes.reduce((pre, cur) => {
+ if (typeof cur === 'string') {
+ return `${pre}${cur}`;
+ }
+ return `${pre}${cur.token}`;
+ }, '');
+ cloneBody.dataStream = `=${text}\r\n`;
+ rangesSet(refSelections);
+ }
+ // Switching between uppercase and lowercase will trigger a reflow, causing the cursor to be misplaced. Let's refresh the cursor position here.
+ const selection = editor.getSelectionRanges();
+ const cloneData = { ...data, body: cloneBody };
+ editor.setDocumentData(cloneData, selection);
+ }, [editorId, sequenceNodes, colorMap]);
+
+ return ranges;
+}
+
+function getFormulaRefSelectionStyle(themeService: ThemeService, refColor: string, id: string): ISelectionStyle {
+ const style = themeService.getCurrentTheme();
+ const fill = new ColorKit(refColor).setAlpha(0.05).toRgbString();
+ return {
+ id,
+ strokeWidth: 1,
+ stroke: refColor,
+ fill,
+ widgets: { tl: true, tc: true, tr: true, ml: true, mr: true, bl: true, bc: true, br: true },
+ widgetSize: 6,
+ widgetStrokeWidth: 1,
+ widgetStroke: style.colorWhite,
+ hasAutoFill: false,
+ hasRowHeader: false,
+ hasColumnHeader: false,
+ };
+}
diff --git a/packages/sheets-formula-ui/src/views/formula-editor/hooks/useResizeScrollObserver.ts b/packages/sheets-formula-ui/src/views/formula-editor/hooks/useResizeScrollObserver.ts
new file mode 100644
index 0000000000..b299d2b98b
--- /dev/null
+++ b/packages/sheets-formula-ui/src/views/formula-editor/hooks/useResizeScrollObserver.ts
@@ -0,0 +1,47 @@
+/**
+ * Copyright 2023-present DreamNum Inc.
+ *
+ * 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 { useEffect } from 'react';
+
+type Callback = () => void;
+
+export const useResizeScrollObserver = (callback: Callback, delay: number = 100): void => {
+ useEffect(() => {
+ let throttleTimeout: number | null = null;
+
+ const throttledCallback = () => {
+ if (throttleTimeout === null) {
+ throttleTimeout = window.setTimeout(() => {
+ callback();
+ throttleTimeout = null;
+ }, delay);
+ }
+ };
+
+ window.addEventListener('scroll', throttledCallback);
+ window.addEventListener('resize', throttledCallback);
+
+ return () => {
+ if (throttleTimeout !== null) {
+ clearTimeout(throttleTimeout);
+ }
+ window.removeEventListener('scroll', throttledCallback);
+ window.removeEventListener('resize', throttledCallback);
+ };
+ }, [callback, delay]);
+};
+
+export default useResizeScrollObserver;
diff --git a/packages/sheets-formula-ui/src/views/formula-editor/hooks/useSelectionAdd.ts b/packages/sheets-formula-ui/src/views/formula-editor/hooks/useSelectionAdd.ts
new file mode 100644
index 0000000000..1ad7b7bcf2
--- /dev/null
+++ b/packages/sheets-formula-ui/src/views/formula-editor/hooks/useSelectionAdd.ts
@@ -0,0 +1,185 @@
+/**
+ * Copyright 2023-present DreamNum Inc.
+ *
+ * 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 { INode } from '../../range-selector/utils/filterReferenceNode';
+import { useDependency } from '@univerjs/core';
+import { compareToken, matchToken, operatorToken } from '@univerjs/engine-formula';
+import { IRenderManagerService } from '@univerjs/engine-render';
+import { useEffect, useMemo, useRef } from 'react';
+import { debounceTime } from 'rxjs';
+import { RefSelectionsRenderService } from '../../../services/render-services/ref-selections.render-service';
+import { findIndexFromSequenceNodes } from '../../range-selector/utils/findIndexFromSequenceNodes';
+import { useStateRef } from './useStateRef';
+
+const createLock = (initValue: boolean, step = 300) => {
+ let isEnableCancel = initValue;
+ let time = 0 as any;
+ const getValue = () => isEnableCancel;
+ const setValue = (v: boolean) => {
+ clearTimeout(time);
+ isEnableCancel = v;
+ };
+ function reset() {
+ clearTimeout(time);
+ time = setTimeout(() => {
+ isEnableCancel = initValue;
+ }, step);
+ }
+ return {
+ getValue,
+ setValue,
+ reset,
+ };
+};
+
+const baseToken = [
+ compareToken.EQUALS,
+ compareToken.GREATER_THAN,
+ compareToken.GREATER_THAN_OR_EQUAL,
+ compareToken.LESS_THAN,
+ compareToken.LESS_THAN_OR_EQUAL,
+ compareToken.NOT_EQUAL,
+ operatorToken.CONCATENATE,
+ operatorToken.DIVIDED,
+ operatorToken.MINUS,
+ operatorToken.MULTIPLY,
+ operatorToken.PLUS,
+ operatorToken.POWER,
+ matchToken.COMMA,
+];
+const currentNodeAddToken = [
+ ...baseToken,
+ matchToken.COLON,
+ matchToken.OPEN_BRACKET,
+];
+
+const nextNodeAddToken = [
+ ...baseToken,
+ matchToken.CLOSE_BRACKET,
+];
+
+const getContent = (node: INode) => typeof node === 'string' ? node : node.token;
+/**
+ * 根据输入内容,以及当前光标位置判断下一个 mouseDown 事件是不是需要新增选区
+ *
+ * @param {string} unitId
+ * @param {INode[]} sequenceNodes
+ * @param {Editor} [editor]
+ * @return {*}
+ */
+// eslint-disable-next-line max-lines-per-function
+export const useSelectionAdd = (unitId: string, sequenceNodes: INode[], editor?: Editor) => {
+ const renderManagerService = useDependency(IRenderManagerService);
+ const render = renderManagerService.getRenderById(unitId);
+ const refSelectionsRenderService = render?.with(RefSelectionsRenderService);
+ const isNeedAddSelection = useRef(false);
+ const sequenceNodesRef = useStateRef(sequenceNodes);
+
+ // 非用户行为导致的选区改变,应该屏蔽选区变更事件
+ const isLockSelectionEvent = useMemo(() => createLock(false, 300), []);
+
+ const setIsAddSelection = (v: boolean) => {
+ if (refSelectionsRenderService) {
+ refSelectionsRenderService.setSkipLastEnabled(v);
+ }
+ isNeedAddSelection.current = v;
+ };
+ const getIsNeedAddSelection = () => isNeedAddSelection.current;
+
+ useEffect(() => {
+ if (editor && refSelectionsRenderService) {
+ const d1 = editor.input$.subscribe((e) => {
+ const content = e.content as any;
+ if (content.length === 1 && currentNodeAddToken.includes(content)) {
+ setIsAddSelection(true);
+ isLockSelectionEvent.setValue(true);
+ isLockSelectionEvent.reset();
+ } else {
+ setIsAddSelection(false);
+ isLockSelectionEvent.setValue(false);
+ }
+ });
+ // sequenceNodes 的创建会在 input 事件之后,为了拿到最新的 sequenceNodes , 这里延后 100ms
+ const d2 = editor.selectionChange$.pipe(debounceTime(100)).subscribe((e) => {
+ if (isLockSelectionEvent.getValue()) {
+ return;
+ }
+ const selections = e.textRanges;
+ if (!selections.length) {
+ return;
+ }
+ if (selections.length !== 1) {
+ setIsAddSelection(false);
+ return;
+ }
+ const range = selections[0];
+ if (!range.collapsed) {
+ setIsAddSelection(false);
+ return;
+ }
+ const sequenceNodes = sequenceNodesRef.current;
+ if (!sequenceNodes.length) {
+ setIsAddSelection(true);
+ return;
+ }
+ // ‘=’不会进入 sequenceNodes ,所以需要 -1
+ const startOffset = range.startOffset - 1;
+
+ if (startOffset === 0) {
+ const nextIndex = findIndexFromSequenceNodes(sequenceNodes, 1, false);
+ const nextNode = sequenceNodes[nextIndex] || '';
+ const nextContent = getContent(nextNode);
+ if (baseToken.includes(nextContent as any)) {
+ setIsAddSelection(true);
+ return;
+ }
+ }
+ const index = findIndexFromSequenceNodes(sequenceNodes, startOffset, false);
+ const currentNode = sequenceNodes[index];
+ if (!currentNode) {
+ setIsAddSelection(false);
+ return;
+ }
+ const nextNode = sequenceNodes[index + 1];
+ const nextContent = getContent(nextNode) as any;
+ const content = getContent(currentNode) as any;
+ if (currentNodeAddToken.includes(content) && (!nextNode || nextNodeAddToken.includes(nextContent))) {
+ setIsAddSelection(true);
+ } else {
+ setIsAddSelection(false);
+ }
+ });
+ // 增加一个延时,外部接收到 moveEnd 事件后,再重置状态
+ refSelectionsRenderService.selectionMoveEnd$.subscribe(() => {
+ Promise.resolve().then(() => {
+ setIsAddSelection(false);
+ });
+ });
+
+ return () => {
+ d1.unsubscribe();
+ d2.unsubscribe();
+ };
+ }
+ }, [editor, refSelectionsRenderService]);
+
+ return {
+ setIsAddSelection,
+ getIsNeedAddSelection,
+ isLockSelectionEvent,
+ };
+};
diff --git a/packages/sheets-formula-ui/src/views/formula-editor/hooks/useSheetSelectionChange.ts b/packages/sheets-formula-ui/src/views/formula-editor/hooks/useSheetSelectionChange.ts
new file mode 100644
index 0000000000..3756caee2e
--- /dev/null
+++ b/packages/sheets-formula-ui/src/views/formula-editor/hooks/useSheetSelectionChange.ts
@@ -0,0 +1,237 @@
+/**
+ * Copyright 2023-present DreamNum Inc.
+ *
+ * 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 { Editor } from '@univerjs/docs-ui';
+
+import type { ISelectionWithCoordAndStyle } from '@univerjs/sheets';
+import type { INode } from '../../range-selector/utils/filterReferenceNode';
+import { DisposableCollection, IUniverInstanceService, useDependency } from '@univerjs/core';
+import { deserializeRangeWithSheet, sequenceNodeType, serializeRange, serializeRangeWithSheet } from '@univerjs/engine-formula';
+import { IRenderManagerService } from '@univerjs/engine-render';
+import { useEffect, useRef } from 'react';
+import { merge } from 'rxjs';
+import { debounceTime, distinctUntilChanged, map, throttleTime } from 'rxjs/operators';
+import { RefSelectionsRenderService } from '../../../services/render-services/ref-selections.render-service';
+import { findIndexFromSequenceNodes } from '../../range-selector/utils/findIndexFromSequenceNodes';
+import { getOffsetFromSequenceNodes } from '../../range-selector/utils/getOffsetFromSequenceNodes';
+import { sequenceNodeToText } from '../../range-selector/utils/sequenceNodeToText';
+import { unitRangesToText } from '../../range-selector/utils/unitRangesToText';
+import { useStateRef } from '../hooks/useStateRef';
+import { useSelectionAdd } from './useSelectionAdd';
+
+const noop = (() => { }) as any;
+export const useSheetSelectionChange = (
+ isNeed: boolean,
+ unitId: string,
+ subUnitId: string,
+ sequenceNodes: INode[],
+ isSupportAcrossSheet: boolean,
+ editor?: Editor,
+ handleRangeChange: ((refString: string, offset: number) => void) = noop) => {
+ const renderManagerService = useDependency(IRenderManagerService);
+ const univerInstanceService = useDependency(IUniverInstanceService);
+
+ const sequenceNodesRef = useStateRef(sequenceNodes);
+
+ const { getIsNeedAddSelection } = useSelectionAdd(unitId, sequenceNodes, editor);
+
+ const workbook = univerInstanceService.getUnit<Workbook>(unitId);
+ const getSheetNameById = (sheetId: string) => workbook?.getSheetBySheetId(sheetId)?.getName() ?? '';
+
+ const render = renderManagerService.getRenderById(unitId);
+ const refSelectionsRenderService = render?.with(RefSelectionsRenderService);
+
+ const isScalingRef = useRef(false);
+
+ useEffect(() => {
+ if (refSelectionsRenderService && isNeed) {
+ let isFirst = true;
+ const handleSelectionsChange = (selections: ISelectionWithCoordAndStyle[]) => {
+ if (isFirst || isScalingRef.current) {
+ isFirst = false;
+ return;
+ }
+ const currentDocSelections = editor?.getSelectionRanges();
+ if (currentDocSelections?.length !== 1) {
+ return;
+ }
+ const docRange = currentDocSelections[0];
+ const offset = docRange.startOffset - 1;
+ const sequenceNodes = [...sequenceNodesRef.current];
+ if (getIsNeedAddSelection()) {
+ if (offset !== 0) {
+ const index = findIndexFromSequenceNodes(sequenceNodes, offset, false);
+ if (index === -1 && sequenceNodes.length) {
+ return;
+ }
+ const range = selections[selections.length - 1];
+ const lastNodes = sequenceNodes.splice(index + 1);
+ const rangeSheetId = range.rangeWithCoord.sheetId ?? subUnitId;
+ const unitRangeName = {
+ range: range.rangeWithCoord,
+ unitId: range.rangeWithCoord.unitId ?? unitId,
+ sheetName: getSheetNameById(rangeSheetId),
+ };
+ const refRanges = unitRangesToText([unitRangeName], isSupportAcrossSheet);
+ sequenceNodes.push({ token: refRanges[0], nodeType: sequenceNodeType.REFERENCE } as any);
+ const newSequenceNodes = [...sequenceNodes, ...lastNodes];
+ const result = sequenceNodeToText(newSequenceNodes);
+ handleRangeChange(result, getOffsetFromSequenceNodes(sequenceNodes));
+ } else {
+ const range = selections[selections.length - 1];
+ const rangeSheetId = range.rangeWithCoord.sheetId ?? subUnitId;
+ const unitRangeName = {
+ range: range.rangeWithCoord,
+ unitId: range.rangeWithCoord.unitId ?? unitId,
+ sheetName: getSheetNameById(rangeSheetId),
+ };
+ const refRanges = unitRangesToText([unitRangeName], isSupportAcrossSheet);
+ sequenceNodes.unshift({ token: refRanges[0], nodeType: sequenceNodeType.REFERENCE } as any);
+ const result = sequenceNodeToText(sequenceNodes);
+ handleRangeChange(result, refRanges[0].length);
+ }
+ } else {
+ // 更新全部的 ref Selection
+ let currentRefIndex = 0;
+ const currentText = sequenceNodes.map((item) => {
+ if (typeof item === 'string') {
+ return item;
+ }
+ if (item.nodeType === sequenceNodeType.REFERENCE) {
+ const selection = selections[currentRefIndex];
+ currentRefIndex++;
+ if (!selection) {
+ return '';
+ }
+ const rangeSheetId = selection.rangeWithCoord.sheetId ?? subUnitId;
+ const unitRangeName = {
+ range: selection.rangeWithCoord,
+ unitId: selection.rangeWithCoord.unitId ?? unitId,
+ sheetName: getSheetNameById(rangeSheetId),
+ };
+ const refRanges = unitRangesToText([unitRangeName], isSupportAcrossSheet);
+ return refRanges[0];
+ }
+ return item.token;
+ }).join('');
+ const theLastList: string[] = [];
+ for (let index = currentRefIndex; index <= selections.length - 1; index++) {
+ const selection = selections[index];
+ const rangeSheetId = selection.rangeWithCoord.sheetId ?? subUnitId;
+ const unitRangeName = {
+ range: selection.rangeWithCoord,
+ unitId: selection.rangeWithCoord.unitId ?? unitId,
+ sheetName: getSheetNameById(rangeSheetId),
+ };
+ const refRanges = unitRangesToText([unitRangeName], isSupportAcrossSheet);
+ theLastList.push(refRanges[0]);
+ }
+ const result = `${currentText}${theLastList.length && currentText.length ? ',' : ''}${theLastList.join(',')}`;
+ handleRangeChange(result, result.length);
+ }
+ };
+ const d1 = refSelectionsRenderService.selectionMoveEnd$.subscribe((selections) => {
+ handleSelectionsChange(selections);
+ isScalingRef.current = false;
+ });
+
+ // const d2 = refSelectionsRenderService.selectionMoving$.subscribe((selections) => {
+ // handleSelectionsChange(selections);
+ // });
+
+ return () => {
+ d1.unsubscribe();
+ // d2.unsubscribe();
+ };
+ }
+ }, [refSelectionsRenderService, editor, isSupportAcrossSheet, isNeed]);
+
+ useEffect(() => {
+ if (isNeed && refSelectionsRenderService && editor) {
+ 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 = sequenceNodesRef.current.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);
+ }
+ offset += cloneNode.token.length;
+ currentIndex++;
+
+ return cloneNode;
+ }
+ if (!isFinish) {
+ offset += node.token.length;
+ }
+ currentIndex++;
+ return node;
+ }
+ if (!isFinish) {
+ offset += node.token.length;
+ }
+ return node;
+ });
+ const result = sequenceNodeToText(newSequenceNodes);
+ handleRangeChange(result, offset || -1);
+ };
+ const reListen = () => {
+ disposableCollection.dispose();
+ const controls = refSelectionsRenderService.getSelectionControls();
+ controls.forEach((control, index) => {
+ disposableCollection.add(merge(control.selectionMoving$, control.selectionScaling$).pipe(
+ throttleTime(30),
+ map((e) => {
+ return serializeRange(e);
+ }),
+ distinctUntilChanged()
+ ).subscribe((rangeText) => {
+ isScalingRef.current = true;
+ handleSequenceNodeReplace(rangeText, index);
+ }));
+ });
+ };
+ const dispose = merge(editor.input$, refSelectionsRenderService.selectionMoveEnd$).pipe(debounceTime(50)).subscribe(() => {
+ reListen();
+ });
+
+ return () => {
+ dispose.unsubscribe();
+ disposableCollection.dispose();
+ };
+ }
+ }, [isNeed, refSelectionsRenderService, editor]);
+};
diff --git a/packages/sheets-formula-ui/src/views/formula-editor/hooks/useStateRef.ts b/packages/sheets-formula-ui/src/views/formula-editor/hooks/useStateRef.ts
new file mode 100644
index 0000000000..37f2bff40a
--- /dev/null
+++ b/packages/sheets-formula-ui/src/views/formula-editor/hooks/useStateRef.ts
@@ -0,0 +1,23 @@
+/**
+ * Copyright 2023-present DreamNum Inc.
+ *
+ * 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 { useRef } from 'react';
+
+export const useStateRef = <T = any>(value: T) => {
+ const cache = useRef<T>();
+ cache.current = value;
+ return cache as { current: T };
+};
diff --git a/packages/sheets-formula-ui/src/views/formula-editor/hooks/useVerify.ts b/packages/sheets-formula-ui/src/views/formula-editor/hooks/useVerify.ts
new file mode 100644
index 0000000000..d1d6088d02
--- /dev/null
+++ b/packages/sheets-formula-ui/src/views/formula-editor/hooks/useVerify.ts
@@ -0,0 +1,46 @@
+/**
+ * Copyright 2023-present DreamNum Inc.
+ *
+ * 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 { IFormulaEditorProps } from '../index';
+import { useDependency } from '@univerjs/core';
+import { LexerTreeBuilder, operatorToken } from '@univerjs/engine-formula';
+import { useEffect, useRef } from 'react';
+
+export const useVerify = (isNeed: boolean, onVerify: IFormulaEditorProps['onVerify'], formulaText: string) => {
+ const lexerTreeBuilder = useDependency(LexerTreeBuilder);
+ 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 = lexerTreeBuilder.checkIfAddBracket(formulaText);
+ onVerify(result === 0 && formulaText.startsWith(operatorToken.EQUALS), `${formulaText}`);
+ }
+ }
+ }, [formulaText, onVerify]);
+};
diff --git a/packages/sheets-formula-ui/src/views/formula-editor/index.module.less b/packages/sheets-formula-ui/src/views/formula-editor/index.module.less
new file mode 100644
index 0000000000..878daf0feb
--- /dev/null
+++ b/packages/sheets-formula-ui/src/views/formula-editor/index.module.less
@@ -0,0 +1,37 @@
+.sheet-embedding-formula-editor {
+ &-active {
+ border-color: rgb(var(--hyacinth-500)) !important;
+ }
+
+ &-wrap {
+ height: 32px;
+ padding: 6px 8px 2px 6px;
+ width: 100%;
+ display: flex;
+ justify-content: space-around;
+ align-items: center;
+ gap: 8px;
+ border: 1px solid rgb(var(--border-color));
+ border-radius: var(--border-radius-base);
+ box-sizing: border-box;
+ position: relative;
+
+ .sheet-embedding-formula-editor-text {
+ width: 100%;
+ height: 100%;
+ position: relative;
+ }
+
+ .sheet-embedding-formula-editor-error-wrap {
+ font-size: 12px;
+ color: rgb(var(--red-500));
+ position: absolute;
+ bottom: -18px;
+ left: 0px;
+ }
+ }
+
+ &-error {
+ border: 1px solid rgb(var(--red-500)) !important;
+ }
+}
diff --git a/packages/sheets-formula-ui/src/views/formula-editor/index.tsx b/packages/sheets-formula-ui/src/views/formula-editor/index.tsx
new file mode 100644
index 0000000000..a018dee429
--- /dev/null
+++ b/packages/sheets-formula-ui/src/views/formula-editor/index.tsx
@@ -0,0 +1,248 @@
+/**
+ * Copyright 2023-present DreamNum Inc.
+ *
+ * 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 { IDisposable } from '@univerjs/core';
+import type { Editor } from '@univerjs/docs-ui';
+import type { ReactNode } from 'react';
+import { createInternalEditorID, generateRandomId, useDependency } from '@univerjs/core';
+import { IEditorService } from '@univerjs/docs-ui';
+import { operatorToken } from '@univerjs/engine-formula';
+import { EMBEDDING_FORMULA_EDITOR } from '@univerjs/sheets-ui';
+import clsx from 'clsx';
+import React, { useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';
+import { useFocus } from '../range-selector/hooks/useFocus';
+import { useFormulaToken } from '../range-selector/hooks/useFormulaToken';
+import { useLeftAndRightArrow } from '../range-selector/hooks/useLeftAndRightArrow';
+import { useRefactorEffect } from '../range-selector/hooks/useRefactorEffect';
+import { useRefocus } from '../range-selector/hooks/useRefocus';
+import { useResetSelection } from '../range-selector/hooks/useResetSelection';
+import { useResize } from '../range-selector/hooks/useResize';
+import { HelpFunction } from './help-function/HelpFunction';
+import { useFormulaDescribe } from './hooks/useFormulaDescribe';
+import { useFormulaSearch } from './hooks/useFormulaSearch';
+import { useDocHight, useSheetHighlight } from './hooks/useHighlight';
+import { useSheetSelectionChange } from './hooks/useSheetSelectionChange';
+import { useVerify } from './hooks/useVerify';
+import styles from './index.module.less';
+import { SearchFunction } from './search-function/SearchFunction';
+import { getFormulaText } from './utils/getFormulaText';
+
+export interface IFormulaEditorProps {
+ unitId: string;
+ subUnitId: string;
+ initValue: `=${string}`;
+ onChange: (text: string) => void;
+ errorText?: string | ReactNode;
+ onVerify?: (res: boolean, result: string) => void;
+ isFocus?: boolean;
+ onFocus?: () => void;
+ onBlur?: () => void;
+ isSupportAcrossSheet?: boolean;
+ actions?: {
+ handleOutClick?: (e: MouseEvent, cb: () => void) => void;
+ };
+}
+const noop = () => { };
+export function FormulaEditor(props: IFormulaEditorProps) {
+ const { errorText, initValue, unitId, subUnitId, isFocus: _isFocus = true, isSupportAcrossSheet = false,
+ onFocus = noop,
+ onChange,
+ onVerify,
+ actions,
+ } = props;
+
+ const editorService = useDependency(IEditorService);
+
+ const sheetEmbeddingRef = useRef<HTMLDivElement>(null);
+ const [formulaText, formulaTextSet] = useState(() => {
+ if (initValue.startsWith(operatorToken.EQUALS)) {
+ return initValue;
+ }
+ return '';
+ });
+
+ // init actions
+ if (actions) {
+ actions.handleOutClick = (e: MouseEvent, cb: () => void) => {
+ if (sheetEmbeddingRef.current) {
+ const isContain = sheetEmbeddingRef.current.contains(e.target as Node);
+ !isContain && cb();
+ }
+ };
+ }
+
+ const formulaWithoutEqualSymbol = useMemo(() => {
+ return getFormulaText(formulaText);
+ }, [formulaText]);
+
+ const searchFunctionRef = useRef<HTMLElement>(null);
+ const [editor, editorSet] = useState<Editor>();
+ const [isFocus, isFocusSet] = useState(_isFocus);
+ const formulaEditorContainerRef = useRef(null);
+ const editorId = useMemo(() => createInternalEditorID(`${EMBEDDING_FORMULA_EDITOR}-${generateRandomId(4)}`), []);
+ const isError = useMemo(() => errorText !== undefined, [errorText]);
+
+ const { sequenceNodes } = useFormulaToken(formulaWithoutEqualSymbol);
+ const refSelections = useDocHight(editorId, sequenceNodes);
+ useVerify(isFocus, onVerify, formulaText);
+ const focus = useFocus(editor);
+
+ const resetSelection = useResetSelection(isFocus);
+
+ useLayoutEffect(() => {
+ // 在进行多个 input 切换的时候,失焦必须快于获得焦点.
+ if (_isFocus) {
+ const time = setTimeout(() => {
+ isFocusSet(_isFocus);
+ if (_isFocus) {
+ focus();
+ }
+ }, 30);
+ return () => {
+ clearTimeout(time);
+ };
+ } else {
+ resetSelection();
+ isFocusSet(_isFocus);
+ }
+ }, [_isFocus, focus]);
+
+ const handleSelectionChange = (refString: string, offset: number) => {
+ const result = `=${refString}`;
+ formulaTextSet(result);
+ onChange(result);
+ if (offset > -1) {
+ setTimeout(() => {
+ editor?.setSelectionRanges([{ startOffset: offset + 1, endOffset: offset + 1 }]);
+ }, 30);
+ }
+ };
+
+ useSheetHighlight(isFocus, unitId, subUnitId, refSelections);
+ useResize(editor);
+ useRefactorEffect(isFocus, unitId);
+ useLeftAndRightArrow(isFocus, editor);
+ useSheetSelectionChange(isFocus, unitId, subUnitId, sequenceNodes, isSupportAcrossSheet, editor, handleSelectionChange);
+ useRefocus();
+
+ const { searchList, searchText, handlerFormulaReplace, reset: resetFormulaSearch } = useFormulaSearch(isFocus, sequenceNodes, editor);
+ const { functionInfo, paramIndex, reset } = useFormulaDescribe(isFocus, formulaText, editor);
+
+ useEffect(() => {
+ if (editor) {
+ const d = editor.input$.subscribe((e) => {
+ const text = (e.data.body?.dataStream ?? '').replaceAll(/\n|\r/g, '');
+ formulaTextSet(text);
+ onChange(text);
+ });
+ return () => {
+ d.unsubscribe();
+ };
+ }
+ }, [editor]);
+
+ useLayoutEffect(() => {
+ let dispose: IDisposable;
+ if (formulaEditorContainerRef.current) {
+ dispose = editorService.register({
+ autofocus: true,
+ editorUnitId: editorId,
+ isSingle: true,
+ initialSnapshot: {
+ id: editorId,
+ body: { dataStream: `${initValue}\r\n` },
+ documentStyle: {},
+ },
+ }, formulaEditorContainerRef.current);
+ const editor = editorService.getEditor(editorId)! as Editor;
+ editorSet(editor);
+ }
+
+ return () => {
+ dispose?.dispose();
+ };
+ }, []);
+
+ const handleFunctionSelect = (v: string) => {
+ const res = handlerFormulaReplace(v);
+ if (res) {
+ formulaTextSet(`=${res.text}`);
+ const selections = editor?.getSelectionRanges();
+ if (selections && selections.length === 1) {
+ const range = selections[0];
+ if (range.collapsed) {
+ const offset = res.offset;
+ setTimeout(() => {
+ editor?.setSelectionRanges([{ startOffset: range.startOffset - offset, endOffset: range.endOffset - offset }]);
+ }, 30);
+ }
+ }
+ resetFormulaSearch();
+ focus();
+ }
+ };
+
+ const handleMouseUp = () => {
+ // 在进行多个 input 切换的时候,失焦必须快于获得焦点.
+ // 即使失焦是 mousedown 事件,
+ // 聚焦是 mouseup 事件,
+ // 但是 react 的 useEffect 无法保证顺序,无法确保失焦在聚焦之前.
+
+ setTimeout(() => {
+ isFocusSet(true);
+ onFocus();
+ focus();
+ }, 30);
+ };
+ return (
+ <div className={styles.sheetEmbeddingFormulaEditor}>
+ <div
+ className={clsx(styles.sheetEmbeddingFormulaEditorWrap, {
+ [styles.sheetEmbeddingFormulaEditorActive]: isFocus,
+ [styles.sheetEmbeddingFormulaEditorError]: isError,
+ })}
+ ref={sheetEmbeddingRef}
+ >
+ <div
+ className={styles.sheetEmbeddingFormulaEditorText}
+ ref={formulaEditorContainerRef}
+ onMouseUp={handleMouseUp}
+ >
+ </div>
+ {errorText !== undefined ? <div className={styles.sheetEmbeddingFormulaEditorErrorWrap}>{errorText}</div> : null}
+ </div>
+ <HelpFunction
+ editorId={editorId}
+ paramIndex={paramIndex}
+ functionInfo={functionInfo}
+ onClose={() => {
+ reset();
+ focus();
+ }}
+ >
+ </HelpFunction>
+ <SearchFunction
+ searchText={searchText}
+ editorId={editorId}
+ searchList={searchList}
+ onSelect={handleFunctionSelect}
+ ref={searchFunctionRef}
+ >
+ </SearchFunction>
+ </div>
+ )
+ ;
+}
diff --git a/packages/sheets-formula-ui/src/views/formula-editor/search-function/SearchFunction.tsx b/packages/sheets-formula-ui/src/views/formula-editor/search-function/SearchFunction.tsx
new file mode 100644
index 0000000000..858d2d1d2c
--- /dev/null
+++ b/packages/sheets-formula-ui/src/views/formula-editor/search-function/SearchFunction.tsx
@@ -0,0 +1,233 @@
+/**
+ * Copyright 2023-present DreamNum Inc.
+ *
+ * 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 { ISearchItem } from '@univerjs/sheets-formula';
+import { CommandType, DisposableCollection, ICommandService, useDependency } from '@univerjs/core';
+import { Popup } from '@univerjs/design';
+import { IEditorService } from '@univerjs/docs-ui';
+import { DeviceInputEventType } from '@univerjs/engine-render';
+import { IShortcutService, KeyCode } from '@univerjs/ui';
+import React, { forwardRef, useEffect, useMemo, useRef, useState } from 'react';
+import { useStateRef } from '../hooks/useStateRef';
+import styles from './index.module.less';
+
+interface ISearchFunctionProps {
+ searchList: ISearchItem[];
+ searchText: string;
+ onSelect: (functionName: string) => void;
+ onChange?: (functionName: string) => void;
+ editorId: string;
+ onClose?: () => void;
+};
+const noop = () => { };
+export const SearchFunction = forwardRef<HTMLElement, ISearchFunctionProps>(SearchFunctionFactory);
+function SearchFunctionFactory(props: ISearchFunctionProps, ref: any) {
+ const { searchText, searchList, onSelect, editorId, onClose = noop } = props;
+ const editorService = useDependency(IEditorService);
+ const shortcutService = useDependency(IShortcutService);
+ const commandService = useDependency(ICommandService);
+
+ const visible = useMemo(() => !!searchList.length, [searchList]);
+ const ulRef = useRef<HTMLUListElement>();
+ const [active, activeSet] = useState(0);
+ const [offset, setOffset] = useState<[number, number]>([0, 0]);
+ const isEnableMouseEnterOrOut = useRef(false);
+
+ const stateRef = useStateRef({ searchList, active });
+ const editor = editorService.getEditor(editorId);
+
+ useEffect(() => {
+ const editor = editorService.getEditor(editorId);
+ const position = editor?.getBoundingClientRect();
+ if (position == null) {
+ return;
+ }
+ const { left, top, height } = position;
+
+ setOffset([left, top + height]);
+ activeSet(0); // Reset active state
+ }, [searchText, searchList]);
+
+ function handleLiMouseEnter(index: number) {
+ if (!isEnableMouseEnterOrOut.current) {
+ return;
+ }
+ activeSet(index);
+ }
+
+ function handleLiMouseLeave() {
+ if (!isEnableMouseEnterOrOut.current) {
+ return;
+ }
+ activeSet(-1);
+ }
+
+ useEffect(() => {
+ if (!searchList.length) {
+ return;
+ }
+ // 注册方向键事件
+ const operationId = `sheet.formula-embedding-editor.search_function.${editorId}`;
+ const d = new DisposableCollection();
+ const handleKeycode = (keycode: KeyCode) => {
+ const { searchList, active } = stateRef.current;
+
+ switch (keycode) {
+ case KeyCode.ARROW_UP: {
+ activeSet((pre) => {
+ const res = Math.max(0, pre - 1);
+ scrollToVisible(res);
+ return res;
+ });
+
+ break;
+ }
+ case KeyCode.ARROW_DOWN: {
+ activeSet((pre) => {
+ const res = Math.min(searchList.length - 1, pre + 1);
+ scrollToVisible(res);
+ return res;
+ });
+ break;
+ }
+ case KeyCode.TAB:
+ case KeyCode.ENTER: {
+ const item = searchList[active];
+ onSelect(item.name);
+ break;
+ }
+ case KeyCode.ESC: {
+ onSelect('');
+ break;
+ }
+ }
+ };
+ d.add(commandService.registerCommand({
+ id: operationId,
+ type: CommandType.OPERATION,
+ handler(_event, params) {
+ const { keyCode } = params as { eventType: DeviceInputEventType; keyCode: KeyCode };
+ handleKeycode(keyCode);
+ },
+ }));
+
+ [KeyCode.ARROW_UP, KeyCode.ARROW_DOWN, KeyCode.ENTER, KeyCode.ESC, KeyCode.TAB].map((keyCode) => {
+ return {
+ id: operationId,
+ binding: keyCode,
+ preconditions: () => true,
+ priority: 1000,
+ staticParameters: {
+ eventType: DeviceInputEventType.Keyboard,
+ keyCode,
+ },
+ };
+ }).forEach((item) => {
+ d.add(shortcutService.registerShortcut(item));
+ });
+
+ return () => {
+ d.dispose();
+ };
+ }, [searchList]);
+
+ function scrollToVisible(liIndex: number) {
+ // Get the <li> element
+ const liElement = ulRef.current?.querySelectorAll(`.${styles.formulaSearchFunctionItem}`)[
+ liIndex
+ ] as HTMLLIElement;
+
+ if (!liElement) return;
+
+ // Get the <ul> element
+ const ulElement = liElement.parentNode as HTMLUListElement;
+
+ if (!ulElement) return;
+
+ // Get the height of the <ul> element
+ const ulRect = ulElement.getBoundingClientRect();
+ const ulTop = ulRect.top;
+ const ulHeight = ulElement.offsetHeight;
+
+ // Get the position and height of the <li> element
+ const liRect = liElement.getBoundingClientRect();
+ const liTop = liRect.top;
+ const liHeight = liRect.height;
+
+ // If the <li> element is within the visible area, no scrolling operation is performed
+ if (liTop >= 0 && liTop > ulTop && liTop - ulTop + liHeight <= ulHeight) {
+ return;
+ }
+
+ // Calculate scroll position
+ const scrollTo = liElement.offsetTop - (ulHeight - liHeight) / 2;
+
+ // Perform scrolling operation
+ ulElement.scrollTo({
+ top: scrollTo,
+ behavior: 'smooth',
+ });
+ }
+
+ const debounceResetMouseState = useMemo(() => {
+ let time = '' as any;
+ return () => {
+ clearTimeout(time);
+ isEnableMouseEnterOrOut.current = true;
+ time = setTimeout(() => {
+ isEnableMouseEnterOrOut.current = false;
+ }, 300);
+ };
+ }, []);
+
+ return searchList.length > 0 && (
+ <Popup visible={visible} offset={offset}>
+ <ul
+ className={styles.formulaSearchFunction}
+ ref={(v) => {
+ ulRef.current = v!;
+ if (ref) {
+ ref.current = v!;
+ }
+ }}
+ >
+ {searchList.map((item, index) => (
+ <li
+ key={index}
+ className={active === index
+ ? `${styles.formulaSearchFunctionItem} ${styles.formulaSearchFunctionItemActive}`
+ : styles.formulaSearchFunctionItem}
+ onMouseEnter={() => handleLiMouseEnter(index)}
+ onMouseLeave={handleLiMouseLeave}
+ onMouseMove={debounceResetMouseState}
+ onClick={() => {
+ onSelect(item.name);
+ if (editor) {
+ editor.focus();
+ }
+ }}
+ >
+ <span className={styles.formulaSearchFunctionItemName}>
+ <span className={styles.formulaSearchFunctionItemNameLight}>{item.name.substring(0, searchText.length)}</span>
+ <span>{item.name.slice(searchText.length)}</span>
+ </span>
+ <span className={styles.formulaSearchFunctionItemDesc}>{item.desc}</span>
+ </li>
+ ))}
+ </ul>
+ </Popup>
+ );
+}
diff --git a/packages/sheets-formula-ui/src/views/formula-editor/search-function/index.module.less b/packages/sheets-formula-ui/src/views/formula-editor/search-function/index.module.less
new file mode 100644
index 0000000000..26b7116c17
--- /dev/null
+++ b/packages/sheets-formula-ui/src/views/formula-editor/search-function/index.module.less
@@ -0,0 +1,55 @@
+@width: 250px;
+@max-height: 400px;
+
+.formula-search-function {
+ overflow-y: auto;
+
+ box-sizing: border-box;
+ width: @width;
+ max-height: @max-height;
+ margin: 0;
+ padding: var(--padding-sm);
+
+ line-height: 20px;
+ list-style: none;
+
+ background-color: rgb(var(--bg-color-secondary));
+ border: 1px solid rgb(var(--border-color));
+ border-radius: var(--border-radius-lg);
+ outline: none;
+ box-shadow: var(--box-shadow-base);
+
+ overflow: hidden;
+ overflow-y: auto;
+
+ &-item {
+ cursor: pointer;
+
+ box-sizing: border-box;
+ padding: var(--padding-xs) var(--padding-sm);
+
+ color: rgb(var(--text-color));
+
+ border-radius: var(--border-radius-base);
+
+ transition: background 0.2s;
+
+ &-name {
+ font-size: var(--font-size-xxs);
+
+ &-light {
+ color: rgb(var(--error-color));
+ }
+ }
+
+ &-desc {
+ display: block;
+ font-size: var(--font-size-xxs);
+ color: rgb(var(--grey-500));
+ }
+
+ &-active {
+ background-color: rgb(var(--bg-color-hover));
+ }
+ }
+}
diff --git a/packages/sheets-formula-ui/src/views/formula-editor/utils/getFormulaText.tsx b/packages/sheets-formula-ui/src/views/formula-editor/utils/getFormulaText.tsx
new file mode 100644
index 0000000000..fabbc724aa
--- /dev/null
+++ b/packages/sheets-formula-ui/src/views/formula-editor/utils/getFormulaText.tsx
@@ -0,0 +1,24 @@
+/**
+ * Copyright 2023-present DreamNum Inc.
+ *
+ * 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 { operatorToken } from '@univerjs/engine-formula';
+
+export const getFormulaText = (formula: string) => {
+ if (formula.startsWith(operatorToken.EQUALS)) {
+ return formula.slice(1);
+ }
+ return '';
+};
diff --git a/packages/sheets-formula-ui/src/views/range-selector/hooks/useFocus.ts b/packages/sheets-formula-ui/src/views/range-selector/hooks/useFocus.ts
new file mode 100644
index 0000000000..60a25bb957
--- /dev/null
+++ b/packages/sheets-formula-ui/src/views/range-selector/hooks/useFocus.ts
@@ -0,0 +1,40 @@
+/**
+ * Copyright 2023-present DreamNum Inc.
+ *
+ * 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 { useMemo } from 'react';
+
+export const useFocus = (editor?: Editor) => {
+ const focus = useMemo(() => {
+ return () => {
+ if (editor) {
+ editor.focus();
+ const selections = [...editor.getSelectionRanges()];
+ if (selections.length) {
+ editor.setSelectionRanges(selections);
+ }
+ // end
+ if (!selections.length) {
+ const body = editor.getDocumentData().body?.dataStream ?? '\r\n';
+ const offset = Math.max(body.length - 2, 0);
+ editor.setSelectionRanges([{ startOffset: offset, endOffset: offset }]);
+ }
+ }
+ };
+ }, [editor]);
+ return focus;
+};
+
diff --git a/packages/sheets-formula-ui/src/views/range-selector/hooks/useFormulaToken.ts b/packages/sheets-formula-ui/src/views/range-selector/hooks/useFormulaToken.ts
index 9246b4cbb9..a2a18ad809 100644
--- a/packages/sheets-formula-ui/src/views/range-selector/hooks/useFormulaToken.ts
+++ b/packages/sheets-formula-ui/src/views/range-selector/hooks/useFormulaToken.ts
@@ -19,10 +19,11 @@ import { useDependency } from '@univerjs/core';
import { LexerTreeBuilder } from '@univerjs/engine-formula';
import { useEffect, useState } from 'react';
+export type INode = (string | ISequenceNode);
export const useFormulaToken = (text: string) => {
const lexerTreeBuilder = useDependency(LexerTreeBuilder);
- const [sequenceNodes, sequenceNodesSet] = useState<(string | ISequenceNode)[]>([]);
+ const [sequenceNodes, sequenceNodesSet] = useState<INode[]>([]);
useEffect(() => {
sequenceNodesSet(lexerTreeBuilder.sequenceNodesBuilder(text) ?? []);
diff --git a/packages/sheets-formula-ui/src/views/range-selector/hooks/useHighlight.ts b/packages/sheets-formula-ui/src/views/range-selector/hooks/useHighlight.ts
index 27bce7459c..c0912eaf73 100644
--- a/packages/sheets-formula-ui/src/views/range-selector/hooks/useHighlight.ts
+++ b/packages/sheets-formula-ui/src/views/range-selector/hooks/useHighlight.ts
@@ -81,7 +81,7 @@ export function useSheetHighlight(isNeed: boolean, unitId: string, subUnitId: st
selectionWithStyle.push({
range,
- primary: undefined,
+ primary: null,
style: getFormulaRefSelectionStyle(themeService, themeColor, refIndex.toString()),
});
}
@@ -90,24 +90,19 @@ export function useSheetHighlight(isNeed: boolean, unitId: string, subUnitId: st
useEffect(() => {
const skeleton = sheetSkeletonManagerService?.getCurrentSkeleton();
- if (skeleton) {
+ if (skeleton && isNeed) {
const allControls = refSelectionsRenderService?.getSelectionControls() || [];
if (allControls.length === ranges.length) {
allControls.forEach((control, index) => {
const selection = ranges[index];
- const primaryCell = skeleton.getCellByIndex(selection.range.startRow, selection.range.startColumn);
- control.updateRange(attachRangeWithCoord(skeleton, selection.range), primaryCell);
+ control.updateRange(attachRangeWithCoord(skeleton, selection.range), null);
control.updateStyle(selection.style!);
});
} else {
refSelectionsService.setSelections(ranges);
}
}
- }, [ranges, sheetSkeletonManagerService]);
-
- useEffect(() => () => {
- refSelectionsService.setSelections([]);
- }, []);
+ }, [ranges, isNeed]);
}
export function useDocHight(editorId: string, sequenceNodes: (string | ISequenceNode)[]) {
diff --git a/packages/sheets-formula-ui/src/views/range-selector/hooks/useLeftAndRightArrow.ts b/packages/sheets-formula-ui/src/views/range-selector/hooks/useLeftAndRightArrow.ts
new file mode 100644
index 0000000000..646262a240
--- /dev/null
+++ b/packages/sheets-formula-ui/src/views/range-selector/hooks/useLeftAndRightArrow.ts
@@ -0,0 +1,82 @@
+/**
+ * Copyright 2023-present DreamNum Inc.
+ *
+ * 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 { CommandType, DisposableCollection, ICommandService, useDependency } from '@univerjs/core';
+import { DeviceInputEventType } from '@univerjs/engine-render';
+import { IShortcutService, KeyCode } from '@univerjs/ui';
+import { useEffect } from 'react';
+import type { Editor } from '@univerjs/docs-ui';
+
+export const useLeftAndRightArrow = (isNeed: boolean, editor?: Editor) => {
+ const commandService = useDependency(ICommandService);
+ const shortcutService = useDependency(IShortcutService);
+
+ useEffect(() => {
+ if (!editor || !isNeed) {
+ return;
+ }
+ const editorId = editor.getEditorId();
+ const operationId = `sheet.formula-embedding-editor.${editorId}`;
+ const d = new DisposableCollection();
+ const handleKeycode = (keycode: KeyCode) => {
+ const selections = editor.getSelectionRanges();
+ if (selections.length === 1) {
+ const range = selections[0];
+ switch (keycode) {
+ case KeyCode.ARROW_LEFT: {
+ const offset = Math.max(range.startOffset - 1, 0);
+ editor.setSelectionRanges([{ startOffset: offset, endOffset: offset }]);
+ break;
+ }
+ case KeyCode.ARROW_RIGHT: {
+ const content = (editor.getDocumentData().body?.dataStream || ',,').length - 2;
+ const offset = Math.min(range.endOffset + 1, content);
+ editor.setSelectionRanges([{ startOffset: offset, endOffset: offset }]);
+ break;
+ }
+ }
+ }
+ };
+
+ d.add(commandService.registerCommand({
+ id: operationId,
+ type: CommandType.OPERATION,
+ handler(_event, params) {
+ const { keyCode } = params as { eventType: DeviceInputEventType; keyCode: KeyCode };
+ handleKeycode(keyCode);
+ },
+ }));
+
+ [KeyCode.ARROW_LEFT, KeyCode.ARROW_RIGHT, KeyCode.ARROW_DOWN, KeyCode.ARROW_UP].map((keyCode) => {
+ return {
+ id: operationId,
+ binding: keyCode,
+ preconditions: () => true,
+ priority: 900,
+ staticParameters: {
+ eventType: DeviceInputEventType.Keyboard,
+ keyCode,
+ },
+ };
+ }).forEach((item) => {
+ d.add(shortcutService.registerShortcut(item));
+ });
+
+ return () => {
+ d.dispose();
+ };
+ }, [editor, isNeed]);
+};
diff --git a/packages/sheets-formula-ui/src/views/range-selector/hooks/useOnlyOneRange.ts b/packages/sheets-formula-ui/src/views/range-selector/hooks/useOnlyOneRange.ts
new file mode 100644
index 0000000000..df1f537b5a
--- /dev/null
+++ b/packages/sheets-formula-ui/src/views/range-selector/hooks/useOnlyOneRange.ts
@@ -0,0 +1,37 @@
+/**
+ * Copyright 2023-present DreamNum Inc.
+ *
+ * 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 { useDependency } from '@univerjs/core';
+import { IRenderManagerService } from '@univerjs/engine-render';
+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/useRefactorEffect.ts b/packages/sheets-formula-ui/src/views/range-selector/hooks/useRefactorEffect.ts
index 4e4261527b..c032e395d3 100644
--- a/packages/sheets-formula-ui/src/views/range-selector/hooks/useRefactorEffect.ts
+++ b/packages/sheets-formula-ui/src/views/range-selector/hooks/useRefactorEffect.ts
@@ -14,53 +14,40 @@
* limitations under the License.
*/
-import type { Workbook } from '@univerjs/core';
-import { IContextService, IUniverInstanceService, UniverInstanceType, useDependency } from '@univerjs/core';
+import { EDITOR_ACTIVATED, IContextService, useDependency } from '@univerjs/core';
import { IRenderManagerService } from '@univerjs/engine-render';
-import { DISABLE_NORMAL_SELECTIONS, SheetsSelectionsService } from '@univerjs/sheets';
-import { IEditorBridgeService } from '@univerjs/sheets-ui';
+import { DISABLE_NORMAL_SELECTIONS, IRefSelectionsService } from '@univerjs/sheets';
import { IContextMenuService } from '@univerjs/ui';
import { useEffect, useLayoutEffect } from 'react';
import { RefSelectionsRenderService } from '../../../services/render-services/ref-selections.render-service';
-export const useRefactorEffect = (isNeed: boolean, unitId: string, isOnlyOneRange: boolean) => {
+export const useRefactorEffect = (isNeed: boolean, unitId: string) => {
const renderManagerService = useDependency(IRenderManagerService);
- const univerInstanceService = useDependency(IUniverInstanceService);
const contextService = useDependency(IContextService);
- const editorBridgeService = useDependency(IEditorBridgeService);
- const sheetsSelectionsService = useDependency(SheetsSelectionsService);
const contextMenuService = useDependency(IContextMenuService);
+ const refSelectionsService = useDependency(IRefSelectionsService);
const render = renderManagerService.getRenderById(unitId);
const refSelectionsRenderService = render?.with(RefSelectionsRenderService);
-
- useEffect(() => {
+ useLayoutEffect(() => {
if (isNeed) {
const d1 = refSelectionsRenderService?.enableSelectionChanging();
contextService.setContextValue(DISABLE_NORMAL_SELECTIONS, true);
- editorBridgeService.enableForceKeepVisible();
+ contextService.setContextValue(EDITOR_ACTIVATED, true);
return () => {
- d1?.dispose();
+ contextService.setContextValue(EDITOR_ACTIVATED, false);
contextService.setContextValue(DISABLE_NORMAL_SELECTIONS, false);
- editorBridgeService.disableForceKeepVisible();
+ d1?.dispose();
};
}
}, [isNeed]);
- // reset selection
useLayoutEffect(() => {
if (isNeed) {
- const workbook = univerInstanceService.getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET);
- const sheet = workbook?.getActiveSheet();
- const selections = [...sheetsSelectionsService.getCurrentSelections()];
return () => {
- const workbook = univerInstanceService.getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET);
- const currentSheet = workbook?.getActiveSheet();
- if (currentSheet && currentSheet === sheet) {
- sheetsSelectionsService.setSelections(selections);
- }
+ refSelectionsService.clear();
};
}
}, [isNeed]);
@@ -81,12 +68,4 @@ export const useRefactorEffect = (isNeed: boolean, unitId: string, isOnlyOneRang
refSelectionsRenderService?.setSkipLastEnabled(false);
}
}, [isNeed]);
-
- useEffect(() => {
- if (isOnlyOneRange) {
- refSelectionsRenderService?.setRemainLastEnabled(false);
- } else {
- refSelectionsRenderService?.setRemainLastEnabled(true);
- }
- }, [isOnlyOneRange]);
};
diff --git a/packages/sheets-formula-ui/src/views/range-selector/hooks/useRefocus.ts b/packages/sheets-formula-ui/src/views/range-selector/hooks/useRefocus.ts
new file mode 100644
index 0000000000..edfab73d0a
--- /dev/null
+++ b/packages/sheets-formula-ui/src/views/range-selector/hooks/useRefocus.ts
@@ -0,0 +1,28 @@
+/**
+ * Copyright 2023-present DreamNum Inc.
+ *
+ * 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 { DOCS_NORMAL_EDITOR_UNIT_ID_KEY, IUniverInstanceService, useDependency } from '@univerjs/core';
+import { useEffect } from 'react';
+
+export const useRefocus = () => {
+ // const univerInstanceService = useDependency(IUniverInstanceService);
+
+ useEffect(() => {
+ return () => {
+ // univerInstanceService.focusUnit(DOCS_NORMAL_EDITOR_UNIT_ID_KEY);
+ };
+ }, []);
+};
diff --git a/packages/sheets-formula-ui/src/views/range-selector/hooks/useResetSelection.ts b/packages/sheets-formula-ui/src/views/range-selector/hooks/useResetSelection.ts
new file mode 100644
index 0000000000..fb06435fa6
--- /dev/null
+++ b/packages/sheets-formula-ui/src/views/range-selector/hooks/useResetSelection.ts
@@ -0,0 +1,43 @@
+/**
+ * Copyright 2023-present DreamNum Inc.
+ *
+ * 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 { IUniverInstanceService, UniverInstanceType, useDependency } from '@univerjs/core';
+import { SheetsSelectionsService } from '@univerjs/sheets';
+import { useMemo } from 'react';
+
+export const useResetSelection = (isNeed: boolean) => {
+ const univerInstanceService = useDependency(IUniverInstanceService);
+ const sheetsSelectionsService = useDependency(SheetsSelectionsService);
+
+ const resetSelection = useMemo(() => {
+ if (isNeed) {
+ const workbook = univerInstanceService.getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET);
+ const sheet = workbook?.getActiveSheet();
+ const selections = [...sheetsSelectionsService.getCurrentSelections()];
+ return () => {
+ const workbook = univerInstanceService.getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET);
+ const currentSheet = workbook?.getActiveSheet();
+ if (currentSheet && currentSheet === sheet) {
+ sheetsSelectionsService.setSelections(selections);
+ }
+ };
+ }
+ return () => { };
+ }, [isNeed]);
+
+ return resetSelection;
+};
diff --git a/packages/sheets-formula-ui/src/views/range-selector/hooks/useSheetSelectionChange.ts b/packages/sheets-formula-ui/src/views/range-selector/hooks/useSheetSelectionChange.ts
index 0e51795096..d8f108037c 100644
--- a/packages/sheets-formula-ui/src/views/range-selector/hooks/useSheetSelectionChange.ts
+++ b/packages/sheets-formula-ui/src/views/range-selector/hooks/useSheetSelectionChange.ts
@@ -20,11 +20,11 @@ import type { Workbook } from '@univerjs/core';
import type { ISelectionWithCoordAndStyle } from '@univerjs/sheets';
import type { INode } from '../utils/filterReferenceNode';
-import { debounce, DisposableCollection, IUniverInstanceService, useDependency } from '@univerjs/core';
+import { DisposableCollection, IUniverInstanceService, useDependency } from '@univerjs/core';
import { deserializeRangeWithSheet, matchToken, sequenceNodeType, serializeRange, serializeRangeWithSheet } from '@univerjs/engine-formula';
import { IRenderManagerService } from '@univerjs/engine-render';
import { useEffect, useMemo, useRef } from 'react';
-import { distinctUntilChanged, map } from 'rxjs';
+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/filterReferenceNode';
@@ -43,15 +43,6 @@ export const useSheetSelectionChange = (isNeed: boolean,
const univerInstanceService = useDependency(IUniverInstanceService);
const isScalingRef = useRef(false);
- const debounceReset = useMemo(() => debounce(() => {
- isScalingRef.current = false;
- }, 300), []);
-
- const setIsScaling = () => {
- isScalingRef.current = true;
- debounceReset();
- };
-
const render = renderManagerService.getRenderById(unitId);
const refSelectionsRenderService = render?.with(RefSelectionsRenderService);
const oldFilterReferenceNodes = useRef<INode[]>([]);
@@ -71,7 +62,7 @@ export const useSheetSelectionChange = (isNeed: boolean,
if (isNeed && refSelectionsRenderService) {
let isFirst = true;
const handleSelectionsChange = (selections: ISelectionWithCoordAndStyle[]) => {
- if (isFirst) {
+ if (isFirst || isScalingRef.current) {
isFirst = false;
return;
}
@@ -138,6 +129,7 @@ export const useSheetSelectionChange = (isNeed: boolean,
};
const d1 = refSelectionsRenderService.selectionMoveEnd$.subscribe((selections) => {
handleSelectionsChange(selections);
+ isScalingRef.current = false;
});
const d2 = refSelectionsRenderService.selectionMoving$.pipe(throttleTime(50)).subscribe((selections) => {
@@ -195,18 +187,18 @@ export const useSheetSelectionChange = (isNeed: boolean,
let time = 0 as any;
const dispose = refSelectionsRenderService.selectionMoveEnd$.subscribe(() => {
time = setTimeout(() => {
+ disposableCollection.dispose();
const controls = refSelectionsRenderService.getSelectionControls();
controls.forEach((control, index) => {
- disposableCollection.add(control.selectionScaling$.subscribe((e) => {
- const rangeText = serializeRange(e);
- handleSequenceNodeReplace(rangeText, index);
- setIsScaling();
- }));
- disposableCollection.add(control.selectionMoving$.pipe(map((e) => {
- return serializeRange(e);
- }), distinctUntilChanged()).subscribe((rangeText) => {
+ disposableCollection.add(merge(control.selectionMoving$, control.selectionScaling$).pipe(
+ throttleTime(30),
+ map((e) => {
+ return serializeRange(e);
+ }),
+ distinctUntilChanged()
+ ).subscribe((rangeText) => {
+ isScalingRef.current = true;
handleSequenceNodeReplace(rangeText, index);
- setIsScaling();
}));
});
}, 30);
diff --git a/packages/sheets-formula-ui/src/views/range-selector/hooks/useVerify.ts b/packages/sheets-formula-ui/src/views/range-selector/hooks/useVerify.ts
index bf422eb13e..94728d1db0 100644
--- a/packages/sheets-formula-ui/src/views/range-selector/hooks/useVerify.ts
+++ b/packages/sheets-formula-ui/src/views/range-selector/hooks/useVerify.ts
@@ -20,18 +20,20 @@ import { useEffect, useRef } from 'react';
import { sequenceNodeToText } from '../utils/sequenceNodeToText';
import { verifyRange } from '../utils/verifyRange';
-export const useVerify = (onVerify: IRangeSelectorProps['onVerify'], sequenceNodes: ReturnType<typeof useFormulaToken>['sequenceNodes']) => {
+export const useVerify = (isNeed: boolean, onVerify: IRangeSelectorProps['onVerify'], sequenceNodes: ReturnType<typeof useFormulaToken>['sequenceNodes']) => {
const isInitRender = useRef(true);
// No validation is performed during the initialization phase.
useEffect(() => {
- const time: any = setTimeout(() => {
- isInitRender.current = false;
- }, 500);
- return () => {
- clearTimeout(time);
- };
- });
+ if (isNeed) {
+ const time = setTimeout(() => {
+ isInitRender.current = false;
+ }, 500);
+ return () => {
+ clearTimeout(time);
+ };
+ }
+ }, [isNeed]);
useEffect(() => {
if (!isInitRender.current) {
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 e30d52e97f..902bd64517 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
@@ -22,7 +22,7 @@
}
&-error {
- border: 1px solid rgb(var(--red-500));
+ border: 1px solid rgb(var(--red-500)) !important;
}
&-error-wrap {
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 ecc23901c8..cb20a634cb 100644
--- a/packages/sheets-formula-ui/src/views/range-selector/index.tsx
+++ b/packages/sheets-formula-ui/src/views/range-selector/index.tsx
@@ -17,7 +17,7 @@
import type { IDisposable, IUnitRangeName } from '@univerjs/core';
import type { Editor } from '@univerjs/docs-ui';
import type { ReactNode } from 'react';
-import { createInternalEditorID, debounce, generateRandomId, ICommandService, LocaleService, useDependency } from '@univerjs/core';
+import { createInternalEditorID, debounce, DOCS_NORMAL_EDITOR_UNIT_ID_KEY, generateRandomId, ICommandService, LocaleService, useDependency } from '@univerjs/core';
import { Button, Dialog, Input, Tooltip } from '@univerjs/design';
import { DocBackScrollRenderController, IEditorService } from '@univerjs/docs-ui';
import { deserializeRangeWithSheet, LexerTreeBuilder, matchToken, sequenceNodeType } from '@univerjs/engine-formula';
@@ -25,16 +25,22 @@ import { IRenderManagerService } from '@univerjs/engine-render';
import { CloseSingle, DeleteSingle, IncreaseSingle, SelectRangeSingle } from '@univerjs/icons';
import { SetWorksheetActiveOperation } from '@univerjs/sheets';
import { IDescriptionService } from '@univerjs/sheets-formula';
-
import { RANGE_SELECTOR_SYMBOLS, SetCellEditVisibleOperation } from '@univerjs/sheets-ui';
+
import cl from 'clsx';
import React, { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';
+import { filter } from 'rxjs';
import { RefSelectionsRenderService } from '../../services/render-services/ref-selections.render-service';
+
import { useEditorInput } from './hooks/useEditorInput';
+import { useFocus } from './hooks/useFocus';
import { useFormulaToken } from './hooks/useFormulaToken';
-
import { buildTextRuns, useColor, useDocHight, useSheetHighlight } from './hooks/useHighlight';
+import { useLeftAndRightArrow } from './hooks/useLeftAndRightArrow';
+import { useOnlyOneRange } from './hooks/useOnlyOneRange';
import { useRefactorEffect } from './hooks/useRefactorEffect';
+import { useRefocus } from './hooks/useRefocus';
+import { useResetSelection } from './hooks/useResetSelection';
import { useResize } from './hooks/useResize';
import { useSheetSelectionChange } from './hooks/useSheetSelectionChange';
import { useVerify } from './hooks/useVerify';
@@ -54,14 +60,11 @@ export interface IRangeSelectorProps {
placeholder?: string;
isFocus?: boolean;
onBlur?: () => void;
- /**
- * 暂无效果
- * @memberof IRangeSelectorProps
- */
+
onFocus?: () => void;
actions?: {
- handleOutClick?: (e: React.MouseEvent<HTMLDivElement, MouseEvent>, cb: (v: boolean) => void) => void;
+ handleOutClick?: (e: MouseEvent, cb: () => void) => void;
};
/**
@@ -88,6 +91,7 @@ export function RangeSelector(props: IRangeSelectorProps) {
onVerify = noopFunction,
onRangeSelectorDialogVisibleChange = noopFunction,
onBlur = noopFunction,
+ onFocus = noopFunction,
isFocus: _isFocus = true,
isOnlyOneRange = false,
isSupportAcrossSheet = false } = props;
@@ -114,10 +118,10 @@ export function RangeSelector(props: IRangeSelectorProps) {
// init actions
if (actions) {
- actions.handleOutClick = (e: React.MouseEvent<HTMLDivElement, MouseEvent>, cb: (v: boolean) => void) => {
- if (rangeSelectorWrapRef.current) {
+ actions.handleOutClick = (e: MouseEvent, cb: () => void) => {
+ if (rangeSelectorWrapRef.current && !rangeDialogVisible) {
const isContain = rangeSelectorWrapRef.current.contains(e.target as Node);
- cb(isContain);
+ !isContain && cb();
}
};
}
@@ -128,6 +132,8 @@ export function RangeSelector(props: IRangeSelectorProps) {
const isError = useMemo(() => errorText !== undefined, [errorText]);
+ const resetSelection = useResetSelection(!rangeDialogVisible && isFocus);
+
const handleInputDebounce = useMemo(() => debounce((text: string) => {
const nodes = lexerTreeBuilder.sequenceNodesBuilder(text);
if (nodes) {
@@ -161,6 +167,9 @@ export function RangeSelector(props: IRangeSelectorProps) {
onChange(text);
rangeDialogVisibleSet(false);
onRangeSelectorDialogVisibleChange(false);
+ setTimeout(() => {
+ editor?.setSelectionRanges([{ startOffset: text.length, endOffset: text.length }]);
+ }, 30);
};
const handleClose = () => {
@@ -170,22 +179,35 @@ export function RangeSelector(props: IRangeSelectorProps) {
const handleOpenModal = () => {
if (!isError) {
- rangeDialogVisibleSet(true);
- onRangeSelectorDialogVisibleChange(true);
+ focus();
+ // 从另一个 editor 直接打开的时候,调整下事件监听顺序,确保打开面板的逻辑在 editor 切换之后
+ setTimeout(() => {
+ rangeDialogVisibleSet(true);
+ onRangeSelectorDialogVisibleChange(true);
+ }, 30);
}
};
- const focus = useMemo(() => {
- let time: NodeJS.Timeout = 0 as any;
- return () => {
- clearTimeout(time);
- if (editor) {
- time = setTimeout(() => {
- editor.focus();
- }, 30);
- }
- };
- }, [editor]);
+ const focus = useFocus(editor);
+
+ useLayoutEffect(() => {
+ // 如果是失去焦点的话,需要立刻执行
+ // 在进行多个 input 切换的时候,失焦必须立刻执行.
+ if (_isFocus) {
+ const time = setTimeout(() => {
+ isFocusSet(_isFocus);
+ if (_isFocus) {
+ focus();
+ }
+ }, 30);
+ return () => {
+ clearTimeout(time);
+ };
+ } else {
+ resetSelection();
+ isFocusSet(_isFocus);
+ }
+ }, [_isFocus, focus]);
const { checkScrollBar } = useResize(editor);
@@ -213,11 +235,17 @@ export function RangeSelector(props: IRangeSelectorProps) {
useSheetSelectionChange(!rangeDialogVisible && isFocus, unitId, subUnitId, sequenceNodes, isSupportAcrossSheet, isOnlyOneRange, handleSheetSelectionChange);
- useRefactorEffect(!rangeDialogVisible && isFocus, unitId, isOnlyOneRange);
+ useRefactorEffect(!rangeDialogVisible && isFocus, unitId);
+
+ useOnlyOneRange(unitId, isOnlyOneRange);
useEditorInput(unitId, rangeString, editor);
- useVerify(onVerify, sequenceNodes);
+ useVerify(!rangeDialogVisible && isFocus, onVerify, sequenceNodes);
+
+ useLeftAndRightArrow(!rangeDialogVisible && isFocus, editor);
+
+ useRefocus();
useEffect(() => {
if (editor) {
@@ -239,6 +267,8 @@ export function RangeSelector(props: IRangeSelectorProps) {
onBlur();
// Refresh the component
sequenceNodesSet((pre) => [...pre]);
+ const editor = editorService.getEditor(DOCS_NORMAL_EDITOR_UNIT_ID_KEY);
+ editor?.focus();
}
});
const d2 = commandService.onCommandExecuted((info) => {
@@ -255,22 +285,6 @@ export function RangeSelector(props: IRangeSelectorProps) {
};
}, [isSupportAcrossSheet]);
- useEffect(() => {
- isFocusSet(_isFocus);
- }, [_isFocus]);
-
- useEffect(() => {
- if (editor && rangeDialogVisible) {
- editor.blur();
- const d = editor.focus$.subscribe(() => {
- editor.blur();
- });
- return () => {
- d.unsubscribe();
- };
- }
- }, [editor, rangeDialogVisible]);
-
useLayoutEffect(() => {
let dispose: IDisposable;
if (containerRef.current) {
@@ -290,7 +304,19 @@ export function RangeSelector(props: IRangeSelectorProps) {
return () => {
dispose?.dispose();
};
- }, [containerRef.current]);
+ }, []);
+
+ const handleClick = () => {
+ // 在进行多个 input 切换的时候,失焦必须快于获得焦点.
+ // 即使失焦是 mousedown 事件,
+ // 聚焦是 mouseup 事件,
+ // 但是 react 的 useEffect 无法保证顺序,无法确保失焦在聚焦之前.
+ setTimeout(() => {
+ onFocus();
+ focus();
+ isFocusSet(true);
+ }, 30);
+ };
return (
<div className={styles.sheetRangeSelector} ref={rangeSelectorWrapRef}>
@@ -299,7 +325,7 @@ export function RangeSelector(props: IRangeSelectorProps) {
[styles.sheetRangeSelectorError]: isError,
})}
>
- <div className={styles.sheetRangeSelectorText} ref={containerRef}>
+ <div className={styles.sheetRangeSelectorText} ref={containerRef} onMouseUp={handleClick}>
</div>
<Tooltip title={localeService.t('rangeSelector.buttonTooltip')} placement="bottom">
<SelectRangeSingle className={styles.sheetRangeSelectorIcon} onClick={handleOpenModal} />
@@ -310,6 +336,7 @@ export function RangeSelector(props: IRangeSelectorProps) {
{rangeDialogVisible && (
<RangeSelectorDialog
+ editorId={editorId}
handleConfirm={handleConfirm}
handleClose={handleClose}
unitId={unitId}
@@ -326,6 +353,7 @@ export function RangeSelector(props: IRangeSelectorProps) {
}
function RangeSelectorDialog(props: {
+ editorId: string;
handleConfirm: (ranges: IUnitRangeName[]) => void;
handleClose: () => void;
visible: boolean;
@@ -335,12 +363,14 @@ function RangeSelectorDialog(props: {
isOnlyOneRange: boolean;
isSupportAcrossSheet: boolean;
}) {
- const { handleConfirm, handleClose: _handleClose, visible, initValue, unitId, subUnitId, isOnlyOneRange, isSupportAcrossSheet } = props;
+ const { editorId, handleConfirm, handleClose: _handleClose, visible, initValue, unitId, subUnitId, isOnlyOneRange, isSupportAcrossSheet } = props;
const localeService = useDependency(LocaleService);
+ const editorService = useDependency(IEditorService);
const descriptionService = useDependency(IDescriptionService);
const lexerTreeBuilder = useDependency(LexerTreeBuilder);
const renderManagerService = useDependency(IRenderManagerService);
+
const render = renderManagerService.getRenderById(unitId);
const refSelectionsRenderService = render?.with(RefSelectionsRenderService);
@@ -422,7 +452,8 @@ function RangeSelectorDialog(props: {
useSheetHighlight(visible, unitId, subUnitId, refSelections);
useSheetSelectionChange(focusIndex >= 0, unitId, subUnitId, sequenceNodes, isSupportAcrossSheet, isOnlyOneRange, handleSheetSelectionChange);
- useRefactorEffect(focusIndex >= 0, unitId, isOnlyOneRange);
+ useRefactorEffect(focusIndex >= 0, unitId);
+ useOnlyOneRange(unitId, isOnlyOneRange);
// 如果只有一个空 range,那么默认自动添加 range
useEffect(() => {
if (ranges.length === 0 || (ranges.length === 1 && !ranges[0])) {
@@ -430,6 +461,21 @@ function RangeSelectorDialog(props: {
}
}, [ranges]);
+ useEffect(() => {
+ const d = editorService.focusStyle$
+ .pipe(
+ filter((e) => !!e && DOCS_NORMAL_EDITOR_UNIT_ID_KEY !== e)
+ )
+ .subscribe((e) => {
+ if (e !== editorId) {
+ handleClose();
+ }
+ });
+ return () => {
+ d.unsubscribe();
+ };
+ }, [editorService, editorId]);
+
return (
<Dialog
width="328px"
diff --git a/packages/sheets-formula-ui/src/views/range-selector/utils/findIndexFromSequenceNodes.ts b/packages/sheets-formula-ui/src/views/range-selector/utils/findIndexFromSequenceNodes.ts
index 80d332df9e..436d7a26f0 100644
--- a/packages/sheets-formula-ui/src/views/range-selector/utils/findIndexFromSequenceNodes.ts
+++ b/packages/sheets-formula-ui/src/views/range-selector/utils/findIndexFromSequenceNodes.ts
@@ -24,7 +24,7 @@ export const findIndexFromSequenceNodes = (sequenceNode: (string | ISequenceNode
}
const oldIndex = pre.currentIndex;
if (typeof cur !== 'string') {
- pre.currentIndex += cur.endIndex - cur.startIndex + 1;
+ pre.currentIndex += cur.token.length;
} else {
const length = cur.length;
pre.currentIndex += length;
diff --git a/packages/sheets-formula-ui/src/views/range-selector/utils/getOffsetFromSequenceNodes.ts b/packages/sheets-formula-ui/src/views/range-selector/utils/getOffsetFromSequenceNodes.ts
index 6e37a91a19..fcb6d39037 100644
--- a/packages/sheets-formula-ui/src/views/range-selector/utils/getOffsetFromSequenceNodes.ts
+++ b/packages/sheets-formula-ui/src/views/range-selector/utils/getOffsetFromSequenceNodes.ts
@@ -21,6 +21,6 @@ export const getOffsetFromSequenceNodes = (sequenceNode: (string | ISequenceNode
if (typeof cur === 'string') {
return pre + cur.length;
}
- return pre + cur.endIndex - cur.startIndex + 1;
+ return pre + cur.token.length;
}, 0);
};
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 f799054497..ab6d49b833 100644
--- a/packages/sheets-hyper-link-ui/src/views/CellLinkEdit/index.tsx
+++ b/packages/sheets-hyper-link-ui/src/views/CellLinkEdit/index.tsx
@@ -82,10 +82,6 @@ export const CellLinkEdit = () => {
const subUnitId = workbook?.getActiveSheet().getSheetId() || '';
- useEffect(() => {
- isFocusRangeSelectorSet(false);
- }, [subUnitId]);
-
useEffect(() => {
if (editing?.row !== undefined && editing.col !== undefined) {
const { label, customRange, row, col } = editing;
@@ -222,10 +218,8 @@ export const CellLinkEdit = () => {
}, [editing, markSelectionService, themeService, univerInstanceService]);
useEffect(() => {
- if (type === SheetHyperLinkType.RANGE && !showLabel && !isFocusRangeSelector) {
- isFocusRangeSelectorSet(true);
- }
- }, [type, isFocusRangeSelector, showLabel, editorBridgeService]);
+ isFocusRangeSelectorSet(type === SheetHyperLinkType.RANGE);
+ }, [type]);
useEffect(() => {
const render = editing?.type === HyperLinkEditSourceType.ZEN_EDITOR ?
@@ -396,7 +390,7 @@ export const CellLinkEdit = () => {
return;
}
const handleOutClick = rangeSelectorActionsRef.current?.handleOutClick;
- handleOutClick && handleOutClick(e, isFocusRangeSelectorSet);
+ handleOutClick && handleOutClick(e as unknown as MouseEvent, () => isFocusRangeSelectorSet(false));
};
if (!editing) {
@@ -471,7 +465,7 @@ export const CellLinkEdit = () => {
initValue={payload}
onChange={handleRangeChange}
isFocus={isFocusRangeSelector}
- onBlur={() => { isFocusRangeSelectorSet(false); }}
+ onFocus={() => isFocusRangeSelectorSet(true)}
actions={rangeSelectorActionsRef.current}
onRangeSelectorDialogVisibleChange={async (visible) => {
if (visible) {
diff --git a/packages/sheets-ui/src/common/keys.ts b/packages/sheets-ui/src/common/keys.ts
index 36adc342bb..1b46f3b056 100644
--- a/packages/sheets-ui/src/common/keys.ts
+++ b/packages/sheets-ui/src/common/keys.ts
@@ -20,6 +20,8 @@ export const SHEET_ZOOM_RANGE = [10, 400];
* TODO@ggg: To avoid introducing the range-selector of the sheet-formula-ui package into sheet-ui, use a component key for now
*/
export const RANGE_SELECTOR_COMPONENT_KEY = 'RANGE_SELECTOR_COMPONENT_KEY';
+export const EMBEDDING_FORMULA_EDITOR_COMPONENT_KEY = 'EMBEDDING_FORMULA_EDITOR_COMPONENT_KEY';
+// end
export enum SHEET_VIEW_KEY {
MAIN = '__SpreadsheetRender__',
diff --git a/packages/sheets-ui/src/controllers/editor/utils/isEmbeddingFormulaEditor.ts b/packages/sheets-ui/src/controllers/editor/utils/isEmbeddingFormulaEditor.ts
new file mode 100644
index 0000000000..f99011fe3a
--- /dev/null
+++ b/packages/sheets-ui/src/controllers/editor/utils/isEmbeddingFormulaEditor.ts
@@ -0,0 +1,22 @@
+/**
+ * Copyright 2023-present DreamNum Inc.
+ *
+ * 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.
+ */
+
+export const EMBEDDING_FORMULA_EDITOR = 'embedding_formula_editor';
+
+export const isEmbeddingFormulaEditor = (unitId: string) => {
+ return unitId.includes(EMBEDDING_FORMULA_EDITOR);
+};
+
diff --git a/packages/sheets-ui/src/controllers/editor/utils/isRangeSelector.ts b/packages/sheets-ui/src/controllers/editor/utils/isRangeSelector.ts
index 754bcbbe13..3e107e560d 100644
--- a/packages/sheets-ui/src/controllers/editor/utils/isRangeSelector.ts
+++ b/packages/sheets-ui/src/controllers/editor/utils/isRangeSelector.ts
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-export const RANGE_SELECTOR_SYMBOLS = 'range-selector';
+export const RANGE_SELECTOR_SYMBOLS = 'range_selector';
export const isRangeSelector = (unitId: string) => {
return unitId.includes(RANGE_SELECTOR_SYMBOLS);
diff --git a/packages/sheets-ui/src/index.ts b/packages/sheets-ui/src/index.ts
index 87d0c19d92..ba7fb36e67 100644
--- a/packages/sheets-ui/src/index.ts
+++ b/packages/sheets-ui/src/index.ts
@@ -73,7 +73,7 @@ export { DragManagerService } from './services/drag-manager.service';
export { CellAlertManagerService, CellAlertType, type ICellAlert } from './services/cell-alert-manager.service';
export { HoverRenderController } from './controllers/hover-render.controller';
export { DragRenderController } from './controllers/drag-render.controller';
-export { RANGE_SELECTOR_COMPONENT_KEY, SHEET_VIEW_KEY } from './common/keys';
+export { EMBEDDING_FORMULA_EDITOR_COMPONENT_KEY, RANGE_SELECTOR_COMPONENT_KEY, SHEET_VIEW_KEY } from './common/keys';
export { type ICanvasPopup, SheetCanvasPopManagerService } from './services/canvas-pop-manager.service';
export { mergeSetRangeValues } from './services/clipboard/utils';
export type { IAutoFillLocation } from './services/auto-fill/type';
@@ -108,6 +108,7 @@ export { FONT_SIZE_COMPONENT } from './components/font-size/interface';
export { attachPrimaryWithCoord, attachSelectionWithCoord } from './services/selection/util';
export { SELECTION_SHAPE_DEPTH } from './services/selection/const';
export { isRangeSelector, RANGE_SELECTOR_SYMBOLS } from './controllers/editor/utils/isRangeSelector';
+export { EMBEDDING_FORMULA_EDITOR, isEmbeddingFormulaEditor } from './controllers/editor/utils/isEmbeddingFormulaEditor';
export { menuSchema } from './controllers/menu.schema';
export { getCellRealRange } from './common/utils';
diff --git a/packages/sheets-ui/src/views/defined-name/DefinedNameInput.tsx b/packages/sheets-ui/src/views/defined-name/DefinedNameInput.tsx
index ca77b6638f..eb022b5586 100644
--- a/packages/sheets-ui/src/views/defined-name/DefinedNameInput.tsx
+++ b/packages/sheets-ui/src/views/defined-name/DefinedNameInput.tsx
@@ -16,15 +16,14 @@
import type { Nullable, Workbook } from '@univerjs/core';
-import { AbsoluteRefType, createInternalEditorID, IUniverInstanceService, LocaleService, Tools, UniverInstanceType, useDependency } from '@univerjs/core';
+import { AbsoluteRefType, IUniverInstanceService, LocaleService, Tools, UniverInstanceType, useDependency } from '@univerjs/core';
import { Button, Input, Radio, RadioGroup, Select } from '@univerjs/design';
-import { TextEditor } from '@univerjs/docs-ui';
import { IDefinedNamesService, type IDefinedNamesServiceParam, IFunctionService, isReferenceStrings, isReferenceStringWithEffectiveColumn, LexerTreeBuilder, operatorToken } from '@univerjs/engine-formula';
import { hasCJKText } from '@univerjs/engine-render';
import { ErrorSingle } from '@univerjs/icons';
-import { ComponentManager } from '@univerjs/ui';
+import { ComponentManager, useSidebarClick } from '@univerjs/ui';
import React, { useEffect, useMemo, useRef, useState } from 'react';
-import { RANGE_SELECTOR_COMPONENT_KEY } from '../../common/keys';
+import { EMBEDDING_FORMULA_EDITOR_COMPONENT_KEY, RANGE_SELECTOR_COMPONENT_KEY } from '../../common/keys';
import { SCOPE_WORKBOOK_VALUE } from './component-name';
import styles from './index.module.less';
@@ -66,7 +65,7 @@ export const DefinedNameInput = (props: IDefinedNameInputProps) => {
const componentManager = useDependency(ComponentManager);
const RangeSelector = useMemo(() => componentManager.get(RANGE_SELECTOR_COMPONENT_KEY), []);
-
+ const FormulaEditor = useMemo(() => componentManager.get(EMBEDDING_FORMULA_EDITOR_COMPONENT_KEY), []);
if (workbook == null) {
return;
}
@@ -192,23 +191,37 @@ export const DefinedNameInput = (props: IDefinedNameInputProps) => {
const typeValueChange = (value: string | number | boolean) => {
const type = value as string;
- if (type === 'formula' && formulaOrRefStringValue.substring(0, 1) !== operatorToken.EQUALS) {
- setFormulaOrRefStringValue(`${operatorToken.EQUALS}`);
- setFormulaOrRefStringValue(`${operatorToken.EQUALS}`);
- } else if (formulaOrRefStringValue.substring(0, 1) === operatorToken.EQUALS) {
- setFormulaOrRefStringValue('');
- setFormulaOrRefStringValue('');
+ if (type === 'formula') {
+ if (formulaOrRefString[0] === operatorToken.EQUALS) {
+ setFormulaOrRefStringValue(formulaOrRefString);
+ } else {
+ setFormulaOrRefStringValue(`${operatorToken.EQUALS}`);
+ }
+ } else {
+ if (formulaOrRefString[0] === operatorToken.EQUALS) {
+ setFormulaOrRefStringValue('');
+ } else {
+ setFormulaOrRefStringValue(formulaOrRefString);
+ }
}
setTypeValue(type);
};
- const handlePanelClick = (e: React.MouseEvent<HTMLDivElement, MouseEvent>) => {
+ const formulaEditorActionsRef = useRef<any>({});
+ const [isFocusFormulaEditor, isFocusFormulaEditorSet] = useState(false);
+
+ useSidebarClick((e: MouseEvent) => {
const handleOutClick = rangeSelectorActionsRef.current?.handleOutClick;
- handleOutClick && handleOutClick(e, isFocusRangeSelectorSet);
- };
+ handleOutClick && handleOutClick(e, () => isFocusRangeSelectorSet(false));
+ });
+
+ useSidebarClick((e: MouseEvent) => {
+ const handleOutClick = formulaEditorActionsRef.current?.handleOutClick;
+ handleOutClick && handleOutClick(e, () => isFocusFormulaEditorSet(false));
+ });
return (
- <div className={styles.definedNameInput} style={{ display: state ? 'block' : 'none' }} onClick={handlePanelClick}>
+ <div className={styles.definedNameInput} style={{ display: state ? 'block' : 'none' }}>
<div>
<Input placeholder={localeService.t('definedName.inputNamePlaceholder')} value={nameValue} allowClear onChange={setNameValue} affixWrapperStyle={widthStyle} />
</div>
@@ -218,36 +231,38 @@ export const DefinedNameInput = (props: IDefinedNameInputProps) => {
<Radio value="formula">{localeService.t('definedName.ratioFormula')}</Radio>
</RadioGroup>
</div>
- {RangeSelector && typeValue === 'range' && (
- <RangeSelector
- unitId={unitId}
- subUnitId={subUnitId}
- initValue={formulaOrRefStringValue}
- onChange={rangeSelectorChange}
- isFocus={isFocusRangeSelector}
- actions={rangeSelectorActionsRef.current}
- isSupportAcrossSheet
- onBlur={() => { isFocusRangeSelectorSet(false); }}
- />
- )}
- {typeValue !== 'range' && (
- <div className="univer-defined-name-input-formula-selector-text-wrap">
- <TextEditor
- key={`${inputId}-editor`}
- value={formulaOrRefStringValue}
- onValid={setValidFormulaOrRange}
- onChange={formulaEditorChange}
- id={createInternalEditorID(`${inputId}-editor`)}
- placeholder={localeService.t('definedName.inputFormulaPlaceholder')}
- openForSheetUnitId={unitId}
- onlyInputFormula={true}
- // style={{ width: '99%' }}
- className="univer-defined-name-input-text-editor-container"
- canvasStyle={{ fontSize: 10 }}
+ {typeValue === 'range'
+ ? (
+ RangeSelector && (
+ <RangeSelector
+ unitId={unitId}
+ subUnitId={subUnitId}
+ initValue={formulaOrRefStringValue}
+ onChange={rangeSelectorChange}
+ isFocus={isFocusRangeSelector}
+ onFocus={() => isFocusRangeSelectorSet(true)}
+ actions={rangeSelectorActionsRef.current}
+ isSupportAcrossSheet
+ />
+ )
+ )
+ : (FormulaEditor && (
+ <FormulaEditor
+ initValue={formulaOrRefStringValue as any}
+ unitId={unitId}
+ subUnitId={subUnitId}
+ isFocus={isFocusFormulaEditor}
+ onChange={(v = '') => {
+ const formula = v || '';
+ formulaEditorChange(formula);
+ }}
+ onVerify={(res: boolean) => {
+ setValidFormulaOrRange(res);
+ }}
+ onFocus={() => isFocusFormulaEditorSet(true)}
+ actions={formulaEditorActionsRef.current}
/>
- </div>
- )}
-
+ ))}
<div>
<Select style={widthStyle} value={localSheetIdValue} options={options} onChange={setLocalSheetIdValue} />
</div>
diff --git a/packages/sheets-ui/src/views/permission/panel-detail/index.tsx b/packages/sheets-ui/src/views/permission/panel-detail/index.tsx
index d413a59aa0..42b1fee57d 100644
--- a/packages/sheets-ui/src/views/permission/panel-detail/index.tsx
+++ b/packages/sheets-ui/src/views/permission/panel-detail/index.tsx
@@ -355,6 +355,7 @@ export const SheetPermissionPanelDetail = ({ fromSheetBar }: { fromSheetBar: boo
subUnitId={subUnitId}
initValue={rangeStr}
onChange={handleRangeChange}
+ onFocus={() => isFocusRangeSelectorSet(true)}
// onVerify={handleVerify}
isFocus={isFocusRangeSelector}
actions={rangeSelectorActionsRef.current}
diff --git a/packages/ui/src/index.ts b/packages/ui/src/index.ts
index ea164f1a01..5e9f54b034 100644
--- a/packages/ui/src/index.ts
+++ b/packages/ui/src/index.ts
@@ -104,6 +104,7 @@ export { KeyCode, MetaKeys } from './services/shortcut/keycode';
export { type IShortcutItem, IShortcutService, ShortcutService } from './services/shortcut/shortcut.service';
export { ShortcutPanelService } from './services/shortcut/shortcut-panel.service';
export { DesktopSidebarService } from './services/sidebar/desktop-sidebar.service';
+export { useSidebarClick } from './services/sidebar/hooks/useSidebarClick';
export { ILeftSidebarService, ISidebarService } from './services/sidebar/sidebar.service';
export { DesktopZenZoneService } from './services/zen-zone/desktop-zen-zone.service';
export { IZenZoneService } from './services/zen-zone/zen-zone.service';
diff --git a/packages/ui/src/services/sidebar/desktop-sidebar.service.ts b/packages/ui/src/services/sidebar/desktop-sidebar.service.ts
index 84bcc6fb41..b2fccba62d 100644
--- a/packages/ui/src/services/sidebar/desktop-sidebar.service.ts
+++ b/packages/ui/src/services/sidebar/desktop-sidebar.service.ts
@@ -14,19 +14,21 @@
* limitations under the License.
*/
-import { toDisposable } from '@univerjs/core';
import type { IDisposable } from '@univerjs/core';
-import { Subject } from 'rxjs';
-
import type { ISidebarMethodOptions } from '../../views/components/sidebar/interface';
import type { ISidebarService } from './sidebar.service';
+import { toDisposable } from '@univerjs/core';
+import { Subject } from 'rxjs';
+
export class DesktopSidebarService implements ISidebarService {
private _sidebarOptions: ISidebarMethodOptions = {};
readonly sidebarOptions$ = new Subject<ISidebarMethodOptions>();
readonly scrollEvent$ = new Subject<Event>();
+ private container?: HTMLElement;
+
get visible(): boolean {
return this._sidebarOptions.visible || false;
}
@@ -60,4 +62,12 @@ export class DesktopSidebarService implements ISidebarService {
this.sidebarOptions$.next(this._sidebarOptions);
this._sidebarOptions.onClose && this._sidebarOptions.onClose();
}
+
+ getContainer() {
+ return this.container;
+ }
+
+ setContainer(element: HTMLElement) {
+ this.container = element;
+ }
}
diff --git a/packages/ui/src/services/sidebar/hooks/useSidebarClick.ts b/packages/ui/src/services/sidebar/hooks/useSidebarClick.ts
new file mode 100644
index 0000000000..a85a4eeebe
--- /dev/null
+++ b/packages/ui/src/services/sidebar/hooks/useSidebarClick.ts
@@ -0,0 +1,35 @@
+/**
+ * Copyright 2023-present DreamNum Inc.
+ *
+ * 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 { useDependency } from '@univerjs/core';
+import { ISidebarService } from '@univerjs/ui';
+import { useEffect } from 'react';
+/**
+ * Response panel to a click event.
+ */
+export const useSidebarClick = (cb: (event: MouseEvent) => void) => {
+ const sidebarService = useDependency(ISidebarService);
+ const container = sidebarService.getContainer();
+
+ useEffect(() => {
+ if (container) {
+ container.addEventListener('mousedown', cb);
+ return () => {
+ container.removeEventListener('mousedown', cb);
+ };
+ }
+ }, [cb, container]);
+};
diff --git a/packages/ui/src/services/sidebar/sidebar.service.ts b/packages/ui/src/services/sidebar/sidebar.service.ts
index 194a4864a7..dc40b96b76 100644
--- a/packages/ui/src/services/sidebar/sidebar.service.ts
+++ b/packages/ui/src/services/sidebar/sidebar.service.ts
@@ -15,11 +15,11 @@
*/
import type { IDisposable } from '@univerjs/core';
-import { createIdentifier } from '@univerjs/core';
import type { Subject } from 'rxjs';
-
import type { ISidebarMethodOptions } from '../../views/components/sidebar/interface';
+import { createIdentifier } from '@univerjs/core';
+
export interface ISidebarService {
readonly sidebarOptions$: Subject<ISidebarMethodOptions>;
readonly scrollEvent$: Subject<Event>;
@@ -30,6 +30,9 @@ export interface ISidebarService {
get visible(): boolean;
get options(): ISidebarMethodOptions;
+
+ getContainer(): HTMLElement | undefined;
+ setContainer(element?: HTMLElement): void;
}
export const ILeftSidebarService = createIdentifier<ISidebarService>('ui.left-sidebar.service');
diff --git a/packages/ui/src/views/components/sidebar/Sidebar.tsx b/packages/ui/src/views/components/sidebar/Sidebar.tsx
index 1c1df99eff..81d53316a3 100644
--- a/packages/ui/src/views/components/sidebar/Sidebar.tsx
+++ b/packages/ui/src/views/components/sidebar/Sidebar.tsx
@@ -14,15 +14,15 @@
* limitations under the License.
*/
-import { CloseSingle } from '@univerjs/icons';
+import type { ISidebarMethodOptions } from './interface';
import { useDependency } from '@univerjs/core';
+import { CloseSingle } from '@univerjs/icons';
import clsx from 'clsx';
import React, { useEffect, useMemo, useRef } from 'react';
import { CustomLabel } from '../../../components/custom-label/CustomLabel';
-import { ISidebarService } from '../../../services/sidebar/sidebar.service';
import { useObservable } from '../../../components/hooks/observable';
+import { ISidebarService } from '../../../services/sidebar/sidebar.service';
import styles from './index.module.less';
-import type { ISidebarMethodOptions } from './interface';
export function Sidebar() {
const sidebarService = useDependency(ISidebarService);
@@ -55,6 +55,14 @@ export function Sidebar() {
return copy;
}, [sidebarOptions]);
+ useEffect(() => {
+ if (scrollRef.current) {
+ sidebarService.setContainer(scrollRef.current);
+ }
+ return () => {
+ sidebarService.setContainer(undefined);
+ };
+ }, [sidebarService]);
useEffect(() => {
const handleScroll = (e: Event) => {
sidebarService.scrollEvent$.next(e);