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(doc): set bold in selection (#346)

Ran Luoc276ef93cd7b
diff --git a/examples/univer-sheet-ts/tsconfig.json b/examples/univer-sheet-ts/tsconfig.json
index f946383d48..d4b3f58716 100644
--- a/examples/univer-sheet-ts/tsconfig.json
+++ b/examples/univer-sheet-ts/tsconfig.json
@@ -8,10 +8,7 @@
"baseUrl": "./",
"esModuleInterop": true, // auto allowSyntheticDefaultImports true
"emitDecoratorMetadata": true,
- "strictPropertyInitialization": false,
+ "strictPropertyInitialization": false
},
- "include": [
- "src/**/*",
- "test/**/*.test.(ts|tsx|js)"
- ]
-}
\ No newline at end of file
+ "include": ["src/**/*", "test/**/*.test.(ts|tsx|js)"]
+}
diff --git a/packages/base-docs/src/Basics/memoryCursor.ts b/packages/base-docs/src/Basics/memoryCursor.ts
new file mode 100644
index 0000000000..0387ac2386
--- /dev/null
+++ b/packages/base-docs/src/Basics/memoryCursor.ts
@@ -0,0 +1,14 @@
+class MemoryCursor {
+ cursor: number = 0;
+
+ reset() {
+ this.cursor = 0;
+ return this;
+ }
+
+ moveCursor(pos: number) {
+ this.cursor += pos;
+ }
+}
+
+export default MemoryCursor;
diff --git a/packages/base-docs/src/Controller/delete-left-input.controller.ts b/packages/base-docs/src/Controller/delete-left-input.controller.ts
index 2440f11b12..ed661c540c 100644
--- a/packages/base-docs/src/Controller/delete-left-input.controller.ts
+++ b/packages/base-docs/src/Controller/delete-left-input.controller.ts
@@ -83,7 +83,7 @@ export class DeleteLeftInputController extends Disposable {
const preIsIndent = isIndentBySpan(preSpan, docsModel.body);
- const { cursorStart, cursorEnd, isCollapse, isEndBack, isStartBack, segmentId, style } = activeRange;
+ const { cursorStart, isCollapse, isStartBack, segmentId, style } = activeRange;
let cursor = cursorStart;
@@ -99,6 +99,7 @@ export class DeleteLeftInputController extends Disposable {
const isUpdateParagraph =
isFirstSpan(preSpan) && span !== preSpan && (preIsBullet === true || preIsIndent === true);
+
if (isUpdateParagraph) {
const paragraph = getParagraphBySpan(preSpan, docsModel.body);
@@ -111,6 +112,7 @@ export class DeleteLeftInputController extends Disposable {
const updateParagraph: IParagraph = { startIndex: 0 };
const paragraphStyle = paragraph.paragraphStyle;
+
if (preIsBullet === true) {
const paragraphStyle = paragraph.paragraphStyle;
if (paragraphStyle) {
diff --git a/packages/base-docs/src/Controller/doc-render.controller.ts b/packages/base-docs/src/Controller/doc-render.controller.ts
index ffef21611d..61f94dbf43 100644
--- a/packages/base-docs/src/Controller/doc-render.controller.ts
+++ b/packages/base-docs/src/Controller/doc-render.controller.ts
@@ -177,6 +177,8 @@ export class DocRenderController extends Disposable {
return;
}
+ skeleton.calculate();
+
if (excludeUnitList.includes(unitId)) {
currentRender.mainComponent?.makeDirty();
return;
diff --git a/packages/base-docs/src/Controller/ime-input.controller.ts b/packages/base-docs/src/Controller/ime-input.controller.ts
index b6c805cf09..d760462dc3 100644
--- a/packages/base-docs/src/Controller/ime-input.controller.ts
+++ b/packages/base-docs/src/Controller/ime-input.controller.ts
@@ -67,6 +67,7 @@ export class IMEInputController extends Disposable {
if (config == null) {
return;
}
+
const { activeRange } = config;
if (activeRange == null) {
@@ -89,8 +90,7 @@ export class IMEInputController extends Disposable {
const { event, activeRange } = config;
- const { cursorStart, cursorEnd, isCollapse, isEndBack, isStartBack, segmentId, style } =
- this._previousIMERange;
+ const { cursorStart, cursorEnd, isEndBack, isStartBack, segmentId, style } = this._previousIMERange;
if (skeleton == null || activeRange == null) {
return;
diff --git a/packages/base-docs/src/Controller/inline-format.controller.ts b/packages/base-docs/src/Controller/inline-format.controller.ts
new file mode 100644
index 0000000000..9b39b98f48
--- /dev/null
+++ b/packages/base-docs/src/Controller/inline-format.controller.ts
@@ -0,0 +1,176 @@
+import { ITextSelectionRangeWithStyle, 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 { TextSelectionManagerService } from '../services/text-selection-manager.service';
+
+/**
+ * Used to manage the addition and removal of inline styles,
+ * and to assemble the command parameters here,
+ * some of the logic may be moved to the command, as the command is testable.
+ */
+@OnLifecycle(LifecycleStages.Rendered, InlineFormatController)
+export class InlineFormatController extends Disposable {
+ constructor(
+ @IUniverInstanceService private readonly _currentUniverService: IUniverInstanceService,
+ @ITextSelectionRenderManager private readonly _textSelectionRenderManager: ITextSelectionRenderManager,
+ @Inject(TextSelectionManagerService) private readonly _textSelectionManagerService: TextSelectionManagerService,
+ @ICommandService private readonly _commandService: ICommandService
+ ) {
+ super();
+
+ this._commandExecutedListener();
+ }
+
+ private _commandExecutedListener() {
+ const updateCommandList = [SetInlineFormatBoldCommand.id];
+
+ this.disposeWithMe(
+ this._commandService.onCommandExecuted((command: ICommandInfo) => {
+ if (!updateCommandList.includes(command.id)) {
+ return;
+ }
+
+ this.handleInlineFormat(command);
+ })
+ );
+ }
+
+ private handleInlineFormat(command: ICommandInfo) {
+ const segmentId = this._textSelectionRenderManager.getActiveRange()?.segmentId;
+ const selections = this._textSelectionManagerService.getSelections();
+
+ if (segmentId == null || !Array.isArray(selections) || selections.length === 0) {
+ 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,
+ });
+
+ const REFRESH_SELECTION_COMMAND_LIST = [SetInlineFormatBoldCommand.id];
+
+ 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/Controller/normal-input.controller.ts b/packages/base-docs/src/Controller/normal-input.controller.ts
index 7e63448a2d..457ac9bc9e 100644
--- a/packages/base-docs/src/Controller/normal-input.controller.ts
+++ b/packages/base-docs/src/Controller/normal-input.controller.ts
@@ -64,7 +64,7 @@ export class NormalInputController extends Disposable {
return;
}
- const { cursorStart, cursorEnd, isCollapse, isEndBack, isStartBack, segmentId, style } = activeRange;
+ const { cursorStart, isEndBack, isStartBack, segmentId, style } = activeRange;
await this._commandService.executeCommand(InsertCommand.id, {
unitId: documentModel.getUnitId(),
diff --git a/packages/base-docs/src/DocPlugin.ts b/packages/base-docs/src/DocPlugin.ts
index 1f9fee8a5a..93dda802fb 100644
--- a/packages/base-docs/src/DocPlugin.ts
+++ b/packages/base-docs/src/DocPlugin.ts
@@ -21,6 +21,7 @@ import {
InsertCommand,
UpdateCommand,
} from './commands/commands/core-editing.command';
+import { SetInlineFormatBoldCommand, SetInlineFormatCommand } 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';
@@ -29,6 +30,7 @@ import { SetTextSelectionsOperation } from './commands/operations/text-selection
import { DeleteLeftInputController } from './Controller/delete-left-input.controller';
import { DocRenderController } from './Controller/doc-render.controller';
import { IMEInputController } from './Controller/ime-input.controller';
+import { InlineFormatController } from './Controller/inline-format.controller';
import { LineBreakInputController } from './Controller/line-break-input.controller';
import { MoveCursorController } from './Controller/move-cursor.controller';
import { NormalInputController } from './Controller/normal-input.controller';
@@ -96,6 +98,8 @@ export class DocPlugin extends Plugin {
[
MoveCursorOperation,
DeleteLeftCommand,
+ SetInlineFormatBoldCommand,
+ SetInlineFormatCommand,
BreakLineCommand,
InsertCommand,
DeleteCommand,
@@ -174,6 +178,7 @@ export class DocPlugin extends Plugin {
[NormalInputController],
[IMEInputController],
[DeleteLeftInputController],
+ [InlineFormatController],
[LineBreakInputController],
[MoveCursorController],
[ZoomController],
diff --git a/packages/base-docs/src/commands/commands/__tests__/core-editing.command.spec.ts b/packages/base-docs/src/commands/commands/__tests__/core-editing.command.spec.ts
new file mode 100644
index 0000000000..594fe784d5
--- /dev/null
+++ b/packages/base-docs/src/commands/commands/__tests__/core-editing.command.spec.ts
@@ -0,0 +1,31 @@
+/* eslint-disable no-magic-numbers */
+
+import { ICommandService, Univer } from '@univerjs/core';
+import { Injector } from '@wendellhu/redi';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { SetInlineFormatBoldCommand } from '../inline-format.command';
+import { createCommandTestBed } from './create-command-test-bed';
+
+describe('example', () => {
+ let univer: Univer;
+ let get: Injector['get'];
+ let commandService: ICommandService;
+
+ beforeEach(() => {
+ const testBed = createCommandTestBed();
+ univer = testBed.univer;
+ get = testBed.get;
+
+ commandService = get(ICommandService);
+ commandService.registerCommand(SetInlineFormatBoldCommand);
+ });
+
+ afterEach(() => univer.dispose());
+
+ describe('XXX', () => {
+ it('Should XXX', async () => {
+ expect(true).toBe(true);
+ });
+ });
+});
diff --git a/packages/base-docs/src/commands/commands/__tests__/create-command-test-bed.ts b/packages/base-docs/src/commands/commands/__tests__/create-command-test-bed.ts
new file mode 100644
index 0000000000..00093332a0
--- /dev/null
+++ b/packages/base-docs/src/commands/commands/__tests__/create-command-test-bed.ts
@@ -0,0 +1,97 @@
+import {
+ BooleanNumber,
+ IDocumentData,
+ ILogService,
+ IUniverInstanceService,
+ Plugin,
+ PluginType,
+ Univer,
+} from '@univerjs/core';
+import { Dependency, Inject, Injector } from '@wendellhu/redi';
+
+import { TextSelectionManagerService } from '../../../services/text-selection-manager.service';
+
+const TEST_DOCUMENT_DATA_EN: IDocumentData = {
+ id: 'test-doc',
+ body: {
+ dataStream: 'What’s New in the 2022 Gartner Hype Cycle for Emerging Technologies\r\n',
+ textRuns: [
+ {
+ st: 0,
+ ed: 67,
+ ts: {
+ bl: BooleanNumber.FALSE,
+ fs: 24,
+ cl: {
+ rgb: 'rgb(0, 40, 86)',
+ },
+ },
+ },
+ ],
+ paragraphs: [],
+ sectionBreaks: [],
+ customBlocks: [],
+ },
+ documentStyle: {
+ pageSize: {
+ width: 594.3,
+ height: 840.51,
+ },
+ marginTop: 72,
+ marginBottom: 72,
+ marginRight: 90,
+ marginLeft: 90,
+ },
+};
+
+export function createCommandTestBed(workbookConfig?: IDocumentData, dependencies?: Dependency[]) {
+ const univer = new Univer();
+
+ let get: Injector['get'] | undefined;
+
+ /**
+ * This plugin hooks into Doc's DI system to expose API to test scripts
+ */
+ class TestSpyPlugin extends Plugin {
+ static override type = PluginType.Univer;
+
+ constructor(
+ _config: undefined,
+ @Inject(Injector) override readonly _injector: Injector
+ ) {
+ super('test-plugin');
+
+ this._injector = _injector;
+ get = this._injector.get.bind(this._injector);
+ }
+
+ override onStarting(injector: Injector): void {
+ injector.add([TextSelectionManagerService]);
+
+ dependencies?.forEach((d) => injector.add(d));
+ }
+
+ override onDestroy(): void {
+ get = undefined;
+ }
+ }
+
+ univer.registerPlugin(TestSpyPlugin);
+ const doc = univer.createUniverDoc(workbookConfig || TEST_DOCUMENT_DATA_EN);
+
+ if (get === undefined) {
+ throw new Error('[TestPlugin]: not hooked on!');
+ }
+
+ const univerInstanceService = get(IUniverInstanceService);
+ univerInstanceService.focusUniverInstance('test-doc');
+
+ const logService = get(ILogService);
+ logService.toggleLogEnabled(false); // change this to `true` to debug tests via logs
+
+ return {
+ univer,
+ get,
+ doc,
+ };
+}
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
new file mode 100644
index 0000000000..02ec7de937
--- /dev/null
+++ b/packages/base-docs/src/commands/commands/__tests__/inline-format.command.spec.ts
@@ -0,0 +1,118 @@
+/* eslint-disable no-magic-numbers */
+
+import {
+ BooleanNumber,
+ ICommand,
+ ICommandService,
+ IUniverInstanceService,
+ RedoCommand,
+ UndoCommand,
+ Univer,
+} from '@univerjs/core';
+import { Injector } from '@wendellhu/redi';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { RichTextEditingMutation } from '../../mutations/core-editing.mutation';
+import { SetInlineFormatCommand } from '../inline-format.command';
+import { createCommandTestBed } from './create-command-test-bed';
+
+describe('Test inline format commands', () => {
+ let univer: Univer;
+ let get: Injector['get'];
+ let commandService: ICommandService;
+
+ function getFormatValueAt(key: 'bl', pos: number) {
+ const univerInstanceService = get(IUniverInstanceService);
+ const docsModel = univerInstanceService.getUniverDocInstance('test-doc');
+
+ if (docsModel?.body?.textRuns == null) {
+ return null;
+ }
+
+ for (const textRun of docsModel.body?.textRuns) {
+ const { st, ed, ts = {} } = textRun;
+
+ if (st <= pos && ed >= pos) {
+ return ts[key] ?? null;
+ }
+ }
+
+ return null;
+ }
+
+ beforeEach(() => {
+ const testBed = createCommandTestBed();
+ univer = testBed.univer;
+ 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: '',
+ // },
+ // ]);
+ });
+
+ afterEach(() => univer.dispose());
+
+ describe('Set Bold by SetInlineFormatBoldCommand', () => {
+ 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: '',
+ },
+ ],
+ },
+ },
+ };
+
+ await commandService.executeCommand(SetInlineFormatCommand.id, doMutation);
+
+ expect(getFormatValueAt('bl', 1)).toBe(BooleanNumber.TRUE);
+
+ await commandService.executeCommand(UndoCommand.id);
+ expect(getFormatValueAt('bl', 1)).toBe(BooleanNumber.FALSE);
+
+ await commandService.executeCommand(RedoCommand.id);
+ expect(getFormatValueAt('bl', 1)).toBe(BooleanNumber.TRUE);
+ });
+ });
+});
diff --git a/packages/base-docs/src/commands/commands/core-editing.command.ts b/packages/base-docs/src/commands/commands/core-editing.command.ts
index 8b1a53e4f6..ee992b3e20 100644
--- a/packages/base-docs/src/commands/commands/core-editing.command.ts
+++ b/packages/base-docs/src/commands/commands/core-editing.command.ts
@@ -56,7 +56,7 @@ export const InsertCommand: ICommand<IInsertCommandParams> = {
const commandService = accessor.get(ICommandService);
const { range, segmentId, body, unitId } = params;
- const { cursorStart, cursorEnd, isEndBack, isStartBack, isCollapse } = range;
+ const { cursorStart, isStartBack, isCollapse } = range;
const textStart = getTextIndexByCursor(cursorStart, isStartBack);
const doMutation: ICommandInfo<IRichTextEditingMutationParams> = {
@@ -66,6 +66,7 @@ export const InsertCommand: ICommand<IInsertCommandParams> = {
mutations: [],
},
};
+
if (isCollapse) {
doMutation.params!.mutations.push({
t: 'r',
@@ -75,6 +76,7 @@ export const InsertCommand: ICommand<IInsertCommandParams> = {
} else {
doMutation.params!.mutations.push(...getRetainAndDeleteFromReplace(range, segmentId));
}
+
doMutation.params!.mutations.push({
t: 'i',
body,
@@ -92,11 +94,11 @@ export const InsertCommand: ICommand<IInsertCommandParams> = {
};
// TODO@wzhudev: prepare undo mutation
-
const result = commandService.syncExecuteCommand<
IRichTextEditingMutationParams,
IRichTextEditingMutationParams
>(doMutation.id, doMutation.params);
+
if (result) {
undoRedoService.pushUndoRedo({
URI: unitId,
@@ -186,10 +188,10 @@ export const UpdateCommand: ICommand<IUpdateCommandParams> = {
throw new Error();
}
+ const { range, segmentId, updateBody, coverType, unitId } = params;
const commandService = accessor.get(ICommandService);
const undoRedoService = accessor.get(IUndoRedoService);
- const { range, segmentId, updateBody, coverType, unitId } = params;
const doMutation: ICommandInfo<IRichTextEditingMutationParams> = {
id: RichTextEditingMutation.id,
params: {
@@ -198,7 +200,7 @@ export const UpdateCommand: ICommand<IUpdateCommandParams> = {
},
};
- const { cursorStart, cursorEnd, isEndBack, isStartBack, isCollapse } = range;
+ const { cursorStart, cursorEnd, isEndBack, isStartBack } = range;
const textStart = getTextIndexByCursor(cursorStart, isStartBack);
const textEnd = getTextIndexByCursor(cursorEnd, isEndBack);
@@ -220,11 +222,12 @@ export const UpdateCommand: ICommand<IUpdateCommandParams> = {
IRichTextEditingMutationParams,
IRichTextEditingMutationParams
>(doMutation.id, doMutation.params);
+
if (result) {
undoRedoService.pushUndoRedo({
URI: unitId,
undo() {
- return commandService.syncExecuteCommand(RichTextEditingMutation.id, result);
+ commandService.syncExecuteCommand(RichTextEditingMutation.id, result);
return true;
},
redo() {
@@ -252,9 +255,9 @@ export const IMEInputCommand: ICommand<IIMEInputCommandParams> = {
id: 'doc.command.ime-input',
type: CommandType.COMMAND,
handler: async (accessor, params: IIMEInputCommandParams) => {
+ const { unitId, newText, oldTextLen, range, segmentId } = params;
const commandService = accessor.get(ICommandService);
- const { unitId, newText, oldTextLen, range, segmentId } = params;
const doMutation: ICommandInfo<IRichTextEditingMutationParams> = {
id: RichTextEditingMutation.id,
params: {
@@ -314,9 +317,10 @@ export const CoverCommand: ICommand<ICoverCommandParams> = {
id: 'doc.command-cover-content',
type: CommandType.COMMAND,
handler: async (accessor, params: ICoverCommandParams) => {
- const univerInstanceService = accessor.get(IUniverInstanceService);
const { unitId, snapshot, clearUndoRedoStack } = params;
+ const univerInstanceService = accessor.get(IUniverInstanceService);
const doc = univerInstanceService.getUniverDocInstance(unitId);
+
if (!doc) {
return false;
}
diff --git a/packages/base-docs/src/commands/commands/inline-format.command.ts b/packages/base-docs/src/commands/commands/inline-format.command.ts
new file mode 100644
index 0000000000..f183b98dc2
--- /dev/null
+++ b/packages/base-docs/src/commands/commands/inline-format.command.ts
@@ -0,0 +1,46 @@
+import { CommandType, ICommand, ICommandInfo, ICommandService, IUndoRedoService } from '@univerjs/core';
+
+import { IRichTextEditingMutationParams, RichTextEditingMutation } from '../mutations/core-editing.mutation';
+
+export const SetInlineFormatBoldCommand: ICommand = {
+ id: 'doc.command.set-inline-format-bold',
+ type: CommandType.COMMAND,
+ handler: async () => true,
+};
+
+export const SetInlineFormatCommand: ICommand = {
+ id: 'doc.command.set-inline-format',
+ type: CommandType.COMMAND,
+ handler: async (
+ accessor,
+ params: {
+ unitId: string;
+ doMutation: ICommandInfo<IRichTextEditingMutationParams>;
+ }
+ ) => {
+ const undoRedoService = accessor.get(IUndoRedoService);
+ const commandService = accessor.get(ICommandService);
+ const { unitId, doMutation } = params;
+
+ const result = commandService.syncExecuteCommand<
+ IRichTextEditingMutationParams,
+ IRichTextEditingMutationParams
+ >(doMutation.id, doMutation.params);
+
+ if (result) {
+ undoRedoService.pushUndoRedo({
+ URI: unitId,
+ undo() {
+ return commandService.syncExecuteCommand(RichTextEditingMutation.id, result);
+ },
+ redo() {
+ return commandService.syncExecuteCommand(doMutation.id, doMutation.params);
+ },
+ });
+
+ return true;
+ }
+
+ return false;
+ },
+};
diff --git a/packages/base-docs/src/commands/mutations/core-editing.mutation.ts b/packages/base-docs/src/commands/mutations/core-editing.mutation.ts
index 5692f74f72..0412ae37f1 100644
--- a/packages/base-docs/src/commands/mutations/core-editing.mutation.ts
+++ b/packages/base-docs/src/commands/mutations/core-editing.mutation.ts
@@ -1,5 +1,13 @@
-import { CommandType, IDocumentBody, IMutation, IUniverInstanceService, UpdateDocsAttributeType } from '@univerjs/core';
+import {
+ CommandType,
+ IDocumentBody,
+ IMutation,
+ IUniverInstanceService,
+ Tools,
+ UpdateDocsAttributeType,
+} from '@univerjs/core';
+import MemoryCursor from '../../Basics/memoryCursor';
import { DeleteApply } from './functions/delete-apply';
import { InsertApply } from './functions/insert-apply';
import { UpdateAttributeApply } from './functions/update-apply';
@@ -58,37 +66,48 @@ export const RichTextEditingMutation: IMutation<IRichTextEditingMutationParams,
}
const undoMutations: Array<IRetainMutationParams | IInsertMutationParams | IDeleteMutationParams> = [];
- const commonParameter = new CommonParameter();
- commonParameter.reset();
+ const memoryCursor = new MemoryCursor();
+
+ memoryCursor.reset();
+
mutations.forEach((mutation) => {
+ // FIXME: @jocs Since UpdateAttributeApply modifies the mutation(used in undo/redo),
+ // so make a deep copy here, does UpdateAttributeApply need to
+ // be modified to have no side effects in the future?
+ mutation = Tools.deepClone(mutation);
+
if (mutation.t === 'r') {
const { coverType, body, len, segmentId } = mutation;
+
if (body != null) {
const documentBody = UpdateAttributeApply(
documentModel,
body,
len,
- commonParameter.cursor,
+ memoryCursor.cursor,
coverType,
segmentId
);
+
undoMutations.push({
...mutation,
t: 'r',
coverType: UpdateDocsAttributeType.REPLACE,
body: documentBody,
});
+ } else {
+ undoMutations.push({
+ ...mutation,
+ t: 'r',
+ });
}
- commonParameter.moveCursor(len);
- undoMutations.push({
- ...mutation,
- t: 'r',
- });
+ memoryCursor.moveCursor(len);
} else if (mutation.t === 'i') {
const { body, len, segmentId, line } = mutation;
- InsertApply(documentModel, body!, len, commonParameter.cursor, segmentId);
- commonParameter.moveCursor(len);
+
+ InsertApply(documentModel, body!, len, memoryCursor.cursor, segmentId);
+ memoryCursor.moveCursor(len);
undoMutations.push({
t: 'd',
len,
@@ -97,7 +116,8 @@ export const RichTextEditingMutation: IMutation<IRichTextEditingMutationParams,
});
} else if (mutation.t === 'd') {
const { len, segmentId } = mutation;
- const documentBody = DeleteApply(documentModel, len, commonParameter.cursor, segmentId);
+ const documentBody = DeleteApply(documentModel, len, memoryCursor.cursor, segmentId);
+
undoMutations.push({
...mutation,
t: 'i',
@@ -114,16 +134,3 @@ export const RichTextEditingMutation: IMutation<IRichTextEditingMutationParams,
};
},
};
-
-class CommonParameter {
- cursor: number = 0;
-
- reset() {
- this.cursor = 0;
- return this;
- }
-
- moveCursor(pos: number) {
- this.cursor += pos;
- }
-}
diff --git a/packages/base-docs/src/commands/mutations/functions/common.ts b/packages/base-docs/src/commands/mutations/functions/common.ts
index 252e5edc2f..0e20c1c247 100644
--- a/packages/base-docs/src/commands/mutations/functions/common.ts
+++ b/packages/base-docs/src/commands/mutations/functions/common.ts
@@ -36,7 +36,8 @@ export function insertTextRuns(
for (let i = 0, len = textRuns.length; i < len; i++) {
const textRun = textRuns[i];
const { st, ed } = textRun;
- if (st > currentIndex) {
+
+ if (st >= currentIndex) {
textRun.st += textLength;
textRun.ed += textLength;
@@ -50,17 +51,21 @@ export function insertTextRuns(
* So, it is necessary to set ed >= currentIndex - 1 to ensure that the new text is inserted while maintaining the style of the existing content.
*/
textRun.ed += textLength;
- insertIndex = i;
+ if (!Number.isFinite(insertIndex)) {
+ insertIndex = i;
+ }
}
}
const insertTextRuns = insertBody.textRuns;
+
if (insertTextRuns) {
for (let i = 0, len = insertTextRuns.length; i < len; i++) {
const insertTextRun = insertTextRuns[i];
insertTextRun.st += currentIndex;
insertTextRun.ed += currentIndex;
}
+
if (insertIndex === Infinity) {
textRuns.push(...insertTextRuns);
}
@@ -69,6 +74,7 @@ export function insertTextRuns(
} else {
const splitTextRun = textRuns[insertIndex];
const { st, ed } = splitTextRun;
+
const startSplitTextRun = {
...splitTextRun,
st,
@@ -82,8 +88,15 @@ export function insertTextRuns(
const lastInsertTextRuns = insertTextRuns[insertTextRuns.length - 1];
+ if (!lastInsertTextRuns) {
+ textRuns.splice(insertIndex, 1, startSplitTextRun);
+
+ return;
+ }
+
if (lastInsertTextRuns.ed === ed) {
textRuns.splice(insertIndex, 1, startSplitTextRun, ...insertTextRuns);
+
return;
}
@@ -313,18 +326,19 @@ export function insertCustomRanges(
export function deleteTextRuns(body: IDocumentBody, textLength: number, currentIndex: number) {
const { textRuns } = body;
-
const startIndex = currentIndex;
- const endIndex = currentIndex + textLength - 1;
+ const endIndex = currentIndex + textLength;
const removeTextRuns: ITextRun[] = [];
+
if (textRuns) {
const newTextRuns = [];
+
for (let i = 0, len = textRuns.length; i < len; i++) {
const textRun = textRuns[i];
const { st, ed } = textRun;
- if (startIndex <= st - 1 && endIndex >= ed - 1) {
+ if (startIndex <= st && endIndex >= ed) {
/**
* If the selection range is larger than the current textRuns, it needs to be deleted.
*/
@@ -334,16 +348,21 @@ export function deleteTextRuns(body: IDocumentBody, textLength: number, currentI
ed: ed - startIndex,
});
continue;
- } else if (st - 1 < startIndex && ed - 1 >= endIndex) {
+ } else if (st <= startIndex && ed >= endIndex) {
/**
* If the selection range is smaller than the current textRun,
* it needs to be trimmed. After trimming, the two segments of textRun should be merged.
*/
- const segments = horizontalLineSegmentsSubtraction(st, ed, startIndex, endIndex);
+ removeTextRuns.push({
+ ...textRun,
+ st: startIndex - startIndex,
+ ed: endIndex - startIndex,
+ });
+ const segments = horizontalLineSegmentsSubtraction(st, ed, startIndex, endIndex - 1);
textRun.st = segments[0];
textRun.ed = segments[1];
- } else if (startIndex > st - 1 && startIndex <= ed - 1) {
+ } else if (startIndex >= st && startIndex < ed) {
/**
* If the cursor start position is within the textRun,
* the content on the right side of the textRun needs to be removed,
@@ -355,7 +374,7 @@ export function deleteTextRuns(body: IDocumentBody, textLength: number, currentI
ed: ed - startIndex,
});
textRun.ed = startIndex;
- } else if (endIndex > st - 1 && endIndex <= ed - 1) {
+ } else if (endIndex > st && endIndex <= ed) {
/**
* If the cursor end position is within the textRun,
* the content on the left side of the textRun needs to be removed,
@@ -366,17 +385,19 @@ export function deleteTextRuns(body: IDocumentBody, textLength: number, currentI
st: st - startIndex,
ed: endIndex - startIndex,
});
- textRun.st = endIndex - textLength + 1;
+ textRun.st = endIndex - textLength;
textRun.ed -= textLength;
- } else if (st > endIndex) {
+ } else if (st >= endIndex) {
/**
* TextRuns to the right of the selection content need to be moved as a whole
*/
textRun.st -= textLength;
textRun.ed -= textLength;
}
+
newTextRuns.push(textRun);
}
+
body.textRuns = newTextRuns;
}
diff --git a/packages/base-docs/src/commands/mutations/functions/update-apply.ts b/packages/base-docs/src/commands/mutations/functions/update-apply.ts
index 1d2941da3f..ed753cf0e0 100644
--- a/packages/base-docs/src/commands/mutations/functions/update-apply.ts
+++ b/packages/base-docs/src/commands/mutations/functions/update-apply.ts
@@ -94,10 +94,12 @@ function updateTextRuns(
}
const removeTextRuns = deleteTextRuns(body, textLength, currentIndex);
+
if (coverType !== UpdateDocsAttributeType.REPLACE) {
const newUpdateTextRun = coverTextRun(updateDataTextRuns, removeTextRuns, coverType);
updateBody.textRuns = newUpdateTextRun;
}
+
insertTextRuns(body, updateBody, textLength, currentIndex);
return removeTextRuns;
@@ -105,75 +107,37 @@ function updateTextRuns(
function coverTextRun(updateDataTextRuns: ITextRun[], removeTextRuns: ITextRun[], coverType: UpdateDocsAttributeType) {
const newUpdateTextRun: ITextRun[] = [];
- for (const updateTextRun of updateDataTextRuns) {
- let { st: updateSt } = updateTextRun;
- const { ed: updateEd, ts: updateStyle } = updateTextRun;
- let splitUpdateTextRuns: ITextRun[] = [];
- for (const removeTextRun of removeTextRuns) {
- const { st: removeSt, ed: removeEd, ts: removeStyle, sId } = removeTextRun;
- let newTs;
- if (coverType === UpdateDocsAttributeType.COVER) {
- newTs = { ...removeStyle, ...updateStyle };
- } else {
- newTs = { ...updateStyle, ...removeStyle };
- }
- if (updateSt >= removeSt && updateEd <= removeEd) {
- splitUpdateTextRuns.push({
- st: updateSt,
- ed: updateEd,
- ts: newTs,
- sId,
- });
- continue;
- } else if (updateSt <= removeSt && updateEd >= removeEd) {
- if (updateSt <= removeSt - 1) {
- splitUpdateTextRuns.push({
- st: updateSt,
- ed: removeSt - 1,
- ts: newTs,
- sId,
- });
- }
- splitUpdateTextRuns.push({
- st: removeSt,
- ed: removeEd,
- ts: newTs,
- sId,
- });
- splitUpdateTextRuns.push({
- st: removeEd + 1,
- ed: updateEd,
- ts: newTs,
- sId,
- });
-
- updateSt = removeEd + 1;
- } else if (updateSt >= removeSt && updateSt <= removeEd) {
- splitUpdateTextRuns.push({
- st: updateSt,
- ed: removeEd,
- ts: newTs,
- sId,
- });
- splitUpdateTextRuns.push({
- st: removeEd + 1,
- ed: updateEd,
- ts: newTs,
- sId,
- });
- updateSt = removeEd + 1;
- } else if (updateEd >= removeSt && updateEd <= removeEd) {
- splitUpdateTextRuns.push({
- st: removeSt,
- ed: updateEd,
- ts: newTs,
- sId,
- });
- }
+ let updateIndex = 0;
+ let removeIndex = 0;
+
+ while (updateIndex !== updateDataTextRuns.length && removeIndex !== removeTextRuns.length) {
+ const { st: updateSt, ed: updateEd, ts: updateStyle } = updateDataTextRuns[updateIndex];
+ const { st: removeSt, ed: removeEd, ts: removeStyle, sId } = removeTextRuns[removeIndex];
+ let newTs;
+
+ if (coverType === UpdateDocsAttributeType.COVER) {
+ newTs = { ...removeStyle, ...updateStyle };
+ } else {
+ newTs = { ...updateStyle, ...removeStyle };
+ }
+
+ newUpdateTextRun.push({
+ st: updateSt >= removeSt ? updateSt : removeSt,
+ ed: updateEd >= removeEd ? removeEd : updateEd,
+ ts: newTs,
+ sId,
+ });
+
+ if (updateEd > removeEd) {
+ removeIndex++;
+ } else if (updateEd === removeEd) {
+ updateIndex++;
+ removeIndex++;
+ } else {
+ updateIndex++;
}
- newUpdateTextRun.push(...splitUpdateTextRuns);
- splitUpdateTextRuns = [];
}
+
return newUpdateTextRun;
}
diff --git a/packages/base-docs/src/commands/operations/text-selection.operation.ts b/packages/base-docs/src/commands/operations/text-selection.operation.ts
index d12f7116f0..bd4107833b 100644
--- a/packages/base-docs/src/commands/operations/text-selection.operation.ts
+++ b/packages/base-docs/src/commands/operations/text-selection.operation.ts
@@ -16,7 +16,9 @@ export const SetTextSelectionsOperation: IOperation<ISetTextSelectionsOperationP
type: CommandType.OPERATION,
handler: (accessor, params) => {
const textSelectionManagerService = accessor.get(TextSelectionManagerService);
+
textSelectionManagerService.replace(params!.ranges);
+
return true;
},
};
diff --git a/packages/base-docs/src/index.ts b/packages/base-docs/src/index.ts
index 4255ec9661..248bf8b325 100644
--- a/packages/base-docs/src/index.ts
+++ b/packages/base-docs/src/index.ts
@@ -13,6 +13,7 @@ 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 {
type IRichTextEditingMutationParams,
RichTextEditingMutation,
diff --git a/packages/base-docs/src/services/text-selection-manager.service.ts b/packages/base-docs/src/services/text-selection-manager.service.ts
index debcd726a6..a1416005ef 100644
--- a/packages/base-docs/src/services/text-selection-manager.service.ts
+++ b/packages/base-docs/src/services/text-selection-manager.service.ts
@@ -37,10 +37,12 @@ export class TextSelectionManagerService implements IDisposable {
if (this._currentSelection == null) {
return;
}
+
this._currentSelection = {
pluginName: NORMAL_TEXT_SELECTION_PLUGIN_NAME,
unitId: this._currentSelection?.unitId,
};
+
this._textSelectionInfo.clear();
this.refresh(this._currentSelection);
@@ -50,6 +52,7 @@ export class TextSelectionManagerService implements IDisposable {
if (this._currentSelection == null) {
return;
}
+
this._currentSelection.pluginName = NORMAL_TEXT_SELECTION_PLUGIN_NAME;
this.refresh(this._currentSelection);
@@ -63,6 +66,7 @@ export class TextSelectionManagerService implements IDisposable {
if (this._currentSelection == null) {
return;
}
+
this.refresh(this._currentSelection);
}
@@ -126,6 +130,7 @@ export class TextSelectionManagerService implements IDisposable {
if (this._currentSelection == null) {
return;
}
+
this._replaceByParam({
...this._currentSelection,
textRanges,
@@ -136,6 +141,7 @@ export class TextSelectionManagerService implements IDisposable {
if (this._currentSelection == null) {
return;
}
+
this._clearByParam(this._currentSelection);
}
@@ -151,7 +157,9 @@ export class TextSelectionManagerService implements IDisposable {
if (param == null) {
return;
}
+
const { pluginName, unitId } = param;
+
return this._textSelectionInfo.get(pluginName)?.get(unitId);
}
diff --git a/packages/base-docs/tsconfig.json b/packages/base-docs/tsconfig.json
index 55a9dcacca..31e6ba7f4f 100644
--- a/packages/base-docs/tsconfig.json
+++ b/packages/base-docs/tsconfig.json
@@ -11,4 +11,4 @@
"src/**/*",
"test/**/*.test.(ts|tsx|js)"
]
-}
\ No newline at end of file
+}
diff --git a/packages/base-render/src/Component/Docs/text-selection-render-manager.ts b/packages/base-render/src/Component/Docs/text-selection-render-manager.ts
index f075065da4..eab06f065d 100644
--- a/packages/base-render/src/Component/Docs/text-selection-render-manager.ts
+++ b/packages/base-render/src/Component/Docs/text-selection-render-manager.ts
@@ -306,6 +306,7 @@ export class TextSelectionRenderManager extends RxDisposable implements ITextSel
getActiveRange(): Nullable<ITextSelectionRangeWithStyle> {
const range = this.getActiveTextSelection()?.getRange();
+
if (range == null) {
return;
}
diff --git a/packages/common-plugin-data/src/Docs/DEFAULT_DOCUMENT_DATA_EN.ts b/packages/common-plugin-data/src/Docs/DEFAULT_DOCUMENT_DATA_EN.ts
index 81f24f6b46..1f0f70c621 100644
--- a/packages/common-plugin-data/src/Docs/DEFAULT_DOCUMENT_DATA_EN.ts
+++ b/packages/common-plugin-data/src/Docs/DEFAULT_DOCUMENT_DATA_EN.ts
@@ -79,7 +79,7 @@ export const DEFAULT_DOCUMENT_DATA_EN: IDocumentData = {
bl: BooleanNumber.TRUE,
fs: 24,
cl: {
- rgb: 'rgb(0,40,86)',
+ rgb: 'rgb(0, 40, 86)',
},
},
},
@@ -89,7 +89,7 @@ export const DEFAULT_DOCUMENT_DATA_EN: IDocumentData = {
ts: {
fs: 18,
cl: {
- rgb: 'rgb(0,40,86)',
+ rgb: 'rgb(0, 40, 86)',
},
},
},
diff --git a/packages/core/src/Docs/Domain/DataStreamTreeNode.ts b/packages/core/src/Docs/Domain/DataStreamTreeNode.ts
index ea25fc64f8..c8045cc848 100644
--- a/packages/core/src/Docs/Domain/DataStreamTreeNode.ts
+++ b/packages/core/src/Docs/Domain/DataStreamTreeNode.ts
@@ -35,14 +35,15 @@ export class DataStreamTreeNode {
}
getProps() {
- return {
- children: this.children,
- parent: this.parent,
- startIndex: this.startIndex,
- endIndex: this.endIndex,
- nodeType: this.nodeType,
+ const { children, parent, startIndex, endIndex, nodeType, content } = this;
- content: this.content,
+ return {
+ children,
+ parent,
+ startIndex,
+ endIndex,
+ nodeType,
+ content,
};
}
@@ -60,7 +61,9 @@ export class DataStreamTreeNode {
}
exclude(index: number) {
- return index < this.startIndex || index > this.endIndex;
+ const { startIndex, endIndex } = this;
+
+ return index < startIndex || index > endIndex;
}
plus(len: number) {
@@ -197,13 +200,17 @@ export class DataStreamTreeNode {
if (this.nodeType !== DataStreamTreeNodeType.PARAGRAPH) {
return;
}
+
if (this.content == null) {
return;
}
+
if (this.content.length === 0) {
return;
}
+
this.blocks = [];
+
for (let i = 0, len = this.content.length; i < len; i++) {
const char = this.content[i];
if (char === DataStreamTreeTokenType.CUSTOM_BLOCK) {
diff --git a/packages/core/src/Docs/Domain/DocumentBodyModel.ts b/packages/core/src/Docs/Domain/DocumentBodyModel.ts
index a2e8af8dfb..6e35486254 100644
--- a/packages/core/src/Docs/Domain/DocumentBodyModel.ts
+++ b/packages/core/src/Docs/Domain/DocumentBodyModel.ts
@@ -73,16 +73,20 @@ export class DocumentBodyModelSimple implements IDisposable {
const sectionList: DataStreamTreeNode[] = [];
let nodeList: DataStreamTreeNode[] = [];
let currentBlocks: number[] = [];
+
// let paragraphIndex = 0;
for (let i = 0; i < dataStreamLen; i++) {
const char = dataStream[i];
+
if (char === DataStreamTreeTokenType.PARAGRAPH) {
content += DataStreamTreeTokenType.PARAGRAPH;
+
const node = DataStreamTreeNode.create(
DataStreamTreeNodeType.PARAGRAPH,
content
);
+
// const isBullet = this._checkParagraphBullet(paragraphIndex);
// const isIndent = isBullet === true ? true : this._checkParagraphIndent(paragraphIndex);
// paragraphIndex++;
@@ -95,11 +99,15 @@ export class DocumentBodyModelSimple implements IDisposable {
currentBlocks = [];
} else if (char === DataStreamTreeTokenType.SECTION_BREAK) {
const sectionTree = DataStreamTreeNode.create(DataStreamTreeNodeType.SECTION_BREAK);
+
this._batchParent(sectionTree, nodeList);
+
const lastNode = nodeList[nodeList.length - 1];
+
if (lastNode && lastNode.content) {
lastNode.content += DataStreamTreeTokenType.SECTION_BREAK;
}
+
sectionList.push(sectionTree);
nodeList = [];
} else if (char === DataStreamTreeTokenType.TABLE_START) {
@@ -233,6 +241,7 @@ export class DocumentBodyModel extends DocumentBodyModelSimple {
const dataStream = insertBody.dataStream;
let dataStreamLen = dataStream.length;
const insertedNode = this.getParagraphByTree(this.children, insertIndex);
+
if (insertedNode == null) {
return;
}
@@ -244,7 +253,7 @@ export class DocumentBodyModel extends DocumentBodyModelSimple {
const insertNodes = insertBodyModel.children;
for (const node of insertNodes) {
- this.foreachDown(node, (newNode) => {
+ this.forEachDown(node, (newNode) => {
newNode.plus(insertIndex);
});
}
@@ -265,7 +274,7 @@ export class DocumentBodyModel extends DocumentBodyModelSimple {
insertedLastNode
);
- this.foreachTop(insertedNode.parent, (currentNode) => {
+ this.forEachTop(insertedNode.parent, (currentNode) => {
// currentNode.endIndex += dataStreamLen;
currentNode.selfPlus(dataStreamLen, currentNode.getPositionInParent());
const children = currentNode.children;
@@ -279,7 +288,7 @@ export class DocumentBodyModel extends DocumentBodyModelSimple {
continue;
}
- this.foreachDown(node, (newNode) => {
+ this.forEachDown(node, (newNode) => {
newNode.plus(dataStreamLen);
});
}
@@ -292,7 +301,7 @@ export class DocumentBodyModel extends DocumentBodyModelSimple {
// insertedNode.endIndex += dataStreamLen;
insertedNode.selfPlus(dataStreamLen, insertIndex);
- this.foreachTop(insertedNode.parent, (currentNode) => {
+ this.forEachTop(insertedNode.parent, (currentNode) => {
// currentNode.endIndex += dataStreamLen;
currentNode.selfPlus(dataStreamLen, currentNode.getPositionInParent());
const children = currentNode.children;
@@ -306,7 +315,7 @@ export class DocumentBodyModel extends DocumentBodyModelSimple {
continue;
}
- this.foreachDown(node, (newNode) => {
+ this.forEachDown(node, (newNode) => {
newNode.plus(dataStreamLen);
});
}
@@ -319,21 +328,25 @@ export class DocumentBodyModel extends DocumentBodyModelSimple {
this.deleteTree(nodes, currentIndex, textLength);
}
- getParagraphByTree(nodes: DataStreamTreeNode[], insertIndex: number): Nullable<DataStreamTreeNode> {
+ private getParagraphByTree(nodes: DataStreamTreeNode[], insertIndex: number): Nullable<DataStreamTreeNode> {
for (const node of nodes) {
- const { startIndex, endIndex, children } = node;
+ const { children } = node;
+
if (node.exclude(insertIndex)) {
continue;
}
+
if (node.nodeType === DataStreamTreeNodeType.PARAGRAPH) {
return node;
}
+
return this.getParagraphByTree(children, insertIndex);
}
+
return null;
}
- foreachTop(
+ private forEachTop(
node: Nullable<DataStreamTreeNode>,
func: (node: DataStreamTreeNode | DocumentBodyModelOrSimple) => void
) {
@@ -346,11 +359,13 @@ export class DocumentBodyModel extends DocumentBodyModelSimple {
func(this);
}
- foreachDown(node: DataStreamTreeNode, func: (node: DataStreamTreeNode) => void) {
+ private forEachDown(node: DataStreamTreeNode, func: (node: DataStreamTreeNode) => void) {
func(node);
+
const children = node.children;
+
for (node of children) {
- this.foreachDown(node, func);
+ this.forEachDown(node, func);
}
}
@@ -457,8 +472,9 @@ export class DocumentBodyModel extends DocumentBodyModelSimple {
}
const curTextRun = textRuns[this.textRunCurrentIndex];
+
if (curTextRun != null) {
- if (index >= curTextRun.st && index <= curTextRun.ed) {
+ if (index >= curTextRun.st && index < curTextRun.ed) {
return curTextRun;
}
@@ -469,6 +485,7 @@ export class DocumentBodyModel extends DocumentBodyModelSimple {
for (let i = this.textRunCurrentIndex, textRunsLen = textRuns.length; i < textRunsLen; i++) {
const textRun = textRuns[i];
+
if (index >= textRun.st && index < textRun.ed) {
this.textRunCurrentIndex = i;
return textRun;
@@ -633,7 +650,7 @@ export class DocumentBodyModel extends DocumentBodyModelSimple {
insertedFirstNode.plus(insertStartIndex);
- this.foreachDown(insertedLastNode, (newNode) => {
+ this.forEachDown(insertedLastNode, (newNode) => {
newNode.plus(insertStartIndex + 1);
});
@@ -644,7 +661,7 @@ export class DocumentBodyModel extends DocumentBodyModelSimple {
insertedLastNode
);
- this.foreachTop(insertedNode.parent, (currentNode) => {
+ this.forEachTop(insertedNode.parent, (currentNode) => {
// currentNode.endIndex += dataStreamLen;
currentNode.selfPlus(1, currentNode.getPositionInParent());
const children = currentNode.children;
@@ -658,7 +675,7 @@ export class DocumentBodyModel extends DocumentBodyModelSimple {
continue;
}
- this.foreachDown(node, (newNode) => {
+ this.forEachDown(node, (newNode) => {
newNode.plus(1);
});
}
diff --git a/packages/core/src/Docs/Domain/DocumentModel.ts b/packages/core/src/Docs/Domain/DocumentModel.ts
index 2dc75d90f6..afaed5dc3c 100644
--- a/packages/core/src/Docs/Domain/DocumentModel.ts
+++ b/packages/core/src/Docs/Domain/DocumentModel.ts
@@ -61,13 +61,14 @@ export class DocumentModelSimple {
headerTree.dispose();
});
- this.footerTreeMap.forEach((headerTree) => {
- headerTree.dispose();
+ this.footerTreeMap.forEach((footerTree) => {
+ footerTree.dispose();
});
}
getShouldRenderLoopImmediately() {
const should = this.snapshot.shouldStartRenderingImmediately;
+
return should !== false;
}
@@ -104,7 +105,8 @@ export class DocumentModelSimple {
}
updateDocumentRenderConfig(config: IDocumentRenderConfig) {
- const documentStyle = this.snapshot.documentStyle;
+ const { documentStyle } = this.snapshot;
+
if (documentStyle.renderConfig == null) {
documentStyle.renderConfig = config;
} else {
@@ -117,7 +119,8 @@ export class DocumentModelSimple {
updateDocumentDataMargin(data: IPaddingData) {
const { t, l, b, r } = data;
- const documentStyle = this.snapshot.documentStyle;
+ const { documentStyle } = this.snapshot;
+
if (t != null) {
documentStyle.marginTop = t;
}
@@ -136,7 +139,8 @@ export class DocumentModelSimple {
}
updateDocumentDataPageSize(width?: number, height?: number) {
- const documentStyle = this.snapshot.documentStyle;
+ const { documentStyle } = this.snapshot;
+
if (!documentStyle.pageSize) {
width = width ?? Infinity;
height = height ?? Infinity;
@@ -144,6 +148,7 @@ export class DocumentModelSimple {
width,
height,
};
+
return;
}
@@ -157,24 +162,21 @@ export class DocumentModelSimple {
}
updateDrawing(id: string, config: IDrawingUpdateConfig) {
- const drawings = this.drawings;
- if (!drawings) {
- return;
- }
-
- const drawing = drawings[id];
+ const { drawings } = this;
+ const { width, height, left, top } = config;
+ const drawing = drawings?.[id];
if (!drawing) {
return;
}
- const objectProperties = drawing.objectProperties;
+ const { objectProperties } = drawing;
- objectProperties.size.width = config.width;
- objectProperties.size.height = config.height;
+ objectProperties.size.width = width;
+ objectProperties.size.height = height;
- objectProperties.positionH.posOffset = config.left;
- objectProperties.positionV.posOffset = config.top;
+ objectProperties.positionH.posOffset = left;
+ objectProperties.positionV.posOffset = top;
}
setZoomRatio(zoomRatio: number = 1) {
@@ -223,6 +225,7 @@ export class DocumentModel extends DocumentModelSimple {
this._unitId = unitId;
}
+ // TODO: @jocs The function name and content don't match?
private _initializeRowColTree() {
this.headerTreeMap = new Map();
this.footerTreeMap = new Map();
diff --git a/packages/core/src/Shared/DocTool.ts b/packages/core/src/Shared/DocTool.ts
index cf2984024c..d45f2a8d11 100644
--- a/packages/core/src/Shared/DocTool.ts
+++ b/packages/core/src/Shared/DocTool.ts
@@ -23,6 +23,7 @@ export function horizontalLineSegmentsSubtraction(A1: number, A2: number, B1: nu
const subLength = B2 - B1 + 1;
let result: number[] = [];
+
if (A1 === B1) {
// Subtract the start segment
result = [B2 + 1 - subLength, A2 - subLength];
diff --git a/packages/core/src/services/undoredo/undoredo.service.ts b/packages/core/src/services/undoredo/undoredo.service.ts
index 2c70758c3c..b1ee090086 100644
--- a/packages/core/src/services/undoredo/undoredo.service.ts
+++ b/packages/core/src/services/undoredo/undoredo.service.ts
@@ -106,6 +106,7 @@ export class LocalUndoRedoService extends Disposable implements IUndoRedoService
pitchTopUndoElement(): IUndoRedoItem | null {
const undoStack = this.getUndoStackForFocused();
+
if (undoStack.length) {
return undoStack[undoStack.length - 1];
}
@@ -221,6 +222,7 @@ export const UndoCommand = new (class extends MultiImplementationCommand impleme
const result = await element.undo();
if (result) {
undoRedoService.popUndoToRedo();
+
return true;
}
@@ -243,6 +245,7 @@ export const RedoCommand = new (class extends MultiImplementationCommand impleme
const result = await element.redo();
if (result) {
undoRedoService.popRedoToUndo();
+
return true;
}
diff --git a/packages/ui-plugin-docs/src/Controller/menu/menu.ts b/packages/ui-plugin-docs/src/Controller/menu/menu.ts
index 9b7ea8f4fc..4c9dfff2d9 100644
--- a/packages/ui-plugin-docs/src/Controller/menu/menu.ts
+++ b/packages/ui-plugin-docs/src/Controller/menu/menu.ts
@@ -1,11 +1,11 @@
-import { BreakLineCommand, DeleteLeftCommand } from '@univerjs/base-docs';
+import { BreakLineCommand, SetInlineFormatBoldCommand } from '@univerjs/base-docs';
import { IMenuButtonItem, MenuItemType, MenuPosition } from '@univerjs/base-ui';
import { IAccessor } from '@wendellhu/redi';
-// TODO@Dushusir: use for test, change id later
+// TODO @Dushusir: use for test, change id later
export function BoldMenuItemFactory(accessor: IAccessor): IMenuButtonItem {
return {
- id: DeleteLeftCommand.id,
+ id: SetInlineFormatBoldCommand.id,
type: MenuItemType.BUTTON,
icon: 'BoldSingle',
title: 'Set bold',