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.

feat(sheet): range selector (#1463)

Univerb6393945492b
diff --git a/examples/src/plugins/debugger/commands/operations/sidebar.operation.ts b/examples/src/plugins/debugger/commands/operations/sidebar.operation.ts
index 9a5bad77da..3eac6f35d2 100644
--- a/examples/src/plugins/debugger/commands/operations/sidebar.operation.ts
+++ b/examples/src/plugins/debugger/commands/operations/sidebar.operation.ts
@@ -43,7 +43,7 @@ export const SidebarOperation: ICommand = {
onClose: () => {
editorService.setOperationSheetUnitId(null);
editorService.setOperationSheetSubUnitId(null);
- editorService.changeEditorFocus();
+ editorService.closeRangePrompt();
},
});
break;
@@ -52,7 +52,7 @@ export const SidebarOperation: ICommand = {
default:
editorService.setOperationSheetUnitId(null);
editorService.setOperationSheetSubUnitId(null);
- editorService.changeEditorFocus();
+ editorService.closeRangePrompt();
sidebarService.close();
break;
}
diff --git a/examples/src/plugins/debugger/views/test-editor/TestTextEditor.tsx b/examples/src/plugins/debugger/views/test-editor/TestTextEditor.tsx
index 0c62a3fa05..4c41fa8bed 100644
--- a/examples/src/plugins/debugger/views/test-editor/TestTextEditor.tsx
+++ b/examples/src/plugins/debugger/views/test-editor/TestTextEditor.tsx
@@ -16,7 +16,9 @@
import React from 'react';
-import { TextEditor } from '@univerjs/ui';
+import { RangeSelector, TextEditor } from '@univerjs/ui';
+import { IUniverInstanceService } from '@univerjs/core';
+import { useDependency } from '@wendellhu/redi/react-bindings';
const containerStyle: React.CSSProperties = {
position: 'absolute',
@@ -35,17 +37,29 @@ const editorStyle: React.CSSProperties = {
* @returns
*/
export const TestEditorContainer = () => {
+ const univerInstanceService = useDependency(IUniverInstanceService);
+ const workbook = univerInstanceService.getCurrentUniverSheetInstance();
+ if (workbook == null) {
+ return;
+ }
+
+ const unitId = workbook.getUnitId();
+
+ const sheetId = workbook.getActiveSheet().getSheetId();
+
return (
<div
style={containerStyle}
>
- <TextEditor id="test-editor-1" isReadonly={true} style={editorStyle} canvasStyle={{ fontSize: 10 }} value="I found one cent on the roadside." />
+ <TextEditor id="test-editor-1" openForSheetUnitId={unitId} openForSheetSubUnitId={sheetId} isReadonly={true} style={editorStyle} canvasStyle={{ fontSize: 10 }} value="I found one cent on the roadside." />
+ <br></br>
+ <TextEditor id="test-editor-2" openForSheetUnitId={unitId} openForSheetSubUnitId={sheetId} onlyInputFormula={true} style={editorStyle} canvasStyle={{ fontSize: 10 }} />
<br></br>
- <TextEditor id="test-editor-2" onlyInputFormula={true} style={editorStyle} canvasStyle={{ fontSize: 10 }} />
+ <TextEditor id="test-editor-3" openForSheetUnitId={unitId} openForSheetSubUnitId={sheetId} onlyInputRange={true} style={editorStyle} canvasStyle={{ fontSize: 10 }} />
<br></br>
- <TextEditor id="test-editor-3" onlyInputRange={true} style={editorStyle} canvasStyle={{ fontSize: 10 }} />
+ <TextEditor id="test-editor-4" openForSheetUnitId={unitId} openForSheetSubUnitId={sheetId} isSingle={false} onlyInputContent={true} style={{ ...editorStyle, height: '140px' }} canvasStyle={{ fontSize: 14 }} />
<br></br>
- <TextEditor id="test-editor-4" isSingle={false} onlyInputContent={true} style={{ ...editorStyle, height: '140px' }} canvasStyle={{ fontSize: 14 }} />
+ <RangeSelector id="test-rangeSelector-1" openForSheetUnitId={unitId} openForSheetSubUnitId={sheetId} />
</div>
);
};
diff --git a/packages/design/src/components/dialog/index.module.less b/packages/design/src/components/dialog/index.module.less
index e8e610a630..379d53c09e 100644
--- a/packages/design/src/components/dialog/index.module.less
+++ b/packages/design/src/components/dialog/index.module.less
@@ -17,9 +17,13 @@
&-title {
margin: 0;
- padding: 24px 28px 20px;
+ // padding: 24px 28px 20px;
font-size: var(--font-size-lg);
font-weight: 500;
+
+ > div:first-child {
+ padding: 24px 28px 20px;
+ }
}
&-content {
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 5498c29ca0..23fab8daf4 100644
--- a/packages/docs-ui/src/controllers/doc-editor-bridge.controller.ts
+++ b/packages/docs-ui/src/controllers/doc-editor-bridge.controller.ts
@@ -18,10 +18,11 @@ import type { ICommandInfo, Nullable } from '@univerjs/core';
import { Disposable, ICommandService, IUniverInstanceService, LifecycleStages, OnLifecycle } from '@univerjs/core';
import { Inject } from '@wendellhu/redi';
-import { ITextSelectionRenderManager, ScrollBar } from '@univerjs/engine-render';
+import { IRenderManagerService, ITextSelectionRenderManager, ScrollBar } from '@univerjs/engine-render';
import type { IRichTextEditingMutationParams } from '@univerjs/docs';
import { CoverContentCommand, DocSkeletonManagerService, RichTextEditingMutation, VIEWPORT_KEY } from '@univerjs/docs';
import { IEditorService, SetEditorResizeOperation } from '@univerjs/ui';
+import { fromEvent } from 'rxjs';
@OnLifecycle(LifecycleStages.Rendered, DocEditorBridgeController)
export class DocEditorBridgeController extends Disposable {
@@ -32,7 +33,8 @@ export class DocEditorBridgeController extends Disposable {
@Inject(DocSkeletonManagerService) private readonly _docSkeletonManagerService: DocSkeletonManagerService,
@IEditorService private readonly _editorService: IEditorService,
@ICommandService private readonly _commandService: ICommandService,
- @ITextSelectionRenderManager private readonly _textSelectionRenderManager: ITextSelectionRenderManager
+ @ITextSelectionRenderManager private readonly _textSelectionRenderManager: ITextSelectionRenderManager,
+ @IRenderManagerService private readonly _renderManagerService: IRenderManagerService
) {
super();
@@ -159,6 +161,23 @@ export class DocEditorBridgeController extends Disposable {
this._textSelectionRenderManager.blur();
})
);
+
+ this.disposeWithMe(
+ this._textSelectionRenderManager.onBlur$.subscribe(() => {
+ const unitId = this._currentUniverService.getCurrentUniverDocInstance().getUnitId();
+ if (unitId == null) {
+ return;
+ }
+
+ const editor = this._editorService.getEditor(unitId);
+
+ if (editor == null || editor.isSheetEditor()) {
+ return;
+ }
+
+ this._editorService.blur();
+ })
+ );
}
private _initialFocus() {
@@ -168,6 +187,39 @@ export class DocEditorBridgeController extends Disposable {
this._textSelectionRenderManager.addTextRanges([textRange]);
})
);
+
+ 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')) {
+ this._editorService.changeSpreadsheetFocusState(true);
+ event.stopPropagation();
+ return;
+ }
+ this._editorService.changeSpreadsheetFocusState(false);
+ })
+ );
+
+ // this.disposeWithMe(
+ // fromEvent(window, 'mousedown').subscribe(() => {
+ // this._editorService.changeSpreadsheetFocusState(false);
+ // })
+ // );
+
+ const currentUniverSheet = this._currentUniverService.getAllUniverSheetsInstance();
+ currentUniverSheet.forEach((unit) => {
+ const unitId = unit.getUnitId();
+ const render = this._renderManagerService.getRenderById(unitId);
+ const canvasEle = render?.engine.getCanvas().getCanvasEle();
+ if (canvasEle == null) {
+ return;
+ }
+ fromEvent(canvasEle, 'mousedown').subscribe((evt) => {
+ this._editorService.changeSpreadsheetFocusState(true);
+ evt.stopPropagation();
+ });
+ });
}
private _initialValueChange() {
diff --git a/packages/docs-ui/src/controllers/text-selection.controller.ts b/packages/docs-ui/src/controllers/text-selection.controller.ts
index 312a290e87..e0ecf26eaa 100644
--- a/packages/docs-ui/src/controllers/text-selection.controller.ts
+++ b/packages/docs-ui/src/controllers/text-selection.controller.ts
@@ -121,9 +121,23 @@ export class TextSelectionController extends Disposable {
this._currentUniverService.setCurrentUniverDocInstance(unitId);
}
- this._textSelectionRenderManager.eventTrigger(evt);
-
- this._setEditorFocus(unitId);
+ if (this._editorService.getEditor(unitId)) {
+ /**
+ * To accommodate focus switching between different editors.
+ * Since the editor for Univer is canvas-based,
+ * it primarily relies on focus and cannot use the focus event.
+ * Our editor's focus monitoring is based on PointerDown.
+ * The order of occurrence is such that PointerDown comes first.
+ * Translate the above text into English.
+ */
+ setTimeout(() => {
+ this._textSelectionRenderManager.eventTrigger(evt);
+
+ this._setEditorFocus(unitId);
+ }, 0);
+ } else {
+ this._textSelectionRenderManager.eventTrigger(evt);
+ }
if (evt.button !== 2) {
state.stopPropagation();
@@ -168,6 +182,7 @@ export class TextSelectionController extends Disposable {
this._editorService.setOperationSheetUnitId(workbook.getUnitId());
// this._editorService.setOperationSheetSubUnitId(workbook.getActiveSheet().getSheetId());
}
+
this._editorService.focusStyle(unitId);
}
diff --git a/packages/engine-formula/src/basics/match-token.ts b/packages/engine-formula/src/basics/match-token.ts
index 32ff8d344b..518c75b70c 100644
--- a/packages/engine-formula/src/basics/match-token.ts
+++ b/packages/engine-formula/src/basics/match-token.ts
@@ -44,3 +44,18 @@ export function normalizeSheetName(sheetName: string) {
}
return sheetName;
}
+
+/**
+ * Determine whether the character is a token keyword for the formula engine.
+ * @param char
+ */
+export function matchRefDrawToken(char: string) {
+ return (
+ (isFormulaLexerToken(char) &&
+ char !== matchToken.CLOSE_BRACES &&
+ char !== matchToken.CLOSE_BRACKET &&
+ char !== matchToken.SINGLE_QUOTATION &&
+ char !== matchToken.DOUBLE_QUOTATION) ||
+ char === ' '
+ );
+}
diff --git a/packages/engine-formula/src/index.ts b/packages/engine-formula/src/index.ts
index 822f602d00..f80384f490 100644
--- a/packages/engine-formula/src/index.ts
+++ b/packages/engine-formula/src/index.ts
@@ -136,3 +136,4 @@ export { FormulaExecutedStateType, type IAllRuntimeData } from './services/runti
export { SetNumfmtFormulaDataMutation } from './commands/mutations/set-numfmt-formula-data.mutation';
export type { ISetNumfmtFormulaDataMutationParams } from './commands/mutations/set-numfmt-formula-data.mutation';
export { isReferenceString } from './basics/regex';
+export { matchRefDrawToken } from './basics/match-token';
diff --git a/packages/engine-render/src/canvas.ts b/packages/engine-render/src/canvas.ts
index 4d91bf5f44..ed7ca5c6cd 100644
--- a/packages/engine-render/src/canvas.ts
+++ b/packages/engine-render/src/canvas.ts
@@ -78,6 +78,8 @@ export class Canvas {
this._canvasEle.style.left = '0';
this._canvasEle.style.zIndex = '8';
+ this._canvasEle.className = 'univer-render-canvas';
+
// support focus
this._canvasEle.tabIndex = 1;
this._canvasEle.style.touchAction = 'none';
diff --git a/packages/engine-render/src/components/docs/text-selection-render-manager.ts b/packages/engine-render/src/components/docs/text-selection-render-manager.ts
index b0676888cb..c4dd4b6343 100644
--- a/packages/engine-render/src/components/docs/text-selection-render-manager.ts
+++ b/packages/engine-render/src/components/docs/text-selection-render-manager.ts
@@ -214,9 +214,11 @@ export class TextSelectionRenderManager extends RxDisposable implements ITextSel
private _input!: HTMLDivElement;
- private _moveObserver: Nullable<Observer<IPointerEvent | IMouseEvent>>;
+ private _moveObservers: Nullable<Observer<IPointerEvent | IMouseEvent>>[] = [];
- private _upObserver: Nullable<Observer<IPointerEvent | IMouseEvent>>;
+ private _upObservers: Nullable<Observer<IPointerEvent | IMouseEvent>>[] = [];
+
+ private _scrollTimers: ScrollTimer[] = [];
private _viewportScrollX: number = 0;
@@ -479,6 +481,7 @@ export class TextSelectionRenderManager extends RxDisposable implements ITextSel
scene.disableEvent();
const scrollTimer = ScrollTimer.create(scene);
+ this._scrollTimers.push(scrollTimer);
scrollTimer.startScroll(evtOffsetX, evtOffsetY);
const { scrollX, scrollY } = getCurrentScrollXY(scrollTimer);
@@ -492,7 +495,7 @@ export class TextSelectionRenderManager extends RxDisposable implements ITextSel
let preMoveOffsetY = evtOffsetY;
- this._moveObserver = scene.onPointerMoveObserver.add((moveEvt: IPointerEvent | IMouseEvent) => {
+ this._moveObservers.push(scene.onPointerMoveObserver.add((moveEvt: IPointerEvent | IMouseEvent) => {
const { offsetX: moveOffsetX, offsetY: moveOffsetY } = moveEvt;
scene.setCursor(CURSOR_TYPE.TEXT);
@@ -508,11 +511,23 @@ export class TextSelectionRenderManager extends RxDisposable implements ITextSel
preMoveOffsetX = moveOffsetX;
preMoveOffsetY = moveOffsetY;
- });
+ }));
+
+ this._upObservers.push(scene.onPointerUpObserver.add(() => {
+ // scene.onPointerMoveObserver.remove(this._moveObserver);
+ // scene.onPointerUpObserver.remove(this._upObserver);
+
+ this._moveObservers.forEach((obs) => {
+ obs?.dispose();
+ });
+
+ this._upObservers.forEach((obs) => {
+ obs?.dispose();
+ });
+
+ this._moveObservers = [];
- this._upObserver = scene.onPointerUpObserver.add(() => {
- scene.onPointerMoveObserver.remove(this._moveObserver);
- scene.onPointerUpObserver.remove(this._upObserver);
+ this._upObservers = [];
scene.enableEvent();
@@ -523,9 +538,14 @@ export class TextSelectionRenderManager extends RxDisposable implements ITextSel
isEditing: false,
});
- scrollTimer.dispose();
+ this._scrollTimers.forEach((timer) => {
+ timer?.dispose();
+ });
+
+ this._scrollTimers = [];
+
this._updateInputPosition();
- });
+ }));
}
removeAllTextRanges() {
diff --git a/packages/engine-render/src/engine.ts b/packages/engine-render/src/engine.ts
index e96dc65090..d846774369 100644
--- a/packages/engine-render/src/engine.ts
+++ b/packages/engine-render/src/engine.ts
@@ -142,7 +142,11 @@ export class Engine extends ThinEngine<Scene> {
* preventing the events from becoming ineffective once the mouse leaves the host.
*/
override setRemainCapture() {
- this._canvasEle.setPointerCapture(this._remainCapture);
+ try {
+ this._canvasEle.setPointerCapture(this._remainCapture);
+ } catch {
+ console.warn('no capture');
+ }
}
getPixelRatio() {
diff --git a/packages/engine-render/src/shape/base-scroll-bar.ts b/packages/engine-render/src/shape/base-scroll-bar.ts
index 24881f71d2..c71c508978 100644
--- a/packages/engine-render/src/shape/base-scroll-bar.ts
+++ b/packages/engine-render/src/shape/base-scroll-bar.ts
@@ -87,10 +87,17 @@ export class BaseScrollBar extends Disposable {
) {
return 1;
}
- return (
+
+ const ratio = (
((this.horizontalThumbWidth - this.horizontalMinusMiniThumb) * this.miniThumbRatioX) /
this.horizontalBarWidth
);
+
+ if (Number.isNaN(ratio)) {
+ return 1;
+ } else {
+ return ratio;
+ }
}
get ratioScrollY(): number {
@@ -101,9 +108,15 @@ export class BaseScrollBar extends Disposable {
) {
return 1;
}
- return (
+ const ratio = (
((this.verticalThumbHeight - this.verticalMinusMiniThumb) * this.miniThumbRatioY) / this.verticalBarHeight
);
+
+ if (Number.isNaN(ratio)) {
+ return 1;
+ } else {
+ return ratio;
+ }
}
get miniThumbRatioX() {
diff --git a/packages/engine-render/src/viewport.ts b/packages/engine-render/src/viewport.ts
index abebf72e64..fb3906f6ee 100644
--- a/packages/engine-render/src/viewport.ts
+++ b/packages/engine-render/src/viewport.ts
@@ -445,6 +445,8 @@ export class Viewport {
x /= scaleX;
} else if (this.actualScrollX !== undefined) {
x = this.actualScrollX;
+ } else {
+ x = 0;
}
if (this._scrollBar.ratioScrollY !== 0) {
@@ -453,6 +455,8 @@ export class Viewport {
y /= scaleY;
} else if (this.actualScrollY !== undefined) {
y = this.actualScrollY;
+ } else {
+ y = 0;
}
// console.log(y, this._scrollBar.miniThumbRatioY);
@@ -461,10 +465,14 @@ export class Viewport {
} else {
if (this.actualScrollX !== undefined) {
x = this.actualScrollX;
+ } else {
+ x = 0;
}
if (this.actualScrollY !== undefined) {
y = this.actualScrollY;
+ } else {
+ y = 0;
}
}
diff --git a/packages/sheets-formula/src/controllers/prompt.controller.ts b/packages/sheets-formula/src/controllers/prompt.controller.ts
index 34f0b2aa1d..8d8ea90610 100644
--- a/packages/sheets-formula/src/controllers/prompt.controller.ts
+++ b/packages/sheets-formula/src/controllers/prompt.controller.ts
@@ -53,8 +53,8 @@ import {
deserializeRangeWithSheet,
generateStringWithSequence,
getAbsoluteRefTypeWitString,
- isFormulaLexerToken,
LexerTreeBuilder,
+ matchRefDrawToken,
matchToken,
normalizeSheetName,
sequenceNodeType,
@@ -185,14 +185,6 @@ export class PromptController extends Disposable {
this._previousInsertRefStringIndex = null;
- // this._currentUnitId = null;
-
- // this._currentSheetId = null;
-
- this._editorService.setOperationSheetUnitId(null);
-
- this._editorService.setOperationSheetSubUnitId(null);
-
this._isSelectionMovingRefSelections = [];
this._previousRangesCount = 0;
@@ -337,20 +329,10 @@ export class PromptController extends Disposable {
this.disposeWithMe(
this._editorBridgeService.afterVisible$.subscribe((visibleParam) => {
if (visibleParam.visible === true) {
- const { unitId, sheetId } = this._getCurrentUnitIdAndSheetId();
-
- if (this._editorService.getOperationSheetUnitId() == null) {
- this._editorService.setOperationSheetUnitId(unitId);
- }
-
- if (this._editorService.getOperationSheetSubUnitId() == null) {
- this._editorService.setOperationSheetSubUnitId(sheetId);
- }
-
return;
}
- this._changeEditor();
+ this._closeRangePrompt();
})
);
}
@@ -369,20 +351,22 @@ export class PromptController extends Disposable {
}
if (!this._editorService.isSheetEditor(editorId)) {
- this._changeEditor(editorId);
+ this._closeRangePrompt(editorId);
this._previousEditorUnitId = editorId;
}
})
);
this.disposeWithMe(
- this._editorService.changeEditorFocus$.subscribe(() => {
- this._changeEditor();
+ this._editorService.closeRangePrompt$.subscribe(() => {
+ if (!this._editorService.getSpreadsheetFocusState() || !this._formulaPromptService.isLockedSelectionInsert()) {
+ this._closeRangePrompt();
+ }
})
);
}
- private _changeEditor(editorId: Nullable<string>) {
+ private _closeRangePrompt(editorId: Nullable<string>) {
/**
* Switching the selection of PluginName causes a refresh.
* Here, a delay is added to prevent the loss of content when pressing enter.
@@ -393,16 +377,6 @@ export class PromptController extends Disposable {
if (current?.pluginName === NORMAL_SELECTION_PLUGIN_NAME) {
this._disableForceKeepVisible();
- /**
- * In the standard selection mode, the pivot table and page fields of the formula selection need to be cleared.
- */
-
- const { unitId, sheetId } = this._getCurrentUnitIdAndSheetId();
-
- this._editorService.setOperationSheetUnitId(unitId);
-
- this._editorService.setOperationSheetSubUnitId(sheetId);
-
return;
}
@@ -491,7 +465,12 @@ export class PromptController extends Disposable {
return;
}
- if (!this._formulaPromptService.isLockedSelectionInsert()) {
+ /**
+ * selectionChangingState
+ * If the selection range in the editor is not restricted by being locked,
+ * it is considered a user experience optimization.
+ */
+ if (this._editorService.selectionChangingState() && !this._formulaPromptService.isLockedSelectionInsert()) {
return;
}
@@ -700,7 +679,7 @@ export class PromptController extends Disposable {
return;
}
- if (this._matchRefDrawToken(char)) {
+ if (matchRefDrawToken(char)) {
this._editorBridgeService.enableForceKeepVisible();
this._contextMenuService.disable();
@@ -717,21 +696,6 @@ export class PromptController extends Disposable {
}
}
- /**
- * Determine whether the character is a token keyword for the formula engine.
- * @param char
- */
- private _matchRefDrawToken(char: string) {
- return (
- (isFormulaLexerToken(char) &&
- char !== matchToken.CLOSE_BRACES &&
- char !== matchToken.CLOSE_BRACKET &&
- char !== matchToken.SINGLE_QUOTATION &&
- char !== matchToken.DOUBLE_QUOTATION) ||
- char === ' '
- );
- }
-
/**
*
* @returns Return the character under the current cursor in the editor.
@@ -1157,6 +1121,23 @@ export class PromptController extends Disposable {
};
}
+ private _getOpenForCurrentSheet() {
+ const documentDataModel = this._currentUniverService.getCurrentUniverDocInstance();
+ const editorUnitId = documentDataModel.getUnitId();
+ const editor = this._editorService.getEditor(editorUnitId);
+ if (editor == null) {
+ return {
+ openUnitId: null,
+ openSheetId: null,
+ };
+ }
+
+ return {
+ openUnitId: editor.getOpenForSheetUnitId(),
+ openSheetId: editor.getOpenForSheetSubUnitId(),
+ };
+ }
+
/**
* Convert the selection range to a ref string for the formula engine, such as A1:B1
* @param currentSelection
@@ -1167,13 +1148,15 @@ export class PromptController extends Disposable {
let refUnitId = '';
let refSheetName = '';
- if (unitId === this._editorService.getOperationSheetUnitId()) {
+ const { openUnitId, openSheetId } = this._getOpenForCurrentSheet();
+
+ if (unitId === openUnitId) {
refUnitId = '';
} else {
refUnitId = unitId;
}
- if (sheetId === this._editorService.getOperationSheetSubUnitId()) {
+ if (sheetId === openSheetId) {
refSheetName = '';
} else {
refSheetName = this._getSheetNameById(unitId, sheetId);
@@ -1416,7 +1399,7 @@ export class PromptController extends Disposable {
this._previousInsertRefStringIndex = this._currentInsertRefStringIndex;
- if (!this._matchRefDrawToken(char)) {
+ if (!matchRefDrawToken(char)) {
this._formulaPromptService.insertSequenceString(this._currentInsertRefStringIndex, matchToken.COMMA);
insertNodes = this._formulaPromptService.getSequenceNodes();
diff --git a/packages/sheets-formula/src/views/more-functions/input-params/InputParams.tsx b/packages/sheets-formula/src/views/more-functions/input-params/InputParams.tsx
index 98e244bfcf..5e1dbf6677 100644
--- a/packages/sheets-formula/src/views/more-functions/input-params/InputParams.tsx
+++ b/packages/sheets-formula/src/views/more-functions/input-params/InputParams.tsx
@@ -15,7 +15,6 @@
*/
import type { IFunctionInfo, IFunctionParam } from '@univerjs/engine-formula';
-import { RangeSelector } from '@univerjs/sheets-ui';
import React, { useState } from 'react';
import { FunctionHelp } from '../function-help/FunctionHelp';
@@ -61,10 +60,10 @@ export function InputParams(props: IInputParamsProps) {
<div className={styles.formulaInputParamsListItemName}>{item.name}</div>
<div className={styles.formulaInputParamsListItemSelector}>
- <RangeSelector
+ {/* <RangeSelector
onChange={(range: string) => handleChange(range, i)}
onActive={() => handleActive(i)}
- />
+ /> */}
</div>
</div>
))}
diff --git a/packages/sheets-formula/src/views/prompt/help-function/HelpFunction.tsx b/packages/sheets-formula/src/views/prompt/help-function/HelpFunction.tsx
index e2819bdfc4..f7cb16356a 100644
--- a/packages/sheets-formula/src/views/prompt/help-function/HelpFunction.tsx
+++ b/packages/sheets-formula/src/views/prompt/help-function/HelpFunction.tsx
@@ -200,17 +200,17 @@ interface IHelpProps {
const Help = (props: IHelpProps) => {
const { prefix, value, active, onClick } = props;
return (
- <div>
- <span>
+ <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}>
+ <span key={i} className={styles.formulaHelpParamItem}>
<span
- className={active === i ? styles.formulaHelpFunctionActive : ''}
+ className={active === i ? styles.formulaHelpFunctionActive : styles.formulaHelpParamActive}
onClick={() => onClick(i)}
>
{item.repeat ? `[${item.name},...]` : item.name}
diff --git a/packages/sheets-formula/src/views/prompt/help-function/index.module.less b/packages/sheets-formula/src/views/prompt/help-function/index.module.less
index 001a5523dd..a77c1681b8 100644
--- a/packages/sheets-formula/src/views/prompt/help-function/index.module.less
+++ b/packages/sheets-formula/src/views/prompt/help-function/index.module.less
@@ -111,3 +111,18 @@
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-ui/src/components/range-selector/RangeSelector.tsx b/packages/sheets-ui/src/components/range-selector/RangeSelector.tsx
deleted file mode 100644
index 1aafa46af6..0000000000
--- a/packages/sheets-ui/src/components/range-selector/RangeSelector.tsx
+++ /dev/null
@@ -1,118 +0,0 @@
-/**
- * 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 { LocaleService } from '@univerjs/core';
-import { Tooltip } from '@univerjs/design';
-import { SelectRangeSingle } from '@univerjs/icons';
-import { SelectionManagerService } from '@univerjs/sheets';
-import { useDependency } from '@wendellhu/redi/react-bindings';
-import React, { useEffect, useRef, useState } from 'react';
-
-import styles from './index.module.less';
-
-export interface IRangeSelectorProps {
- onChange: (range: string) => void;
- onActive: (active: boolean) => void;
-}
-
-export function RangeSelector(props: IRangeSelectorProps) {
- const { onChange, onActive } = props;
- const [active, setActive] = useState(false);
- const editableRef = useRef<HTMLDivElement>(null);
- const localeService = useDependency(LocaleService);
- const textSelectionManagerService = useDependency(SelectionManagerService);
-
- useEffect(() => {
- if (active) {
- onActive(active);
- const subscribe = textSelectionManagerService.selectionMoveEnd$.subscribe((selectionInfo) => {
- // TODO@Dushusir: get range text info from selectionInfo
- const rangeTextList = ['A1', 'B2:C3', 'Sheet2!A1:B2', 'D10:E11,F1:G2,H3:I4'];
- const randomIndex = Math.floor(Math.random() * rangeTextList.length);
- const range = rangeTextList[randomIndex];
-
- if (editableRef.current) {
- editableRef.current.innerHTML = range;
- }
- });
-
- document.addEventListener('click', handleActiveClick);
-
- return () => {
- document.removeEventListener('click', handleActiveClick);
- subscribe.unsubscribe();
- };
- }
- onChange(editableRef.current?.innerHTML || '');
- }, [active]);
-
- function handleActiveClick(e: MouseEvent) {
- // content and footer area, used to select the area
- const selector = (e.target as Element)?.closest('[data-range-selector="true"]');
- if (selector) return;
-
- // Current editor area
- if (e.target === editableRef.current) return;
-
- // Right button
- const editorContainer = (e.target as Element)?.closest(`.${styles.rangeSelector}`);
- const editor = editorContainer?.querySelector(`.${styles.rangeSelectorEditor}`);
- if (editor === editableRef.current) return;
-
- setActive(false);
- editableRef.current?.blur();
- }
-
- function handleKeyDown(e: React.KeyboardEvent<HTMLDivElement>) {
- e.stopPropagation();
- if (e.key === 'Enter') {
- e.preventDefault();
- e.currentTarget.blur();
- setActive(false);
- }
- }
-
- function handleFocus() {
- setActive(true);
- }
-
- function handleClick() {
- if (!active) {
- editableRef.current?.focus();
- return;
- }
- setActive(!active);
- }
-
- return (
- <div className={active ? `${styles.rangeSelector} ${styles.rangeSelectorActive}` : styles.rangeSelector}>
- <div
- ref={editableRef}
- className={styles.rangeSelectorEditor}
- contentEditable
- data-placeholder={localeService.t('rangeSelector.placeholder')}
- onKeyDown={handleKeyDown}
- onFocus={handleFocus}
- />
-
- <Tooltip title={localeService.t('rangeSelector.tooltip')} placement="bottom">
- <button className={styles.rangeSelectorIcon} onClick={handleClick}>
- <SelectRangeSingle />
- </button>
- </Tooltip>
- </div>
- );
-}
diff --git a/packages/sheets-ui/src/components/range-selector/index.module.less b/packages/sheets-ui/src/components/range-selector/index.module.less
deleted file mode 100644
index 99732ce333..0000000000
--- a/packages/sheets-ui/src/components/range-selector/index.module.less
+++ /dev/null
@@ -1,81 +0,0 @@
-@padding-top-bottom: 6px;
-@height: 20px;
-@width: 218px;
-@icon-size: 24px;
-
-.range-selector {
- overflow: hidden;
- display: flex;
- align-items: center;
- justify-content: space-between;
-
- padding: 0 var(--padding-sm) 0 var(--padding-base);
-
- border: 1px solid rgb(var(--border-color));
- border-radius: var(--border-radius-base);
-
- &-editor {
- cursor: text;
-
- overflow: hidden;
- display: inline-block;
-
- width: @width;
- height: @height;
- padding: @padding-top-bottom 0;
-
- font-size: var(--font-size-xs);
- line-height: @height;
- text-wrap: nowrap;
-
- border: 0;
- outline: 0;
-
- &::selection {
- color: rgb(var(--color-white));
- background-color: rgb(var(--primary-color));
- }
-
- &:empty::before {
- content: attr(data-placeholder);
- color: rgb(var(--grey-400));
- }
- }
-
- &-icon {
- cursor: pointer;
-
- display: flex;
- align-items: center;
- justify-content: center;
-
- width: @icon-size;
- height: @icon-size;
- padding: 0;
-
- font-size: var(--font-size-lg);
- color: rgb(var(--text-color));
-
- background-color: transparent;
- border: none;
- border-radius: var(--border-radius-base);
- outline: none;
-
- &:not([disabled]):hover {
- background-color: rgb(var(--grey-100));
- }
-
- &[disabled] {
- cursor: not-allowed;
- color: rgb(var(--grey-200));
- }
- }
-
- &-active {
- border-color: rgb(var(--primary-color));
-
- .range-selector-icon {
- color: rgb(var(--primary-color));
- }
- }
-}
diff --git a/packages/sheets-ui/src/controllers/editor-bridge.controller.ts b/packages/sheets-ui/src/controllers/editor-bridge.controller.ts
index a37c432e08..4f641fc1f7 100644
--- a/packages/sheets-ui/src/controllers/editor-bridge.controller.ts
+++ b/packages/sheets-ui/src/controllers/editor-bridge.controller.ts
@@ -26,7 +26,7 @@ import {
} from '@univerjs/sheets';
import { Inject, Injector, Quantity } from '@wendellhu/redi';
import { merge, takeUntil } from 'rxjs';
-import { IEditorService, ILayoutService } from '@univerjs/ui';
+import { IEditorService, ILayoutService, IRangeSelectorService } from '@univerjs/ui';
import { SetZoomRatioCommand } from '../commands/commands/set-zoom-ratio.command';
import { SetActivateCellEditOperation } from '../commands/operations/activate-cell-edit.operation';
@@ -47,7 +47,8 @@ export class EditorBridgeController extends RxDisposable {
@ILayoutService private readonly _layoutService: ILayoutService,
@IEditorService private readonly _editorService: IEditorService,
@IContextService private readonly _contextService: IContextService,
- @Inject(SelectionManagerService) private readonly _selectionManagerService: SelectionManagerService
+ @Inject(SelectionManagerService) private readonly _selectionManagerService: SelectionManagerService,
+ @IRangeSelectorService private readonly _rangeSelectorService: IRangeSelectorService
) {
super();
@@ -62,6 +63,7 @@ export class EditorBridgeController extends RxDisposable {
this._initSelectionChangeListener();
this._initialEventListener();
this._initialChangeEditorListener();
+ this._initialRangeSelector();
}
private _initSelectionChangeListener() {
@@ -184,7 +186,6 @@ export class EditorBridgeController extends RxDisposable {
if (this._editorBridgeService.isForceKeepVisible()) {
return;
}
- this._editorService.changeEditorFocus();
this._hideEditor();
}
@@ -214,6 +215,22 @@ export class EditorBridgeController extends RxDisposable {
}, 0);
}
+ private _initialRangeSelector() {
+ this.disposeWithMe(
+ this._selectionManagerService.selectionMoving$.subscribe((selectionWithStyle: Nullable<ISelectionWithStyle[]>) => {
+ if (!selectionWithStyle) {
+ return;
+ }
+
+ const ranges = selectionWithStyle.map((value: ISelectionWithStyle) => {
+ return value.range;
+ });
+
+ this._rangeSelectorService.selectionChange(ranges);
+ })
+ );
+ }
+
private _getSheetObject() {
return getSheetObject(this._currentUniverService, this._renderManagerService);
}
diff --git a/packages/sheets-ui/src/controllers/editor/start-edit.controller.ts b/packages/sheets-ui/src/controllers/editor/start-edit.controller.ts
index fb51748dd3..245003991c 100644
--- a/packages/sheets-ui/src/controllers/editor/start-edit.controller.ts
+++ b/packages/sheets-ui/src/controllers/editor/start-edit.controller.ts
@@ -461,6 +461,7 @@ export class StartEditController extends Disposable {
this._editorVisiblePrevious = visible;
if (visible === false) {
+ this._setOpenForCurrent(null, null);
return;
}
@@ -478,6 +479,7 @@ export class StartEditController extends Disposable {
scaleY,
editorUnitId,
unitId,
+ sheetId,
isInArrayFormulaRange = false,
} = editCellState;
@@ -487,6 +489,8 @@ export class StartEditController extends Disposable {
return;
}
+ this._setOpenForCurrent(unitId, sheetId);
+
const { document, scene } = editorObject;
this._contextService.setContextValue(EDITOR_ACTIVATED, true);
@@ -667,6 +671,18 @@ export class StartEditController extends Disposable {
);
}
+ private _setOpenForCurrent(unitId: Nullable<string>, sheetId: Nullable<string>) {
+ const sheetEditors = this._editorService.getAllEditor();
+ for (const [id, sheetEditor] of sheetEditors) {
+ if (!sheetEditor.isSheetEditor()) {
+ continue;
+ }
+
+ sheetEditor.setOpenForSheetUnitId(unitId);
+ sheetEditor.setOpenForSheetSubUnitId(sheetId);
+ }
+ }
+
private _getEditorObject() {
return getEditorObject(this._editorBridgeService.getCurrentEditorId(), this._renderManagerService);
}
diff --git a/packages/sheets-ui/src/index.ts b/packages/sheets-ui/src/index.ts
index 0bc7fa1f6a..c74e0ea20a 100644
--- a/packages/sheets-ui/src/index.ts
+++ b/packages/sheets-ui/src/index.ts
@@ -24,7 +24,6 @@ export { SetCellEditVisibleArrowOperation } from './commands/operations/cell-edi
export { SetScrollOperation } from './commands/operations/scroll.operation';
export { SetZoomRatioOperation } from './commands/operations/set-zoom-ratio.operation';
export { VIEWPORT_KEY } from './common/keys';
-export { RangeSelector } from './components/range-selector/RangeSelector';
export { AutoFillController } from './controllers/auto-fill.controller';
export { PASTE_SPECIAL_MENU_ID } from './controllers/menu/menu';
export { whenFormulaEditorActivated } from './controllers/shortcuts/utils';
diff --git a/packages/ui/src/components/editor/TextEditor.tsx b/packages/ui/src/components/editor/TextEditor.tsx
index 803da1f4eb..c75fa54317 100644
--- a/packages/ui/src/components/editor/TextEditor.tsx
+++ b/packages/ui/src/components/editor/TextEditor.tsx
@@ -36,32 +36,52 @@ const excludeProps = new Set([
'onlyInputRange',
'value',
'onlyInputContent',
+ 'openForSheetUnitId',
+ 'openForSheetSubUnitId',
+ 'onChange',
+ 'onFocus',
+ 'onValid',
]);
export interface ITextEditorProps {
- id: string;
- className?: string;
-
- snapshot?: IDocumentData;
- resizeCallBack?: (editor: Nullable<HTMLDivElement>) => void;
- cancelDefaultResizeListener?: boolean;
- isSheetEditor?: boolean;
- canvasStyle?: IEditorCanvasStyle;
-
- value?: string;
-
- isSingle?: boolean;
- isReadonly?: boolean;
- onlyInputFormula?: boolean;
- onlyInputRange?: boolean;
- onlyInputContent?: boolean;
+ id: string; // unitId
+ className?: string; // Parent class name.
+
+ snapshot?: IDocumentData; // The default initialization snapshot for the editor can be simply replaced with the value attribute, for cellEditor and formulaBar
+
+ resizeCallBack?: (editor: Nullable<HTMLDivElement>) => void; // Container scale callback.
+
+ cancelDefaultResizeListener?: boolean; // Disable the default container scaling listener, for cellEditor and formulaBar
+
+ isSheetEditor?: boolean; // Specify whether the editor is bound to a sheet. Currently, there are cellEditor and formulaBar.
+
+ canvasStyle?: IEditorCanvasStyle; // Setting the style of the editor is similar to setting the drawing style of a canvas, and therefore, it should be distinguished from the CSS 'style'. At present, it only supports the 'fontsize' attribute.
+
+ value?: string; // default values.
+
+ isSingle?: boolean; // Set whether the editor allows multiline input, default is true, equivalent to input; false is equivalent to textarea.
+ isReadonly?: boolean; // Set the editor to read-only state.
+
+ onlyInputFormula?: boolean; // Only input formula string
+ onlyInputRange?: boolean; // Only input ref range
+ onlyInputContent?: boolean; // Only plain content can be entered, turning off formula and range input highlighting.
+
+ 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.
+
+ onChange?: (value: Nullable<string>) => void; // Callback for changes in the selector value.
+
+ onFocus?: (state: boolean) => void; // Callback for editor focus.
+
+ onValid?: (state: boolean) => void; // Editor input value validation, currently effective only under onlyRange and onlyFormula conditions.
+
}
/**
* The component to render toolbar item label and menu item label.
* @param props
*/
-export function TextEditor(props: ITextEditorProps & MyComponentProps): JSX.Element | null {
+export function TextEditor(props: ITextEditorProps & Omit<MyComponentProps, 'onChange' | 'onFocus'>): JSX.Element | null {
const {
id,
snapshot,
@@ -75,6 +95,15 @@ export function TextEditor(props: ITextEditorProps & MyComponentProps): JSX.Elem
onlyInputFormula = false,
onlyInputRange = false,
onlyInputContent = false,
+
+ openForSheetUnitId,
+ openForSheetSubUnitId,
+
+ onChange,
+
+ onFocus,
+
+ onValid,
} = props;
const editorService = useDependency(IEditorService);
@@ -107,7 +136,7 @@ export function TextEditor(props: ITextEditorProps & MyComponentProps): JSX.Elem
resizeObserver.observe(editor);
- editorService.register({
+ const registerSubscription = editorService.register({
editorUnitId: id,
initialSnapshot: snapshot,
cancelDefaultResizeListener,
@@ -118,15 +147,18 @@ export function TextEditor(props: ITextEditorProps & MyComponentProps): JSX.Elem
onlyInputFormula,
onlyInputRange,
onlyInputContent,
+ openForSheetUnitId,
+ openForSheetSubUnitId,
},
editor);
- const focusStyleSubscription = editorService.focusStyle$.subscribe((unitId: string) => {
+ const focusStyleSubscription = editorService.focusStyle$.subscribe((unitId: Nullable<string>) => {
+ let state = false;
if (unitId === id) {
- setActive(true);
- } else {
- setActive(false);
+ state = true;
}
+ setActive(state);
+ onFocus && onFocus(state);
});
const valueChangeSubscription = editorService.valueChange$.subscribe((editor) => {
@@ -151,14 +183,18 @@ export function TextEditor(props: ITextEditorProps & MyComponentProps): JSX.Elem
} else {
setValidationContent(localeService.t('textEditor.rangeError'));
}
- }, 100)();
+
+ onValid && onValid(isLegality);
+
+ onChange && onChange(editorService.getValue(id));
+ }, 10)();
});
// Clean up on unmount
return () => {
resizeObserver.unobserve(editor);
- editorService.unRegister(id);
+ registerSubscription.dispose();
focusStyleSubscription?.unsubscribe();
diff --git a/packages/ui/src/components/range-selector/RangeSelector.tsx b/packages/ui/src/components/range-selector/RangeSelector.tsx
new file mode 100644
index 0000000000..41ad14e602
--- /dev/null
+++ b/packages/ui/src/components/range-selector/RangeSelector.tsx
@@ -0,0 +1,250 @@
+/**
+ * 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 { IRange, IUnitRange, Nullable } from '@univerjs/core';
+import { IUniverInstanceService, LocaleService } from '@univerjs/core';
+import { Button, Dialog, Input, Tooltip } from '@univerjs/design';
+import { CloseSingle, DeleteSingle, SelectRangeSingle } from '@univerjs/icons';
+import { useDependency } from '@wendellhu/redi/react-bindings';
+import React, { useEffect, useRef, useState } from 'react';
+
+import { deserializeRangeWithSheet, isReferenceString, serializeRange } from '@univerjs/engine-formula';
+import { TextEditor } from '../editor/TextEditor';
+import { IEditorService } from '../../services/editor/editor.service';
+import { IRangeSelectorService } from '../../services/range-selector/range-selector.service';
+import styles from './index.module.less';
+
+export interface IRangeSelectorProps {
+ id: string;
+ value?: string; // default values.
+ onChange?: (ranges: IUnitRange[]) => void; // Callback for changes in the selector value.
+
+ 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 [rangeDataList, setRangeDataList] = useState<string[]>(['']);
+
+ const addNewItem = (newValue: string) => {
+ setRangeDataList((prevRangeDataList) => [...prevRangeDataList, newValue]);
+ };
+
+ const removeItem = (indexToRemove: number) => {
+ setRangeDataList((prevRangeDataList) =>
+ prevRangeDataList.filter((_, index) => index !== indexToRemove)
+ );
+ };
+
+ const changeItem = (indexToChange: number, newValue: string) => {
+ setRangeDataList((prevRangeDataList) =>
+ prevRangeDataList.map((item, index) =>
+ index === indexToChange ? newValue : item
+ )
+ );
+ };
+
+ const changeLastItem = (newValue: string) => {
+ setRangeDataList((prevRangeDataList) => {
+ const newList = [...prevRangeDataList];
+ if (newList.length > 0) {
+ newList[newList.length - 1] = newValue;
+ }
+ return newList;
+ });
+ };
+
+ const editorService = useDependency(IEditorService);
+
+ const rangeSelectorService = useDependency(IRangeSelectorService);
+
+ const currentUniverService = useDependency(IUniverInstanceService);
+
+ const [selectorVisible, setSelectorVisible] = useState(false);
+
+ const localeService = useDependency(LocaleService);
+
+ const [active, setActive] = useState(false);
+
+ const [valid, setValid] = useState(true);
+
+ const [rangeValue, setRangeValue] = useState(value);
+
+ const selectorRef = useRef<HTMLDivElement>(null);
+
+ useEffect(() => {
+ const selector = selectorRef.current;
+
+ if (!selector) {
+ return;
+ }
+
+ const resizeObserver = new ResizeObserver(() => {
+ editorService.resize(id);
+ });
+ resizeObserver.observe(selector);
+
+ let prevRangesCount = 1;
+ const valueChangeSubscription = rangeSelectorService.selectionChange$.subscribe((ranges: IRange[]) => {
+ if (ranges.length === 0) {
+ prevRangesCount = 0;
+ return;
+ }
+
+ const addItemCount = ranges.length - prevRangesCount;
+
+ prevRangesCount = ranges.length;
+
+ if (addItemCount < 0) {
+ return;
+ }
+
+ const lastRange = ranges[ranges.length - 1];
+ if (addItemCount >= 1) {
+ addNewItem(serializeRange(lastRange));
+ } else {
+ changeLastItem(serializeRange(lastRange));
+ }
+ });
+
+ // Clean up on unmount
+ return () => {
+ valueChangeSubscription.unsubscribe();
+ resizeObserver.unobserve(selector);
+ };
+ }, []);
+
+ function handleCloseModal() {
+ setSelectorVisible(false);
+ rangeSelectorService.setCurrentSelectorId(null);
+ }
+
+ function handleOpenModal() {
+ if (valid) {
+ setRangeDataList(rangeValue.split(','));
+ } else {
+ setRangeDataList(['']);
+ }
+
+ rangeSelectorService.setCurrentSelectorId(id);
+
+ setSelectorVisible(true);
+ }
+
+ function onFocus(state: boolean) {
+ setActive(state);
+ }
+
+ function onValid(state: boolean) {
+ setValid(state);
+ }
+
+ function handleConform() {
+ let result = '';
+ const list = rangeDataList.filter((rangeRef) => {
+ return isReferenceString(rangeRef.trim());
+ });
+ if (list.length === 1) {
+ const rangeRef = list[0];
+ if (isReferenceString(rangeRef.trim())) {
+ result = rangeRef.trim();
+ }
+ } else {
+ result = list.join(',');
+ }
+
+ editorService.setValue(result, id);
+
+ handleCloseModal();
+ }
+
+ function handleAddRange() {
+ addNewItem('');
+ }
+
+ function getSheetIdByName(name: string) {
+ return currentUniverService.getCurrentUniverSheetInstance().getSheetBySheetName(name) || '';
+ }
+
+ function handleTextValueChange(value: Nullable<string>) {
+ setRangeValue(value || '');
+
+ const ranges = rangeValue.split(',').map((ref) => {
+ const unitRange = deserializeRangeWithSheet(ref);
+ return {
+ unitId: unitRange.unitId,
+ sheetId: getSheetIdByName(unitRange.sheetName),
+ range: unitRange.range,
+ } as IUnitRange;
+ });
+ onChange && onChange(ranges);
+ }
+
+ let sClassName = styles.rangeSelector;
+ if (!valid) {
+ sClassName = `${styles.rangeSelector} ${styles.rangeSelectorError}`;
+ } else if (active) {
+ sClassName = `${styles.rangeSelector} ${styles.rangeSelectorActive}`;
+ }
+
+ 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} />
+ <Tooltip title={localeService.t('rangeSelector.buttonTooltip')} placement="bottom">
+ <button className={styles.rangeSelectorIcon} onClick={handleOpenModal}>
+ <SelectRangeSingle />
+ </button>
+ </Tooltip>
+ </div>
+
+ <Dialog
+ width="300px"
+ visible={selectorVisible}
+ title={localeService.t('rangeSelector.title')}
+ draggable
+ closeIcon={<CloseSingle />}
+ footer={(
+ <footer>
+ <Button size="small" onClick={handleCloseModal}>{localeService.t('rangeSelector.cancel')}</Button>
+ <Button style={{ marginLeft: 10 }} size="small" onClick={handleConform} type="primary">{localeService.t('rangeSelector.confirm')}</Button>
+ </footer>
+ )}
+ onClose={handleCloseModal}
+ >
+ <div className={styles.rangeSelectorModal}>
+ {rangeDataList.map((item, index) => (
+ <div key={index} className={styles.rangeSelectorModalContainer}>
+ <div style={{ display: rangeDataList.length === 1 ? '220px' : '200px' }} className={styles.rangeSelectorModalContainerInput}>
+ <Input size="small" value={item} onChange={(value) => changeItem(index, value)} />
+ </div>
+ <div style={{ display: rangeDataList.length === 1 ? 'none' : 'inline-block' }} className={styles.rangeSelectorModalContainerButton}>
+ <DeleteSingle onClick={() => removeItem(index)} />
+ </div>
+ </div>
+ ))}
+
+ <div className={styles.rangeSelectorModalAdd}>
+ <Button size="small" onClick={handleAddRange}>{localeService.t('rangeSelector.addAnotherRange')}</Button>
+ </div>
+ </div>
+
+ </Dialog>
+ </>
+ );
+}
diff --git a/packages/ui/src/components/range-selector/index.module.less b/packages/ui/src/components/range-selector/index.module.less
new file mode 100644
index 0000000000..493b7a62e2
--- /dev/null
+++ b/packages/ui/src/components/range-selector/index.module.less
@@ -0,0 +1,120 @@
+@padding-top-bottom: 6px;
+@height: 32px;
+@width: 218px;
+@icon-size: 24px;
+
+.range-selector {
+ overflow: hidden;
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+
+ color: rgb(var(--grey-600));
+
+ // padding: 0 var(--padding-sm) 0 var(--padding-base);
+
+ border: 1px solid rgb(var(--border-color));
+ border-radius: var(--border-radius-base);
+
+ width: @width;
+ height: @height;
+
+ &-editor {
+ position: relative;
+ user-select: none;
+ width: 100%;
+ height: 100%;
+ border: 0;
+ outline: 0;
+ }
+
+ &-icon {
+ cursor: pointer;
+
+ display: flex;
+ align-items: center;
+ justify-content: center;
+
+ width: @icon-size;
+ height: @icon-size;
+ padding: 0;
+
+ margin-right: 4px;
+
+ font-size: var(--font-size-lg);
+ color: rgb(var(--text-color));
+
+ background-color: transparent;
+ border: none;
+ border-radius: var(--border-radius-base);
+ outline: none;
+
+ &:not([disabled]):hover {
+ background-color: rgb(var(--grey-100));
+ }
+
+ &[disabled] {
+ cursor: not-allowed;
+ color: rgb(var(--grey-200));
+ }
+ }
+
+ &-active {
+ border-color: rgb(var(--primary-color));
+
+ .range-selector-icon {
+ color: rgb(var(--primary-color));
+ }
+ }
+
+ &-error {
+ border-color: rgb(var(--error-color));
+
+ .range-selector-icon {
+ color: rgb(var(--error-color));
+ }
+ }
+}
+
+.range-selector-modal {
+ position: relative;
+
+ max-height: 500px;
+
+ width: 260px;
+
+ overflow: hidden;
+
+ overflow-y: auto;
+
+ &-container {
+ display: flex;
+ flex-direction: row;
+ // justify-content: center;
+ align-items: center;
+ width: 230px;
+ margin-bottom: 10px;
+
+ &-input {
+ display: inline-block;
+ width: 200px;
+ }
+
+ &-button {
+ display: inline-block;
+ text-align: center;
+ width: 30px;
+
+ &:hover {
+ cursor: pointer;
+ color: rgb(var(--primary-color));
+ }
+ }
+ }
+
+ &--add {
+ position: relative;
+ width: 300px;
+ margin-top: 5px;
+ }
+}
diff --git a/packages/ui/src/index.ts b/packages/ui/src/index.ts
index 28fc13e9e3..50e758614c 100644
--- a/packages/ui/src/index.ts
+++ b/packages/ui/src/index.ts
@@ -82,3 +82,7 @@ export { IEditorService, EditorService } from './services/editor/editor.service'
export { TextEditor } from './components/editor/TextEditor';
export { SetEditorResizeOperation } from './commands/operations/editor/set-editor-resize.operation';
+
+export { RangeSelector } from './components/range-selector/RangeSelector';
+
+export { IRangeSelectorService } from './services/range-selector/range-selector.service';
diff --git a/packages/ui/src/locale/en-US.ts b/packages/ui/src/locale/en-US.ts
index 46d28dfd68..6d788de66b 100644
--- a/packages/ui/src/locale/en-US.ts
+++ b/packages/ui/src/locale/en-US.ts
@@ -65,6 +65,13 @@ const locale: typeof zhCN = {
formulaError: 'Please enter a valid formula, such as =SUM(A1)',
rangeError: 'Please enter a valid range, such as A1:B10',
},
+ rangeSelector: {
+ title: 'Select a data range',
+ addAnotherRange: 'Add another range',
+ buttonTooltip: 'Select data range',
+ confirm: 'Confirm',
+ cancel: 'Cancel',
+ },
};
export default locale;
diff --git a/packages/ui/src/locale/zh-CN.ts b/packages/ui/src/locale/zh-CN.ts
index 44314d11fc..4de4a77506 100644
--- a/packages/ui/src/locale/zh-CN.ts
+++ b/packages/ui/src/locale/zh-CN.ts
@@ -63,6 +63,13 @@ const locale = {
formulaError: '请输入合法的公式,例如=SUM(A1)',
rangeError: '请输入合法的范围,例如 A1:B10',
},
+ rangeSelector: {
+ title: '选择一个数据范围',
+ addAnotherRange: '添加新范围',
+ buttonTooltip: '选择数据范围',
+ confirm: '确认',
+ cancel: '取消',
+ },
};
export default locale;
diff --git a/packages/ui/src/services/editor/editor.service.ts b/packages/ui/src/services/editor/editor.service.ts
index 7e71dea8bd..6b4562dc91 100644
--- a/packages/ui/src/services/editor/editor.service.ts
+++ b/packages/ui/src/services/editor/editor.service.ts
@@ -46,6 +46,9 @@ export interface IEditorConfigParam {
onlyInputRange: boolean;
onlyInputContent: boolean;
+ openForSheetUnitId: Nullable<string>;
+ openForSheetSubUnitId: Nullable<string>;
+
}
export interface IEditorSetParam extends IEditorConfigParam, IEditorStateParam {
@@ -69,8 +72,13 @@ class Editor {
private _valueLegality = true;
- constructor(private _param: IEditorSetParam) {
+ private _openForSheetUnitId: Nullable<string>;
+
+ private _openForSheetSubUnitId: Nullable<string>;
+ constructor(private _param: IEditorSetParam) {
+ this._openForSheetUnitId = this._param.openForSheetUnitId;
+ this._openForSheetSubUnitId = this._param.openForSheetSubUnitId;
}
get documentDataModel() {
@@ -89,6 +97,22 @@ class Editor {
return this._param.render;
}
+ setOpenForSheetUnitId(unitId: Nullable<string>) {
+ this._openForSheetUnitId = unitId;
+ }
+
+ getOpenForSheetUnitId() {
+ return this._openForSheetUnitId;
+ }
+
+ setOpenForSheetSubUnitId(subUnitId: Nullable<string>) {
+ this._openForSheetSubUnitId = subUnitId;
+ }
+
+ getOpenForSheetSubUnitId() {
+ return this._openForSheetSubUnitId;
+ }
+
isValueLegality() {
return this._valueLegality === true;
}
@@ -138,7 +162,8 @@ class Editor {
}
getValue() {
- return this._param.documentDataModel.getBody()?.dataStream || '';
+ const value = this._param.documentDataModel.getBody()?.dataStream || '';
+ return value.replace(/\r\n/g, '').replace(/\n/g, '').replace(/\n/g, '');
}
getBody() {
@@ -208,8 +233,6 @@ export interface IEditorService {
register(config: IEditorConfigParam, container: HTMLDivElement): IDisposable;
- unRegister(editorUnitId: string): void;
-
isVisible(id: string): Nullable<boolean>;
inputFormula$: Observable<IEditorInputFormulaParam>;
@@ -242,9 +265,9 @@ export interface IEditorService {
isSheetEditor(editorUnitId: string): boolean;
- changeEditorFocus$: Observable<unknown>;
+ closeRangePrompt$: Observable<unknown>;
- changeEditorFocus(): void;
+ closeRangePrompt(): void;
blur$: Observable<unknown>;
@@ -264,13 +287,23 @@ export interface IEditorService {
getFirstEditor(): Editor;
- focusStyle$: Observable<string>;
+ focusStyle$: Observable<Nullable<string>>;
- focusStyle(editorUnitId: string): void;
+ focusStyle(editorUnitId: Nullable<string>): void;
refreshValueChange(editorId: string): void;
checkValueLegality(editorId: string): boolean;
+
+ getValue(id: string): Nullable<string>;
+
+ getRichValue(id: string): Nullable<IDocumentBody>;
+
+ changeSpreadsheetFocusState(state: boolean): void;
+
+ getSpreadsheetFocusState(): boolean;
+
+ selectionChangingState(): boolean;
}
export class EditorService extends Disposable implements IEditorService, IDisposable {
@@ -289,8 +322,8 @@ export class EditorService extends Disposable implements IEditorService, IDispos
private readonly _resize$ = new Subject<string>();
readonly resize$ = this._resize$.asObservable();
- private readonly _changeEditorFocus$ = new Subject<unknown>();
- readonly changeEditorFocus$ = this._changeEditorFocus$.asObservable();
+ private readonly _closeRangePrompt$ = new Subject<unknown>();
+ readonly closeRangePrompt$ = this._closeRangePrompt$.asObservable();
private readonly _blur$ = new Subject();
readonly blur$ = this._blur$.asObservable();
@@ -304,10 +337,12 @@ export class EditorService extends Disposable implements IEditorService, IDispos
private readonly _valueChange$ = new Subject<Readonly<Editor>>();
readonly valueChange$ = this._valueChange$.asObservable();
- private readonly _focusStyle$ = new Subject<string>();
+ private readonly _focusStyle$ = new Subject<Nullable<string>>();
readonly focusStyle$ = this._focusStyle$.asObservable();
+ private _spreadsheetFocusState: boolean = false;
+
constructor(
@IUniverInstanceService private readonly _currentUniverService: IUniverInstanceService,
@IRenderManagerService private readonly _renderManagerService: IRenderManagerService,
@@ -326,28 +361,32 @@ export class EditorService extends Disposable implements IEditorService, IDispos
return !!(editor && editor.isSheetEditor());
}
- changeEditorFocus() {
+ closeRangePrompt() {
const documentDataModel = this._currentUniverService.getCurrentUniverDocInstance();
const editorUnitId = documentDataModel.getUnitId();
if (!this.isEditor(editorUnitId) || this.isSheetEditor(editorUnitId)) {
return;
}
- // const editor = this._editors.get(editorUnitId);
- this._changeEditorFocus$.next(null);
+
+ this.changeSpreadsheetFocusState(false);
this.blur();
}
+ changeSpreadsheetFocusState(state: boolean) {
+ this._spreadsheetFocusState = state;
+ }
+
+ getSpreadsheetFocusState() {
+ return this._spreadsheetFocusState;
+ }
+
focusStyle(editorUnitId: string) {
const editor = this.getEditor(editorUnitId);
if (!editor) {
return false;
}
- this.getAllEditor().forEach((editor) => {
- editor.setFocus(false);
- });
-
editor.setFocus(true);
this._contextService.setContextValue(FOCUSING_UNIVER_EDITOR_SINGLE_MODE, editor.isSingle());
@@ -355,7 +394,23 @@ export class EditorService extends Disposable implements IEditorService, IDispos
this._focusStyle$.next(editorUnitId);
}
+ selectionChangingState() {
+ const documentDataModel = this._currentUniverService.getCurrentUniverDocInstance();
+ const editorUnitId = documentDataModel.getUnitId();
+ const editor = this.getEditor(editorUnitId);
+
+ return !this.getSpreadsheetFocusState() || !editor || editor.isSheetEditor();
+ }
+
blur() {
+ if (!this._spreadsheetFocusState) {
+ this._closeRangePrompt$.next(null);
+ }
+
+ this.getAllEditor().forEach((editor) => {
+ editor.setFocus(false);
+ });
+ this._focusStyle$.next();
this._blur$.next(null);
}
@@ -402,12 +457,16 @@ export class EditorService extends Disposable implements IEditorService, IDispos
}
this._refreshValueChange(editorUnitId);
+
+ this.resize(editorUnitId);
}
- getValue(id?: string) {
+ getValue(id: string) {
const editor = this.getEditor(id);
-
- return editor?.getValue();
+ if (editor == null) {
+ return;
+ }
+ return editor.getValue();
}
setRichValue(body: IDocumentBody, editorUnitId?: string) {
@@ -420,10 +479,12 @@ export class EditorService extends Disposable implements IEditorService, IDispos
this._refreshValueChange(editorUnitId);
}
- getRichValue(id?: string) {
+ getRichValue(id: string) {
const editor = this.getEditor(id);
-
- return editor?.getBody();
+ if (editor == null) {
+ return;
+ }
+ return editor.getBody();
}
override dispose(): void {
@@ -514,11 +575,11 @@ export class EditorService extends Disposable implements IEditorService, IDispos
}
return toDisposable(() => {
- this.unRegister(editorUnitId);
+ this._unRegister(editorUnitId);
});
}
- unRegister(editorUnitId: string) {
+ private _unRegister(editorUnitId: string) {
const editor = this._editors.get(editorUnitId);
if (editor == null) {
diff --git a/packages/ui/src/services/range-selector/range-selector.service.ts b/packages/ui/src/services/range-selector/range-selector.service.ts
new file mode 100644
index 0000000000..b9e957102b
--- /dev/null
+++ b/packages/ui/src/services/range-selector/range-selector.service.ts
@@ -0,0 +1,59 @@
+/**
+ * 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 { IRange, Nullable } from '@univerjs/core';
+import { Disposable } from '@univerjs/core';
+import type { IDisposable } from '@wendellhu/redi';
+import { createIdentifier } from '@wendellhu/redi';
+import type { Observable } from 'rxjs';
+import { Subject } from 'rxjs';
+
+export interface IRangeSelectorService {
+ selectionChange$: Observable<IRange[]>;
+
+ setCurrentSelectorId(id: Nullable<string>): void;
+
+ getCurrentSelectorId(): Nullable<string>;
+
+ selectionChange(ranges: IRange[]): void;
+}
+
+export class RangeSelectorService extends Disposable implements IRangeSelectorService, IDisposable {
+ private _currentSelectorId: Nullable<string>;
+
+ private readonly _selectionChange$ = new Subject<IRange[]>();
+
+ readonly selectionChange$ = this._selectionChange$.asObservable();
+
+ setCurrentSelectorId(id: Nullable<string>) {
+ this._currentSelectorId = id;
+ }
+
+ getCurrentSelectorId(): Nullable<string> {
+ return this._currentSelectorId;
+ }
+
+ selectionChange(range: IRange[]) {
+ if (!this._currentSelectorId) {
+ return;
+ }
+ this._selectionChange$.next(range);
+ }
+}
+
+export const IRangeSelectorService = createIdentifier<IRangeSelectorService>(
+ 'univer.range-selector.service'
+);
diff --git a/packages/ui/src/ui-plugin.ts b/packages/ui/src/ui-plugin.ts
index c9bdf8124f..62ea06ed49 100644
--- a/packages/ui/src/ui-plugin.ts
+++ b/packages/ui/src/ui-plugin.ts
@@ -51,6 +51,7 @@ import { ISidebarService } from './services/sidebar/sidebar.service';
import { DesktopZenZoneService } from './services/zen-zone/desktop-zen-zone.service';
import { IZenZoneService } from './services/zen-zone/zen-zone.service';
import { EditorService, IEditorService } from './services/editor/editor.service';
+import { IRangeSelectorService, RangeSelectorService } from './services/range-selector/range-selector.service';
const PLUGIN_NAME = 'ui';
@@ -112,6 +113,7 @@ export class UniverUIPlugin extends Plugin {
[ILocalStorageService, { useClass: DesktopLocalStorageService, lazy: true }],
[IBeforeCloseService, { useClass: DesktopBeforeCloseService }],
[IEditorService, { useClass: EditorService }],
+ [IRangeSelectorService, { useClass: RangeSelectorService }],
// controllers
[IUIController, { useClass: DesktopUIController }],