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: inline format in sheet range (#375)

Ran Luo459c542bc443
diff --git a/packages/base-docs/src/Controller/inline-format.controller.ts b/packages/base-docs/src/Controller/inline-format.controller.ts
index 9b39b98f48..8e86942413 100644
--- a/packages/base-docs/src/Controller/inline-format.controller.ts
+++ b/packages/base-docs/src/Controller/inline-format.controller.ts
@@ -1,21 +1,24 @@
-import { ITextSelectionRangeWithStyle, ITextSelectionRenderManager } from '@univerjs/base-render';
+import { ITextSelectionRenderManager } from '@univerjs/base-render';
import {
- BooleanNumber,
Disposable,
- getTextIndexByCursor,
ICommandInfo,
ICommandService,
- IDocumentBody,
- ITextRun,
IUniverInstanceService,
LifecycleStages,
OnLifecycle,
} from '@univerjs/core';
import { Inject } from '@wendellhu/redi';
-import MemoryCursor from '../Basics/memoryCursor';
-import { SetInlineFormatBoldCommand, SetInlineFormatCommand } from '../commands/commands/inline-format.command';
-import { IRichTextEditingMutationParams, RichTextEditingMutation } from '../commands/mutations/core-editing.mutation';
+import {
+ SetInlineFormatBoldCommand,
+ SetInlineFormatCommand,
+ SetInlineFormatFontFamilyCommand,
+ SetInlineFormatFontSizeCommand,
+ SetInlineFormatItalicCommand,
+ SetInlineFormatStrikethroughCommand,
+ SetInlineFormatTextColorCommand,
+ SetInlineFormatUnderlineCommand,
+} from '../commands/commands/inline-format.command';
import { TextSelectionManagerService } from '../services/text-selection-manager.service';
/**
@@ -37,7 +40,15 @@ export class InlineFormatController extends Disposable {
}
private _commandExecutedListener() {
- const updateCommandList = [SetInlineFormatBoldCommand.id];
+ const updateCommandList = [
+ SetInlineFormatBoldCommand.id,
+ SetInlineFormatItalicCommand.id,
+ SetInlineFormatUnderlineCommand.id,
+ SetInlineFormatStrikethroughCommand.id,
+ SetInlineFormatFontSizeCommand.id,
+ SetInlineFormatFontFamilyCommand.id,
+ SetInlineFormatTextColorCommand.id,
+ ];
this.disposeWithMe(
this._commandService.onCommandExecuted((command: ICommandInfo) => {
@@ -52,125 +63,28 @@ export class InlineFormatController extends Disposable {
private handleInlineFormat(command: ICommandInfo) {
const segmentId = this._textSelectionRenderManager.getActiveRange()?.segmentId;
- const selections = this._textSelectionManagerService.getSelections();
- if (segmentId == null || !Array.isArray(selections) || selections.length === 0) {
+ if (segmentId == null) {
return;
}
- const docsModel = this._currentUniverService.getCurrentUniverDocInstance();
- const unitId = docsModel.getUnitId();
-
- let formatValue;
-
- switch (command.id) {
- case SetInlineFormatBoldCommand.id: {
- formatValue = getFormatValueInSelection(docsModel.body!.textRuns!, 'bl', selections);
- break;
- }
-
- default: {
- throw new Error(`Unknown command: ${command.id} in handleInlineFormat`);
- }
- }
-
- const doMutation: ICommandInfo<IRichTextEditingMutationParams> = {
- id: RichTextEditingMutation.id,
- params: {
- unitId,
- mutations: [],
- },
- };
-
- const memoryCursor = new MemoryCursor();
-
- memoryCursor.reset();
-
- for (const selection of selections) {
- const { cursorStart, cursorEnd, isStartBack, isEndBack } = selection;
- const textStart = getTextIndexByCursor(cursorStart, isStartBack);
- const textEnd = getTextIndexByCursor(cursorEnd, isEndBack);
-
- const body: IDocumentBody = {
- dataStream: '',
- textRuns: [
- {
- st: 0,
- ed: textEnd - textStart,
- ts: {
- bl: formatValue,
- },
- },
- ],
- };
-
- const len = textStart + 1 - memoryCursor.cursor;
- if (len !== 0) {
- doMutation.params!.mutations.push({
- t: 'r',
- len,
- segmentId,
- });
- }
-
- doMutation.params!.mutations.push({
- t: 'r',
- body,
- len: textEnd - textStart,
- segmentId,
- });
-
- memoryCursor.reset();
- memoryCursor.moveCursor(textEnd + 1);
- }
-
this._commandService.executeCommand(SetInlineFormatCommand.id, {
- unitId,
- doMutation,
+ segmentId,
+ preCommandId: command.id,
+ ...(command.params ?? {}),
});
- const REFRESH_SELECTION_COMMAND_LIST = [SetInlineFormatBoldCommand.id];
+ const REFRESH_SELECTION_COMMAND_LIST = [
+ SetInlineFormatBoldCommand.id,
+ SetInlineFormatFontSizeCommand.id,
+ SetInlineFormatFontFamilyCommand.id,
+ ];
+ /**
+ * refresh selection.
+ */
if (REFRESH_SELECTION_COMMAND_LIST.includes(command.id)) {
this._textSelectionManagerService.refreshSelection();
}
}
}
-
-/**
- * When clicking on a Bold menu item, you should un-bold if there is bold in the selections,
- * or bold if there is no bold text. This method is used to get the style value calculated
- * from textRuns in the selection
- */
-function getFormatValueInSelection(
- textRuns: ITextRun[],
- key: 'bl',
- selections: ITextSelectionRangeWithStyle[]
-): BooleanNumber {
- let ti = 0;
- let si = 0;
-
- while (ti !== textRuns.length && si !== selections.length) {
- const { cursorStart, cursorEnd, isStartBack, isEndBack } = selections[si];
-
- const textStart = getTextIndexByCursor(cursorStart, isStartBack) + 1;
- const textEnd = getTextIndexByCursor(cursorEnd, isEndBack) + 1;
-
- // TODO: @jocs handle sid in textRun
- const { st, ed, ts } = textRuns[ti];
-
- if (textEnd <= st) {
- si++;
- } else if (ed <= textStart) {
- ti++;
- } else {
- if (ts?.[key] === BooleanNumber.TRUE) {
- return BooleanNumber.FALSE;
- }
-
- ti++;
- }
- }
-
- return BooleanNumber.TRUE;
-}
diff --git a/packages/base-docs/src/DocPlugin.ts b/packages/base-docs/src/DocPlugin.ts
index 62796b6f3c..5742c4102e 100644
--- a/packages/base-docs/src/DocPlugin.ts
+++ b/packages/base-docs/src/DocPlugin.ts
@@ -21,7 +21,16 @@ import {
InsertCommand,
UpdateCommand,
} from './commands/commands/core-editing.command';
-import { SetInlineFormatBoldCommand, SetInlineFormatCommand } from './commands/commands/inline-format.command';
+import {
+ SetInlineFormatBoldCommand,
+ SetInlineFormatCommand,
+ SetInlineFormatFontFamilyCommand,
+ SetInlineFormatFontSizeCommand,
+ SetInlineFormatItalicCommand,
+ SetInlineFormatStrikethroughCommand,
+ SetInlineFormatTextColorCommand,
+ SetInlineFormatUnderlineCommand,
+} from './commands/commands/inline-format.command';
import { SetDocZoomRatioCommand } from './commands/commands/set-doc-zoom-ratio.command';
import { RichTextEditingMutation } from './commands/mutations/core-editing.mutation';
import { MoveCursorOperation } from './commands/operations/cursor.operation';
@@ -99,6 +108,12 @@ export class DocPlugin extends Plugin {
MoveCursorOperation,
DeleteLeftCommand,
SetInlineFormatBoldCommand,
+ SetInlineFormatItalicCommand,
+ SetInlineFormatUnderlineCommand,
+ SetInlineFormatStrikethroughCommand,
+ SetInlineFormatFontSizeCommand,
+ SetInlineFormatFontFamilyCommand,
+ SetInlineFormatTextColorCommand,
SetInlineFormatCommand,
BreakLineCommand,
InsertCommand,
diff --git a/packages/base-docs/src/commands/commands/__tests__/inline-format.command.spec.ts b/packages/base-docs/src/commands/commands/__tests__/inline-format.command.spec.ts
index 02ec7de937..98c6db72ee 100644
--- a/packages/base-docs/src/commands/commands/__tests__/inline-format.command.spec.ts
+++ b/packages/base-docs/src/commands/commands/__tests__/inline-format.command.spec.ts
@@ -4,6 +4,7 @@ import {
BooleanNumber,
ICommand,
ICommandService,
+ IStyleBase,
IUniverInstanceService,
RedoCommand,
UndoCommand,
@@ -12,8 +13,19 @@ import {
import { Injector } from '@wendellhu/redi';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+import { NORMAL_TEXT_SELECTION_PLUGIN_NAME } from '../../../Basics/docs-view-key';
+import { TextSelectionManagerService } from '../../../services/text-selection-manager.service';
import { RichTextEditingMutation } from '../../mutations/core-editing.mutation';
-import { SetInlineFormatCommand } from '../inline-format.command';
+import {
+ SetInlineFormatBoldCommand,
+ SetInlineFormatCommand,
+ SetInlineFormatFontFamilyCommand,
+ SetInlineFormatFontSizeCommand,
+ SetInlineFormatItalicCommand,
+ SetInlineFormatStrikethroughCommand,
+ SetInlineFormatTextColorCommand,
+ SetInlineFormatUnderlineCommand,
+} from '../inline-format.command';
import { createCommandTestBed } from './create-command-test-bed';
describe('Test inline format commands', () => {
@@ -21,23 +33,21 @@ describe('Test inline format commands', () => {
let get: Injector['get'];
let commandService: ICommandService;
- function getFormatValueAt(key: 'bl', pos: number) {
+ function getFormatValueAt(key: keyof IStyleBase, pos: number) {
const univerInstanceService = get(IUniverInstanceService);
const docsModel = univerInstanceService.getUniverDocInstance('test-doc');
if (docsModel?.body?.textRuns == null) {
- return null;
+ return;
}
for (const textRun of docsModel.body?.textRuns) {
const { st, ed, ts = {} } = textRun;
if (st <= pos && ed >= pos) {
- return ts[key] ?? null;
+ return ts[key];
}
}
-
- return null;
}
beforeEach(() => {
@@ -46,65 +56,40 @@ describe('Test inline format commands', () => {
get = testBed.get;
commandService = get(ICommandService);
- // commandService.registerCommand(SetInlineFormatBoldCommand);
commandService.registerCommand(SetInlineFormatCommand);
commandService.registerCommand(RichTextEditingMutation as unknown as ICommand);
- // const selectionManager = get(TextSelectionManagerService);
-
- // selectionManager.setCurrentSelection({
- // pluginName: NORMAL_TEXT_SELECTION_PLUGIN_NAME,
- // unitId: 'test-doc',
- // });
-
- // selectionManager.add([
- // {
- // cursorStart: 0,
- // isStartBack: true,
- // cursorEnd: 5,
- // isEndBack: false,
- // isCollapse: false,
- // segmentId: '',
- // },
- // ]);
+ const selectionManager = get(TextSelectionManagerService);
+
+ selectionManager.setCurrentSelection({
+ pluginName: NORMAL_TEXT_SELECTION_PLUGIN_NAME,
+ unitId: 'test-doc',
+ });
+
+ selectionManager.add([
+ {
+ cursorStart: 0,
+ isStartBack: true,
+ cursorEnd: 5,
+ isEndBack: false,
+ isCollapse: false,
+ segmentId: '',
+ },
+ ]);
});
afterEach(() => univer.dispose());
- describe('Set Bold by SetInlineFormatBoldCommand', () => {
+ describe('Set Bold by SetInlineFormatCommand', () => {
it('Should change text in range(0, 5) to bold', async () => {
expect(getFormatValueAt('bl', 1)).toBe(BooleanNumber.FALSE);
- const doMutation = {
- unitId: 'test-doc',
- doMutation: {
- id: 'doc.mutation.rich-text-editing',
- params: {
- unitId: 'test-doc',
- mutations: [
- {
- t: 'r',
- body: {
- dataStream: '',
- textRuns: [
- {
- st: 0,
- ed: 5,
- ts: {
- bl: BooleanNumber.TRUE,
- },
- },
- ],
- },
- len: 5,
- segmentId: '',
- },
- ],
- },
- },
+ const commandParams = {
+ segmentId: '',
+ preCommandId: SetInlineFormatBoldCommand.id,
};
- await commandService.executeCommand(SetInlineFormatCommand.id, doMutation);
+ await commandService.executeCommand(SetInlineFormatCommand.id, commandParams);
expect(getFormatValueAt('bl', 1)).toBe(BooleanNumber.TRUE);
@@ -115,4 +100,141 @@ describe('Test inline format commands', () => {
expect(getFormatValueAt('bl', 1)).toBe(BooleanNumber.TRUE);
});
});
+
+ describe('Set Italic by SetInlineFormatCommand', () => {
+ it('Should change text in range(0, 5) to italic', async () => {
+ expect(getFormatValueAt('it', 1)).toBe(undefined);
+
+ const commandParams = {
+ segmentId: '',
+ preCommandId: SetInlineFormatItalicCommand.id,
+ };
+
+ await commandService.executeCommand(SetInlineFormatCommand.id, commandParams);
+
+ expect(getFormatValueAt('it', 1)).toBe(BooleanNumber.TRUE);
+
+ await commandService.executeCommand(UndoCommand.id);
+ expect(getFormatValueAt('it', 1)).toBe(undefined);
+
+ await commandService.executeCommand(RedoCommand.id);
+ expect(getFormatValueAt('it', 1)).toBe(BooleanNumber.TRUE);
+ });
+ });
+
+ describe('Set Underline by SetInlineFormatCommand', () => {
+ it('Should change text in range(0, 5) to underline', async () => {
+ expect(getFormatValueAt('ul', 1)).toBe(undefined);
+
+ const commandParams = {
+ segmentId: '',
+ preCommandId: SetInlineFormatUnderlineCommand.id,
+ };
+
+ await commandService.executeCommand(SetInlineFormatCommand.id, commandParams);
+
+ expect(getFormatValueAt('ul', 1)).toStrictEqual({ s: BooleanNumber.TRUE });
+
+ await commandService.executeCommand(UndoCommand.id);
+ expect(getFormatValueAt('ul', 1)).toStrictEqual(undefined);
+
+ await commandService.executeCommand(RedoCommand.id);
+ expect(getFormatValueAt('ul', 1)).toStrictEqual({ s: BooleanNumber.TRUE });
+ });
+ });
+
+ describe('Set Strickthrough by SetInlineFormatCommand', () => {
+ it('Should change text in range(0, 5) to stroke', async () => {
+ expect(getFormatValueAt('st', 1)).toBe(undefined);
+
+ const commandParams = {
+ segmentId: '',
+ preCommandId: SetInlineFormatStrikethroughCommand.id,
+ };
+
+ await commandService.executeCommand(SetInlineFormatCommand.id, commandParams);
+
+ expect(getFormatValueAt('st', 1)).toStrictEqual({ s: BooleanNumber.TRUE });
+
+ await commandService.executeCommand(UndoCommand.id);
+ expect(getFormatValueAt('st', 1)).toStrictEqual(undefined);
+
+ await commandService.executeCommand(RedoCommand.id);
+ expect(getFormatValueAt('st', 1)).toStrictEqual({ s: BooleanNumber.TRUE });
+ });
+ });
+
+ describe('Set FontFamily by SetInlineFormatCommand', () => {
+ it('Should change text in range(0, 5) to Arial', async () => {
+ expect(getFormatValueAt('ff', 1)).toBe(undefined);
+
+ const commandParams = {
+ segmentId: '',
+ preCommandId: SetInlineFormatFontFamilyCommand.id,
+ value: 'Arial',
+ };
+
+ await commandService.executeCommand(SetInlineFormatCommand.id, commandParams);
+
+ expect(getFormatValueAt('ff', 1)).toBe('Arial');
+
+ await commandService.executeCommand(UndoCommand.id);
+ expect(getFormatValueAt('ff', 1)).toBe(undefined);
+
+ await commandService.executeCommand(RedoCommand.id);
+ expect(getFormatValueAt('ff', 1)).toBe('Arial');
+ });
+ });
+
+ describe('Set FontSize by SetInlineFormatCommand', () => {
+ it('Should change text in range(0, 5) to 28', async () => {
+ expect(getFormatValueAt('fs', 1)).toBe(24);
+
+ const commandParams = {
+ segmentId: '',
+ preCommandId: SetInlineFormatFontSizeCommand.id,
+ value: 28,
+ };
+
+ await commandService.executeCommand(SetInlineFormatCommand.id, commandParams);
+
+ expect(getFormatValueAt('fs', 1)).toBe(28);
+
+ await commandService.executeCommand(UndoCommand.id);
+ expect(getFormatValueAt('fs', 1)).toBe(24);
+
+ await commandService.executeCommand(RedoCommand.id);
+ expect(getFormatValueAt('fs', 1)).toBe(28);
+ });
+ });
+
+ describe('Set Text color by SetInlineFormatCommand', () => {
+ it('Should change text in range(0, 5) to #000000', async () => {
+ expect(getFormatValueAt('cl', 1)).toStrictEqual({
+ rgb: 'rgb(0, 40, 86)',
+ });
+
+ const commandParams = {
+ segmentId: '',
+ preCommandId: SetInlineFormatTextColorCommand.id,
+ value: '#000000',
+ };
+
+ await commandService.executeCommand(SetInlineFormatCommand.id, commandParams);
+
+ expect(getFormatValueAt('cl', 1)).toStrictEqual({
+ rgb: '#000000',
+ });
+
+ await commandService.executeCommand(UndoCommand.id);
+ expect(getFormatValueAt('cl', 1)).toStrictEqual({
+ rgb: 'rgb(0, 40, 86)',
+ });
+
+ await commandService.executeCommand(RedoCommand.id);
+ expect(getFormatValueAt('cl', 1)).toStrictEqual({
+ rgb: '#000000',
+ });
+ });
+ });
});
diff --git a/packages/base-docs/src/commands/commands/inline-format.command.ts b/packages/base-docs/src/commands/commands/inline-format.command.ts
index f183b98dc2..631e9c4a14 100644
--- a/packages/base-docs/src/commands/commands/inline-format.command.ts
+++ b/packages/base-docs/src/commands/commands/inline-format.command.ts
@@ -1,26 +1,183 @@
-import { CommandType, ICommand, ICommandInfo, ICommandService, IUndoRedoService } from '@univerjs/core';
+import { ITextSelectionRangeWithStyle } from '@univerjs/base-render';
+import {
+ BooleanNumber,
+ CommandType,
+ getTextIndexByCursor,
+ ICommand,
+ ICommandInfo,
+ ICommandService,
+ IDocumentBody,
+ IStyleBase,
+ ITextDecoration,
+ ITextRun,
+ IUndoRedoService,
+ IUniverInstanceService,
+} from '@univerjs/core';
+import MemoryCursor from '../../Basics/memoryCursor';
+import { TextSelectionManagerService } from '../../services/text-selection-manager.service';
import { IRichTextEditingMutationParams, RichTextEditingMutation } from '../mutations/core-editing.mutation';
+export interface ISetInlineFormatCommandParams {
+ segmentId: string;
+ preCommandId: string;
+ value?: string;
+}
+
export const SetInlineFormatBoldCommand: ICommand = {
id: 'doc.command.set-inline-format-bold',
type: CommandType.COMMAND,
handler: async () => true,
};
-export const SetInlineFormatCommand: ICommand = {
+export const SetInlineFormatItalicCommand: ICommand = {
+ id: 'doc.command.set-inline-format-italic',
+ type: CommandType.COMMAND,
+ handler: async () => true,
+};
+
+export const SetInlineFormatUnderlineCommand: ICommand = {
+ id: 'doc.command.set-inline-format-underline',
+ type: CommandType.COMMAND,
+ handler: async () => true,
+};
+
+export const SetInlineFormatStrikethroughCommand: ICommand = {
+ id: 'doc.command.set-inline-format-strikethrough',
+ type: CommandType.COMMAND,
+ handler: async () => true,
+};
+
+export const SetInlineFormatFontSizeCommand: ICommand = {
+ id: 'doc.command.set-inline-format-fontsize',
+ type: CommandType.COMMAND,
+ handler: async () => true,
+};
+
+export const SetInlineFormatFontFamilyCommand: ICommand = {
+ id: 'doc.command.set-inline-format-font-family',
+ type: CommandType.COMMAND,
+ handler: async () => true,
+};
+
+export const SetInlineFormatTextColorCommand: ICommand = {
+ id: 'doc.command.set-inline-format-text-color',
+ type: CommandType.COMMAND,
+ handler: async () => true,
+};
+
+export const SetInlineFormatCommand: ICommand<ISetInlineFormatCommandParams> = {
id: 'doc.command.set-inline-format',
type: CommandType.COMMAND,
- handler: async (
- accessor,
- params: {
- unitId: string;
- doMutation: ICommandInfo<IRichTextEditingMutationParams>;
- }
- ) => {
+ handler: async (accessor, params: ISetInlineFormatCommandParams) => {
+ const { segmentId, value, preCommandId } = params;
const undoRedoService = accessor.get(IUndoRedoService);
const commandService = accessor.get(ICommandService);
- const { unitId, doMutation } = params;
+ const textSelectionManagerService = accessor.get(TextSelectionManagerService);
+ const currentUniverService = accessor.get(IUniverInstanceService);
+
+ const selections = textSelectionManagerService.getSelections();
+
+ if (!Array.isArray(selections) || selections.length === 0) {
+ return false;
+ }
+
+ const docsModel = currentUniverService.getCurrentUniverDocInstance();
+ const unitId = docsModel.getUnitId();
+
+ let formatValue;
+
+ const COMMAND_ID_TO_FORMAT_KEY_MAP: Record<string, keyof IStyleBase> = {
+ [SetInlineFormatBoldCommand.id]: 'bl',
+ [SetInlineFormatItalicCommand.id]: 'it',
+ [SetInlineFormatUnderlineCommand.id]: 'ul',
+ [SetInlineFormatStrikethroughCommand.id]: 'st',
+ [SetInlineFormatFontSizeCommand.id]: 'fs',
+ [SetInlineFormatFontFamilyCommand.id]: 'ff',
+ [SetInlineFormatTextColorCommand.id]: 'cl',
+ };
+
+ switch (preCommandId) {
+ case SetInlineFormatBoldCommand.id: // fallthrough
+ case SetInlineFormatItalicCommand.id: // fallthrough
+ case SetInlineFormatUnderlineCommand.id: // fallthrough
+ case SetInlineFormatStrikethroughCommand.id: {
+ formatValue = getReverseFormatValueInSelection(
+ docsModel.body!.textRuns!,
+ COMMAND_ID_TO_FORMAT_KEY_MAP[preCommandId],
+ selections
+ );
+
+ break;
+ }
+
+ case SetInlineFormatFontSizeCommand.id:
+ case SetInlineFormatFontFamilyCommand.id: {
+ formatValue = value;
+ break;
+ }
+
+ case SetInlineFormatTextColorCommand.id: {
+ formatValue = {
+ rgb: value,
+ };
+ break;
+ }
+
+ default: {
+ throw new Error(`Unknown command: ${preCommandId} in handleInlineFormat`);
+ }
+ }
+
+ const doMutation: ICommandInfo<IRichTextEditingMutationParams> = {
+ id: RichTextEditingMutation.id,
+ params: {
+ unitId,
+ mutations: [],
+ },
+ };
+
+ const memoryCursor = new MemoryCursor();
+
+ memoryCursor.reset();
+
+ for (const selection of selections) {
+ const { cursorStart, cursorEnd, isStartBack, isEndBack } = selection;
+ const textStart = getTextIndexByCursor(cursorStart, isStartBack);
+ const textEnd = getTextIndexByCursor(cursorEnd, isEndBack);
+
+ const body: IDocumentBody = {
+ dataStream: '',
+ textRuns: [
+ {
+ st: 0,
+ ed: textEnd - textStart,
+ ts: {
+ [COMMAND_ID_TO_FORMAT_KEY_MAP[preCommandId]]: formatValue,
+ },
+ },
+ ],
+ };
+
+ const len = textStart + 1 - memoryCursor.cursor;
+ if (len !== 0) {
+ doMutation.params!.mutations.push({
+ t: 'r',
+ len,
+ segmentId,
+ });
+ }
+
+ doMutation.params!.mutations.push({
+ t: 'r',
+ body,
+ len: textEnd - textStart,
+ segmentId,
+ });
+
+ memoryCursor.reset();
+ memoryCursor.moveCursor(textEnd + 1);
+ }
const result = commandService.syncExecuteCommand<
IRichTextEditingMutationParams,
@@ -44,3 +201,63 @@ export const SetInlineFormatCommand: ICommand = {
return false;
},
};
+
+function isTextDecoration(value: unknown | ITextDecoration): value is ITextDecoration {
+ return value !== null && typeof value === 'object';
+}
+
+/**
+ * When clicking on a Bold menu item, you should un-bold if there is bold in the selections,
+ * or bold if there is no bold text. This method is used to get the reverse style value calculated
+ * from textRuns in the selection
+ */
+function getReverseFormatValueInSelection(
+ textRuns: ITextRun[],
+ key: keyof IStyleBase,
+ selections: ITextSelectionRangeWithStyle[]
+): BooleanNumber | ITextDecoration {
+ let ti = 0;
+ let si = 0;
+
+ while (ti !== textRuns.length && si !== selections.length) {
+ const { cursorStart, cursorEnd, isStartBack, isEndBack } = selections[si];
+
+ const textStart = getTextIndexByCursor(cursorStart, isStartBack) + 1;
+ const textEnd = getTextIndexByCursor(cursorEnd, isEndBack) + 1;
+
+ // TODO: @jocs handle sid in textRun
+ const { st, ed, ts } = textRuns[ti];
+
+ if (textEnd <= st) {
+ si++;
+ } else if (ed <= textStart) {
+ ti++;
+ } else {
+ if (ts?.[key] == null) {
+ return /bl|it/.test(key)
+ ? BooleanNumber.TRUE
+ : {
+ s: BooleanNumber.TRUE,
+ };
+ }
+
+ if (ts[key] === BooleanNumber.FALSE) {
+ return BooleanNumber.TRUE;
+ }
+
+ if (isTextDecoration(ts[key]) && (ts[key] as ITextDecoration).s === BooleanNumber.FALSE) {
+ return {
+ s: BooleanNumber.TRUE,
+ };
+ }
+
+ ti++;
+ }
+ }
+
+ return /bl|it/.test(key)
+ ? BooleanNumber.FALSE
+ : {
+ s: BooleanNumber.FALSE,
+ };
+}
diff --git a/packages/base-docs/src/commands/mutations/functions/common.ts b/packages/base-docs/src/commands/mutations/functions/common.ts
index 0e20c1c247..534bfde2e4 100644
--- a/packages/base-docs/src/commands/mutations/functions/common.ts
+++ b/packages/base-docs/src/commands/mutations/functions/common.ts
@@ -68,8 +68,7 @@ export function insertTextRuns(
if (insertIndex === Infinity) {
textRuns.push(...insertTextRuns);
- }
- if (insertIndex === -Infinity) {
+ } else if (insertIndex === -Infinity) {
textRuns.unshift(...insertTextRuns);
} else {
const splitTextRun = textRuns[insertIndex];
diff --git a/packages/base-docs/src/index.ts b/packages/base-docs/src/index.ts
index f4b0db4148..2ab8888404 100644
--- a/packages/base-docs/src/index.ts
+++ b/packages/base-docs/src/index.ts
@@ -13,7 +13,16 @@ export {
UpdateCommand,
} from './commands/commands/core-editing.command';
export { BreakLineCommand, DeleteLeftCommand } from './commands/commands/core-editing.command';
-export { SetInlineFormatBoldCommand, SetInlineFormatCommand } from './commands/commands/inline-format.command';
+export {
+ SetInlineFormatBoldCommand,
+ SetInlineFormatCommand,
+ SetInlineFormatFontFamilyCommand,
+ SetInlineFormatFontSizeCommand,
+ SetInlineFormatItalicCommand,
+ SetInlineFormatStrikethroughCommand,
+ SetInlineFormatTextColorCommand,
+ SetInlineFormatUnderlineCommand,
+} from './commands/commands/inline-format.command';
export {
type IRichTextEditingMutationParams,
RichTextEditingMutation,
diff --git a/packages/base-sheets/src/commands/commands/clear-selection-format.command.ts b/packages/base-sheets/src/commands/commands/clear-selection-format.command.ts
index 72ace6410f..38edf101fa 100644
--- a/packages/base-sheets/src/commands/commands/clear-selection-format.command.ts
+++ b/packages/base-sheets/src/commands/commands/clear-selection-format.command.ts
@@ -127,10 +127,12 @@ export const ClearSelectionFormatCommand: ICommand = {
};
// Generate cellValue from range and set s to null
-export function generateNullCellValue(range: IRange[]): ObjectMatrixPrimitiveType<ICellData> {
+export function generateNullCellValue(ranges: IRange[]): ObjectMatrixPrimitiveType<ICellData> {
const cellValue = new ObjectMatrix<ICellData>();
- range.forEach((range: IRange) => {
+
+ ranges.forEach((range: IRange) => {
const { startRow, startColumn, endRow, endColumn } = range;
+
for (let i = startRow; i <= endRow; i++) {
for (let j = startColumn; j <= endColumn; j++) {
cellValue.setValue(i, j, {
diff --git a/packages/base-sheets/src/commands/commands/set-style.command.ts b/packages/base-sheets/src/commands/commands/set-style.command.ts
index db0afbac40..36f86ab132 100644
--- a/packages/base-sheets/src/commands/commands/set-style.command.ts
+++ b/packages/base-sheets/src/commands/commands/set-style.command.ts
@@ -59,12 +59,13 @@ export const SetStyleCommand: ICommand<ISetStyleParams<unknown>> = {
const workbookId = univerInstanceService.getCurrentUniverSheetInstance().getUnitId();
const worksheetId = univerInstanceService.getCurrentUniverSheetInstance().getActiveSheet().getSheetId();
- const style = params.style;
+ const { style } = params;
const workbook = univerInstanceService.getUniverSheetInstance(workbookId);
- if (!workbook) return false;
- const worksheet = workbook.getSheetBySheetId(worksheetId);
- if (!worksheet) return false;
+ const worksheet = workbook?.getSheetBySheetId(worksheetId);
+ if (worksheet == null) {
+ return false;
+ }
const cellValue = new ObjectMatrix<ICellData>();
// let value: ObjectMatrixPrimitiveType<ICellData> | undefined;
@@ -150,25 +151,22 @@ export const SetStyleCommand: ICommand<ISetStyleParams<unknown>> = {
};
/**
- * Set bold font style to currently selected ranges. If the cell is already bold then it will cancel the bold style.
+ * Set bold font style to currently selected ranges.
+ * If the cell is already bold then it will cancel the bold style.
*/
export const SetBoldCommand: ICommand = {
type: CommandType.COMMAND,
id: 'sheet.command.set-bold',
handler: async (accessor) => {
const selection = accessor.get(SelectionManagerService).getLast();
+
if (!selection) {
return false;
}
- const worksheet = accessor
- .get(IUniverInstanceService)
- .getCurrentUniverSheetInstance()
-
- .getActiveSheet();
- const currentlyBold =
- worksheet.getRange(selection.primary.actualRow, selection.primary.actualColumn).getFontWeight() ===
- FontWeight.BOLD;
+ const worksheet = accessor.get(IUniverInstanceService).getCurrentUniverSheetInstance().getActiveSheet();
+ const { actualRow, actualColumn } = selection.primary;
+ const currentlyBold = worksheet.getRange(actualRow, actualColumn).getFontWeight() === FontWeight.BOLD;
const setStyleParams: ISetStyleParams<BooleanNumber> = {
style: {
@@ -182,27 +180,26 @@ export const SetBoldCommand: ICommand = {
};
/**
- * Set italic font style to currently selected ranges. If the cell is already italic then it will cancel the italic style.
+ * Set italic font style to currently selected ranges.
+ * If the cell is already italic then it will cancel the italic style.
*/
export const SetItalicCommand: ICommand = {
type: CommandType.COMMAND,
id: 'sheet.command.set-italic',
handler: async (accessor) => {
const selection = accessor.get(SelectionManagerService).getLast();
+
if (!selection) {
return false;
}
- const worksheet = accessor
- .get(IUniverInstanceService)
- .getCurrentUniverSheetInstance()
-
- .getActiveSheet();
+ const worksheet = accessor.get(IUniverInstanceService).getCurrentUniverSheetInstance().getActiveSheet();
let currentlyItalic = true;
+
if (selection.primary) {
- currentlyItalic =
- worksheet.getRange(selection.primary.startRow, selection.primary.startColumn).getFontStyle() ===
- FontItalic.ITALIC;
+ const { startRow, startColumn } = selection.primary;
+
+ currentlyItalic = worksheet.getRange(startRow, startColumn).getFontStyle() === FontItalic.ITALIC;
}
const setStyleParams: ISetStyleParams<BooleanNumber> = {
diff --git a/packages/base-sheets/src/commands/mutations/set-border-styles.mutation.ts b/packages/base-sheets/src/commands/mutations/set-border-styles.mutation.ts
index db8353bbf0..bc168b0451 100644
--- a/packages/base-sheets/src/commands/mutations/set-border-styles.mutation.ts
+++ b/packages/base-sheets/src/commands/mutations/set-border-styles.mutation.ts
@@ -205,9 +205,11 @@ export function mergeStyle(
if ('ul' in backupStyle) {
backupStyle.ul.cl = backupStyle.cl;
}
+
if ('ol' in backupStyle) {
backupStyle.ol.cl = backupStyle.cl;
}
+
if ('st' in backupStyle) {
backupStyle.st.cl = backupStyle.cl;
}
diff --git a/packages/base-sheets/src/commands/mutations/set-range-values.mutation.ts b/packages/base-sheets/src/commands/mutations/set-range-values.mutation.ts
index 808194770f..37fff130c6 100644
--- a/packages/base-sheets/src/commands/mutations/set-range-values.mutation.ts
+++ b/packages/base-sheets/src/commands/mutations/set-range-values.mutation.ts
@@ -45,14 +45,12 @@ export const SetRangeValuesUndoMutationFactory = (
): ISetRangeValuesMutationParams => {
const { workbookId, worksheetId, cellValue } = params;
const univerInstanceService = accessor.get(IUniverInstanceService);
- const universheet = univerInstanceService.getUniverSheetInstance(workbookId);
+ const workbook = univerInstanceService.getUniverSheetInstance(workbookId);
- if (universheet == null) {
- throw new Error('universheet is null error!');
+ if (workbook == null) {
+ throw new Error('workbook is null error!');
}
- const workbook = universheet;
-
const worksheet = workbook.getSheetBySheetId(worksheetId);
if (worksheet == null) {
throw new Error('worksheet is null error!');
@@ -64,25 +62,15 @@ export const SetRangeValuesUndoMutationFactory = (
const newValues = new ObjectMatrix(cellValue);
- // for (let i = 0; i < range.length; i++) {
newValues.forValue((row, col, newVal) => {
const cell = Tools.deepClone(cellMatrix?.getValue(row, col)) || {}; // clone cell data,prevent modify the original data
const oldStyle = styles.getStyleByCell(cell);
const newStyle = transformStyle(oldStyle, newVal && newVal.s ? (newVal.s as Nullable<IStyleData>) : null);
+
cell.s = newStyle;
undoData.setValue(row, col, setNull(cell));
});
- // for (let i = 0; i < params.range.length; i++) {
- // const { startRow, endRow, startColumn, endColumn } = params.range[i];
-
- // for (let r = startRow; r <= endRow; r++) {
- // for (let c = startColumn; c <= endColumn; c++) {
- // const value = cellMatrix?.getValue(r, c);
- // undoData.setValue(r, c, Tools.deepClone(value as ICellData));
- // }
- // }
- // }
return {
...Tools.deepClone(params),
@@ -126,15 +114,17 @@ export const SetRangeValuesMutation: IMutation<ISetRangeValuesMutationParams, bo
id: 'sheet.mutation.set-range-values',
type: CommandType.MUTATION,
handler: (accessor, params) => {
+ const { cellValue, worksheetId } = params;
const univerInstanceService = accessor.get(IUniverInstanceService);
const workbook = univerInstanceService.getCurrentUniverSheetInstance();
- const worksheet = workbook.getSheetBySheetId(params.worksheetId);
+ const worksheet = workbook.getSheetBySheetId(worksheetId);
+
if (!worksheet) {
return false;
}
+
const cellMatrix = worksheet.getCellMatrix();
const styles = workbook.getStyles();
- const { cellValue } = params;
const newValues = new ObjectMatrix(cellValue);
newValues.forValue((row, col, newVal) => {
@@ -172,6 +162,10 @@ export const SetRangeValuesMutation: IMutation<ISetRangeValuesMutationParams, bo
delete oldVal.s;
}
+ if (typeof newVal.s === 'string') {
+ newVal.s = styles.get(newVal.s);
+ }
+
// set style
const merge = mergeStyle(oldStyle, newVal.s ? (newVal.s as Nullable<IStyleData>) : null);
diff --git a/packages/core/src/Shared/ObjectArray.ts b/packages/core/src/Shared/ObjectArray.ts
index 5bd3692f87..c2dc0395a7 100644
--- a/packages/core/src/Shared/ObjectArray.ts
+++ b/packages/core/src/Shared/ObjectArray.ts
@@ -142,6 +142,7 @@ export class ObjectArray<T> {
// if (define(value)) {
const length = this._length;
this._objectArray[index] = value;
+
if (index >= length) {
this._length = index + 1;
}
diff --git a/packages/core/src/services/command/command.service.ts b/packages/core/src/services/command/command.service.ts
index ae5375a60d..359f7b571e 100644
--- a/packages/core/src/services/command/command.service.ts
+++ b/packages/core/src/services/command/command.service.ts
@@ -226,6 +226,7 @@ export class CommandService implements ICommandService {
onCommandExecuted(listener: (commandInfo: ICommandInfo) => void): IDisposable {
if (this._commandExecutedListeners.indexOf(listener) === -1) {
this._commandExecutedListeners.push(listener);
+
return toDisposable(() => {
const index = this._commandExecutedListeners.indexOf(listener);
this._commandExecutedListeners.splice(index, 1);
@@ -289,6 +290,7 @@ export class CommandService implements ICommandService {
// compose a multi command and register it
const registry = this._commandRegistry.getCommand(command.id);
let multiCommand: MultiCommand;
+
if (!registry) {
multiCommand = new MultiCommand(command.id);
this._multiCommandDisposables.set(
@@ -304,6 +306,7 @@ export class CommandService implements ICommandService {
}
const commandDisposable = multiCommand.registerImplementation(command as IMultiCommand, injector);
+
return toDisposable(() => {
commandDisposable.dispose();
if (!multiCommand.hasImplementations()) {
@@ -418,6 +421,7 @@ class MultiCommand implements IMultiCommand {
export function sequenceExecute(tasks: ICommandInfo[], commandService: ICommandService, options?: IExecutionOptions) {
const promises = tasks.map((task) => () => commandService.syncExecuteCommand(task.id, task.params, options));
+
return syncSequence(promises);
}
@@ -427,5 +431,6 @@ export function sequenceExecuteAsync(
options?: IExecutionOptions
) {
const promises = tasks.map((task) => () => commandService.executeCommand(task.id, task.params, options));
+
return sequence(promises);
}
diff --git a/packages/core/src/services/undoredo/undoredo.service.ts b/packages/core/src/services/undoredo/undoredo.service.ts
index b1ee090086..c9f55fd34b 100644
--- a/packages/core/src/services/undoredo/undoredo.service.ts
+++ b/packages/core/src/services/undoredo/undoredo.service.ts
@@ -5,7 +5,7 @@ import { Disposable, toDisposable } from '../../Shared/lifecycle';
import { CommandService, CommandType, ICommand, ICommandInfo, ICommandService } from '../command/command.service';
import { IUniverInstanceService } from '../instance/instance.service';
-// TODO:: an undo redo element may be mergeable to another undo redo element
+// TODO: an undo redo element may be mergeable to another undo redo element
interface IUndoRedoItem {
/** URI maps to unitId for UniverSheet / UniverDoc / UniverSlide */
@@ -82,6 +82,7 @@ export class LocalUndoRedoService extends Disposable implements IUndoRedoService
// TODO: undo element maybe mergeable
// TODO: undo redo stack should have a maximum capacity, maybe we should get the config from IConfigService?
undoStack.push(item);
+
if (undoStack.length > STACK_CAPACITY) {
undoStack.splice(0, 1);
}
diff --git a/packages/core/src/sheets/range.ts b/packages/core/src/sheets/range.ts
index ca8923e0f8..eadc66bba7 100644
--- a/packages/core/src/sheets/range.ts
+++ b/packages/core/src/sheets/range.ts
@@ -6,9 +6,11 @@ import {
ICellData,
IDocumentData,
IRange,
+ IStyleBase,
IStyleData,
ITextDecoration,
ITextRotation,
+ ITextRun,
} from '../Types/Interfaces';
import { Styles } from './styles';
import type { Worksheet } from './worksheet';
@@ -27,6 +29,39 @@ export interface IRangeDependencies {
getStyles(): Readonly<Styles>;
}
+function isAllFormatInTextRuns(key: keyof IStyleBase, textRuns: ITextRun[]): BooleanNumber {
+ for (const textRun of textRuns) {
+ const { ts = {} } = textRun;
+
+ if (ts[key] == null) {
+ return BooleanNumber.FALSE;
+ }
+
+ switch (key) {
+ case 'bl': // fallthrough
+ case 'it': {
+ if (ts[key] === BooleanNumber.FALSE) {
+ return BooleanNumber.FALSE;
+ }
+ break;
+ }
+
+ case 'ul': // fallthrough
+ case 'st': {
+ if (ts[key]!.s === BooleanNumber.FALSE) {
+ return BooleanNumber.FALSE;
+ }
+ break;
+ }
+
+ default:
+ throw new Error(`unknown style key: ${key} in IStyleBase`);
+ }
+ }
+
+ return BooleanNumber.TRUE;
+}
+
/**
* Access and modify spreadsheet ranges.
*
@@ -94,11 +129,14 @@ export class Range {
getValues(): Array<Array<Nullable<ICellData>>> {
const { startRow, endRow, startColumn, endColumn } = this._range;
const range: Array<Array<Nullable<ICellData>>> = [];
+
for (let r = startRow; r <= endRow; r++) {
const row: Array<Nullable<ICellData>> = [];
+
for (let c = startColumn; c <= endColumn; c++) {
row.push(this.getMatrix().getValue(r, c) || null);
}
+
range.push(row);
}
return range;
@@ -338,6 +376,18 @@ export class Range {
* Returns the underline of the cells in the range.
*/
getUnderline(): ITextDecoration {
+ const { p } = this.getValue() ?? {};
+
+ if (p && Array.isArray(p.body?.textRuns)) {
+ return isAllFormatInTextRuns('ul', p.body?.textRuns!) === BooleanNumber.TRUE
+ ? {
+ s: BooleanNumber.TRUE,
+ }
+ : {
+ s: BooleanNumber.FALSE,
+ };
+ }
+
return this.getUnderlines()[0][0];
}
@@ -356,17 +406,29 @@ export class Range {
}
/**
- * Returns the strikeThroughs of the cells in the range.
+ * Returns the strikeThrough of the cells in the range.
*/
- getStrikeThroughs(): ITextDecoration[][] {
- return this._getStyles('st') as ITextDecoration[][];
+ getStrikeThrough(): ITextDecoration {
+ const { p } = this.getValue() ?? {};
+
+ if (p && Array.isArray(p.body?.textRuns)) {
+ return isAllFormatInTextRuns('st', p.body?.textRuns!) === BooleanNumber.TRUE
+ ? {
+ s: BooleanNumber.TRUE,
+ }
+ : {
+ s: BooleanNumber.FALSE,
+ };
+ }
+
+ return this.getStrikeThroughs()[0][0];
}
/**
- * Returns the strikeThrough of the cells in the range.
+ * Returns the strikeThroughs of the cells in the range.
*/
- getStrikeThrough(): ITextDecoration {
- return this.getStrikeThroughs()[0][0];
+ private getStrikeThroughs(): ITextDecoration[][] {
+ return this._getStyles('st') as ITextDecoration[][];
}
/**
@@ -399,27 +461,46 @@ export class Range {
* Returns the font style ('italic' or 'normal') of the cell in the top-left corner of the range.
*/
getFontStyle(): FontItalic {
+ const { p } = this.getValue() ?? {};
+
+ if (p && Array.isArray(p.body?.textRuns)) {
+ return isAllFormatInTextRuns('it', p.body?.textRuns!) === BooleanNumber.TRUE
+ ? FontItalic.ITALIC
+ : FontItalic.NORMAL;
+ }
+
return this.getFontStyles()[0][0];
}
/**
* Returns the font styles of the cells in the range.
*/
- getFontStyles(): FontItalic[][] {
+ private getFontStyles(): FontItalic[][] {
return this._getStyles('it') as FontItalic[][];
}
/**
* Returns the font weight (normal/bold) of the cell in the top-left corner of the range.
+ * If the cell has rich text, the return value according to the textRuns of the rich text,
+ * when all styles of textRuns are bold, it will return FontWeight.BOLD,
+ * otherwise return FontWeight.NORMAL.
*/
getFontWeight(): FontWeight {
+ const { p } = this.getValue() ?? {};
+
+ if (p && Array.isArray(p.body?.textRuns)) {
+ return isAllFormatInTextRuns('bl', p.body?.textRuns!) === BooleanNumber.TRUE
+ ? FontWeight.BOLD
+ : FontWeight.NORMAL;
+ }
+
return this.getFontWeights()[0][0];
}
/**
* Returns the font weights of the cells in the range.
*/
- getFontWeights(): FontWeight[][] {
+ private getFontWeights(): FontWeight[][] {
return this._getStyles('bl') as FontWeight[][];
}
@@ -625,12 +706,14 @@ export class Range {
* @param arg Shorthand for the style that gets
* @returns style value
*/
- private _getStyles(arg: keyof IStyleData): Array<Array<IStyleData[keyof IStyleData]>> {
+ private _getStyles(styleKey: keyof IStyleData): Array<Array<IStyleData[keyof IStyleData]>> {
const styles = this._deps.getStyles();
+
return this.getValues().map((row) =>
row.map((cell: Nullable<ICellData>) => {
const style = styles && styles.getStyleByCell(cell);
- return (style && style[arg]) || (DEFAULT_STYLES as IStyleData)[arg];
+
+ return (style && style[styleKey]) || (DEFAULT_STYLES as IStyleData)[styleKey];
})
);
}
diff --git a/packages/core/src/sheets/styles.ts b/packages/core/src/sheets/styles.ts
index 25eec307e9..787cc888fb 100644
--- a/packages/core/src/sheets/styles.ts
+++ b/packages/core/src/sheets/styles.ts
@@ -38,6 +38,7 @@ export class Styles {
// Move the accessed entry to the end of the Map to represent its recent usage
this._cacheMap.delete(styleObject);
this._cacheMap.set(styleObject, id);
+
return id;
}
@@ -52,6 +53,7 @@ export class Styles {
get(id: string | Nullable<IStyleData>): Nullable<IStyleData> {
if (typeof id !== 'string') return id;
id = String(id);
+
return this._styles[id];
}
diff --git a/packages/ui-plugin-docs/src/Controller/doc-ui.controller.ts b/packages/ui-plugin-docs/src/Controller/doc-ui.controller.ts
index c5a48acc33..c065fdc28f 100644
--- a/packages/ui-plugin-docs/src/Controller/doc-ui.controller.ts
+++ b/packages/ui-plugin-docs/src/Controller/doc-ui.controller.ts
@@ -9,7 +9,12 @@ import {
import { Disposable, ICommandService, LifecycleStages, OnLifecycle } from '@univerjs/core';
import { Inject, Injector } from '@wendellhu/redi';
-import { BoldMenuItemFactory, ItalicMenuItemFactory } from './menu/menu';
+import {
+ BoldMenuItemFactory,
+ ItalicMenuItemFactory,
+ StrikeThroughMenuItemFactory,
+ UnderlineMenuItemFactory,
+} from './menu/menu';
// FIXME: LifecycleStages.Rendered must be used, otherwise the menu cannot be added to the DOM, but the sheet ui plug-in can be added in LifecycleStages.Ready
@OnLifecycle(LifecycleStages.Rendered, DocUIController)
@@ -29,7 +34,14 @@ export class DocUIController extends Disposable {
private _init(): void {
// init menus
- ([BoldMenuItemFactory, ItalicMenuItemFactory] as IMenuItemFactory[]).forEach((factory) => {
+ (
+ [
+ BoldMenuItemFactory,
+ ItalicMenuItemFactory,
+ UnderlineMenuItemFactory,
+ StrikeThroughMenuItemFactory,
+ ] as IMenuItemFactory[]
+ ).forEach((factory) => {
this.disposeWithMe(this._menuService.addMenuItem(this._injector.invoke(factory)));
});
}
diff --git a/packages/ui-plugin-docs/src/Controller/menu/menu.ts b/packages/ui-plugin-docs/src/Controller/menu/menu.ts
index 4c9dfff2d9..a7fe5b9478 100644
--- a/packages/ui-plugin-docs/src/Controller/menu/menu.ts
+++ b/packages/ui-plugin-docs/src/Controller/menu/menu.ts
@@ -1,4 +1,9 @@
-import { BreakLineCommand, SetInlineFormatBoldCommand } from '@univerjs/base-docs';
+import {
+ SetInlineFormatBoldCommand,
+ SetInlineFormatItalicCommand,
+ SetInlineFormatStrikethroughCommand,
+ SetInlineFormatUnderlineCommand,
+} from '@univerjs/base-docs';
import { IMenuButtonItem, MenuItemType, MenuPosition } from '@univerjs/base-ui';
import { IAccessor } from '@wendellhu/redi';
@@ -16,7 +21,7 @@ export function BoldMenuItemFactory(accessor: IAccessor): IMenuButtonItem {
export function ItalicMenuItemFactory(accessor: IAccessor): IMenuButtonItem {
return {
- id: BreakLineCommand.id,
+ id: SetInlineFormatItalicCommand.id,
type: MenuItemType.BUTTON,
icon: 'ItalicSingle',
title: 'Set italic',
@@ -24,3 +29,25 @@ export function ItalicMenuItemFactory(accessor: IAccessor): IMenuButtonItem {
positions: [MenuPosition.TOOLBAR_START],
};
}
+
+export function UnderlineMenuItemFactory(accessor: IAccessor): IMenuButtonItem {
+ return {
+ id: SetInlineFormatUnderlineCommand.id,
+ type: MenuItemType.BUTTON,
+ icon: 'UnderlineSingle',
+ title: 'Set underline',
+ tooltip: 'toolbar.underline',
+ positions: [MenuPosition.TOOLBAR_START],
+ };
+}
+
+export function StrikeThroughMenuItemFactory(accessor: IAccessor): IMenuButtonItem {
+ return {
+ id: SetInlineFormatStrikethroughCommand.id,
+ type: MenuItemType.BUTTON,
+ icon: 'StrikethroughSingle',
+ title: 'Set strike through',
+ tooltip: 'toolbar.strikethrough',
+ positions: [MenuPosition.TOOLBAR_START],
+ };
+}
diff --git a/packages/ui-plugin-sheets/src/commands/commands/inline-format.command.ts b/packages/ui-plugin-sheets/src/commands/commands/inline-format.command.ts
new file mode 100644
index 0000000000..c065968566
--- /dev/null
+++ b/packages/ui-plugin-sheets/src/commands/commands/inline-format.command.ts
@@ -0,0 +1,137 @@
+import {
+ SetInlineFormatBoldCommand,
+ SetInlineFormatFontFamilyCommand,
+ SetInlineFormatFontSizeCommand,
+ SetInlineFormatItalicCommand,
+ SetInlineFormatStrikethroughCommand,
+ SetInlineFormatTextColorCommand,
+ SetInlineFormatUnderlineCommand,
+} from '@univerjs/base-docs';
+import {
+ SetBoldCommand,
+ SetFontFamilyCommand,
+ SetFontSizeCommand,
+ SetItalicCommand,
+ SetStrikeThroughCommand,
+ SetTextColorCommand,
+ SetUnderlineCommand,
+} from '@univerjs/base-sheets';
+import { CommandType, FOCUSING_EDITOR, ICommand, ICommandService, IContextService } from '@univerjs/core';
+
+/**
+ * It is used to set the bold style of selections or one cell, need to distinguish between
+ * **selection state** and **edit state**. If you are in the selective state,
+ * you need to set the style on the cell and the style on the rich text(p textRuns) at the same time,
+ * and if it is only in edit state, then you only need to set the style of the rich text(p textRuns)
+ */
+export const SetRangeBoldCommand: ICommand = {
+ type: CommandType.COMMAND,
+ id: 'sheet.command.set-range-bold',
+ handler: async (accessor) => {
+ const commandService = accessor.get(ICommandService);
+ const contextService = accessor.get(IContextService);
+ const isCellEditorFocus = contextService.getContextValue(FOCUSING_EDITOR);
+
+ if (isCellEditorFocus) {
+ return commandService.executeCommand(SetInlineFormatBoldCommand.id);
+ }
+
+ return commandService.executeCommand(SetBoldCommand.id);
+ },
+};
+
+export const SetRangeItalicCommand: ICommand = {
+ type: CommandType.COMMAND,
+ id: 'sheet.command.set-range-italic',
+ handler: async (accessor) => {
+ const commandService = accessor.get(ICommandService);
+ const contextService = accessor.get(IContextService);
+ const isCellEditorFocus = contextService.getContextValue(FOCUSING_EDITOR);
+
+ if (isCellEditorFocus) {
+ return commandService.executeCommand(SetInlineFormatItalicCommand.id);
+ }
+
+ return commandService.executeCommand(SetItalicCommand.id);
+ },
+};
+
+export const SetRangeUnderlineCommand: ICommand = {
+ type: CommandType.COMMAND,
+ id: 'sheet.command.set-range-underline',
+ handler: async (accessor) => {
+ const commandService = accessor.get(ICommandService);
+ const contextService = accessor.get(IContextService);
+ const isCellEditorFocus = contextService.getContextValue(FOCUSING_EDITOR);
+
+ if (isCellEditorFocus) {
+ return commandService.executeCommand(SetInlineFormatUnderlineCommand.id);
+ }
+
+ return commandService.executeCommand(SetUnderlineCommand.id);
+ },
+};
+
+export const SetRangeStrickThroughCommand: ICommand = {
+ type: CommandType.COMMAND,
+ id: 'sheet.command.set-range-stroke',
+ handler: async (accessor) => {
+ const commandService = accessor.get(ICommandService);
+ const contextService = accessor.get(IContextService);
+ const isCellEditorFocus = contextService.getContextValue(FOCUSING_EDITOR);
+
+ if (isCellEditorFocus) {
+ return commandService.executeCommand(SetInlineFormatStrikethroughCommand.id);
+ }
+
+ return commandService.executeCommand(SetStrikeThroughCommand.id);
+ },
+};
+
+export const SetRangeFontSizeCommand: ICommand = {
+ type: CommandType.COMMAND,
+ id: 'sheet.command.set-range-fontsize',
+ handler: async (accessor, params) => {
+ const commandService = accessor.get(ICommandService);
+ const contextService = accessor.get(IContextService);
+ const isCellEditorFocus = contextService.getContextValue(FOCUSING_EDITOR);
+
+ if (isCellEditorFocus) {
+ return commandService.executeCommand(SetInlineFormatFontSizeCommand.id, params);
+ }
+
+ return commandService.executeCommand(SetFontSizeCommand.id, params);
+ },
+};
+
+export const SetRangeFontFamilyCommand: ICommand = {
+ type: CommandType.COMMAND,
+ id: 'sheet.command.set-range-font-family',
+ handler: async (accessor, params) => {
+ const commandService = accessor.get(ICommandService);
+ const contextService = accessor.get(IContextService);
+ const isCellEditorFocus = contextService.getContextValue(FOCUSING_EDITOR);
+
+ if (isCellEditorFocus) {
+ return commandService.executeCommand(SetInlineFormatFontFamilyCommand.id, params);
+ }
+
+ return commandService.executeCommand(SetFontFamilyCommand.id, params);
+ },
+};
+
+export const SetRangeTextColorCommand: ICommand = {
+ type: CommandType.COMMAND,
+ id: 'sheet.command.set-range-text-color',
+ handler: async (accessor, params) => {
+ const commandService = accessor.get(ICommandService);
+ const contextService = accessor.get(IContextService);
+ const isCellEditorFocus = contextService.getContextValue(FOCUSING_EDITOR);
+
+ if (isCellEditorFocus) {
+ return commandService.executeCommand(SetInlineFormatTextColorCommand.id, params);
+ }
+
+ return commandService.executeCommand(SetTextColorCommand.id, params);
+ },
+};
diff --git a/packages/ui-plugin-sheets/src/controllers/editor-bridge.controller.ts b/packages/ui-plugin-sheets/src/controllers/editor-bridge.controller.ts
index 232c39dbd4..f3602c2111 100644
--- a/packages/ui-plugin-sheets/src/controllers/editor-bridge.controller.ts
+++ b/packages/ui-plugin-sheets/src/controllers/editor-bridge.controller.ts
@@ -140,7 +140,6 @@ export class EditorBridgeController extends Disposable {
spreadsheet.onDblclickObserver.add(() => {
// this._editorBridgeService.show(DeviceInputEventType.Dblclick);
-
this._commandService.executeCommand(SetCellEditVisibleOperation.id, {
visible: true,
eventType: DeviceInputEventType.Dblclick,
diff --git a/packages/ui-plugin-sheets/src/controllers/editor/end-edit.controller.ts b/packages/ui-plugin-sheets/src/controllers/editor/end-edit.controller.ts
index 1e8e1bb3b8..c1486309d8 100644
--- a/packages/ui-plugin-sheets/src/controllers/editor/end-edit.controller.ts
+++ b/packages/ui-plugin-sheets/src/controllers/editor/end-edit.controller.ts
@@ -25,6 +25,7 @@ import {
Nullable,
Observer,
OnLifecycle,
+ Tools,
} from '@univerjs/core';
import { Inject } from '@wendellhu/redi';
import { Subscription } from 'rxjs';
@@ -93,7 +94,7 @@ export class EndEditController extends Disposable {
private _initialExitInput() {
this._onInputSubscription = this._editorBridgeService.visible$.subscribe((param) => {
- const { visible, keycode, eventType } = param;
+ const { visible, keycode } = param;
if (visible === this._editorVisiblePrevious) {
return;
@@ -136,7 +137,7 @@ export class EndEditController extends Disposable {
return;
}
- const cellData: ICellData = worksheet.getCell(row, column) || {};
+ const cellData: ICellData = Tools.deepClone(worksheet.getCell(row, column) || {});
const documentModel = documentLayoutObject.documentModel as DocumentModel;
@@ -161,6 +162,7 @@ export class EndEditController extends Disposable {
}
cellData.v = newDataStream;
+ cellData.m = newDataStream;
}
this._commandService.executeCommand(SetRangeValuesCommand.id, {
diff --git a/packages/ui-plugin-sheets/src/controllers/editor/initialize-editor.controller.ts b/packages/ui-plugin-sheets/src/controllers/editor/initialize-editor.controller.ts
index 6b7e657268..4a983cca3c 100644
--- a/packages/ui-plugin-sheets/src/controllers/editor/initialize-editor.controller.ts
+++ b/packages/ui-plugin-sheets/src/controllers/editor/initialize-editor.controller.ts
@@ -17,6 +17,7 @@ export class InitializeEditorController extends Disposable {
) {
super();
+ // TODO: @JOCS, remove use setTimeout.
setTimeout(() => {
this._initialize();
}, 0);
diff --git a/packages/ui-plugin-sheets/src/controllers/editor/start-edit.controller.ts b/packages/ui-plugin-sheets/src/controllers/editor/start-edit.controller.ts
index e94366dd35..90c71c9d79 100644
--- a/packages/ui-plugin-sheets/src/controllers/editor/start-edit.controller.ts
+++ b/packages/ui-plugin-sheets/src/controllers/editor/start-edit.controller.ts
@@ -208,6 +208,7 @@ export class StartEditController extends Disposable {
} else {
// Set the top margin under vertical alignment.
let offsetTop = paddingData.t || 0;
+
if (verticalAlign === VerticalAlign.MIDDLE) {
offsetTop = (editorHeight - actualHeight) / 2;
} else if (verticalAlign === VerticalAlign.BOTTOM) {
@@ -367,6 +368,7 @@ export class StartEditController extends Disposable {
private _addBackground(scene: Scene, editorWidth: number, editorHeight: number, fill?: Nullable<string>) {
const fillRectKey = '_backgroundRectHelperColor_';
const rect = scene.getObject(fillRectKey) as Rect;
+
if (rect == null && fill == null) {
return;
}
@@ -389,6 +391,7 @@ export class StartEditController extends Disposable {
rect.setProps({
fill,
});
+
rect.transformByState({
width: editorWidth,
height: editorHeight,
@@ -411,6 +414,7 @@ export class StartEditController extends Disposable {
}
const state = this._editorBridgeService.getState();
+
if (state == null) {
return;
}
@@ -448,6 +452,7 @@ export class StartEditController extends Disposable {
document.makeDirty();
+ // @JOCS, Why calculate here?
if (keycode === KeyCode.BACKSPACE) {
skeleton.calculate();
}
@@ -462,6 +467,7 @@ export class StartEditController extends Disposable {
},
]);
} else {
+ // TODO: @JOCS, Get the position close to the cursor after clicking on the cell.
const cursor = documentModel.getBodyModel().getLastIndex() - 1 || 0;
scene.getViewport(VIEWPORT_KEY.VIEW_MAIN)?.scrollTo({
diff --git a/packages/ui-plugin-sheets/src/controllers/menu/menu.ts b/packages/ui-plugin-sheets/src/controllers/menu/menu.ts
index 85b6d8f681..89e801409e 100644
--- a/packages/ui-plugin-sheets/src/controllers/menu/menu.ts
+++ b/packages/ui-plugin-sheets/src/controllers/menu/menu.ts
@@ -18,15 +18,11 @@ import {
ResetTextColorCommand,
SelectionManagerService,
SetBackgroundColorCommand,
- SetBoldCommand,
SetColHiddenCommand,
SetColHiddenMutation,
SetColVisibleMutation,
SetColWidthCommand,
- SetFontFamilyCommand,
- SetFontSizeCommand,
SetHorizontalTextAlignCommand,
- SetItalicCommand,
SetRangeStyleMutation,
SetRangeValuesMutation,
SetRowHeightCommand,
@@ -36,12 +32,9 @@ import {
SetSelectedColsVisibleCommand,
SetSelectedRowsVisibleCommand,
SetSelectionsOperation,
- SetStrikeThroughCommand,
SetTabColorCommand,
- SetTextColorCommand,
SetTextRotationCommand,
SetTextWrapCommand,
- SetUnderlineCommand,
SetVerticalTextAlignCommand,
SetWorksheetHideCommand,
SetWorksheetRowIsAutoHeightCommand,
@@ -70,6 +63,15 @@ import {
import { IAccessor } from '@wendellhu/redi';
import { Observable } from 'rxjs';
+import {
+ SetRangeBoldCommand,
+ SetRangeFontFamilyCommand,
+ SetRangeFontSizeCommand,
+ SetRangeItalicCommand,
+ SetRangeStrickThroughCommand,
+ SetRangeTextColorCommand,
+ SetRangeUnderlineCommand,
+} from '../../commands/commands/inline-format.command';
import { RenameSheetOperation } from '../../commands/commands/rename.command';
import {
SetInfiniteFormatPainterCommand,
@@ -125,7 +127,7 @@ export function BoldMenuItemFactory(accessor: IAccessor): IMenuButtonItem {
const selectionManagerService = accessor.get(SelectionManagerService);
return {
- id: SetBoldCommand.id,
+ id: SetRangeBoldCommand.id,
type: MenuItemType.BUTTON,
icon: 'BoldSingle',
title: 'Set bold',
@@ -160,6 +162,7 @@ export function BoldMenuItemFactory(accessor: IAccessor): IMenuButtonItem {
const primary = selectionManagerService.getLast()?.primary;
const worksheet = univerInstanceService.getCurrentUniverSheetInstance().getActiveSheet();
let isBold = FontWeight.NORMAL;
+
if (primary != null) {
const range = worksheet.getRange(primary.startRow, primary.startColumn);
isBold = range?.getFontWeight();
@@ -169,6 +172,7 @@ export function BoldMenuItemFactory(accessor: IAccessor): IMenuButtonItem {
});
subscriber.next(false);
+
return disposable.dispose;
}),
};
@@ -181,7 +185,7 @@ export function ItalicMenuItemFactory(accessor: IAccessor): IMenuButtonItem {
const selectionManagerService = accessor.get(SelectionManagerService);
return {
- id: SetItalicCommand.id,
+ id: SetRangeItalicCommand.id,
type: MenuItemType.BUTTON,
icon: 'ItalicSingle',
title: 'Set italic',
@@ -239,7 +243,7 @@ export function UnderlineMenuItemFactory(accessor: IAccessor): IMenuButtonItem {
const selectionManagerService = accessor.get(SelectionManagerService);
return {
- id: SetUnderlineCommand.id,
+ id: SetRangeUnderlineCommand.id,
type: MenuItemType.BUTTON,
icon: 'UnderlineSingle',
title: 'Set underline',
@@ -297,7 +301,7 @@ export function StrikeThroughMenuItemFactory(accessor: IAccessor): IMenuButtonIt
const selectionManagerService = accessor.get(SelectionManagerService);
return {
- id: SetStrikeThroughCommand.id,
+ id: SetRangeStrickThroughCommand.id,
type: MenuItemType.BUTTON,
icon: 'StrikethroughSingle',
title: 'Set strike through',
@@ -490,7 +494,7 @@ export function FontFamilySelectorMenuItemFactory(accessor: IAccessor): IMenuSel
const selectionManagerService = accessor.get(SelectionManagerService);
return {
- id: SetFontFamilyCommand.id,
+ id: SetRangeFontFamilyCommand.id,
tooltip: 'toolbar.font',
type: MenuItemType.SELECTOR,
@@ -552,7 +556,7 @@ export function FontSizeSelectorMenuItemFactory(accessor: IAccessor): IMenuSelec
const selectionManagerService = accessor.get(SelectionManagerService);
return {
- id: SetFontSizeCommand.id,
+ id: SetRangeFontSizeCommand.id,
tooltip: 'toolbar.fontSize',
type: MenuItemType.SELECTOR,
label: {
@@ -616,7 +620,7 @@ export function ResetTextColorMenuItemFactory(): IMenuButtonItem {
id: ResetTextColorCommand.id,
type: MenuItemType.BUTTON,
title: 'toolbar.resetColor',
- positions: SetTextColorCommand.id,
+ positions: SetRangeTextColorCommand.id,
};
}
@@ -624,7 +628,7 @@ export function TextColorSelectorMenuItemFactory(accessor: IAccessor): IMenuSele
const commandService = accessor.get(ICommandService);
return {
- id: SetTextColorCommand.id,
+ id: SetRangeTextColorCommand.id,
icon: 'FontColor',
tooltip: 'toolbar.textColor.main',
type: MenuItemType.SELECTOR,
@@ -637,7 +641,7 @@ export function TextColorSelectorMenuItemFactory(accessor: IAccessor): IMenuSele
value$: new Observable<string>((subscriber) => {
const defaultColor = '#000';
const disposable = commandService.onCommandExecuted((c) => {
- if (c.id === SetTextColorCommand.id) {
+ if (c.id === SetRangeTextColorCommand.id) {
const color = (c.params as { value: string }).value;
subscriber.next(color ?? defaultColor);
}
diff --git a/packages/ui-plugin-sheets/src/controllers/selection.controller.ts b/packages/ui-plugin-sheets/src/controllers/selection.controller.ts
index 1b1eb582ec..df024512cf 100644
--- a/packages/ui-plugin-sheets/src/controllers/selection.controller.ts
+++ b/packages/ui-plugin-sheets/src/controllers/selection.controller.ts
@@ -89,12 +89,14 @@ export class SelectionController extends Disposable {
toDisposable(
spreadsheet?.onPointerDownObserver.add((evt: IPointerEvent | IMouseEvent, state) => {
this._selectionRenderService.enableDetectMergedCell();
+
this._selectionRenderService.eventTrigger(
evt,
spreadsheet.zIndex + 1,
RANGE_TYPE.NORMAL,
viewportMain
);
+
if (evt.button !== 2) {
state.stopPropagation();
}
diff --git a/packages/ui-plugin-sheets/src/controllers/sheet-ui.controller.ts b/packages/ui-plugin-sheets/src/controllers/sheet-ui.controller.ts
index 1a2162d199..f2dbecb3e1 100644
--- a/packages/ui-plugin-sheets/src/controllers/sheet-ui.controller.ts
+++ b/packages/ui-plugin-sheets/src/controllers/sheet-ui.controller.ts
@@ -19,6 +19,15 @@ import { Disposable, ICommandService, LifecycleStages, OnLifecycle } from '@univ
import { Inject, Injector } from '@wendellhu/redi';
import { connectInjector } from '@wendellhu/redi/react-bindings';
+import {
+ SetRangeBoldCommand,
+ SetRangeFontFamilyCommand,
+ SetRangeFontSizeCommand,
+ SetRangeItalicCommand,
+ SetRangeStrickThroughCommand,
+ SetRangeTextColorCommand,
+ SetRangeUnderlineCommand,
+} from '../commands/commands/inline-format.command';
import { RenameSheetOperation } from '../commands/commands/rename.command';
import {
SetCopySelectionCommand,
@@ -198,17 +207,24 @@ export class SheetUIController extends Disposable {
SetCellEditVisibleOperation,
SetCopySelectionCommand,
SetCopySelectionsOperation,
+ SetRangeBoldCommand,
+ SetRangeItalicCommand,
+ SetRangeUnderlineCommand,
+ SetRangeStrickThroughCommand,
+ SetRangeFontSizeCommand,
+ SetRangeFontFamilyCommand,
+ SetRangeTextColorCommand,
+ SetItalicCommand,
+ SetStrikeThroughCommand,
SetFontFamilyCommand,
SetFontSizeCommand,
SetFormatPainterOperation,
SetInfiniteFormatPainterCommand,
- SetItalicCommand,
SetOnceFormatPainterCommand,
SetScrollOperation,
SetScrollRelativeCommand,
SetSelectionFrozenCommand,
SetSelectionsOperation,
- SetStrikeThroughCommand,
SetUnderlineCommand,
SetZoomRatioCommand,
SetZoomRatioOperation,
diff --git a/packages/ui-plugin-sheets/src/services/editor-bridge.service.ts b/packages/ui-plugin-sheets/src/services/editor-bridge.service.ts
index 5505b4be02..7f2193a583 100644
--- a/packages/ui-plugin-sheets/src/services/editor-bridge.service.ts
+++ b/packages/ui-plugin-sheets/src/services/editor-bridge.service.ts
@@ -66,24 +66,6 @@ export class EditorBridgeService implements IEditorBridgeService, IDisposable {
this._visible$.next(this._visible);
}
- // show(eventType = DeviceInputEventType.Dblclick) {
- // this._visible = {
- // visible: true,
- // eventType,
- // };
-
- // this._visible$.next(this._visible);
- // }
-
- // hide() {
- // this._visible = {
- // visible: false,
- // eventType: this._visible.eventType,
- // };
-
- // this._visible$.next(this._visible);
- // }
-
isVisible() {
return this._visible;
}