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.
TypeScript boardcollaborationdocdocxexceloffce365officepdfpptpptxpresentationsdksheetslidesspreadsheetuniverwordwordprocessorworkspacexlsx
feat(doc): continuous punctuation extrusion and paragraph align (#1625)
Ran Luob50997dff3f8
diff --git a/.vscode/settings.json b/.vscode/settings.jsonindex 7a6eeac0f4..0fe39aab5f 100644--- a/.vscode/settings.json+++ b/.vscode/settings.json@@ -46,6 +46,7 @@"Jamo","jikkai","Jocs",+ "justifiables","Kaiti","KANBAN","kcode",diff --git a/examples/src/data/docs/default-document-data-cn.ts b/examples/src/data/docs/default-document-data-cn.tsindex 2aa2459104..e5c8eb8d51 100644--- a/examples/src/data/docs/default-document-data-cn.ts+++ b/examples/src/data/docs/default-document-data-cn.ts@@ -15,7 +15,7 @@*/import type { IDocumentData } from '@univerjs/core';-import { BooleanNumber } from '@univerjs/core';+import { BooleanNumber, HorizontalAlign } from '@univerjs/core';import { ptToPixel } from '@univerjs/engine-render';export const DEFAULT_DOCUMENT_DATA_CN: IDocumentData = {@@ -115,6 +115,7 @@ export const DEFAULT_DOCUMENT_DATA_CN: IDocumentData = {spaceAbove: 10,lineSpacing: 2,spaceBelow: 0,+ horizontalAlign: HorizontalAlign.JUSTIFIED,},},{diff --git a/packages/docs-ui/src/controllers/doc-ui.controller.ts b/packages/docs-ui/src/controllers/doc-ui.controller.tsindex ce05dd77d0..3392ba9b78 100644--- a/packages/docs-ui/src/controllers/doc-ui.controller.ts+++ b/packages/docs-ui/src/controllers/doc-ui.controller.ts@@ -31,6 +31,10 @@ import {import { FONT_SIZE_COMPONENT, FontSize } from '../components/font-size';import { DocBackground } from '../views/doc-background/DocBackground';import {+ AlignCenterMenuItemFactory,+ AlignJustifyMenuItemFactory,+ AlignLeftMenuItemFactory,+ AlignRightMenuItemFactory,BoldMenuItemFactory,BulletListMenuItemFactory,FontFamilySelectorMenuItemFactory,@@ -82,6 +86,10 @@ export class DocUIController extends Disposable {FontSizeSelectorMenuItemFactory,FontFamilySelectorMenuItemFactory,TextColorSelectorMenuItemFactory,+ AlignLeftMenuItemFactory,+ AlignCenterMenuItemFactory,+ AlignRightMenuItemFactory,+ AlignJustifyMenuItemFactory,OrderListMenuItemFactory,BulletListMenuItemFactory,] as IMenuItemFactory[]diff --git a/packages/docs-ui/src/controllers/menu/menu.ts b/packages/docs-ui/src/controllers/menu/menu.tsindex 9dea384484..dff88e2b33 100644--- a/packages/docs-ui/src/controllers/menu/menu.ts+++ b/packages/docs-ui/src/controllers/menu/menu.ts@@ -17,12 +17,18 @@import {BaselineOffset,BooleanNumber,+ HorizontalAlign,ICommandService,IUniverInstanceService,ThemeService,UniverInstanceType,} from '@univerjs/core';import {+ AlignCenterCommand,+ AlignJustifyCommand,+ AlignLeftCommand,+ AlignOperationCommand,+ AlignRightCommand,BulletListCommand,OrderListCommand,SetInlineFormatBoldCommand,@@ -54,7 +60,6 @@ import { COLOR_PICKER_COMPONENT } from '../../components/color-picker';import { FONT_FAMILY_COMPONENT, FONT_FAMILY_ITEM_COMPONENT } from '../../components/font-family';import { FONT_SIZE_COMPONENT } from '../../components/font-size';-// TODO @Dushusir: use for test, change id laterexport function BoldMenuItemFactory(accessor: IAccessor): IMenuButtonItem {const commandService = accessor.get(ICommandService);@@ -395,6 +400,146 @@ export function TextColorSelectorMenuItemFactory(accessor: IAccessor): IMenuSele};}+export function AlignLeftMenuItemFactory(accessor: IAccessor): IMenuButtonItem {+ const commandService = accessor.get(ICommandService);++ return {+ id: AlignLeftCommand.id,+ group: MenuGroup.TOOLBAR_LAYOUT,+ type: MenuItemType.BUTTON,+ icon: 'LeftJustifyingSingle',+ tooltip: 'toolbar.alignLeft',+ positions: [MenuPosition.TOOLBAR_START],+ activated$: new Observable<boolean>((subscriber) => {+ const disposable = commandService.onCommandExecuted((c) => {+ const id = c.id;++ if (id === SetTextSelectionsOperation.id || id === AlignOperationCommand.id) {+ const paragraph = getParagraphStyleAtCursor(accessor);++ if (paragraph == null) {+ return;+ }++ const alignType = paragraph.paragraphStyle?.horizontalAlign;++ subscriber.next(alignType === HorizontalAlign.LEFT);+ }+ });++ subscriber.next(false);++ return disposable.dispose;+ }),+ hidden$: getMenuHiddenObservable(accessor, UniverInstanceType.DOC),+ };+}++export function AlignCenterMenuItemFactory(accessor: IAccessor): IMenuButtonItem {+ const commandService = accessor.get(ICommandService);++ return {+ id: AlignCenterCommand.id,+ group: MenuGroup.TOOLBAR_LAYOUT,+ type: MenuItemType.BUTTON,+ icon: 'HorizontallySingle',+ tooltip: 'toolbar.alignCenter',+ positions: [MenuPosition.TOOLBAR_START],+ activated$: new Observable<boolean>((subscriber) => {+ const disposable = commandService.onCommandExecuted((c) => {+ const id = c.id;++ if (id === SetTextSelectionsOperation.id || id === AlignOperationCommand.id) {+ const paragraph = getParagraphStyleAtCursor(accessor);++ if (paragraph == null) {+ return;+ }++ const alignType = paragraph.paragraphStyle?.horizontalAlign;++ subscriber.next(alignType === HorizontalAlign.CENTER);+ }+ });++ subscriber.next(false);++ return disposable.dispose;+ }),+ hidden$: getMenuHiddenObservable(accessor, UniverInstanceType.DOC),+ };+}++export function AlignRightMenuItemFactory(accessor: IAccessor): IMenuButtonItem {+ const commandService = accessor.get(ICommandService);++ return {+ id: AlignRightCommand.id,+ group: MenuGroup.TOOLBAR_LAYOUT,+ type: MenuItemType.BUTTON,+ icon: 'RightJustifyingSingle',+ tooltip: 'toolbar.alignRight',+ positions: [MenuPosition.TOOLBAR_START],+ activated$: new Observable<boolean>((subscriber) => {+ const disposable = commandService.onCommandExecuted((c) => {+ const id = c.id;++ if (id === SetTextSelectionsOperation.id || id === AlignOperationCommand.id) {+ const paragraph = getParagraphStyleAtCursor(accessor);++ if (paragraph == null) {+ return;+ }++ const alignType = paragraph.paragraphStyle?.horizontalAlign;++ subscriber.next(alignType === HorizontalAlign.RIGHT);+ }+ });++ subscriber.next(false);++ return disposable.dispose;+ }),+ hidden$: getMenuHiddenObservable(accessor, UniverInstanceType.DOC),+ };+}++export function AlignJustifyMenuItemFactory(accessor: IAccessor): IMenuButtonItem {+ const commandService = accessor.get(ICommandService);++ return {+ id: AlignJustifyCommand.id,+ group: MenuGroup.TOOLBAR_LAYOUT,+ type: MenuItemType.BUTTON,+ icon: 'AlignTextBothSingle',+ tooltip: 'toolbar.alignJustify',+ positions: [MenuPosition.TOOLBAR_START],+ activated$: new Observable<boolean>((subscriber) => {+ const disposable = commandService.onCommandExecuted((c) => {+ const id = c.id;++ if (id === SetTextSelectionsOperation.id || id === AlignOperationCommand.id) {+ const paragraph = getParagraphStyleAtCursor(accessor);++ if (paragraph == null) {+ return;+ }++ const alignType = paragraph.paragraphStyle?.horizontalAlign;++ subscriber.next(alignType === HorizontalAlign.JUSTIFIED);+ }+ });++ subscriber.next(false);++ return disposable.dispose;+ }),+ hidden$: getMenuHiddenObservable(accessor, UniverInstanceType.DOC),+ };+}+export function OrderListMenuItemFactory(accessor: IAccessor): IMenuButtonItem {return {id: OrderListCommand.id,@@ -441,3 +586,35 @@ function getFontStyleAtCursor(accessor: IAccessor) {return textRun;}++function getParagraphStyleAtCursor(accessor: IAccessor) {+ const currentUniverService = accessor.get(IUniverInstanceService);+ const textSelectionService = accessor.get(TextSelectionManagerService);+ const editorDataModel = currentUniverService.getCurrentUniverDocInstance();+ const activeTextRange = textSelectionService.getActiveRange();++ if (editorDataModel == null || activeTextRange == null) {+ return;+ }++ const paragraphs = editorDataModel.getBody()?.paragraphs;++ if (paragraphs == null) {+ return;+ }++ const { startOffset } = activeTextRange;++ let prevIndex = -1;++ for (const paragraph of paragraphs) {+ const { startIndex } = paragraph;+ if (startOffset > prevIndex && startOffset <= startIndex) {+ return paragraph;+ }++ prevIndex = startIndex;+ }++ return null;+}diff --git a/packages/docs-ui/src/locale/en-US.ts b/packages/docs-ui/src/locale/en-US.tsindex 5358072751..821ca926f2 100644--- a/packages/docs-ui/src/locale/en-US.ts+++ b/packages/docs-ui/src/locale/en-US.ts@@ -35,6 +35,10 @@ const locale: typeof zhCN = {resetColor: 'Reset',order: 'Ordered list',unorder: 'Unordered list',+ alignLeft: 'Align Left',+ alignCenter: 'Align Center',+ alignRight: 'Align Right',+ alignJustify: 'Justify',},};diff --git a/packages/docs-ui/src/locale/zh-CN.ts b/packages/docs-ui/src/locale/zh-CN.tsindex 3b5a98ad90..1ab5147eeb 100644--- a/packages/docs-ui/src/locale/zh-CN.ts+++ b/packages/docs-ui/src/locale/zh-CN.ts@@ -33,6 +33,10 @@ const locale = {resetColor: '重置颜色',order: '有序列表',unorder: '无序列表',+ alignLeft: '左对齐',+ alignCenter: '居中对齐',+ alignRight: '右对齐',+ alignJustify: '两端对齐',},};diff --git a/packages/docs/src/commands/commands/inline-format.command.ts b/packages/docs/src/commands/commands/inline-format.command.tsindex baa55cf9d4..150e6d8195 100644--- a/packages/docs/src/commands/commands/inline-format.command.ts+++ b/packages/docs/src/commands/commands/inline-format.command.ts@@ -33,64 +33,183 @@ import { serializeTextRange, TextSelectionManagerService } from '../../services/import type { IRichTextEditingMutationParams } from '../mutations/core-editing.mutation';import { RichTextEditingMutation } from '../mutations/core-editing.mutation';+function handleInlineFormat(+ preCommandId: string,+ params: object | undefined,+ textSelectionManagerService: TextSelectionManagerService,+ commandService: ICommandService+) {+ const { segmentId } = textSelectionManagerService.getActiveRange() ?? {};++ if (segmentId == null) {+ return false;+ }++ // eslint-disable-next-line ts/no-use-before-define+ return commandService.executeCommand(SetInlineFormatCommand.id, {+ segmentId,+ preCommandId,+ ...(params ?? {}),+ });+}+export interface ISetInlineFormatCommandParams {segmentId: string;preCommandId: string;value?: string;}+const SetInlineFormatBoldCommandId = 'doc.command.set-inline-format-bold';export const SetInlineFormatBoldCommand: ICommand = {- id: 'doc.command.set-inline-format-bold',+ id: SetInlineFormatBoldCommandId,type: CommandType.COMMAND,- handler: async () => true,+ handler: async (accessor, params) => {+ const commandService = accessor.get(ICommandService);+ const textSelectionManagerService = accessor.get(TextSelectionManagerService);++ return handleInlineFormat(+ SetInlineFormatBoldCommandId,+ params,+ textSelectionManagerService,+ commandService+ );+ },};+const SetInlineFormatItalicCommandId = 'doc.command.set-inline-format-italic';export const SetInlineFormatItalicCommand: ICommand = {- id: 'doc.command.set-inline-format-italic',+ id: SetInlineFormatItalicCommandId,type: CommandType.COMMAND,- handler: async () => true,+ handler: async (accessor, params) => {+ const commandService = accessor.get(ICommandService);+ const textSelectionManagerService = accessor.get(TextSelectionManagerService);++ return handleInlineFormat(+ SetInlineFormatItalicCommandId,+ params,+ textSelectionManagerService,+ commandService+ );+ },};+const SetInlineFormatUnderlineCommandId = 'doc.command.set-inline-format-underline';export const SetInlineFormatUnderlineCommand: ICommand = {- id: 'doc.command.set-inline-format-underline',+ id: SetInlineFormatUnderlineCommandId,type: CommandType.COMMAND,- handler: async () => true,+ handler: async (accessor, params) => {+ const commandService = accessor.get(ICommandService);+ const textSelectionManagerService = accessor.get(TextSelectionManagerService);++ return handleInlineFormat(+ SetInlineFormatUnderlineCommandId,+ params,+ textSelectionManagerService,+ commandService+ );+ },};+const SetInlineFormatStrikethroughCommandId = 'doc.command.set-inline-format-strikethrough';export const SetInlineFormatStrikethroughCommand: ICommand = {- id: 'doc.command.set-inline-format-strikethrough',+ id: SetInlineFormatStrikethroughCommandId,type: CommandType.COMMAND,- handler: async () => true,+ handler: async (accessor, params) => {+ const commandService = accessor.get(ICommandService);+ const textSelectionManagerService = accessor.get(TextSelectionManagerService);++ return handleInlineFormat(+ SetInlineFormatStrikethroughCommandId,+ params,+ textSelectionManagerService,+ commandService+ );+ },};+const SetInlineFormatSubscriptCommandId = 'doc.command.set-inline-format-subscript';export const SetInlineFormatSubscriptCommand: ICommand = {- id: 'doc.command.set-inline-format-subscript',+ id: SetInlineFormatSubscriptCommandId,type: CommandType.COMMAND,- handler: async () => true,+ handler: async (accessor, params) => {+ const commandService = accessor.get(ICommandService);+ const textSelectionManagerService = accessor.get(TextSelectionManagerService);++ return handleInlineFormat(+ SetInlineFormatSubscriptCommandId,+ params,+ textSelectionManagerService,+ commandService+ );+ },};+const SetInlineFormatSuperscriptCommandId = 'doc.command.set-inline-format-superscript';export const SetInlineFormatSuperscriptCommand: ICommand = {- id: 'doc.command.set-inline-format-superscript',+ id: SetInlineFormatSuperscriptCommandId,type: CommandType.COMMAND,- handler: async () => true,+ handler: async (accessor, params) => {+ const commandService = accessor.get(ICommandService);+ const textSelectionManagerService = accessor.get(TextSelectionManagerService);++ return handleInlineFormat(+ SetInlineFormatSuperscriptCommandId,+ params,+ textSelectionManagerService,+ commandService+ );+ },};+const SetInlineFormatFontSizeCommandId = 'doc.command.set-inline-format-fontsize';export const SetInlineFormatFontSizeCommand: ICommand = {- id: 'doc.command.set-inline-format-fontsize',+ id: SetInlineFormatFontSizeCommandId,type: CommandType.COMMAND,- handler: async () => true,+ handler: async (accessor, params) => {+ const commandService = accessor.get(ICommandService);+ const textSelectionManagerService = accessor.get(TextSelectionManagerService);++ return handleInlineFormat(+ SetInlineFormatFontSizeCommandId,+ params,+ textSelectionManagerService,+ commandService+ );+ },};+const SetInlineFormatFontFamilyCommandId = 'doc.command.set-inline-format-font-family';export const SetInlineFormatFontFamilyCommand: ICommand = {- id: 'doc.command.set-inline-format-font-family',+ id: SetInlineFormatFontFamilyCommandId,type: CommandType.COMMAND,- handler: async () => true,+ handler: async (accessor, params) => {+ const commandService = accessor.get(ICommandService);+ const textSelectionManagerService = accessor.get(TextSelectionManagerService);++ return handleInlineFormat(+ SetInlineFormatFontFamilyCommandId,+ params,+ textSelectionManagerService,+ commandService+ );+ },};+const SetInlineFormatTextColorCommandId = 'doc.command.set-inline-format-text-color';export const SetInlineFormatTextColorCommand: ICommand = {- id: 'doc.command.set-inline-format-text-color',+ id: SetInlineFormatTextColorCommandId,type: CommandType.COMMAND,- handler: async () => true,+ handler: async (accessor, params) => {+ const commandService = accessor.get(ICommandService);+ const textSelectionManagerService = accessor.get(TextSelectionManagerService);++ return handleInlineFormat(+ SetInlineFormatTextColorCommandId,+ params,+ textSelectionManagerService,+ commandService+ );+ },};const COMMAND_ID_TO_FORMAT_KEY_MAP: Record<string, keyof IStyleBase> = {diff --git a/packages/docs/src/commands/commands/list.command.ts b/packages/docs/src/commands/commands/list.command.tsindex c2c14095ed..c915cc8c30 100644--- a/packages/docs/src/commands/commands/list.command.ts+++ b/packages/docs/src/commands/commands/list.command.ts@@ -191,7 +191,7 @@ export const OrderListCommand: ICommand<IOrderListCommandParams> = {},};-function getParagraphsInRange(activeRange: IActiveTextRange, paragraphs: IParagraph[]) {+export function getParagraphsInRange(activeRange: IActiveTextRange, paragraphs: IParagraph[]) {const { startOffset, endOffset } = activeRange;const results: IParagraph[] = [];diff --git a/packages/docs/src/commands/commands/paragraph-align.command.ts b/packages/docs/src/commands/commands/paragraph-align.command.tsnew file mode 100644index 0000000000..504ba6fa44--- /dev/null+++ b/packages/docs/src/commands/commands/paragraph-align.command.ts@@ -0,0 +1,190 @@+/**+ * Copyright 2023-present DreamNum Inc.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import type { ICommand, IMutationInfo, IParagraphStyle } from '@univerjs/core';+import { CommandType, HorizontalAlign,+ ICommandService,+ IUniverInstanceService,+ MemoryCursor,+ TextX,+ TextXActionType,+ UpdateDocsAttributeType,+} from '@univerjs/core';++import { serializeTextRange, TextSelectionManagerService } from '../../services/text-selection-manager.service';+import type { IRichTextEditingMutationParams } from '../mutations/core-editing.mutation';+import { RichTextEditingMutation } from '../mutations/core-editing.mutation';+import { getParagraphsInRange } from './list.command';++interface IAlignOperationCommandParams {+ alignType: HorizontalAlign;+}++export const AlignOperationCommand: ICommand<IAlignOperationCommandParams> = {+ id: 'doc.command.align-operation',++ type: CommandType.COMMAND,++ handler: (accessor, params: IAlignOperationCommandParams) => {+ const textSelectionManagerService = accessor.get(TextSelectionManagerService);+ const currentUniverService = accessor.get(IUniverInstanceService);+ const commandService = accessor.get(ICommandService);++ const { alignType } = params;++ const dataModel = currentUniverService.getCurrentUniverDocInstance();++ const activeRange = textSelectionManagerService.getActiveRange();+ const selections = textSelectionManagerService.getSelections() ?? [];+ const paragraphs = dataModel.getBody()?.paragraphs;+ const serializedSelections = selections.map(serializeTextRange);++ if (activeRange == null || paragraphs == null) {+ return false;+ }++ const currentParagraphs = getParagraphsInRange(activeRange, paragraphs);++ const { segmentId } = activeRange;++ const unitId = dataModel.getUnitId();++ const isAlreadyAligned = currentParagraphs.every((paragraph) => paragraph.paragraphStyle?.horizontalAlign === alignType);++ const doMutation: IMutationInfo<IRichTextEditingMutationParams> = {+ id: RichTextEditingMutation.id,+ params: {+ unitId,+ actions: [],+ textRanges: serializedSelections,+ },+ };++ const memoryCursor = new MemoryCursor();++ memoryCursor.reset();++ const textX = new TextX();++ for (const paragraph of currentParagraphs) {+ const { startIndex } = paragraph;++ textX.push({+ t: TextXActionType.RETAIN,+ len: startIndex - memoryCursor.cursor,+ segmentId,+ });++ // See: univer/packages/engine-render/src/components/docs/block/paragraph/layout-ruler.ts line:802 comments.+ const paragraphStyle: IParagraphStyle = {+ ...paragraph.paragraphStyle,+ horizontalAlign: isAlreadyAligned ? HorizontalAlign.UNSPECIFIED : alignType,+ };++ textX.push({+ t: TextXActionType.RETAIN,+ len: 1,+ body: {+ dataStream: '',+ paragraphs: [+ {+ ...paragraph,+ paragraphStyle,+ startIndex: 0,+ },+ ],+ },+ segmentId,+ coverType: UpdateDocsAttributeType.REPLACE,+ });++ memoryCursor.moveCursorTo(startIndex + 1);+ }++ doMutation.params.actions = textX.serialize();++ const result = commandService.syncExecuteCommand<+ IRichTextEditingMutationParams,+ IRichTextEditingMutationParams+ >(doMutation.id, doMutation.params);++ return Boolean(result);+ },+};++interface IAlignLeftCommandParams {}++export const AlignLeftCommand: ICommand<IAlignLeftCommandParams> = {+ id: 'doc.command.align-left',++ type: CommandType.COMMAND,++ handler: (accessor) => {+ const commandService = accessor.get(ICommandService);++ return commandService.syncExecuteCommand(AlignOperationCommand.id, {+ alignType: HorizontalAlign.LEFT,+ });+ },+};++interface IAlignCenterCommandParams {}++export const AlignCenterCommand: ICommand<IAlignCenterCommandParams> = {+ id: 'doc.command.align-center',++ type: CommandType.COMMAND,++ handler: (accessor) => {+ const commandService = accessor.get(ICommandService);++ return commandService.syncExecuteCommand(AlignOperationCommand.id, {+ alignType: HorizontalAlign.CENTER,+ });+ },+};++interface IAlignRightCommandParams {}++export const AlignRightCommand: ICommand<IAlignRightCommandParams> = {+ id: 'doc.command.align-right',++ type: CommandType.COMMAND,++ handler: (accessor) => {+ const commandService = accessor.get(ICommandService);++ return commandService.syncExecuteCommand(AlignOperationCommand.id, {+ alignType: HorizontalAlign.RIGHT,+ });+ },+};++interface IAlignJustifyCommandParams {}++export const AlignJustifyCommand: ICommand<IAlignJustifyCommandParams> = {+ id: 'doc.command.align-justify',++ type: CommandType.COMMAND,++ handler: (accessor) => {+ const commandService = accessor.get(ICommandService);++ return commandService.syncExecuteCommand(AlignOperationCommand.id, {+ alignType: HorizontalAlign.JUSTIFIED,+ });+ },+};diff --git a/packages/docs/src/controllers/inline-format.controller.ts b/packages/docs/src/controllers/inline-format.controller.tsdeleted file mode 100644index 08749b560a..0000000000--- a/packages/docs/src/controllers/inline-format.controller.ts+++ /dev/null@@ -1,88 +0,0 @@-/**- * Copyright 2023-present DreamNum Inc.- *- * Licensed under the Apache License, Version 2.0 (the "License");- * you may not use this file except in compliance with the License.- * You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */--import type { ICommandInfo } from '@univerjs/core';-import { Disposable, ICommandService, LifecycleStages, OnLifecycle } from '@univerjs/core';-import { Inject } from '@wendellhu/redi';--import {- SetInlineFormatBoldCommand,- SetInlineFormatCommand,- SetInlineFormatFontFamilyCommand,- SetInlineFormatFontSizeCommand,- SetInlineFormatItalicCommand,- SetInlineFormatStrikethroughCommand,- SetInlineFormatSubscriptCommand,- SetInlineFormatSuperscriptCommand,- SetInlineFormatTextColorCommand,- SetInlineFormatUnderlineCommand,-} from '../commands/commands/inline-format.command';-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(- @Inject(TextSelectionManagerService) private readonly _textSelectionManagerService: TextSelectionManagerService,- @ICommandService private readonly _commandService: ICommandService- ) {- super();-- this._commandExecutedListener();- }-- private _commandExecutedListener() {- const updateCommandList = [- SetInlineFormatBoldCommand.id,- SetInlineFormatItalicCommand.id,- SetInlineFormatUnderlineCommand.id,- SetInlineFormatStrikethroughCommand.id,- SetInlineFormatSubscriptCommand.id,- SetInlineFormatSuperscriptCommand.id,- SetInlineFormatFontSizeCommand.id,- SetInlineFormatFontFamilyCommand.id,- SetInlineFormatTextColorCommand.id,- ];-- this.disposeWithMe(- this._commandService.onCommandExecuted((command: ICommandInfo) => {- if (!updateCommandList.includes(command.id)) {- return;- }-- this._handleInlineFormat(command);- })- );- }-- private _handleInlineFormat(command: ICommandInfo) {- const { segmentId } = this._textSelectionManagerService.getActiveRange() ?? {};-- if (segmentId == null) {- return;- }-- this._commandService.executeCommand(SetInlineFormatCommand.id, {- segmentId,- preCommandId: command.id,- ...(command.params ?? {}),- });- }-}diff --git a/packages/docs/src/doc-plugin.ts b/packages/docs/src/doc-plugin.tsindex 1c5e13c3ed..083ae95ba0 100644--- a/packages/docs/src/doc-plugin.ts+++ b/packages/docs/src/doc-plugin.ts@@ -17,9 +17,6 @@import type { ICommand } from '@univerjs/core';import {ICommandService,- IConfigService,- IUniverInstanceService,- LocaleService,Plugin,PluginType,} from '@univerjs/core';@@ -51,7 +48,6 @@ import { SelectAllOperation } from './commands/operations/select-all.operation';import { SetDocZoomRatioOperation } from './commands/operations/set-doc-zoom-ratio.operation';import { SetTextSelectionsOperation } from './commands/operations/text-selection.operation';import { IMEInputController } from './controllers/ime-input.controller';-import { InlineFormatController } from './controllers/inline-format.controller';import { MoveCursorController } from './controllers/move-cursor.controller';import { NormalInputController } from './controllers/normal-input.controller';import { DocSkeletonManagerService } from './services/doc-skeleton-manager.service';@@ -59,6 +55,7 @@ import { DocViewModelManagerService } from './services/doc-view-model-manager.seimport { IMEInputManagerService } from './services/ime-input-manager.service';import { TextSelectionManagerService } from './services/text-selection-manager.service';import { DocStateChangeManagerService } from './services/doc-state-change-manager.service';+import { AlignCenterCommand, AlignJustifyCommand, AlignLeftCommand, AlignOperationCommand, AlignRightCommand } from './commands/commands/paragraph-align.command';export interface IUniverDocsConfig {hasScroll?: boolean;@@ -77,10 +74,7 @@ export class UniverDocsPlugin extends Plugin {constructor(config: Partial<IUniverDocsConfig> = {},- @Inject(Injector) override _injector: Injector,- @Inject(LocaleService) private readonly _localeService: LocaleService,- @IConfigService private readonly _configService: IConfigService,- @IUniverInstanceService private readonly _currentUniverService: IUniverInstanceService+ @Inject(Injector) override _injector: Injector) {super(PLUGIN_NAME);@@ -126,6 +120,11 @@ export class UniverDocsPlugin extends Plugin {OrderListCommand,BulletListCommand,ListOperationCommand,+ AlignLeftCommand,+ AlignCenterCommand,+ AlignRightCommand,+ AlignOperationCommand,+ AlignJustifyCommand,] as ICommand[]).forEach((command) => {this._injector.get(ICommandService).registerCommand(command);@@ -155,7 +154,6 @@ export class UniverDocsPlugin extends Plugin {// controllers[NormalInputController],[IMEInputController],- [InlineFormatController],[MoveCursorController],] as Dependency[]).forEach((d) => docInjector.add(d));diff --git a/packages/docs/src/index.ts b/packages/docs/src/index.tsindex 7cb94a4558..b89935cacd 100644--- a/packages/docs/src/index.ts+++ b/packages/docs/src/index.ts@@ -41,6 +41,7 @@ export {SetInlineFormatTextColorCommand,SetInlineFormatUnderlineCommand,} from './commands/commands/inline-format.command';+export { AlignOperationCommand, AlignLeftCommand, AlignCenterCommand, AlignRightCommand, AlignJustifyCommand } from './commands/commands/paragraph-align.command';export { BulletListCommand, OrderListCommand } from './commands/commands/list.command';export { CoverContentCommand, ReplaceContentCommand } from './commands/commands/replace-content.command';export {diff --git a/packages/engine-render/src/basics/i-document-skeleton-cached.ts b/packages/engine-render/src/basics/i-document-skeleton-cached.tsindex 9453bf32bc..a0ba1176a3 100644--- a/packages/engine-render/src/basics/i-document-skeleton-cached.ts+++ b/packages/engine-render/src/basics/i-document-skeleton-cached.ts@@ -174,7 +174,7 @@ export interface IDocumentSkeletonGlyph {streamType: DataStreamTreeTokenType;width: number; // cum widthbBox: IDocumentSkeletonBoundingBox; // bBox: size of glyph- paddingLeft: number; // paddingLeft, adjust text align in glyph+ xOffset: number; // xOffset, adjust text align in glyphleft: number; // leftcount: number; // count, content length,default 1content: string; // contentdiff --git a/packages/engine-render/src/components/docs/document.ts b/packages/engine-render/src/components/docs/document.tsindex 0f46687a4f..ad6a507a71 100644--- a/packages/engine-render/src/components/docs/document.ts+++ b/packages/engine-render/src/components/docs/document.ts@@ -395,7 +395,7 @@ export class Documents extends DocComponent {continue;}- const { width: spanWidth, left: spanLeft, paddingLeft } = glyph;+ const { width: spanWidth, left: spanLeft, xOffset } = glyph;const { x: translateX, y: translateY } = this._drawLiquid;@@ -404,7 +404,7 @@ export class Documents extends DocComponent {const centerPoint = Vector2.create(spanWidth / 2, lineHeight / 2);const spanStartPoint = calculateRectRotate(- originTranslate.addByPoint(spanLeft + paddingLeft, 0),+ originTranslate.addByPoint(spanLeft + xOffset, 0),centerPoint,centerAngle,vertexAngle,@@ -413,7 +413,7 @@ export class Documents extends DocComponent {const spanPointWithFont = calculateRectRotate(originTranslate.addByPoint(- spanLeft + maxLineAscSin + paddingLeft,+ spanLeft + maxLineAscSin + xOffset,maxLineAscCos),centerPoint,diff --git a/packages/engine-render/src/components/docs/layout/block/paragraph/layout-ruler.ts b/packages/engine-render/src/components/docs/layout/block/paragraph/layout-ruler.tsindex b8a91f9047..354b6ad188 100644--- a/packages/engine-render/src/components/docs/layout/block/paragraph/layout-ruler.ts+++ b/packages/engine-render/src/components/docs/layout/block/paragraph/layout-ruler.ts@@ -17,8 +17,6 @@import type { INumberUnit, IParagraphStyle } from '@univerjs/core';import { BooleanNumber, DataStreamTreeTokenType, GridType, SpacingRule } from '@univerjs/core';-import { hasCJKText } from '../../../../../basics';-import { FontCache } from '../../../../../basics/font-cache';import type {IDocumentSkeletonBullet,IDocumentSkeletonColumn,@@ -38,7 +36,7 @@ import {import { createSkeletonPage } from '../../model/page';import { setColumnFullState } from '../../model/section';-import { addGlyphToDivide, createSkeletonBulletGlyph, hasMixedTextLayout } from '../../model/glyph';+import { addGlyphToDivide, createSkeletonBulletGlyph } from '../../model/glyph';import {getCharSpaceApply,getCharSpaceConfig,@@ -74,8 +72,8 @@ export function layoutParagraph(__bulletIndentHandler(paragraphStyle, bulletSkeleton, charSpaceApply);- const bulletSpan = createSkeletonBulletGlyph(glyphGroup[0], bulletSkeleton, charSpaceApply);- _lineOperator([bulletSpan, ...glyphGroup], pages, sectionBreakConfig, paragraphConfig, paragraphStart);+ const bulletGlyph = createSkeletonBulletGlyph(glyphGroup[0], bulletSkeleton, charSpaceApply);+ _lineOperator([bulletGlyph, ...glyphGroup], pages, sectionBreakConfig, paragraphConfig, paragraphStart);} else {_lineOperator(glyphGroup, pages, sectionBreakConfig, paragraphConfig, paragraphStart);}@@ -92,7 +90,6 @@ function _divideOperator(sectionBreakConfig: ISectionBreakConfig,paragraphConfig: IParagraphConfig,paragraphStart = false,- isOutMost = true,defaultSpanLineHeight?: number) {const lastPage = getLastPage(pages);@@ -102,29 +99,9 @@ function _divideOperator(const width = __getSpanGroupWidth(glyphGroup);const { divide } = divideInfo;const lastGlyph = divide?.glyphGroup?.[divide.glyphGroup.length - 1];- const preWidth = lastGlyph?.width || 0;- const preLeft = lastGlyph?.left || 0;-- // Last glyph is western char and the current glyph is Chinese word or vice verse.- const isMixedCJKWesternTextLayout = hasMixedTextLayout(lastGlyph, glyphGroup[0]);- let wordSpaceWidth = 0;- let preOffsetLeft = preWidth + preLeft;-- // Only add word space between Chinese text and Western text when processing glyph for the first time,- // otherwise it will be added multiple times during recursion.- if (isMixedCJKWesternTextLayout && isOutMost) {- const lastSpanIsCJKWord = hasCJKText(lastGlyph.content!);- const WORD_INNER_SPACE = '\u0020';-- wordSpaceWidth = FontCache.getTextSize(- WORD_INNER_SPACE, // word space.- lastSpanIsCJKWord ? glyphGroup[0].fontStyle! : lastGlyph.fontStyle!- ).width;-- preOffsetLeft += wordSpaceWidth;-- lastGlyph.width += wordSpaceWidth;- }+ const lastWidth = lastGlyph?.width || 0;+ const lastLeft = lastGlyph?.left || 0;+ const preOffsetLeft = lastWidth + lastLeft;if (preOffsetLeft + width > divide.width) {// width 超过 divide 宽度@@ -233,12 +210,11 @@ function _divideOperator(pages,sectionBreakConfig,paragraphConfig,- paragraphStart,- false+ paragraphStart);}- _divideOperator(glyphGroup, pages, sectionBreakConfig, paragraphConfig, paragraphStart, false);+ _divideOperator(glyphGroup, pages, sectionBreakConfig, paragraphConfig, paragraphStart);return;}@@ -423,7 +399,7 @@ function _lineOperator(column.lines.push(newLine);newLine.parent = column;createAndUpdateBlockAnchor(paragraphIndex, newLine, lineTop, drawingAnchor);- _divideOperator(glyphGroup, pages, sectionBreakConfig, paragraphConfig, paragraphStart, true, defaultSpanLineHeight);+ _divideOperator(glyphGroup, pages, sectionBreakConfig, paragraphConfig, paragraphStart, defaultSpanLineHeight);}function _columnOperator(diff --git a/packages/engine-render/src/components/docs/layout/block/paragraph/layout.ts b/packages/engine-render/src/components/docs/layout/block/paragraph/layout.tsindex a07107c25e..fbbfbdd884 100644--- a/packages/engine-render/src/components/docs/layout/block/paragraph/layout.ts+++ b/packages/engine-render/src/components/docs/layout/block/paragraph/layout.ts@@ -14,22 +14,19 @@* limitations under the License.*/-import { HorizontalAlign } from '@univerjs/core';import type {- IDocumentSkeletonLine,IDocumentSkeletonPage,ISkeletonResourceReference,} from '../../../../../basics/i-document-skeleton-cached';import type { ISectionBreakConfig } from '../../../../../basics/interfaces';import {clearFontCreateConfigCache,- getSpanGroupWidth,- lineIterator,} from '../../tools';import type { DataStreamTreeNode } from '../../../view-model/data-stream-tree-node';import type { DocumentViewModel } from '../../../view-model/document-view-model';import { shaping } from './shaping';import { lineBreaking } from './linebreaking';+import { lineAdjustment } from './line-adjustment';export function dealWidthParagraph(bodyModel: DocumentViewModel,@@ -42,6 +39,7 @@ export function dealWidthParagraph(// Step 1: Text Shaping.const { endIndex, content = '' } = paragraphNode;+const paragraph = bodyModel.getParagraph(endIndex) || { startIndex: 0 };const { paragraphStyle = {} } = paragraph;@@ -64,11 +62,8 @@ export function dealWidthParagraph();// Step 3: Line Adjustment.- // Handle horizontal align: left\center\right\justified.- const { horizontalAlign = HorizontalAlign.UNSPECIFIED } = paragraphStyle;- lineIterator(allPages, (line) => {- horizontalAlignHandler(line, horizontalAlign);- });+ // Handle line adjustment(stretch and shrink) and punctuation adjustment.+ lineAdjustment(allPages, paragraph);return allPages;}@@ -96,36 +91,3 @@ function _checkAndPush(pages: IDocumentSkeletonPage[], currentPages: IDocumentSk// ...paragraphAffectSkeDrawings,// ]);// }--/**- * todo: @author DR-univer- * When aligning text horizontally within a document,- * it may be ineffective if the total line width is not initially calculated.- * Therefore, multiple calculations are performed, which may impact performance.- * Needs optimization for efficiency.- */-function horizontalAlignHandler(line: IDocumentSkeletonLine, horizontalAlign: HorizontalAlign) {- if (horizontalAlign === HorizontalAlign.UNSPECIFIED || horizontalAlign === HorizontalAlign.LEFT) {- return;- }-- const { divides } = line;- const divideLength = divides.length;- for (let i = 0; i < divideLength; i++) {- const divide = divides[i];- const { width } = divide;- const spanGroupWidth = getSpanGroupWidth(divide);-- if (width === Number.POSITIVE_INFINITY) {- continue;- }-- if (horizontalAlign === HorizontalAlign.CENTER) {- divide.paddingLeft = (width - spanGroupWidth) / 2;- } else if (horizontalAlign === HorizontalAlign.RIGHT) {- divide.paddingLeft = width - spanGroupWidth;- } else if (horizontalAlign === HorizontalAlign.JUSTIFIED) {- /**todo */- }- }-}diff --git a/packages/engine-render/src/components/docs/layout/block/paragraph/line-adjustment.ts b/packages/engine-render/src/components/docs/layout/block/paragraph/line-adjustment.tsnew file mode 100644index 0000000000..df2cb09630--- /dev/null+++ b/packages/engine-render/src/components/docs/layout/block/paragraph/line-adjustment.ts@@ -0,0 +1,246 @@+/**+ * Copyright 2023-present DreamNum Inc.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import type { IParagraph } from '@univerjs/core';+import { HorizontalAlign } from '@univerjs/core';+import type { IDocumentSkeletonDivide, IDocumentSkeletonLine, IDocumentSkeletonPage } from '../../../../../basics/i-document-skeleton-cached';+import { getGlyphGroupWidth, lineIterator } from '../../tools';+import { setGlyphGroupLeft } from '../../model/glyph';+import { hasCJK, hasCJKText, isCjkLeftAlignedPunctuation, isCjkRightAlignedPunctuation } from '../../../../../basics/tools';++// How much a character should hang into the end margin.+// For more discussion, see:+// https://recoveringphysicist.com/21/+// https://www.w3.org/TR/clreq/#hanging_punctuation_marks_at_line_end+function overhang(c: string): number {+ switch (c) {+ // Dashes.+ case '–':+ case '—': {+ return 0.2;+ }+ // Punctuation.+ case '.':+ case ',': {+ return 0.8;+ }+ case ':':+ case ';': {+ return 0.3;+ }+ // Arabic+ case '\u{60C}':+ case '\u{6D4}': {+ return 0.4;+ }+ default: {+ return 0;+ }+ }+}++function getDivideShrinkability(divide: IDocumentSkeletonDivide): number {+ const { glyphGroup } = divide;+ let shrinkability = 0;++ for (const glyph of glyphGroup) {+ const [left, right] = glyph.adjustability.shrinkability;++ shrinkability += left + right;+ }++ return shrinkability;+}++function getDivideStretchability(divide: IDocumentSkeletonDivide): number {+ const { glyphGroup } = divide;+ let stretchability = 0;++ for (const glyph of glyphGroup) {+ const [left, right] = glyph.adjustability.stretchability;++ stretchability += left + right;+ }++ return stretchability;+}++function getJustifiables(divide: IDocumentSkeletonDivide): number {+ const justifiables = divide.glyphGroup.filter((glyph) => glyph.isJustifiable).length;+ const lastGlyph = divide.glyphGroup[divide.glyphGroup.length - 1];++ // CJK character at line end should not be adjusted.+ if (hasCJK(lastGlyph.content)) {+ return justifiables - 1;+ }++ return justifiables;+}++function adjustGlyphsInDivide(divide: IDocumentSkeletonDivide, justificationRatio: number, extraJustification: number) {+ for (const glyph of divide.glyphGroup) {+ const adjustabilityLeft = justificationRatio < 0+ ? glyph.adjustability.shrinkability[0]+ : glyph.adjustability.stretchability[0];+ const adjustabilityRight = justificationRatio < 0+ ? glyph.adjustability.shrinkability[1]+ : glyph.adjustability.stretchability[1];++ const justificationLeft = adjustabilityLeft * justificationRatio;+ let justificationRight = adjustabilityRight * justificationRatio;++ if (glyph.isJustifiable) {+ justificationRight += extraJustification;+ }++ glyph.width += justificationLeft + justificationRight;+ glyph.xOffset += justificationLeft;+ }++ setGlyphGroupLeft(divide.glyphGroup);+}++/**+ * When aligning text horizontally within a document,+ * it may be ineffective if the total line width is not initially calculated.+ * Therefore, multiple calculations are performed, which may impact performance.+ * Needs optimization for efficiency.+ */+function horizontalAlignHandler(line: IDocumentSkeletonLine, horizontalAlign: HorizontalAlign) {+ const { divides } = line;++ for (let i = 0; i < divides.length; i++) {+ const divide = divides[i];+ const { width } = divide;+ let glyphGroupWidth = getGlyphGroupWidth(divide);++ if (width === Number.POSITIVE_INFINITY) {+ continue;+ }++ if (divide.isFull) {+ let remaining = width - glyphGroupWidth;++ // Handle hanging punctuation to the right.+ // TODO: @jocs Handle hanging punctuation to the left if text dir is RTL.+ if (divide.glyphGroup.length > 1) {+ const lastGlyph = divide.glyphGroup[divide.glyphGroup.length - 1];+ const amount = overhang(lastGlyph.content) * lastGlyph.width;++ remaining += amount;+ }++ let justificationRatio = 0;+ let extraJustification = 0;+ const shrink = getDivideShrinkability(divide);+ const stretch = getDivideStretchability(divide);++ if (remaining < 0 && shrink > 0) {+ // Attempt to reduce the length of the line, using shrinkability.+ justificationRatio = Math.max(remaining / shrink, -1.0);+ remaining = Math.min(remaining + shrink, 0);+ } else if (horizontalAlign === HorizontalAlign.JUSTIFIED) {+ // Attempt to increase the length of the line, using stretchability.+ if (stretch > 0) {+ justificationRatio = Math.min(remaining / stretch, 1.0);+ remaining = Math.max(remaining - stretch, 0);+ }++ const justifiables = getJustifiables(divide);++ if (justifiables > 0 && remaining > 0) {+ extraJustification = remaining / justifiables;+ remaining = 0;+ }+ }++ if (justificationRatio !== 0 || extraJustification !== 0) {+ // Extrude or stretch row so that they fit within a specified width,+ // or they can be squeezed or stretched to justify the row.+ adjustGlyphsInDivide(divide, justificationRatio, extraJustification);+ // Recalculate the glyph group width, because we adjust the width and xOffset of glyphs.+ glyphGroupWidth = getGlyphGroupWidth(divide);+ }+ }++ if (horizontalAlign === HorizontalAlign.CENTER) {+ divide.paddingLeft = (width - glyphGroupWidth) / 2;+ } else if (horizontalAlign === HorizontalAlign.RIGHT) {+ divide.paddingLeft = width - glyphGroupWidth;+ }+ }+}++// If the last glyph is a CJK character adjusted by [`addCJKLatinSpacing`],+// restore the original width.+function restoreLastCJKGlyphWidth(line: IDocumentSkeletonLine) {+ for (const divide of line.divides) {+ const lastGlyph = divide.glyphGroup[divide.glyphGroup.length - 1];++ if (+ divide.isFull &&+ hasCJKText(lastGlyph.content) &&+ lastGlyph.width - lastGlyph.xOffset > lastGlyph.bBox.width+ ) {+ const shrinkAmount = lastGlyph.width - lastGlyph.xOffset - lastGlyph.bBox.width;++ lastGlyph.width -= shrinkAmount;+ lastGlyph.adjustability.shrinkability[1] = 0;+ }+ }+}++// If the last glyph is a CJK punctuation, we want to shrink it.+// See Requirements for Chinese Text Layout, Section 3.1.6.3+// Compression of punctuation marks at line start or line end+function shrinkStartAndEndCJKPunctuation(line: IDocumentSkeletonLine) {+ for (const divide of line.divides) {+ const firstGlyph = divide.glyphGroup[0];+ const lastGlyph = divide.glyphGroup[divide.glyphGroup.length - 1];++ if (isCjkRightAlignedPunctuation(firstGlyph.content)) {+ const shrinkAmount = firstGlyph.adjustability.shrinkability[0];++ firstGlyph.width -= shrinkAmount;+ firstGlyph.adjustability.shrinkability[0] -= shrinkAmount;+ firstGlyph.xOffset -= shrinkAmount;+ }++ if (isCjkLeftAlignedPunctuation(lastGlyph.content)) {+ const shrinkAmount = lastGlyph.adjustability.shrinkability[1];++ lastGlyph.width -= shrinkAmount;+ lastGlyph.adjustability.shrinkability[1] -= shrinkAmount;+ }+ }+}++export function lineAdjustment(pages: IDocumentSkeletonPage[], paragraph: IParagraph) {+ lineIterator(pages, (line) => {+ // Only need to adjust the current paragraph.+ if (line.paragraphIndex !== paragraph.startIndex) {+ return;+ }+ const { paragraphStyle = {} } = paragraph;+ const { horizontalAlign = HorizontalAlign.UNSPECIFIED } = paragraphStyle;+ // If the last glyph is a CJK punctuation, we want to shrink it.+ shrinkStartAndEndCJKPunctuation(line);+ // restore the original glyph width.+ restoreLastCJKGlyphWidth(line);+ // Handle horizontal align: left\center\right\justified.+ horizontalAlignHandler(line, horizontalAlign);+ });+}diff --git a/packages/engine-render/src/components/docs/layout/block/paragraph/shaping.ts b/packages/engine-render/src/components/docs/layout/block/paragraph/shaping.tsindex 633b9cc245..7fbff08273 100644--- a/packages/engine-render/src/components/docs/layout/block/paragraph/shaping.ts+++ b/packages/engine-render/src/components/docs/layout/block/paragraph/shaping.ts@@ -19,14 +19,69 @@ import { BooleanNumber, DataStreamTreeTokenType, GridType } from '@univerjs/coreimport type { IDocumentSkeletonGlyph } from '../../../../../basics/i-document-skeleton-cached';import { LineBreaker } from '../../linebreak';import { tabLineBreakExtension } from '../../linebreak/extensions/tab-linebreak-extension';-import { createSkeletonLetterGlyph, createSkeletonTabGlyph } from '../../model/glyph';+import { createSkeletonLetterGlyph, createSkeletonTabGlyph, glyphShrinkLeft, glyphShrinkRight } from '../../model/glyph';import { getCharSpaceApply, getFontCreateConfig } from '../../tools';import type { DataStreamTreeNode } from '../../../view-model/data-stream-tree-node';import type { DocumentViewModel } from '../../../view-model/document-view-model';import type { ISectionBreakConfig } from '../../../../../basics/interfaces';-import { hasArabic, hasCJK, hasTibetan, startWithEmoji } from '../../../../../basics/tools';+import { hasArabic, hasCJK, hasCJKPunctuation, hasCJKText, hasTibetan, startWithEmoji } from '../../../../../basics/tools';import { ArabicHandler, emojiHandler, otherHandler, TibetanHandler } from './language-ruler';+// Now we apply consecutive punctuation adjustment, specified in Chinese Layout+// Requirements, section 3.1.6.1 Punctuation Adjustment Space, and Japanese Layout+// Requirements, section 3.1 Line Composition Rules for Punctuation Marks+function punctuationSpaceAdjustment(shapedGlyphs: IDocumentSkeletonGlyph[]) {+ const len = shapedGlyphs.length;+ for (let i = 0; i < len - 1; i++) {+ const curGlyph = shapedGlyphs[i];+ const nextGlyph = shapedGlyphs[i + 1];+ const { width, content } = curGlyph;+ const delta = width / 2;++ if (+ hasCJKPunctuation(content) &&+ hasCJKPunctuation(nextGlyph.content) &&+ curGlyph.adjustability.shrinkability[1] + nextGlyph.adjustability.shrinkability[0] >= delta+ ) {+ const leftDelta = Math.min(curGlyph.adjustability.shrinkability[1], delta);++ glyphShrinkRight(curGlyph, leftDelta);+ glyphShrinkLeft(nextGlyph, delta - leftDelta);+ }+ }+}++// Add some spacing between Han characters and western characters.+// See Requirements for Chinese Text Layout, Section 3.2.2 Mixed Text Composition in Horizontal+// Written Mode+function addCJKLatinSpacing(shapedTextList: IShapedText[]) {+ const shapedGlyphs = shapedTextList.flatMap((shapedText) => shapedText.glyphs);+ let prevGlyph = null;+ const len = shapedGlyphs.length;+ const LATIN_REG = /[a-z\d]/i;++ for (let i = 0; i < len; i++) {+ const curGlyph = shapedGlyphs[i];+ const nextGlyph = i < len - 1 ? shapedGlyphs[i + 1] : null;+ const { width } = curGlyph;++ // Case 1: CJ followed by a Latin character.+ if (hasCJKText(curGlyph.content) && nextGlyph && LATIN_REG.test(nextGlyph.content)) {+ curGlyph.width += width / 4;+ curGlyph.adjustability.shrinkability[1] += width / 8;+ }++ // Case 2: Latin followed by a CJ character.+ if (hasCJKText(curGlyph.content) && prevGlyph && LATIN_REG.test(prevGlyph.content)) {+ curGlyph.width += width / 4;+ curGlyph.xOffset += width / 4;+ curGlyph.adjustability.shrinkability[0] += width / 8;+ }++ prevGlyph = curGlyph;+ }+}+export interface IShapedText {text: string;glyphs: IDocumentSkeletonGlyph[];@@ -134,6 +189,9 @@ export function shaping(}}+ // Continuous punctuation space adjustment.+ punctuationSpaceAdjustment(shapedGlyphs);+shapedTextList.push({text: word,glyphs: shapedGlyphs,@@ -141,5 +199,8 @@ export function shaping(last = bk.position;}+ // Add some spacing between Han characters and western characters.+ addCJKLatinSpacing(shapedTextList);+return shapedTextList;}diff --git a/packages/engine-render/src/components/docs/layout/model/__test__/glyph.spec.ts b/packages/engine-render/src/components/docs/layout/model/__test__/glyph.spec.tsindex 4aa423917f..0e3e9094d6 100644--- a/packages/engine-render/src/components/docs/layout/model/__test__/glyph.spec.ts+++ b/packages/engine-render/src/components/docs/layout/model/__test__/glyph.spec.ts@@ -15,7 +15,8 @@*/import { describe, expect, it } from 'vitest';-import { baseAdjustability } from '../glyph';+import { baseAdjustability, glyphShrinkLeft, glyphShrinkRight, isJustifiable, isSpace } from '../glyph';+import type { IDocumentSkeletonGlyph } from '../../../../../basics/i-document-skeleton-cached';describe('Glyph utils test cases', () => {describe('test baseAdjustability', () => {@@ -51,4 +52,87 @@ describe('Glyph utils test cases', () => {});});});++ describe('test isJustifiable', () => {+ it('should return true for space', () => {+ const result = isJustifiable(' ');+ expect(result).toBe(true);+ });++ it('should return true for Chinese', () => {+ const result = isJustifiable('中');+ expect(result).toBe(true);+ });++ it('should return true for CJK left aligned punctuation', () => {+ const result = isJustifiable(',');+ expect(result).toBe(true);+ });++ it('should return true for CJK right aligned punctuation', () => {+ const result = isJustifiable('“');+ expect(result).toBe(true);+ });++ it('should return true for CJK center aligned punctuation', () => {+ const result = isJustifiable('\u{30FB}');+ expect(result).toBe(true);+ });+ });++ describe('test isSpace', () => {+ it('should return true for space', () => {+ const result = isSpace(' ');+ expect(result).toBe(true);+ });++ it('should return true for non-breaking space', () => {+ const result = isSpace('\u{00A0}');+ expect(result).toBe(true);+ });++ it('should return true for full-width space', () => {+ const result = isSpace(' ');+ expect(result).toBe(true);+ });++ it('should return false for other characters', () => {+ const result = isSpace('a');+ expect(result).toBe(false);+ });+ });++ describe('test glyphShrinkRight', () => {+ it('should shrink right', () => {+ const glyph = {+ adjustability: {+ shrinkability: [10, 10],+ stretchability: [10, 10],+ },+ width: 20,+ } as IDocumentSkeletonGlyph;+ glyphShrinkRight(glyph, 5);+ expect(glyph.adjustability.shrinkability).toEqual([10, 5]);+ expect(glyph.adjustability.stretchability).toEqual([10, 15]);+ expect(glyph.width).toBe(15);+ });+ });++ describe('test glyphShrinkLeft', () => {+ it('should shrink left', () => {+ const glyph = {+ adjustability: {+ shrinkability: [10, 10],+ stretchability: [10, 10],+ },+ xOffset: 0,+ width: 20,+ } as IDocumentSkeletonGlyph;+ glyphShrinkLeft(glyph, 5);+ expect(glyph.adjustability.shrinkability).toEqual([5, 10]);+ expect(glyph.adjustability.stretchability).toEqual([15, 10]);+ expect(glyph.width).toBe(15);+ expect(glyph.xOffset).toBe(-5);+ });+ });});diff --git a/packages/engine-render/src/components/docs/layout/model/glyph.ts b/packages/engine-render/src/components/docs/layout/model/glyph.tsindex bec6244ab2..3139c30e42 100644--- a/packages/engine-render/src/components/docs/layout/model/glyph.ts+++ b/packages/engine-render/src/components/docs/layout/model/glyph.ts@@ -14,7 +14,6 @@* limitations under the License.*/-import type { Nullable } from '@univerjs/core';import { BooleanNumber, BulletAlignment, DataStreamTreeTokenType as DT, GridType } from '@univerjs/core';import { FontCache } from '../../../../basics/font-cache';@@ -138,7 +137,7 @@ export function _createSkeletonWordOrLetter(spr: 0,spo: 0,},- paddingLeft: 0,+ xOffset: 0,left: 0,isJustifiable: false,adjustability: baseAdjustability(content, 0),@@ -155,14 +154,14 @@ export function _createSkeletonWordOrLetter(const bBox = FontCache.getTextSize(content, fontStyle);const { width: contentWidth = 0 } = bBox;let width = glyphWidth ?? contentWidth;- let paddingLeft = 0;+ let xOffset = 0;if (validationGrid(gridType, snapToGrid)) {// 当文字也需要对齐到网格式,进行处理// const multiple = Math.ceil(contentWidth / charSpace);width = contentWidth + (hasCJK(content) ? charSpace : charSpace / 2);if (gridType === GridType.SNAP_TO_CHARS) {- paddingLeft = (width - contentWidth) / 2;+ xOffset = (width - contentWidth) / 2;}}@@ -172,7 +171,7 @@ export function _createSkeletonWordOrLetter(fontStyle,width,bBox,- paddingLeft,+ xOffset,left: 0,glyphType,streamType,@@ -221,7 +220,7 @@ export function createSkeletonBulletGlyph(ts: textStyle,fontStyle,width,- paddingLeft: 0,+ xOffset: 0,bBox,left,isJustifiable: isJustifiable(content),@@ -255,24 +254,6 @@ export function addGlyphToDivide(glyphGroup: IDocumentSkeletonGlyph[],offsetLeft: number = 0) {- // const line = divide.parent;- // if (line != null) {- // const isFirstLine = line.divides[0].glyphGroup[0] == null;- // const firstSpan = glyphGroup[0];- // const firstSpanContent = firstSpan.content || ' ';- // if (isFirstLine && firstSpanContent === ' ') {- // const width = firstSpan.width;- // firstSpan.width = 0;- // for (const glyph of glyphGroup) {- // if (glyph === firstSpan) {- // continue;- // }-- // glyph.left -= width;- // }- // }- // }-setGlyphGroupLeft(glyphGroup, offsetLeft);// Set glyph parent pointer.@@ -294,21 +275,15 @@ function _getMaxBoundingBox(glyph: IDocumentSkeletonGlyph, bulletSkeleton: IDocureturn bulletSkeleton.bBox;}-export function hasMixedTextLayout(preGlyph: Nullable<IDocumentSkeletonGlyph>, glyph: IDocumentSkeletonGlyph) {- if (preGlyph == null) {- return false;- }- const { content: preContent } = preGlyph;- const { content: curContent } = glyph;-- if (preContent == null || curContent == null) {- return false;- }-- const ENG_NUMBERS_REG = /[a-z\d]/i;+export function glyphShrinkRight(glyph: IDocumentSkeletonGlyph, amount: number) {+ glyph.width -= amount;+ glyph.adjustability.shrinkability[1] -= amount;+ glyph.adjustability.stretchability[1] += amount;+}- return (- (ENG_NUMBERS_REG.test(preContent) && hasCJKText(curContent)) ||- (hasCJKText(preContent) && ENG_NUMBERS_REG.test(curContent))- );+export function glyphShrinkLeft(glyph: IDocumentSkeletonGlyph, amount: number) {+ glyph.width -= amount;+ glyph.xOffset -= amount;+ glyph.adjustability.shrinkability[0] -= amount;+ glyph.adjustability.stretchability[0] += amount;}diff --git a/packages/engine-render/src/components/docs/layout/tools.ts b/packages/engine-render/src/components/docs/layout/tools.tsindex 75e1032a81..0cfcd192e3 100644--- a/packages/engine-render/src/components/docs/layout/tools.ts+++ b/packages/engine-render/src/components/docs/layout/tools.ts@@ -651,11 +651,10 @@ export function getPositionVertical(}}-export function getSpanGroupWidth(divide: IDocumentSkeletonDivide) {- const glyphGroup = divide.glyphGroup;+export function getGlyphGroupWidth(divide: IDocumentSkeletonDivide) {let width = 0;- for (const glyph of glyphGroup) {+ for (const glyph of divide.glyphGroup) {width += glyph.width;}diff --git a/packages/ui/src/common/component-manager.ts b/packages/ui/src/common/component-manager.tsindex 52419c8a97..d36f5f9801 100644--- a/packages/ui/src/common/component-manager.ts+++ b/packages/ui/src/common/component-manager.ts@@ -19,6 +19,7 @@ import {AdjustHeight,AdjustWidth,AlignBottomSingle,+ AlignTextBothSingle,AlignTopSingle,AllBorderSingle,AmplifySingle,@@ -170,6 +171,7 @@ export class ComponentManager {RedoSingle,RightBorder,RightJustifyingSingle,+ AlignTextBothSingle,RightRotationFortyFiveDegreesSingle,RightRotationNinetyDegreesSingle,StrikethroughSingle,