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(docs): support change space rule type (#3176)
Gpound.liu4936567b3311
diff --git a/packages/core/src/types/interfaces/i-document-data.ts b/packages/core/src/types/interfaces/i-document-data.tsindex 7bb457b876..647b418d5d 100644--- a/packages/core/src/types/interfaces/i-document-data.ts+++ b/packages/core/src/types/interfaces/i-document-data.ts@@ -760,9 +760,19 @@ export enum NamedStyleType {export enum SpacingRule {// 17.18.48 ST_LineSpacingRule (Line Spacing Rule)- AUTO, // Specifies that the line spacing of the parent object shall be automatically determined by the size of its contents, with no predetermined minimum or maximum size.- AT_LEAST, // Specifies that the height of the line shall be at least the value specified, but might be expanded to fit its content as needed.- EXACT, // Specifies that the height of the line shall be exactly the value specified, regardless of the size of the contents of the contents.++ /**+ * Specifies that the line spacing of the parent object shall be automatically determined by the size of its contents, with no predetermined minimum or maximum size.+ */+ AUTO,+ /**+ * Specifies that the height of the line shall be at least the value specified, but might be expanded to fit its content as needed.+ */+ AT_LEAST,+ /**+ * Specifies that the height of the line shall be exactly the value specified, regardless of the size of the contents of the contents.+ */+ EXACT,}/**diff --git a/packages/docs-ui/src/commands/commands/doc-paragraph-setting.command.ts b/packages/docs-ui/src/commands/commands/doc-paragraph-setting.command.tsindex e8998a5162..f59b7f9188 100644--- a/packages/docs-ui/src/commands/commands/doc-paragraph-setting.command.ts+++ b/packages/docs-ui/src/commands/commands/doc-paragraph-setting.command.ts@@ -19,7 +19,10 @@ import { CommandType, ICommandService, IUniverInstanceService, JSONX, MemoryCursimport type { IRichTextEditingMutationParams } from '@univerjs/docs';import { getParagraphsInRanges, getRichTextEditPath, RichTextEditingMutation, serializeDocRange, TextSelectionManagerService } from '@univerjs/docs';-export type IDocParagraphSettingCommandParams = Partial<Pick<IParagraphStyle, 'hanging' | 'horizontalAlign' | 'spaceBelow' | 'spaceAbove' | 'indentEnd' | 'indentStart' | 'lineSpacing' | 'indentFirstLine'>>;+export interface IDocParagraphSettingCommandParams {+ paragraph: Partial<Pick<IParagraphStyle, 'hanging' | 'horizontalAlign' | 'spaceBelow' | 'spaceAbove' | 'indentEnd' | 'indentStart' | 'lineSpacing' | 'indentFirstLine' | 'snapToGrid' | 'spacingRule'>>;+ sections?: Record<string, any>;+};export const DocParagraphSettingCommand: ICommand<IDocParagraphSettingCommandParams> = {id: 'doc-paragraph-setting.command',type: CommandType.COMMAND,@@ -70,7 +73,7 @@ export const DocParagraphSettingCommand: ICommand<IDocParagraphSettingCommandPar// See: univer/packages/engine-render/src/components/docs/block/paragraph/layout-ruler.ts line:802 comments.const paragraphStyle: IParagraphStyle = {...paragraph.paragraphStyle,- ...config,+ ...config.paragraph,};textX.push({t: TextXActionType.RETAIN,diff --git a/packages/docs-ui/src/controllers/doc-paragraph-setting.controller.ts b/packages/docs-ui/src/controllers/doc-paragraph-setting.controller.tsindex 07eec2bcfa..c46ff717cb 100644--- a/packages/docs-ui/src/controllers/doc-paragraph-setting.controller.ts+++ b/packages/docs-ui/src/controllers/doc-paragraph-setting.controller.ts@@ -22,6 +22,8 @@ const paragraphSettingIndexKey = 'doc_ui_paragraph-setting-panel';@OnLifecycle(LifecycleStages.Rendered, DocParagraphSettingController)export class DocParagraphSettingController extends Disposable {+ private _id: 'DocParagraphSetting';+constructor(@ICommandService private readonly _commandService: ICommandService,@Inject(ComponentManager) private readonly _componentManager: ComponentManager,@@ -39,12 +41,16 @@ export class DocParagraphSettingController extends Disposable {public openPanel() {const props = {header: { title: 'doc.slider.paragraphSetting' },+ id: this._id,children: {label: paragraphSettingIndexKey,},width: 300,};-this._sidebarService.open(props);}++ public closePanel() {+ this._sidebarService.close(this._id);+ }}diff --git a/packages/docs-ui/src/locale/en-US.ts b/packages/docs-ui/src/locale/en-US.tsindex 9b87a1affc..15027d6cc9 100644--- a/packages/docs-ui/src/locale/en-US.ts+++ b/packages/docs-ui/src/locale/en-US.ts@@ -92,6 +92,8 @@ const locale: typeof zhCN = {before: 'Before',after: 'After',lineSpace: 'Line Space',+ multiSpace: 'Multi Space',+ fixedValue: 'Fixed Value(px)',},},};diff --git a/packages/docs-ui/src/locale/ru-RU.ts b/packages/docs-ui/src/locale/ru-RU.tsindex c86c3332d7..87e0644618 100644--- a/packages/docs-ui/src/locale/ru-RU.ts+++ b/packages/docs-ui/src/locale/ru-RU.ts@@ -92,6 +92,8 @@ const locale: typeof zhCN = {before: 'Before',after: 'After',lineSpace: 'Line Space',+ multiSpace: 'Multi Space',+ fixedValue: 'Fixed Value(px)',},},};diff --git a/packages/docs-ui/src/locale/vi-VN.ts b/packages/docs-ui/src/locale/vi-VN.tsindex b977ad99b6..1eeb16c95b 100644--- a/packages/docs-ui/src/locale/vi-VN.ts+++ b/packages/docs-ui/src/locale/vi-VN.ts@@ -92,6 +92,8 @@ const locale: typeof zhCN = {before: 'Before',after: 'After',lineSpace: 'Line Space',+ multiSpace: 'Multi Space',+ fixedValue: 'Fixed Value(px)',},},};diff --git a/packages/docs-ui/src/locale/zh-CN.ts b/packages/docs-ui/src/locale/zh-CN.tsindex 98f3307757..a26b8d6734 100644--- a/packages/docs-ui/src/locale/zh-CN.ts+++ b/packages/docs-ui/src/locale/zh-CN.ts@@ -90,6 +90,8 @@ const locale = {before: '段落前',after: '段落后',lineSpace: '行距',+ multiSpace: '多倍行距',+ fixedValue: '固定值(px)',},},};diff --git a/packages/docs-ui/src/locale/zh-TW.ts b/packages/docs-ui/src/locale/zh-TW.tsindex 4c0fd472d6..cd72cc169c 100644--- a/packages/docs-ui/src/locale/zh-TW.ts+++ b/packages/docs-ui/src/locale/zh-TW.ts@@ -92,6 +92,8 @@ const locale: typeof zhCN = {before: 'Before',after: 'After',lineSpace: 'Line Space',+ multiSpace: 'Multi Space',+ fixedValue: 'Fixed Value(px)',},},};diff --git a/packages/docs-ui/src/views/paragraph-setting/Setting.tsx b/packages/docs-ui/src/views/paragraph-setting/Setting.tsxindex d0e855811a..7cb1fa1433 100644--- a/packages/docs-ui/src/views/paragraph-setting/Setting.tsx+++ b/packages/docs-ui/src/views/paragraph-setting/Setting.tsx@@ -15,9 +15,9 @@*/import * as React from 'react';-import { HorizontalAlign, LocaleService, useDependency } from '@univerjs/core';+import { HorizontalAlign, LocaleService, SpacingRule, useDependency } from '@univerjs/core';import { useMemo } from 'react';-import { InputNumber, Tooltip } from '@univerjs/design';+import { InputNumber, Select, Tooltip } from '@univerjs/design';import clsx from 'clsx';import { AlignTextBothSingle, HorizontallySingle, LeftJustifyingSingle, RightJustifyingSingle } from '@univerjs/icons';import {@@ -34,12 +34,13 @@ import {import styles from './index.module.less';const AutoFocusInputNumber = (props: {- value: number; onChange: (v: number) => Promise<unknown>; className?: string; min?: number; max?: number;+ value: number; onChange: (v: number) => Promise<unknown>; className?: string; min?: number; max?: number; step?: number;}) => {- const { value, onChange, className = '', min = 0, max = 100 } = props;+ const { value, onChange, className = '', min = 0, max = 100, step = 1 } = props;const ref = React.useRef<HTMLInputElement>(null);return (<InputNumber+ step={step}ref={ref}min={min}max={max}@@ -51,7 +52,7 @@ const AutoFocusInputNumber = (props: {// To re-focus after the scroll ends, you need to ensure that the re-focusing takes place after the scrolling process.setTimeout(() => {ref.current?.focus();- }, 2);+ }, 30);});}}className={className}@@ -80,7 +81,14 @@ export function ParagraphSetting() {const [spaceAbove, spaceAboveSet] = useFirstParagraphIndentSpaceAbove(currentParagraph);const [spaceBelow, spaceBelowSet] = useFirstParagraphSpaceBelow(currentParagraph);- const [lineSpacing, lineSpacingSet] = useFirstParagraphLineSpacing(currentParagraph);+ const { lineSpacing: [lineSpacing, lineSpacingSet], spacingRule: [spacingRule, spacingRuleSet] } = useFirstParagraphLineSpacing(currentParagraph);++ const lineSpaceConfig = useMemo(() => {+ if (spacingRule === SpacingRule.AUTO) {+ return { min: 1, max: 5, step: lineSpacing < 2 ? 0.5 : 1 };+ }+ return { min: 1, max: 100 };+ }, [spacingRule, lineSpacing]);return (<div className={styles.paragraphSetting}>@@ -155,9 +163,25 @@ export function ParagraphSetting() {<AutoFocusInputNumber className={styles.paragraphSettingMtBase} value={spaceBelow} onChange={(v) => spaceBelowSet(v ?? 0)}></AutoFocusInputNumber></div><div className={styles.paragraphSettingFlexCol}>-<div className={styles.paragraphSettingLabel}>{localeService.t('doc.paragraphSetting.lineSpace')}</div>- <AutoFocusInputNumber min={1} max={5} className={styles.paragraphSettingMtBase} value={lineSpacing} onChange={(v) => lineSpacingSet(v ?? 0)}></AutoFocusInputNumber>+ <div className={`${styles.paragraphSettingMtBase} ${styles.paragraphSettingSpaceLine}`} style={{ width: 162 }}>+ <Select+ value={`${spacingRule}`}+ options={[+ { label: localeService.t('doc.paragraphSetting.multiSpace'), value: `${SpacingRule.AUTO}` },+ { label: localeService.t('doc.paragraphSetting.fixedValue'), value: `${SpacingRule.AT_LEAST}` },+ ]}+ onChange={(v) => spacingRuleSet(Number(v))}+ >+ </Select>+ <AutoFocusInputNumber+ {...lineSpaceConfig}+ value={lineSpacing}+ onChange={(v) => lineSpacingSet(v ?? 0)}+ >+ </AutoFocusInputNumber>+ </div>+</div></div></div>diff --git a/packages/docs-ui/src/views/paragraph-setting/hook/utils.ts b/packages/docs-ui/src/views/paragraph-setting/hook/utils.tsindex d01a708831..9b47d752ab 100644--- a/packages/docs-ui/src/views/paragraph-setting/hook/utils.ts+++ b/packages/docs-ui/src/views/paragraph-setting/hook/utils.ts@@ -14,18 +14,21 @@* limitations under the License.*/-import type { DocumentDataModel, IParagraph } from '@univerjs/core';-import { ICommandService, IUniverInstanceService, UniverInstanceType, useDependency } from '@univerjs/core';-import { getParagraphsInRanges, TextSelectionManagerService } from '@univerjs/docs';-import { useMemo, useState } from 'react';-import { getNumberUnitValue } from '@univerjs/engine-render';+import type { DocumentDataModel, IParagraph, ISectionBreak } from '@univerjs/core';+import { ICommandService, IUniverInstanceService, SpacingRule, UniverInstanceType, useDependency } from '@univerjs/core';+import { DocSkeletonManagerService, findNearestSectionBreak, getParagraphsInRanges, TextSelectionManagerService } from '@univerjs/docs';+import { useEffect, useMemo, useRef, useState } from 'react';+import { getNumberUnitValue, IRenderManagerService } from '@univerjs/engine-render';+import { BehaviorSubject } from 'rxjs';+import { bufferTime, filter, map } from 'rxjs/operators';import type { IDocParagraphSettingCommandParams } from '../../../commands/commands/doc-paragraph-setting.command';import { DocParagraphSettingCommand } from '../../../commands/commands/doc-paragraph-setting.command';+import { DocParagraphSettingController } from '../../../controllers/doc-paragraph-setting.controller';-export const useCurrentParagraph = () => {+const useDocRanges = () => {const textSelectionManagerService = useDependency(TextSelectionManagerService);- const univerInstanceService = useDependency(IUniverInstanceService);- const docDataModel = univerInstanceService.getCurrentUnitForType<DocumentDataModel>(UniverInstanceType.UNIVER_DOC);+ const docParagraphSettingController = useDependency(DocParagraphSettingController);+// The `getDocRanges` function internally needs to use `range.position` to obtain the offset.// However, when the form control changes and triggers the `getDocRanges` function, the `Skeleton` has already been updated.// The information of `range.position` in the textSelectionManagerService does not match the `Skeleton`, causing errors in value retrieval.@@ -33,6 +36,20 @@ export const useCurrentParagraph = () => {// TODO@GGGPOUND, the business side should not be aware of the timing issue with getDocRanges.const docRanges = useMemo(() => textSelectionManagerService.getDocRanges(), []);+ useEffect(() => {+ if (!docRanges.length) {+ docParagraphSettingController.closePanel();+ }+ }, [docRanges]);++ return docRanges;+};++export const useCurrentParagraph = () => {+ const univerInstanceService = useDependency(IUniverInstanceService);+ const docDataModel = univerInstanceService.getCurrentUnitForType<DocumentDataModel>(UniverInstanceType.UNIVER_DOC);+ const docRanges = useDocRanges();+if (!docDataModel || docRanges.length === 0) {return [];}@@ -45,6 +62,36 @@ export const useCurrentParagraph = () => {return currentParagraphs;};+export const useCurrentSections = (currentParagraphs: IParagraph[]) => {+ const univerInstanceService = useDependency(IUniverInstanceService);+ const docDataModel = univerInstanceService.getCurrentUnitForType<DocumentDataModel>(UniverInstanceType.UNIVER_DOC);+ const docRanges = useDocRanges();++ if (!docDataModel || docRanges.length === 0) {+ return [];+ }++ const segmentId = docRanges[0].segmentId;++ const sectionBreaks = docDataModel.getSelfOrHeaderFooterModel(segmentId).getBody()?.sectionBreaks ?? [];+ const currentSectionBreaks = currentParagraphs+ .map((item) => findNearestSectionBreak(item.startIndex, sectionBreaks))+ .reduce((a, b, index, list) => {+ const isEnd = list.length - 1 === index;+ if (b) {+ a.map[b.startIndex] = b;+ }+ if (isEnd) {+ for (const key in a.map) {+ const v = a.map[key];+ a.result.push(v);+ }+ }+ return a;+ }, { map: {}, result: [] } as { map: Record<string, ISectionBreak>; result: ISectionBreak[] }).result;+ return currentSectionBreaks;+};+export const useFirstParagraphHorizontalAlign = (paragraph: IParagraph[], defaultValue: string) => {const commandService = useDependency(ICommandService);@@ -58,7 +105,7 @@ export const useFirstParagraphHorizontalAlign = (paragraph: IParagraph[], defaulconst horizontalAlignSet = (v: string) => {_horizontalAlignSet(v);return commandService.executeCommand(DocParagraphSettingCommand.id, {- horizontalAlign: Number(v),+ paragraph: { horizontalAlign: Number(v) },} as IDocParagraphSettingCommandParams);};return [horizontalAlign, horizontalAlignSet] as const;@@ -77,7 +124,7 @@ export const useFirstParagraphIndentStart = (paragraph: IParagraph[]) => {const indentStartSet = (v: number) => {_indentStartSet(v);return commandService.executeCommand(DocParagraphSettingCommand.id, {- indentStart: { v },+ paragraph: { indentStart: { v } },} as IDocParagraphSettingCommandParams);};return [indentStart, indentStartSet] as const;@@ -96,7 +143,7 @@ export const useFirstParagraphIndentEnd = (paragraph: IParagraph[]) => {const indentEndSet = (v: number) => {_indentEndSet(v);return commandService.executeCommand(DocParagraphSettingCommand.id, {- indentEnd: { v },+ paragraph: { indentEnd: { v } },} as IDocParagraphSettingCommandParams);};return [indentEnd, indentEndSet] as const;@@ -115,7 +162,7 @@ export const useFirstParagraphIndentFirstLine = (paragraph: IParagraph[]) => {const indentFirstLineSet = (v: number) => {_indentFirstLineSet(v);return commandService.executeCommand(DocParagraphSettingCommand.id, {- indentFirstLine: { v },+ paragraph: { indentFirstLine: { v } },} as IDocParagraphSettingCommandParams);};return [indentFirstLine, indentFirstLineSet] as const;@@ -134,7 +181,7 @@ export const useFirstParagraphIndentHanging = (paragraph: IParagraph[]) => {const hangingSet = (v: number) => {_hangingSet(v);return commandService.executeCommand(DocParagraphSettingCommand.id, {- hanging: { v },+ paragraph: { hanging: { v } },} as IDocParagraphSettingCommandParams);};return [hanging, hangingSet] as const;@@ -153,7 +200,7 @@ export const useFirstParagraphIndentSpaceAbove = (paragraph: IParagraph[]) => {const spaceAboveSet = (v: number) => {_spaceAboveSet(v);return commandService.executeCommand(DocParagraphSettingCommand.id, {- spaceAbove: { v },+ paragraph: { spaceAbove: { v } },} as IDocParagraphSettingCommandParams);};return [spaceAbove, spaceAboveSet] as const;@@ -172,14 +219,27 @@ export const useFirstParagraphSpaceBelow = (paragraph: IParagraph[]) => {const spaceBelowSet = (v: number) => {_spaceBelowSet(v);return commandService.executeCommand(DocParagraphSettingCommand.id, {- spaceBelow: { v },+ paragraph: { spaceBelow: { v } },} as IDocParagraphSettingCommandParams);};return [spaceBelow, spaceBelowSet] as const;};+// eslint-disable-next-line max-lines-per-functionexport const useFirstParagraphLineSpacing = (paragraph: IParagraph[]) => {const commandService = useDependency(ICommandService);+ const renderManagerService = useDependency(IRenderManagerService);+ const univerInstanceService = useDependency(IUniverInstanceService);++ const skeleton = useMemo(() => {+ const docDataModel = univerInstanceService.getCurrentUnitForType<DocumentDataModel>(UniverInstanceType.UNIVER_DOC);+ if (!docDataModel) {+ return undefined;+ }+ return renderManagerService.getRenderById(docDataModel?.getUnitId())?.with(DocSkeletonManagerService).getSkeleton();+ }, []);++ const stateChange$ = useMemo(() => new BehaviorSubject<{ spacingRule?: SpacingRule; lineSpacing?: number }>({}), []);const [lineSpacing, _lineSpacingSet] = useState(() => {const firstParagraph = paragraph[0];@@ -188,11 +248,70 @@ export const useFirstParagraphLineSpacing = (paragraph: IParagraph[]) => {}return firstParagraph.paragraphStyle?.lineSpacing ?? 1;});- const lineSpacingSet = (v: number) => {++ const lineSpacingCache = useRef<number>(lineSpacing);++ const [spacingRule, _spacingRuleSet] = useState<SpacingRule>(() => {+ const firstParagraph = paragraph[0];+ if (!firstParagraph) {+ return SpacingRule.AUTO;+ }+ return firstParagraph.paragraphStyle?.spacingRule ?? SpacingRule.AUTO;+ });++ const lineSpacingSet = async (v: number) => {_lineSpacingSet(v);- return commandService.executeCommand(DocParagraphSettingCommand.id, {- lineSpacing: v,- } as IDocParagraphSettingCommandParams);+ stateChange$.next({ lineSpacing: v, spacingRule });+ };++ const spacingRuleSet = async (v: SpacingRule) => {+ if (v !== spacingRule) {+ let cache = lineSpacingCache.current;+ if (v === SpacingRule.AT_LEAST) {+ const glyphNode = skeleton?.findNodeByCharIndex(paragraph[0].startIndex);+ const divideNode = glyphNode?.parent;+ const lineNode = divideNode?.parent;+ if (lineNode?.contentHeight !== undefined) {+ cache = Math.max(lineNode.contentHeight, cache);+ }+ } else {+ // If the paragraph is set to fixed-spacing by default,+ // the first time you enter the panel,+ // you will set the fixed-spacing value to the initial value of multiple-spacing+ if (cache > 5) {+ cache = 2;+ }+ }+ lineSpacingCache.current = lineSpacing;+ lineSpacingSet(cache);+ _spacingRuleSet(v);+ stateChange$.next({ spacingRule: v });+ }+ };++ useEffect(() => {+ const dispose = stateChange$.pipe(+ filter((obj) => !!Object.keys(obj).length),+ bufferTime(16),+ filter((list) => !!list.length),+ map((list) => {+ return list.reduce((a, b) => {+ Object.keys(b).forEach((key) => {+ a[key as 'spacingRule'] = b[key as 'spacingRule'];+ });+ return a;+ }, {} as { spacingRule?: SpacingRule; lineSpacing?: number });+ })).subscribe((v) => {+ return commandService.executeCommand(DocParagraphSettingCommand.id, {+ paragraph: { ...v },+ } as IDocParagraphSettingCommandParams);+ });+ return () => dispose.unsubscribe();+ }, []);++ return {+ lineSpacing: [lineSpacing, lineSpacingSet] as const,+ spacingRule: [spacingRule, spacingRuleSet] as const,+};- return [lineSpacing, lineSpacingSet] as const;};diff --git a/packages/docs-ui/src/views/paragraph-setting/index.module.less b/packages/docs-ui/src/views/paragraph-setting/index.module.lessindex bc36363452..d9aadfb649 100644--- a/packages/docs-ui/src/views/paragraph-setting/index.module.less+++ b/packages/docs-ui/src/views/paragraph-setting/index.module.less@@ -8,6 +8,7 @@justify-content: space-between;border: 1px solid var(---Grey-200, #e5e5e5);border-radius: var(--radius-m, 6px);+&-item {padding: 4px 14px;border-radius: 4px;@@ -16,32 +17,44 @@justify-content: center;align-items: center;cursor: pointer;+&:hover {background: var(--black-6, rgba(30, 34, 43, 0.06));}}+&-item&-active {background: var(--black-9, rgba(30, 34, 43, 0.09));}}+&-title {margin-top: var(--margin-base);font-size: 13px;color: #1e222b;font-weight: 500;}+&-label {font-size: 12px;margin-top: var(--margin-sm);color: #1e222b;font-weight: 400;}+&-mt-base {margin-top: var(--margin-base);}+&-flex-col {display: flex;justify-content: space-between;align-items: center;}++ &-space-line {+ display: flex;+ flex-direction: column;+ gap: 6px;+ }}diff --git a/packages/docs/src/index.ts b/packages/docs/src/index.tsindex c8c366b38e..e3169236f5 100644--- a/packages/docs/src/index.ts+++ b/packages/docs/src/index.ts@@ -15,7 +15,7 @@*/export { getCustomRangesInterestsWithRange } from './basics/custom-range';-export { getParagraphsInRange, getParagraphsInRanges } from './commands/commands/list.command';+export { getParagraphsInRange, getParagraphsInRanges, findNearestSectionBreak } from './commands/commands/list.command';export { replaceSelectionFactory } from './basics/replace';export { makeSelection, getSelectionText, getDeleteSelection, getInsertSelection, isSegmentIntersects } from './basics/selection';export { hasParagraphInTable } from './basics/paragraph';