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.

fix(editor): cursor and menu and single choice (#1499)

Univer6cdccdeb57e6
diff --git a/examples/src/plugins/debugger/views/test-editor/TestTextEditor.tsx b/examples/src/plugins/debugger/views/test-editor/TestTextEditor.tsx
index 4c41fa8bed..0a366c81d4 100644
--- a/examples/src/plugins/debugger/views/test-editor/TestTextEditor.tsx
+++ b/examples/src/plugins/debugger/views/test-editor/TestTextEditor.tsx
@@ -19,6 +19,7 @@ import React from 'react';
import { RangeSelector, TextEditor } from '@univerjs/ui';
import { IUniverInstanceService } from '@univerjs/core';
import { useDependency } from '@wendellhu/redi/react-bindings';
+import { Input } from '@univerjs/design';
const containerStyle: React.CSSProperties = {
position: 'absolute',
@@ -60,6 +61,10 @@ export const TestEditorContainer = () => {
<TextEditor id="test-editor-4" openForSheetUnitId={unitId} openForSheetSubUnitId={sheetId} isSingle={false} onlyInputContent={true} style={{ ...editorStyle, height: '140px' }} canvasStyle={{ fontSize: 14 }} />
<br></br>
<RangeSelector id="test-rangeSelector-1" openForSheetUnitId={unitId} openForSheetSubUnitId={sheetId} />
+ <br></br>
+ <RangeSelector id="test-rangeSelector-2" isSingleChoice={true} openForSheetUnitId={unitId} openForSheetSubUnitId={sheetId} />
+ <br></br>
+ <Input allowClear />
</div>
);
};
diff --git a/packages/core/src/shared/compare.ts b/packages/core/src/shared/compare.ts
index 0e18b6d27d..af88a097ee 100644
--- a/packages/core/src/shared/compare.ts
+++ b/packages/core/src/shared/compare.ts
@@ -46,3 +46,7 @@ export function isSameStyleTextRun(tr1: ITextRun, tr2: ITextRun) {
return deepCompare(ts1, ts2);
}
+
+export function checkForSubstrings(searchString: string, substrings: string[]): boolean {
+ return substrings.some((substring) => searchString.indexOf(substring) > -1);
+}
diff --git a/packages/docs-ui/src/controllers/doc-editor-bridge.controller.ts b/packages/docs-ui/src/controllers/doc-editor-bridge.controller.ts
index 23fab8daf4..2dcdd963b4 100644
--- a/packages/docs-ui/src/controllers/doc-editor-bridge.controller.ts
+++ b/packages/docs-ui/src/controllers/doc-editor-bridge.controller.ts
@@ -15,7 +15,7 @@
*/
import type { ICommandInfo, Nullable } from '@univerjs/core';
-import { Disposable, ICommandService, IUniverInstanceService, LifecycleStages, OnLifecycle } from '@univerjs/core';
+import { checkForSubstrings, Disposable, ICommandService, IUniverInstanceService, LifecycleStages, OnLifecycle } from '@univerjs/core';
import { Inject } from '@wendellhu/redi';
import { IRenderManagerService, ITextSelectionRenderManager, ScrollBar } from '@univerjs/engine-render';
@@ -87,6 +87,8 @@ export class DocEditorBridgeController extends Disposable {
return;
}
+ skeleton.calculate();
+
const { marginTop = 0, marginBottom = 0, marginLeft = 0, marginRight = 0 } = editorDataModel.getSnapshot().documentStyle;
const { scene, mainComponent } = editor.render;
@@ -188,11 +190,19 @@ export class DocEditorBridgeController extends Disposable {
})
);
+ const focusExcepts = [
+ 'univer-formula-search',
+ 'univer-formula-help',
+ 'formula-help-decorator',
+ 'univer-formula-help-param',
+ ];
+
this.disposeWithMe(
fromEvent(window, 'mousedown').subscribe((event) => {
const target = event.target as HTMLElement;
- const hasSearch = target.classList[0];
- if (hasSearch?.indexOf('univer-formula-search') > -1 || hasSearch?.indexOf('univer-formula-help') > -1 || hasSearch?.indexOf('formula-help-decorator') || hasSearch?.indexOf('univer-formula-help-param')) {
+ const hasSearch = target.classList[0] || '';
+
+ if (checkForSubstrings(hasSearch, focusExcepts)) {
this._editorService.changeSpreadsheetFocusState(true);
event.stopPropagation();
return;
diff --git a/packages/sheets-formula/src/controllers/prompt.controller.ts b/packages/sheets-formula/src/controllers/prompt.controller.ts
index 8d8ea90610..27748ff5c7 100644
--- a/packages/sheets-formula/src/controllers/prompt.controller.ts
+++ b/packages/sheets-formula/src/controllers/prompt.controller.ts
@@ -1218,7 +1218,7 @@ export class PromptController extends Disposable {
editorUnitId?: string,
canUndo: boolean = true
) {
- const dataStream = generateStringWithSequence(sequenceNodes);
+ let dataStream = generateStringWithSequence(sequenceNodes);
const { textRuns, refSelections } = this._buildTextRuns(sequenceNodes);
@@ -1242,8 +1242,13 @@ export class PromptController extends Disposable {
const editor = this._editorService.getEditor(editorUnitId);
+ if (editor?.isSingleChoice()) {
+ dataStream = dataStream.split(',')[0];
+ }
+
let formulaString = dataStream;
let offset = 1;
+
if (!editor || !editor.onlyInputRange()) {
formulaString = `${compareToken.EQUALS}${dataStream}`;
offset = 0;
@@ -1818,6 +1823,16 @@ export class PromptController extends Disposable {
})
)
);
+
+ this.disposeWithMe(
+ this._editorService.singleSelection$.subscribe((state) => {
+ if (state === true) {
+ this._selectionRenderService.enableSingleSelection();
+ } else {
+ this._selectionRenderService.disableSingleSelection();
+ }
+ })
+ );
}
private _changeRefString() {
diff --git a/packages/sheets-ui/src/services/selection/selection-render.service.ts b/packages/sheets-ui/src/services/selection/selection-render.service.ts
index f68c907cb6..037a6c9da9 100644
--- a/packages/sheets-ui/src/services/selection/selection-render.service.ts
+++ b/packages/sheets-ui/src/services/selection/selection-render.service.ts
@@ -90,6 +90,9 @@ export interface ISelectionRenderService {
reset(): void;
refreshSelectionMoveStart(): void;
+
+ enableSingleSelection(): void;
+ disableSingleSelection(): void;
}
/**
@@ -164,6 +167,8 @@ export class SelectionRenderService implements ISelectionRenderService {
private _isSkipRemainLastEnable: boolean = false;
+ private _isSingleSelection: boolean = false; // Multiple selections are prohibited
+
private readonly _selectionMoveEnd$ = new BehaviorSubject<ISelectionWithCoordAndStyle[]>([]);
// When the user draws a selection area in the canvas content area, this event is broadcasted when the drawing ends.
@@ -250,6 +255,14 @@ export class SelectionRenderService implements ISelectionRenderService {
this._isSkipRemainLastEnable = false;
}
+ enableSingleSelection() {
+ this._isSingleSelection = true;
+ }
+
+ disableSingleSelection() {
+ this._isSingleSelection = false;
+ }
+
getViewPort() {
return this._activeViewport;
}
@@ -258,7 +271,6 @@ export class SelectionRenderService implements ISelectionRenderService {
* add a selection
* @param selectionRange
* @param curCellRange
- * @returns
*/
addControlToCurrentByRangeData(data: ISelectionWithCoordAndStyle) {
const currentControls = this.getCurrentControls();
@@ -598,11 +610,11 @@ export class SelectionRenderService implements ISelectionRenderService {
// In addition to pressing the ctrl or shift key, we must clear the previous selection
if (
- curControls.length > 0 &&
+ (curControls.length > 0 &&
!evt.ctrlKey &&
!evt.shiftKey &&
!this._isShowPreviousEnable &&
- !this._isRemainLastEnable
+ !this._isRemainLastEnable) || (curControls.length > 0 && this._isSingleSelection && !evt.shiftKey)
) {
for (const control of curControls) {
control.dispose();
@@ -682,7 +694,7 @@ export class SelectionRenderService implements ISelectionRenderService {
selectionControl &&
!evt.ctrlKey &&
!evt.shiftKey &&
- !this._isSkipRemainLastEnable
+ !this._isSkipRemainLastEnable && !this._isSingleSelection
) {
/**
* Supports the formula ref text selection feature,
@@ -978,9 +990,6 @@ export class SelectionRenderService implements ISelectionRenderService {
/**
* When mousedown and mouseup need to go to the coordination and undo stack, when mousemove does not need to go to the coordination and undo stack
- * @param moveEvt
- * @param selectionControl
- * @returns
*/
private _moving(
moveOffsetX: number,
diff --git a/packages/ui/src/components/editor/TextEditor.tsx b/packages/ui/src/components/editor/TextEditor.tsx
index c75fa54317..5900336e02 100644
--- a/packages/ui/src/components/editor/TextEditor.tsx
+++ b/packages/ui/src/components/editor/TextEditor.tsx
@@ -18,7 +18,7 @@ import { debounce, type IDocumentData, LocaleService, type Nullable } from '@uni
import { useDependency } from '@wendellhu/redi/react-bindings';
import React, { useEffect, useRef, useState } from 'react';
import { Popup } from '@univerjs/design';
-import type { IEditorCanvasStyle } from '../../services/editor/editor.service';
+import type { Editor, IEditorCanvasStyle } from '../../services/editor/editor.service';
import { IEditorService } from '../../services/editor/editor.service';
import styles from './index.module.less';
@@ -36,6 +36,7 @@ const excludeProps = new Set([
'onlyInputRange',
'value',
'onlyInputContent',
+ 'isSingleChoice',
'openForSheetUnitId',
'openForSheetSubUnitId',
'onChange',
@@ -66,6 +67,8 @@ export interface ITextEditorProps {
onlyInputRange?: boolean; // Only input ref range
onlyInputContent?: boolean; // Only plain content can be entered, turning off formula and range input highlighting.
+ isSingleChoice?: boolean; // Whether to restrict to only selecting a single region/area/district.
+
openForSheetUnitId?: Nullable<string>; // Configuring which workbook the selector defaults to opening in determines whether the ref includes a [unitId] prefix.
openForSheetSubUnitId?: Nullable<string>; // Configuring the default worksheet where the selector opens determines whether the ref includes a [unitId]sheet1 prefix.
@@ -96,6 +99,8 @@ export function TextEditor(props: ITextEditorProps & Omit<MyComponentProps, 'onC
onlyInputRange = false,
onlyInputContent = false,
+ isSingleChoice = false,
+
openForSheetUnitId,
openForSheetSubUnitId,
@@ -144,6 +149,7 @@ export function TextEditor(props: ITextEditorProps & Omit<MyComponentProps, 'onC
canvasStyle,
isSingle,
isReadonly,
+ isSingleChoice,
onlyInputFormula,
onlyInputRange,
onlyInputContent,
@@ -161,6 +167,25 @@ export function TextEditor(props: ITextEditorProps & Omit<MyComponentProps, 'onC
onFocus && onFocus(state);
});
+ const valueChange = debounce((editor: Readonly<Editor>) => {
+ const unitId = editor.editorUnitId;
+ const isLegality = editorService.checkValueLegality(unitId);
+ setValidationVisible(!isLegality);
+ const rect = editor.getBoundingClientRect();
+
+ setValidationOffset([rect.left, rect.top - 16]);
+
+ if (editor.onlyInputFormula()) {
+ setValidationContent(localeService.t('textEditor.formulaError'));
+ } else {
+ setValidationContent(localeService.t('textEditor.rangeError'));
+ }
+
+ onValid && onValid(isLegality);
+
+ onChange && onChange(editorService.getValue(id));
+ }, 10);
+
const valueChangeSubscription = editorService.valueChange$.subscribe((editor) => {
if (!editor.onlyInputFormula() && !editor.onlyInputRange()) {
return;
@@ -170,24 +195,7 @@ export function TextEditor(props: ITextEditorProps & Omit<MyComponentProps, 'onC
return;
}
- debounce(() => {
- const unitId = editor.editorUnitId;
- const isLegality = editorService.checkValueLegality(unitId);
- setValidationVisible(!isLegality);
- const rect = editor.getBoundingClientRect();
-
- setValidationOffset([rect.left, rect.top - 16]);
-
- if (editor.onlyInputFormula()) {
- setValidationContent(localeService.t('textEditor.formulaError'));
- } else {
- setValidationContent(localeService.t('textEditor.rangeError'));
- }
-
- onValid && onValid(isLegality);
-
- onChange && onChange(editorService.getValue(id));
- }, 10)();
+ valueChange(editor);
});
// Clean up on unmount
diff --git a/packages/ui/src/components/range-selector/RangeSelector.tsx b/packages/ui/src/components/range-selector/RangeSelector.tsx
index 41ad14e602..b304a7fcf0 100644
--- a/packages/ui/src/components/range-selector/RangeSelector.tsx
+++ b/packages/ui/src/components/range-selector/RangeSelector.tsx
@@ -32,12 +32,14 @@ export interface IRangeSelectorProps {
value?: string; // default values.
onChange?: (ranges: IUnitRange[]) => void; // Callback for changes in the selector value.
+ isSingleChoice?: boolean; // Whether to restrict to only selecting a single region/area/district.
+
openForSheetUnitId?: Nullable<string>; // Configuring which workbook the selector defaults to opening in determines whether the ref includes a [unitId] prefix.
openForSheetSubUnitId?: Nullable<string>; // Configuring the default worksheet where the selector opens determines whether the ref includes a [unitId]sheet1 prefix.
}
export function RangeSelector(props: IRangeSelectorProps) {
- const { onChange, id, value = '', openForSheetUnitId, openForSheetSubUnitId } = props;
+ const { onChange, id, value = '', isSingleChoice = false, openForSheetUnitId, openForSheetSubUnitId } = props;
const [rangeDataList, setRangeDataList] = useState<string[]>(['']);
@@ -115,7 +117,7 @@ export function RangeSelector(props: IRangeSelectorProps) {
}
const lastRange = ranges[ranges.length - 1];
- if (addItemCount >= 1) {
+ if (addItemCount >= 1 && !isSingleChoice) {
addNewItem(serializeRange(lastRange));
} else {
changeLastItem(serializeRange(lastRange));
@@ -205,7 +207,7 @@ export function RangeSelector(props: IRangeSelectorProps) {
return (
<>
<div className={sClassName} ref={selectorRef}>
- <TextEditor openForSheetUnitId={openForSheetUnitId} openForSheetSubUnitId={openForSheetSubUnitId} onValid={onValid} onFocus={onFocus} onChange={handleTextValueChange} id={id} onlyInputRange={true} canvasStyle={{ fontSize: 10 }} className={styles.rangeSelectorEditor} />
+ <TextEditor isSingleChoice={isSingleChoice} openForSheetUnitId={openForSheetUnitId} openForSheetSubUnitId={openForSheetSubUnitId} onValid={onValid} onFocus={onFocus} onChange={handleTextValueChange} id={id} onlyInputRange={true} canvasStyle={{ fontSize: 10 }} className={styles.rangeSelectorEditor} />
<Tooltip title={localeService.t('rangeSelector.buttonTooltip')} placement="bottom">
<button className={styles.rangeSelectorIcon} onClick={handleOpenModal}>
<SelectRangeSingle />
@@ -239,7 +241,7 @@ export function RangeSelector(props: IRangeSelectorProps) {
</div>
))}
- <div className={styles.rangeSelectorModalAdd}>
+ <div style={{ display: isSingleChoice ? 'none' : 'unset' }} className={styles.rangeSelectorModalAdd}>
<Button size="small" onClick={handleAddRange}>{localeService.t('rangeSelector.addAnotherRange')}</Button>
</div>
</div>
diff --git a/packages/ui/src/services/editor/editor.service.ts b/packages/ui/src/services/editor/editor.service.ts
index 6b4562dc91..389e40e274 100644
--- a/packages/ui/src/services/editor/editor.service.ts
+++ b/packages/ui/src/services/editor/editor.service.ts
@@ -46,6 +46,8 @@ export interface IEditorConfigParam {
onlyInputRange: boolean;
onlyInputContent: boolean;
+ isSingleChoice: boolean;
+
openForSheetUnitId: Nullable<string>;
openForSheetSubUnitId: Nullable<string>;
@@ -67,7 +69,7 @@ export interface IEditorInputFormulaParam {
formulaString: string;
}
-class Editor {
+export class Editor {
private _focus = false;
private _valueLegality = true;
@@ -97,6 +99,10 @@ class Editor {
return this._param.render;
}
+ isSingleChoice() {
+ return this._param.isSingleChoice;
+ }
+
setOpenForSheetUnitId(unitId: Nullable<string>) {
this._openForSheetUnitId = unitId;
}
@@ -240,7 +246,6 @@ export interface IEditorService {
setFormula(formulaString: string): void;
resize$: Observable<string>;
-
resize(id: string): void;
getAllEditor(): Map<string, Editor>;
@@ -250,15 +255,12 @@ export interface IEditorService {
* whether to include unitId information in the ref.
*/
setOperationSheetUnitId(unitId: Nullable<string>): void;
-
getOperationSheetUnitId(): Nullable<string>;
-
/**
* The sub-table within the sheet currently being operated on
* will determine whether to include subUnitId information in the ref.
*/
setOperationSheetSubUnitId(sheetId: Nullable<string>): void;
-
getOperationSheetSubUnitId(): Nullable<string>;
isEditor(editorUnitId: string): boolean;
@@ -266,19 +268,15 @@ export interface IEditorService {
isSheetEditor(editorUnitId: string): boolean;
closeRangePrompt$: Observable<unknown>;
-
closeRangePrompt(): void;
blur$: Observable<unknown>;
-
blur(): void;
focus$: Observable<ISuccinctTextRangeParam>;
-
focus(editorUnitId?: string): void;
setValue$: Observable<IEditorSetValueParam>;
-
valueChange$: Observable<Readonly<Editor>>;
setValue(val: string, editorUnitId?: string): void;
@@ -288,7 +286,6 @@ export interface IEditorService {
getFirstEditor(): Editor;
focusStyle$: Observable<Nullable<string>>;
-
focusStyle(editorUnitId: Nullable<string>): void;
refreshValueChange(editorId: string): void;
@@ -304,6 +301,9 @@ export interface IEditorService {
getSpreadsheetFocusState(): boolean;
selectionChangingState(): boolean;
+
+ singleSelection$: Observable<boolean>;
+ singleSelection(state: boolean): void;
}
export class EditorService extends Disposable implements IEditorService, IDisposable {
@@ -338,9 +338,11 @@ export class EditorService extends Disposable implements IEditorService, IDispos
readonly valueChange$ = this._valueChange$.asObservable();
private readonly _focusStyle$ = new Subject<Nullable<string>>();
-
readonly focusStyle$ = this._focusStyle$.asObservable();
+ private readonly _singleSelection$ = new Subject<boolean>();
+ readonly singleSelection$ = this._singleSelection$.asObservable();
+
private _spreadsheetFocusState: boolean = false;
constructor(
@@ -391,9 +393,17 @@ export class EditorService extends Disposable implements IEditorService, IDispos
this._contextService.setContextValue(FOCUSING_UNIVER_EDITOR_SINGLE_MODE, editor.isSingle());
+ if (!this._spreadsheetFocusState) {
+ this.singleSelection(editor.isSingleChoice());
+ }
+
this._focusStyle$.next(editorUnitId);
}
+ singleSelection(state: boolean) {
+ this._singleSelection$.next(state);
+ }
+
selectionChangingState() {
const documentDataModel = this._currentUniverService.getCurrentUniverDocInstance();
const editorUnitId = documentDataModel.getUnitId();
@@ -405,11 +415,13 @@ export class EditorService extends Disposable implements IEditorService, IDispos
blur() {
if (!this._spreadsheetFocusState) {
this._closeRangePrompt$.next(null);
+ this.singleSelection(false);
}
this.getAllEditor().forEach((editor) => {
editor.setFocus(false);
});
+
this._focusStyle$.next();
this._blur$.next(null);
}
@@ -430,6 +442,8 @@ export class EditorService extends Disposable implements IEditorService, IDispos
const valueCount = editor.getValue().length;
+ this.focusStyle(editorUnitId);
+
this._focus$.next({
startOffset: valueCount - 2,
endOffset: valueCount - 2,
@@ -593,6 +607,16 @@ export class EditorService extends Disposable implements IEditorService, IDispos
this._editors.delete(editorUnitId);
this._currentUniverService.disposeDocument(editorUnitId);
+
+ /**
+ * Compatible with the editor in the sheet scenario,
+ * it is necessary to refocus back to the current sheet when unloading.
+ */
+ const sheets = this._currentUniverService.getAllUniverSheetsInstance();
+ if (sheets.length > 0) {
+ const current = this._currentUniverService.getCurrentUniverSheetInstance();
+ this._currentUniverService.focusUniverInstance(current.getUnitId());
+ }
}
refreshValueChange(editorUnitId: string) {
@@ -625,6 +649,10 @@ export class EditorService extends Disposable implements IEditorService, IDispos
editor.setValueLegality(bracketCount === 0);
} else if (editor.onlyInputRange()) {
const valueArray = value.split(',');
+ if (editor.isSingleChoice() && valueArray.length > 1) {
+ editor.setValueLegality(false);
+ return false;
+ }
const result = valueArray.every((refString) => {
return isReferenceString(refString.trim());
});