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): doc support table (#2814)
Ran Luob5efb0deee74
diff --git a/.github/workflows/sync-mirror.yml b/.github/workflows/sync-mirror.ymlindex 5924c96982..5b9bf66b71 100644--- a/.github/workflows/sync-mirror.yml+++ b/.github/workflows/sync-mirror.yml@@ -1,4 +1,4 @@-name: 🔮 Sync mirror+name: 🔮 Sync Mirroron:push:diff --git a/.github/workflows/sync-pro.yml b/.github/workflows/sync-pro.ymlindex bb43927b2e..bb97183e98 100644--- a/.github/workflows/sync-pro.yml+++ b/.github/workflows/sync-pro.yml@@ -1,4 +1,4 @@-name: 🔫 Sync pro version+name: 🔫 Sync to Proon:push:diff --git a/.github/workflows/update-snapshots.yml b/.github/workflows/update-snapshots.ymlindex 6dc91ec46f..3765c0e9d3 100644--- a/.github/workflows/update-snapshots.yml+++ b/.github/workflows/update-snapshots.yml@@ -32,7 +32,7 @@ jobs:update_snapshots:# Run this job only on comments of pull requests that strictly match# the "/update-snapshots" string- if: ${{ github.event.issue.pull_request && github.event.comment.body == '/update-snapshots'}}+ if: ${{ github.event.issue.pull_request && github.event.comment.body == '/update-snapshots' }}timeout-minutes: 10runs-on: ubuntu-lateststeps:diff --git a/.vscode/settings.json b/.vscode/settings.jsonindex 0cdd4eb906..dfc3162f9f 100644--- a/.vscode/settings.json+++ b/.vscode/settings.json@@ -94,6 +94,7 @@"SUMIF","SUMIFS","Tahoma",+ "tblp","TBRL","undoredo","undos",diff --git a/e2e/visual-comparison/README.md b/e2e-experimental/visual-comparison/README.mdsimilarity index 100%rename from e2e/visual-comparison/README.mdrename to e2e-experimental/visual-comparison/README.mddiff --git a/e2e/visual-comparison/docs/docs-visual-comparison.spec.ts b/e2e-experimental/visual-comparison/docs/docs-visual-comparison.spec.tssimilarity index 100%rename from e2e/visual-comparison/docs/docs-visual-comparison.spec.tsrename to e2e-experimental/visual-comparison/docs/docs-visual-comparison.spec.tsdiff --git a/e2e-experimental/visual-comparison/docs/docs-visual-comparison.spec.ts-snapshots/diff-default-doc-content-1-chromium-linux.png b/e2e-experimental/visual-comparison/docs/docs-visual-comparison.spec.ts-snapshots/diff-default-doc-content-1-chromium-linux.pngnew file mode 100644index 0000000000..294213e3ceBinary files /dev/null and b/e2e-experimental/visual-comparison/docs/docs-visual-comparison.spec.ts-snapshots/diff-default-doc-content-1-chromium-linux.png differdiff --git a/e2e/visual-comparison/sheet/sheets-visual-comparison.spec.ts b/e2e-experimental/visual-comparison/sheet/sheets-visual-comparison.spec.tssimilarity index 100%rename from e2e/visual-comparison/sheet/sheets-visual-comparison.spec.tsrename to e2e-experimental/visual-comparison/sheet/sheets-visual-comparison.spec.tsdiff --git a/e2e-experimental/visual-comparison/sheet/sheets-visual-comparison.spec.ts-snapshots/diff-default-sheet-content-1-chromium-darwin.png b/e2e-experimental/visual-comparison/sheet/sheets-visual-comparison.spec.ts-snapshots/diff-default-sheet-content-1-chromium-darwin.pngnew file mode 100644index 0000000000..6de6691a55Binary files /dev/null and b/e2e-experimental/visual-comparison/sheet/sheets-visual-comparison.spec.ts-snapshots/diff-default-sheet-content-1-chromium-darwin.png differdiff --git a/e2e/visual-comparison/sheet/sheets-visual-comparison.spec.ts-snapshots/diff-default-sheet-content-1-chromium-linux.png b/e2e-experimental/visual-comparison/sheet/sheets-visual-comparison.spec.ts-snapshots/diff-default-sheet-content-1-chromium-linux.pngsimilarity index 100%rename from e2e/visual-comparison/sheet/sheets-visual-comparison.spec.ts-snapshots/diff-default-sheet-content-1-chromium-linux.pngrename to e2e-experimental/visual-comparison/sheet/sheets-visual-comparison.spec.ts-snapshots/diff-default-sheet-content-1-chromium-linux.pngdiff --git a/e2e/visual-comparison/docs/docs-visual-comparison.spec.ts-snapshots/diff-default-doc-content-1-chromium-linux.png b/e2e/visual-comparison/docs/docs-visual-comparison.spec.ts-snapshots/diff-default-doc-content-1-chromium-linux.pngdeleted file mode 100644index 4cd62b455d..0000000000Binary files a/e2e/visual-comparison/docs/docs-visual-comparison.spec.ts-snapshots/diff-default-doc-content-1-chromium-linux.png and /dev/null differdiff --git a/examples/src/data/docs/default-document-data-cn.ts b/examples/src/data/docs/default-document-data-cn.tsindex 5abdf4e3c5..cb59d88c59 100644--- a/examples/src/data/docs/default-document-data-cn.ts+++ b/examples/src/data/docs/default-document-data-cn.ts@@ -20,177 +20,9 @@ import { ptToPixel } from '@univerjs/engine-render';export const DEFAULT_DOCUMENT_DATA_CN: IDocumentData = {id: 'd',- drawings: {- // shapeTest1: {- // unitId: 'd',- // subUnitId: 'd',- // drawingType: DrawingTypeEnum.DRAWING_SHAPE,- // drawingId: 'shapeTest1',- // title: 'test shape',- // description: 'test shape',- // docTransform: {- // size: {- // width: 1484 * 0.12,- // height: 864 * 0.15,- // },- // positionH: {- // relativeFrom: ObjectRelativeFromH.MARGIN,- // posOffset: 100,- // },- // positionV: {- // relativeFrom: ObjectRelativeFromV.PAGE,- // posOffset: 230,- // },- // angle: 0,- // },- // layoutType: PositionedObjectLayoutType.WRAP_NONE,- // behindDoc: BooleanNumber.TRUE,- // wrapText: WrapTextType.BOTH_SIDES,- // distT: 0,- // distB: 0,- // distL: 0,- // distR: 0,- // },- // shapeTest2: {- // unitId: 'd',- // subUnitId: 'd',- // drawingType: DrawingTypeEnum.DRAWING_SHAPE,- // drawingId: 'shapeTest2',- // title: 'test shape',- // description: 'test shape',- // docTransform: {- // size: {- // width: 1484 * 0.3,- // height: 864 * 0.3,- // },- // positionH: {- // relativeFrom: ObjectRelativeFromH.PAGE,- // posOffset: 100,- // },- // positionV: {- // relativeFrom: ObjectRelativeFromV.PARAGRAPH,- // posOffset: 20,- // },- // angle: 0,- // },- // layoutType: PositionedObjectLayoutType.WRAP_NONE,- // behindDoc: BooleanNumber.FALSE,- // wrapText: WrapTextType.BOTH_SIDES,- // },- // shapeTest3: {- // unitId: 'd',- // subUnitId: 'd',- // drawingType: DrawingTypeEnum.DRAWING_SHAPE,- // drawingId: 'shapeTest3',- // title: 'test shape',- // description: 'test shape',- // docTransform: {- // size: {- // width: 1484 * 0.3,- // height: 864 * 0.3,- // },- // positionH: {- // relativeFrom: ObjectRelativeFromH.PAGE,- // posOffset: 100,- // },- // positionV: {- // relativeFrom: ObjectRelativeFromV.PARAGRAPH,- // posOffset: 200,- // },- // angle: 0,- // },- // layoutType: PositionedObjectLayoutType.INLINE,- // behindDoc: BooleanNumber.FALSE,- // wrapText: WrapTextType.BOTH_SIDES,- // },- // shapeTest4: {- // unitId: 'd',- // subUnitId: 'd',- // drawingType: DrawingTypeEnum.DRAWING_SHAPE,- // drawingId: 'shapeTest4',- // title: 'test shape',- // description: 'test shape',- // docTransform: {- // size: {- // width: 1484 * 0.3,- // height: 864 * 0.3,- // },- // positionH: {- // relativeFrom: ObjectRelativeFromH.PAGE,- // posOffset: 100,- // },- // positionV: {- // relativeFrom: ObjectRelativeFromV.LINE,- // posOffset: 200,- // },- // angle: 0,- // },- // layoutType: PositionedObjectLayoutType.INLINE,- // behindDoc: BooleanNumber.FALSE,- // wrapText: WrapTextType.BOTH_SIDES,- // },- // shapeTest5: {- // unitId: 'd',- // subUnitId: 'd',- // drawingType: DrawingTypeEnum.DRAWING_SHAPE,- // drawingId: 'shapeTest5',- // title: 'test shape',- // description: 'test shape',- // docTransform: {- // size: {- // width: 1484 * 0.3,- // height: 864 * 0.3,- // },- // positionH: {- // relativeFrom: ObjectRelativeFromH.PAGE,- // posOffset: 100,- // },- // positionV: {- // relativeFrom: ObjectRelativeFromV.PAGE,- // posOffset: 200,- // },- // angle: 0,- // },- // layoutType: PositionedObjectLayoutType.INLINE,- // behindDoc: BooleanNumber.FALSE,- // wrapText: WrapTextType.BOTH_SIDES,- // },- // zYeeTi: {- // unitId: 'd',- // subUnitId: 'd',- // drawingId: 'zYeeTi',- // drawingType: 0,- // imageSourceType: 'BASE64',- // source: 'data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEAAkGBxIPDxUPEBAVFRUVFRUVFhYVFRUWGhcYGBUWFhUVFhgYHSggGRslHRcXITEhJSktLi4vFx8zODMsNygtLisBCgoKDg0OGxAQGy0lICUtLS0tLS0tLS0tLS8tLi0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLf/AABEIANMA7wMBEQACEQEDEQH/xAAcAAEAAgMBAQEAAAAAAAAAAAAAAQYEBQcDAgj/xABIEAABAwICBgcEBwUFCAMAAAABAAIDBBEFIQYSMUFRYQcTIjJxgZEUQqGxFSNSYnKCwTNDkrLRJFNzovE0NUVUdJOz4RYlJv/EABsBAQACAwEBAAAAAAAAAAAAAAABBQMEBgIH/8QANhEAAgICAAQDBgUDBAMBAAAAAAECAwQRBRIhMRNBUQYiMmFxgRRCkaHRUrHBIzPh8DQ1YhX/2gAMAwEAAhEDEQA/AO4oAgCAIAgCAICmdMDpW4LUuhc5pAbrFpIOprDW2clAPzVg2kFVRPElNUyRkbmuOqeTmnsuHiF52Dr2hnTaHOEOJsDb5CeMHVH42bQOYUpg7JTVDJWNkje17HAFrmkEEHMEEbVPQHqgJUgIAgCAIAgCAIAgCAIAgCAICEALgMzkEBr67HqSnF56qGMcXyMb8yo2DFw/S6gqH9XDXQPdn2WytJy2kC+aA3akBAEAQBAEAQGHi9A2qp5ad/dljcw8tYEX8tqA/GtTTuie6KQWfG5zHDg5pLXD1C8Mk81AOpdGP0pSUnt1G4TQ67g6jcSNdrT2nRnYx172+N1oXcUpovVM39zJGqUo7R2rRXSqnxKMuhJa9uUkLxqyRneHt/XYrGMlJbTMWtPRvbr0CUAQBAEAQBAEAQBAEAQEXQGHiuKwUkRmqJWxsG1zjbyHE8kBzOu6Ta2tf1eC0JezZ7TO1wZwu0XHxJ8FqZGbRQv9SSXy8z3GEpdjkWlek2IzTyQ1dXI4se5jmsdqMuDYgNbYELLCxTipR7M8taeitao4L1sF56HMBbXYq1sjdaOKOSR4IyN2ljQfN1/yqUiD9Qr2AgCAIAgCAIAgPzN02aPupMUfOGWiqfrGkDLXtaRvjca35l5aBz8LySfpHo+o2w4VStb70LZD4yDrCf8AMvnXGrHLNs366/ToWVC1BGLpXgEplZiOHER1kPDITs3xP433X+GS3uC8X/Dy8K1+6/2Md9HN1iW3QjS6LE4TYGOePszwOydG7jY5lp3FdxCUZrmT2jRfTuWVekQFICAIAgCAIAgCAlARdAUHTPpGZSyexUEftVYezqMzbGeMhG8bbbt9ljttjVFzm9ImKb6I0VDoa+qkFXjExqptoiP7GL7rWbD8jzXHcQ9oZSbhj9F6+f8AwbteMu8i5RxhoDWgADIACwA4ADYuZlZKb3J7NpJJaPzLpf8A7xqv+ol/nK+nYX/jw+iKuz4malbJ4P0h0JaImgojUzNLZqkNdqnayMZxtPAm+sRzXtIg6UpAQBAEAQBAEAQFP6U9GDieGyRRgGaMiWLm5u1n5m3HiQoYPys5pBIIIIuCCLEEbQRxXknzP01of/u2k/6WD/xNXzTiv/mWfVlrV8CNsq/Z7KnpdhE7JWYph2VVCO03dPHvY4bzw/0XTcD4r4MvBtfuvt8jVvp5uq7l60Q0jixOkZVRZXyew7Y5B32HwO/eLLt09roaBuk2CVICAIAgCAIAgIugOY6W6YT11Q7CsIdYjKpq/diG9sZG1/PyG8jTzM2vFr55/Zep7rg5vSM7RrRqnw6Lq4G9o9+R2b3neXH9F8+z+I25c9yfT08iyrqjA3KrmZAFPfoD8vaSSB9dUuBuDUTkHiOsdZfUsZaogv8A5X9ipn8TL50MaCGunFdUM/s0LuyCMpZBuF9rW7+eXFbKR4P0ZZegEBKAIAgCAIAgCAgoD8+dOmhns1R9JQM+pmNpQBlHLuceDXfMcwvLQReujysE2FUrh7sTYz4x3jP8vxXzjjVfLm2fXf69S0ofuIsKqjMSpT0QVSqqfoSt9vY0+yVLmtq2t2RvJs2pA3bbO4+O3tvZ/iTtj4Fj6rsaGRVp8yOnxSB7Q5pBBAII2EHMELpjVPRSAgCAIAgCAhAc906x6WpqBg1BIWvI1qudufURH3GndI71A9Ro52bDEpc5fZep7rrc3pGXgmDw0ULYKdmq0erjvc47SSvnWXl25M3OxlnCCgtIz1qHslAeVTUNiY6R5s1jS4k7gBcrPjQc7YqPqeZvUWzgvRtoHLi84e8ObTMP1smzW39Ww73Hedy+qpFSz9P0FHHTxMhhYGMY0Na0ZAAbAF6IPdASgIQBAEAQBAEAQBAeFdSMnjdDKwPY9pa5rhcEHaCgOU09O7R2p9klJNBO8mnmP7l7jnFKdwvsP/u3O8c4U8iPi1/Eu/zNmi7l91l1BXCNNPTLD6EqCTzqIWyMdG9oc1wLXNIuCCLEELJVZKuanF9UeWk1owOjmpNM6XCJXEmD6ynJ9+mccgOJY7snxavpnDsxZVKmu/n9Srshyy0XoLeMZ8STNb3nAeJA+aAwZMdpWmzqqEHnIwfqo2kD4/8AklH/AM5B/wB1n9VHMgZVNiMMv7OaN/4XtPyKlaBlKQVvTzSI4fSF0Q16iUiKmj260rsmm28DafBeJzUE5S7IlJt6NFongpoqfVe7XmkJknk2l8js3G+8bgvnHFM95dzf5V2LOqvlRulVmUIDzqJmxsL3uDWtBJcTYADeV7rrlZLlgtshtLuUaCjqNJZyGl8OFxusXd11SQdjfu893js7/hPCY4kFOfWb/YrrrnN6XY65h1BFTxNghjDI2CzWtFgAFeGAyUAQBAQgJQBAEAQEIAgCjYCkGDjWEw1tO+mqGB8cgs4H4EHcRtBQHMKF9RgdQ2hr5OspJDq0tU7LVO6GU7AbbPDhs5fjXCFavGpXvea9Tbou17rLqDfYuKlFxemb2woBW9MWTxdRXUcXWVFPKOyNr4n9mWM8j2Tysuh4BnRx7ZRseotfua2RW5La7nvLWYvW5ukiw+Mjuxjr5sxvkdZo8m+qucr2jor6Vrm/sYYYrfVmJFoHSE61SZqp9yS6ole+5Jv3AQy3kqO/2hyrOkdR+hnjjRRtYdHqNgsykhA5Rt/oq6XEcmT25syquPoexwam/wCXi/gb/Refx+R/WyfDj6GDVaIUMmZpY2uGx8YMbx4PYQ4eqz08Xy6ntTZ4dMH5Hg3R6opzrUOJVEed+rmd7REeRD+1/mKt8f2msT/1Yp/TuYpYq8j5wzD62WudV4k+KQxsDKcRAtYy9+scGuJIccszdeeK8ahk0qFW1vuRTQ4vbLKuYNsIDVaQY/BQRdbO+25rBm953Na3aVvYWBblS5a19/I8TsjFdTUYToxV4y9tTiYdBSA60dG02dJwdOeH3fku84fwurEj06y9f4K6y1zOn09O2NgjjaGtaLNa0WAA3ABWhiPVAEAQEICUAQBAEAQEIBdAeFVWRxNL5ZGMaNrnua0DxJNggKtifSZhcB1RVCZ32adpm+LOz8V5cku7JSZrH9I9RNcUWD1Un2XTAQMPm9alnEcWv4rF+u/7HpVyfkavG24xikL6adlFTwyCzmkOneOBF7NBBsQRmCFWXe0eJH4dsyxxZPuYVDFVYFEBK91XSAdpwB6yDmBftR8typ7Hj8Tk+X3bP2f/ACZ481XR9UWrA8dgrmOkpnF7GnV1ixzQTa+WsBdUmXhW4suWzuzPXNTW0bJaiej2EJCAIAgCAIAgCkgrP0/PWzSUmGQXkiOrLLOCyOI52y7zybXAC6jh3s87ErLn7r66XmaluRrojf6L6CRUsntVS81dWds8ovqHeIWbIx4bsl2FVNdUeSC0jSlJvuW9ZSAgCAICUAQEXQC6AXQGLiOJw0zC+eZkbQLkvcGi3HNAVDE+lfDouzA6Srf9imjL/MuNm28/JeJzjDrJ6+pKW+xqDprjVUCKbCY4Adj6iW+W42AGfJV13GMSrvP9DIqJvyMU4Fi9Tc1mMOY122OlZq+jzYj0Kqb/AGnrT1VDfzZmjit92ZdFoFRMs6Vj6h32qh7pT42OQ8gqa/j+XZ2evoZ448F3LBS0MUItFExn4WgfJVc8m2fxSb+5lUIrsZCwHohSCm6QvdilUcLicRBHqurJGnbfu07TxNrnkr/DisGj8VYvefwr/JrzbnLlXYtlFRxwRtiiYGMaLNa0WAAVLfdO6bnY+rM8YqK0j1c4N2kDxNl4jXKXwocyJBvmFEouPcnfoSvICEhACgIQg+ZJGt7zgL7LkC/qvcapS+FEOSXc+l5a13J2vIrmk9LNA4YnQj+0Qj6xmwVEQzdE8DaRmQdoXR8D4m6Jqmx+6/2Zq31JrmRfcDxWOspoqqE3ZKwPHEXGbTwIOR8F3JoGcpAQBAEAQBAYOLYxT0bOsqZ44m8XuDb+AOZ8Ao2DnGM9L3WvMGD0j6qT7Za4Rt5kDMjmSBzWK26uqPNN6+p6jCT7GDJSY/iOdXWso4ztipxY+BcCT6uIVJk+0WPX0rXMzPHGk+5nUHR5RsIfUdZVPHvVEjnjyZfV9bqgyfaDKt6RfKvl/JsRxoLuWWkoYoRaKJjBwY1rfkFUWZNtnxybMyhFeRkLCeugUAXQkIAhDNFpvjZoKF8zM5HWjiHGR+TfTM+Ss+FYn4nISl8K6v6IxXT5URoTgpoqNrHm8shMszjmXSPzNzyyHknFsr8RkPl+FdF9BTDlj1J010hGHUb6iwL+7G07C87L8htPgo4Xhfi71F9u7+gtnyR2Vjoaohirqisr5XzvY9rWxue4MaHC5cWA2PAbsl9Bqxaa0oxikV7tk2Z2kuIfQ+Nw07HH2arY28RJIik1jGHMvm1p7OWzMqu4twyu+luC1JdTJTc1LqXdfPtFj36kKCQgCArunmkf0bROmaAZHHUiBzGsQcyOAAJ8la8Iwfxd+n8K7mG6zkR9aC6P01bhcVRWMFTLUNL5JJe0QbkasZ/dhtstW1iLr6FVjVVx1CKSKtzk3tlA0f0lkw7GJMNdO6Wl650Tdc6xjPukOOeRyI3+Kp+McLqtpdkI6kuvTzNii5p6Z19cD1T+ZY9ytaK1TsOxl+Hk2pqxr54G7mTC7pmN4Bwu62zLJfReC5n4jHW+66P/AAVl8OWR01XBhJQBAEAQHGBpLi2L1U9JFLHQMp3lkob25tpGVxvtty5XVbxHiMcOHNJN77ehlqq8TszZYb0e0UTutma6plObpKhxkJPHNchk8fybfhfKvkbsMeK7lop4Gxt1I2NY0bGtAaPQKmsunY+ab2zMopdj0WMkISEICEhAEICEhEQym6YQCoxPDqU5tD5Z3DcRG3L4j4q/4ZLwcO635Jfqa9q3OKLkqE2NHP8ApqonSYeyRouIpQ53IOGrfwvb1XR+zd0Y3uD80a2V8JxzCMZqKKQyUs74nEWJYbXHAjYV25odjOw6SpxLEIteR8sz5GdtxuQGkEnkAAStfKsjVTKcu2meq9uWj9KlfLX3ZbLtoKAEJCA5302UTpKGOVouIpbv5Nc0tv629V03szbGN0oPu10NTJTaTOS4fpFWU0Zhgq5o4zfsMe4DPaRbu+S7ZPRoLqRo7SvnrYI2XLnSsPPJwc4/Ala+TZGumcpdtM9QW2j9PgL5bN7k9FsuiKb0muMMNPXtNnUtVFJf7pdquv8AD1XR+zV3LkOHqv7GtlR93Z1eCUPa17djgHDwIuF3JoH2gJQEIAgOa9JGBupJm49SA68QAqoxslg2Odbi0Z+AvuWpm4kcmqVcvPt8me658sto3eH1rKiJk0Tg5j2hzSOB/VfMsiiVNjhNdUWkZJrZ7rCeghJKAhAEAQBAEAQgqFY7/wDQ04O6km1fHWF/1XQV/wDqZa/qRry/3kemP6aNppTDHH1jm5OJdqgHgMjcrBi8KdsOactHQ4fCJ3w55PSPfBNJYa8GCRga5wIMbrOa8bwDv8LLzfg2YjVlb7eZgz+FTx1vvH1K1i3RBTySa9PUPhaTcsLRIB+E3BA5G6saPaayEdWQ2/Xeiili9ehZdEtCqbDATEC+UizpX21rcGgCzRy9SVW5/F7svo+kfQy10qBZFUmYISEAQg8qqnZKx0cjQ5jhZzXC4IO4rJVbOqalB6ZDSfc53inQ/TSSa0FRJC0+4WiQD8JJBt43XS0+01kY6sht+vY1ZYu3tG80d0OosHa6o1i54FjLJa4G8MAybf15rRy+KZGe1UlpeiNjHxW5csVtmLWdILQ+0UGs0b3O1b+AsfivdfBdr3pdTpKuAzlHc5aZ8aeYjHWYBUSs2WjyO1rhNHksnC8eePxGEX8/7M5/iONOjcJHVMDv7LBfb1Mf8gXeFKZ6AhAEAQHzLGHNLXAEEEEHYQciCo0DjdPE/R/FPYXk+w1bi6mcdkUhOcd920Zc2niqDjnDVkV+LBe9H91/wbNFvK9Mvy4JryLAlQAhIQBAEICA1WN6RUtE29RM1pPdYO0934WDM/Jb+Jw6/JlqEXr1Mc7Ix7lQqtMq+apgpqehdA2ocdSSdpDjG0jrJAzKwANwTtuNqv5cCpxqJW5EttLsv2Rr/iHKWom00pIhxXDqn7Tpqc8O2y7b+Z+C0+G/62JdV6af7mWfSyLZQsRv10mtt133/iKuK9cq0fScRrwIa9DyhlcxzXtNnNIIPAg3ClxUk0/My21Rsg4S8zs2EVnX08c322g+e9cZlVeHa4Hz6+vw7ZQ9GZbhcW48MvQrDF6ezCymSVWK0TnRNpvbo7nq5esYx4G5sgJFyPtK/UOHZKU3Lw35rrr7Gu3ZHstnyKHGKzOaoZRMPuQgPktwMm4+BR38Nxvgjzv1fYctku70S7RGth7VNi9QX8Kg9aw8rOvbyT/9XFs6WUrXy6DwZLqpENxbGYexLh0c5/vIZWtB/K4ghHjcMs6wt5fk1/A57V5G0wKGuml9prSIQAQymjdcC+10rh33cBsC1MyzErr8LHXM33k/8HuPM/iLEqlmU5r0g4m6So9nB7EdiRxcRtPgF1HC8eMKufzZ1nBMVRr8V932KmrQvzZ1LicIlp99TUwRMHE67HOt/D8VGNXzZsJL8qe/utHE+08lzpfI/QlFD1cbGfZY1voAF0ZyJ7oAgCAICEBptLtHIsTpH0s2Qdmxw2seO69vMKNAoeh2MytkfhVdlVUwtrf30fuSN45ELhuO8LdM/HrXuvv8iwx7U1p9y2rmzZJQEIAmgafHtJqWhA6+XtnJsbO1I4nIBrBndWGHwzIyn7kenr5GOdsYI11Nh+K4sQT/APXUp42fUvb4bGXHpzXYYXAaKPen7z/Y0rMiT7FswTQ+gw1rpWRAvALnzzHrJDYXLi92zZfJXiSitI1+5UtFpn4hUz4vKOzITDStPuwMcRrDm8i54+Flx/tJm7kqIvt3N3Fr6czMrTrB3VlE5sWUsTmzQn78dyB5i481UcIylRkLm+GXR/cz2x5o7OdVz/aImV7BZsvZkG+OduUjHcLnMeK6Xl8Obq9O3zR2HAeIK6nw5d0a9ei+bS22dh0YgMdHExwsQwXHxXIcQmpZDaOAzZqV8mvU2i0jVCDQQBBoIAgCA5DpY0iumv8Abv5WFl2WD1oj9DuuFtPFho11JTPmkbHG27nGwH9eS2JzUI7l2Rt3XRpg5SfRFt0Zwv2vGoKePtU2GAvlfufUkZAcw6x/IRwW/wALqfI7Zd5f28j5jxLKeRe5M7UFaleSgCAhAEAQAoCi9JmiL6uNtdREsrqYExubYGRozMRvkb52vxtsJWO2qFkHCa2mSnyvaNToLpezEoi1wDKiPKWPYcjYuaDna/ocl8+4twqWJPmj8D7MsablNdS0KnM+zS6TaU0uHM1qiQax7sbbF7vBu4cyrDC4Zfly9xdPXyMc7Yw7lfoW4tjjgYmuw6jOfWOH10o3aoOYHhYZ7SuwweBUY/WfvP8AY0rMiUu3QvejOgtFh56yOMyTHvTzHrJD4E90chZXcYKK0jA9lnUkFB6Uqp8wgwmB5a+rcTMRtZTs/aHlrEho/MtXMyljUysfl/c9whzPRsKKlZDEyGNuqyNoY0cA0WAXzK62Vs5WSfVstYxUVpGJpDizaKmfUPz1RZrd7nuNmMHMkhZ+H4ssi+NaPFk+WJSodH6nB4RWTt6+nqe3WxBt+pe4kiRg3gA2I25Lu87B8ateG9Sj2f8Ag06MmdU+aLLRh2jtAdSohia4OAex2u9zSDmCASQuLvzcuDdVj15dtF6+KZNsOVz2vsb5Vndml3YUAISEAQBAEBKA0uN6NQVbg+QOa8C2s02JHA7it/F4hbQuVdUbuLxC7HWoPoV/EY20LhQ4ZEZK6cZEm/VMOXWyHYxozt4b1e8Px7s+fiW9K15epqcQ4ndatTZ0TQ3RqLDKRtPH2nd6WQ7ZJDm55J57F2CWkUfzN6vQCAIAgCAIAgCA5H0qaISU0wxzDRqyxnWnY0d9pyMlht4OG8G+5YMiiF1brn2Z6jLlezXYXjeK47ZlBCKSHLrKl+efvCPLM8APMhU2L7P0VS5p+98vIzzyJNaLzot0bUdE7r5b1VSc3Tz9s63FoOQ+eQzV9GEYrUVpGtvZdF6AsgPKsqGQxulkcGsY0ucTsAAuT6BAcs0He+unqcZmB+vd1dO0+5Awm1uGsflzXGe0uZzSVEfLq/qbuLXr3i4rlDcNJpVo1HiUcccskjBHIJGmMgHWAIBz4XOfNWPDuIyw5OUVva0Y7a1NdTXS6EMc0iWvrXNtnr1UhFrZ3ztZWS9osqT0kv0MX4aCKl0eUdY1tRPh0rTTNne2KCe9pGg7Q8dx1rbrX28VY8WtxXyQyV7zXWS8v5MVKl1cex03C6t8rNaSB8LgbFjy0+bXNJDm81yeTTCuWoSUl6o3IttdTMWuz2EAQBAEAQgICq45iGISiSOjpura3WvNK5oLrf3bcznuJV9h42HXKLuntvyX+TDY5+Rv+i6ipxQR1UQvNMP7RI7N7pWkh7XE52DgQBwsu8qjCMEo9itl36lysshBKAIAgIQEoAgCAhACL5ID5jjDRqtAA4AWHoFAPqykEoAgKB01MqpMM6ikhkkMkjRIIwSerbdxBtnYkNGXNQwUyh05qoI2RHAapjWNDRqtl3C2QMQXMZHs54s3Z4nV+qNuOTyrWjYxdIp97Cq8HlBf9QtKXsvd5TX7ntZS9DJZp6y1zQVzRxNM/L0WJ+zWQvzI9fio+hg6SabRTYRNUUuvd7vZ2azS0l7gL6o35HdwXrB4ROnNjGxrouYid24bRaNFcJFFRQ0wAuxjdcje8i7z/Ff4Ko4jku/IlPy30M1ceSKRtVopNvRkfQ8KKsZOwSRPDm3IuNxBsQeBB3LJdROmXLNaZEZJ9j3WI9BAEAQBEQeVPUsk1tRwdqOLHW3OG1viFlsqlXrm81shSTPZY+zJK70f1XsuKVmGnJjz7TCPxAa4HkR/CvpfCsjxsaMisujyyOlKyMIQBAEAQBAQgCAICUAQEIAgCAIAgCAo+nmLySyNwikdaSZpdUSDbBT7CeT3d0eN1o5+ZHFpdj+3zZ7qg5vRUKzDI5MVpMOiAFPRRCdzBs6wkiPW4nLWv97muYhkzhh2ZM/im9L6G3yLnUfQv5XLt+ZtoJsFZoWikxSSAZR1bOvYNwlYdWUDhcFh8+Subt5ODGzzg9P6eX+TBH3Z69SzKlM4QkIAgNHpZijoY2wQf7RUO6uEcPtyHgGg3v4cVacNxlZN2WfDHq/4+5htlpaXdmfg2GtpadkDMwwWLjtc7a57uJJufNauVkPItdj/AOo9wjyrRmrV2einabE0dTS4szZA8MmttMbjv42BdlxK6z2aytN0v6o1cmOzrDSCLg3B2LsjQJQBAEAQBAEAQBAEAQBAEAQBAEBoNNdJo8LpHVDxrPPYhj3ySHusHK+08F5k0u4KrophT6aKSqq3a1TOetqH8MriMfdaMrLgOL5zzMhQj8Kel/JY0w5Ftmn6OpvapqvEX5GeUsiudscYGziO74ZrY4xHwqa8dflW2Kercn5l6XNGwAgK1p3GWU7a1gu+kkbMAN7O7I3zaSFb8ImpWOiXaa1/H7mG7oub0LFFIHtD2m4cA4HiCLg+iq7IOE3F+RlXbZ9rwSQhJKnuyCq4C32yvqK85tiPssHCzc5njxcbfl5K7zH+GxoY67v3pf4X/fUwQXNLmZaVR7M5IQM1ukVB7TSTQWuXMdb8QF2/ELd4fc6ciMl6nixbibLo1xI1OFU73G7mN6p3jH2R8AF9Pi01tFVJddFnXoglAQgCAICUBCAIAgCAIAgCAIAgOSdJVNVx4pFiM1M6ooKZoLGxWJjfYF0sjdpsc77AGg5b9TNpsuplXB6bPcGk9s1ul2ndNU4c+Oim1ppyyEMsQ9oebPJB2dm4vxIXK8P4PdRk89y92O3s27LlKGkeuK0X0Z9FPbkyF5gkts+uDbl35m/FTTd+M/EV+vVfYSThys6CuWa09G2FBJ5VUDZY3RvF2vaWnwcCCstFrqsU15HmUdrRo9BZnOoWRyd+Bz6d3jE4sB9AFYcXrUcjmXaS3+pjpe46LCqoyhAaPTPFjR0Msre+QI4xxe86rfmT5Kx4Xjq/Jin2XV/RGO2XLEyNGMNFJRxQb2sBceL3dp5PMuJKx8Rv8bIlP/vQmtaibRaRkCaIK9g+JSVNfUar/wCzwBsIAtZ03ekdffYWH+qt8mmGPjQ2vfl1+3kYYycpP0HRlUGCur8Ocf3hqIx915uQOQ1meq7jh1ysxoSXojRtjqR0hb5iJQBAEAQEICUAQBAEAQBAEAQBAQUBxzSrAaV+klNHBA1jmRmonLRYHPsEgZXJyvzVXxi/wcWTX0M1EeaZaNJcJFbSS0zvfadW+5wzafVcFgZTx8iMywsjuOjX6B4waqjaJP20JMMwO3WZ2bnmbet1scXxVTfzR+GXVfc80y3HRY1VGUIDQYK/q6+sp+PVVDfCRpYR/FGT5q3y4OeJVb9V/wB/UwweptG/VQZwhBUNJ7VWJ0VD7rC6qkH4BZgPmfir7A/0cO27zfur7mvb700i3qifXqbAUElc00xt1NE2CnGtU1B6uFvC/ekdwA+dlbcLxI2zdlnSEer/AIMNs9LlXdmw0bwhtFSsp2m5Fy929z3G73nmT8gtbPynkXOf6fQ9Vx5Vo01dIKXH6Kp92Zrqd9uLgWs/zFp8l1Xs3dzVOHoamSuuzql105qBAEAQBAEAQBAEAQBAEAQBAEBVeknS4YRQunABlcdSFp2F5G13IC5PggORyjE6XqsWZUsmlrurif1jB2C67mNFsg3s2y2cFQXX42bKdFqfudTYjFwSaL3ohj0tSJIKuMRVUBtIwbHNObZGZ7CuX4ngQp1ZS9wfb+Dcqm37r7mpxqT6KxJtYBanqyI6jgyT3ZR47/PetzG1n4jqfxw6x+a9DHL/AE58y7MvLSCLg3BzHhuXPOLi9SNhPa2F5RJT8dkNLi9JOx1/aQaaSPfq95sjfA/C66DDSvwLK5fl6p/4Neb5bEXFc+bJCmPV6IKZoYDW1U2LuyDgaeFm9sbHDWc7gSWjJX/E3+Gx4Yi+rfzNelc0nMuYXPmweFfWMp4nzSu1WMaXOPILNRTK6xQiurPMpcq2VXQ+jdVzOxipB1pAW07DsihvkfxO4/1VzxK6OPWsSry+J+rMNceZ87N3pJj8VBD1kmbjkxg2vPAcuar8HBnlT0uiXdmSc+RHPcXxyqxGMyimbCaFxlc/XNw5vuWIHauNnyXWYWJVw+xJT25mrZOVi7HZ9GdI6evj1oJmvcxrOsAyLS4XzG7MO9CujNQ3KAIAgCAIAgCAIAgCAIAgCAICj9JDWGbDxK0OjdUyRuDhcfWU8jGg7syQPNaPEXOONOUO6W/0MleubqVWKgMmHTYfl11FIHRZ7Qx3WwG5zs5vZJ/FwXLStUcmGR+Wxaf1a0zcS9xx9CNLpXRtpsdp2m7GNEzdhfA/Mh3NpJ8LlMDkk7MGx930fzIs6asRaqqmhxGj1HDWinjDhyDhrNcOBGR8lS12WYWRtdHFmdpTiVzRuvlw69DXkhjL9RUm+o9n2HO2NcOatMzHrzErsfW38UTDCbg+WR9VPSLT31KeCed97arI3C/MEjNeK+BWd7JKK+qJeQvymRo1g075xiVcR17oy1kQaAIGk3t+O20+K8Z2VVXW8XH+HfV+pMIN+9ItSpDOET0wUM1hwavkEoAoqpzpQ8NceqksNYG17AnP8110vhR4jixcf9yK1r1NXbrl17F3hqWPYJGPa5pGsHAixHHwVBKiyMuVxezYUkyjVb3Y7VGBhIoYHjrHj9+9p7jfujiugrjHhlHPL/dkui9DBvxZa8i92bGzc1rR4AAD5ALnvfus9W2Z+iRTsBpfbamTFqn9m0kUzXbGxt/egc8zfxPBdBkWLHhHDq+J/EYUub3ma91I4YQf7zEKljjxtLMHW/hB9VnVnNmJeVcf3S0R2j9SydGdO1mJ4kI2BscYpogGgAEgS3yG/wDqui4ZKUseM5d2alqSZ0lWBiCAIAgCAIAgCAIAgCAIAgCAr2nuDurMPljj/atAlhPCWM68dvEi3mvMoqScX2ZKemaLR2siq4WVrGgOmjYHm2d237B8CXeq+Z59dlFjpk+ib19y0r01tGfVUzJY3RPbdrmlpHIiy1abpV2Ka7o9uKa0VPo2ldHHPh8hJdSTOjB4sJuwjyz81c8bhGbhkR7SW/uYKHrcX5FyIvkVRKTXY2OvmQ1gGwAeAsnPJ92NH0vICEhAec8LZGlj2hzXCxBFwQsldkoSUovTR5a30ZVHdHND+7EsYN9Zsc0ga4HaHC+zwVwuP5OuqTfq0YnQizUFFHTxthiYGMaLNaNn+qqb753T55vbZlUeVdDQab1LnNioIjZ9U/UJG1sYsZD57PVWnCaormyJ9or9zFa/y+pv2UMYgFPq/VhnV2+7a1vRVk8iTu8XfXezIl00YtdRQsEczxZlK1zmDY1tm2BtyaLBbOPfbObhHvPuzzJLX0PforonNo31TxZ1XM+ex2hhs2Megv8AmX0fGq8KqMPRFbN7ZdFnPAQEICUBCAlAEAQBAEAQBAEAQEIDm1RT/ROJGM5Utc9z4uEVRa74+TX94cwVznH+HeNX40O8e/zRtY1mpcrLCuF7G/5lTpCYsemjA7M1KyU83MdqX8bEegV7bqfDIy/pejBHpYy2KgNgKSAhIQBAEAQBAVS3W49Y7IKQuHi9wHycVevdXDdr8zNd9bC1qiM5WNKi6snhwiE9qYh85HuQsN3a3iQBzyG9dT7O4PPPx5dl2NbInpaR0umhbGxsbBZrQGgcABYLtUV56IAgCAIAgCAIAgCAIAgCAIAgCA1mkeBRYhTOppxdrrEEZOY4d17TucOKhpNaYKHHiFRhbvZ8Tu6MZRVjGkseNzZrZseLZnYuS4pwF7dmOu/dfwbtN/TUjUVmKyOxH2+ippKuFkHUufEDq3Lg46rrEG1h6r3i8HtswnTN8r3sSuSns2A0/iblNSVcbuHVA+huFoT9mr0+jMiyYn3Hpu2Q2hoKx5/wgPjrFTH2avfeSIeSjMjxTEZP2eDyj/EljZ87LYh7MS85/sefxS9D0H0wf+HQjkaht/gVnXszD+o8/ivkQ+rxSMXkwku/wp43fDasU/Zf+mZKyl6GPJpb1X+00FZDzMWsB4lpv8Fp2ezd8V7rTMiyYs9KbTbD5DYVTWnhIHRn/OAtGzguZDvEyK6LNrBisEncnjd4Paf1WnPDvh0cWeuePqVoVbI8e77T11KGCxBs5rgQD4hpVy6bLOG611izCpJTNtpNpLDQMu460hyZEO847stwWhw/hluTPtpeZ7naoxNp0e4DJBG+rqs6mqIfJl3G+5EOFhuX0THojRWoQ8itnJyey3WWc8koCEAQBAEAQBAEAQBAEAQBAEAQBAfEjA4WcARwIuFDIfcRxhos1oA4AAD4KSSXMB2gHxF0BIFti8sEqUApAKBHza+RUkmFW4JTTjVmponjg5jT+iggr1b0dYW/bRMH4HSM/kcFGkSpM0uPdH+HU9M+WKmLXsF2uE9RkeOciOKa00TtmB0PYTDM6Wqlj6yVjgGveXOLRbdrG1+e1eY1xj0iiZN6OshezwSgCAIAgCA//9k=',- // docTransform: {- // size: {- // width: 239,- // height: 211,- // },- // angle: 0,- // positionH: {- // relativeFrom: 0,- // posOffset: 256,- // },- // positionV: {- // relativeFrom: ObjectRelativeFromV.PARAGRAPH,- // posOffset: 100,- // },- // },- // behindDoc: 0,- // title: '',- // description: '',- // wrapText: 0,- // distB: 0,- // distL: 0,- // distR: 0,- // distT: 0,- // layoutType: PositionedObjectLayoutType.WRAP_TOP_AND_BOTTOM,- // },- },- drawingsOrder: [- // 'zYeeTi',- ],+ tableSource: {},+ drawings: {},+ drawingsOrder: [],headers: {},footers: {},body: {@@ -767,32 +599,8 @@ export const DEFAULT_DOCUMENT_DATA_CN: IDocumentData = {// contentDirection: textDirection!,},],- customBlocks: [- // {- // startIndex: 189,- // blockId: 'shapeTest1',- // },- // {- // startIndex: 367,- // blockId: 'shapeTest2',- // },- // {- // startIndex: 489,- // blockId: 'shapeTest3',- // },- // {- // startIndex: 668,- // blockId: 'shapeTest4',- // },- // {- // startIndex: 962,- // blockId: 'shapeTest5',- // },- // {- // blockId: 'zYeeTi',- // startIndex: 463,- // },- ],+ customBlocks: [],+ tables: [],},documentStyle: {pageSize: {diff --git a/examples/src/data/docs/default-document.data-simple.ts b/examples/src/data/docs/default-document.data-simple.tsindex 27fcef8eff..fb11834cdb 100644--- a/examples/src/data/docs/default-document.data-simple.ts+++ b/examples/src/data/docs/default-document.data-simple.ts@@ -14,17 +14,179 @@* limitations under the License.*/-import type { IDocumentData } from '@univerjs/core';-import { BooleanNumber, DocumentFlavor } from '@univerjs/core';+import type { IDocumentData, IParagraph, ISectionBreak, ITable, ITableCell, ITableColumn, ITableRow } from '@univerjs/core';+import { BooleanNumber, DocumentFlavor, HorizontalAlign, ObjectRelativeFromH, ObjectRelativeFromV, TableAlignmentType, TableCellHeightRule, TableSizeType, TableTextWrapType, Tools } from '@univerjs/core';+import { ptToPixel } from '@univerjs/engine-render';++const TABLE_START = '\x1A'; // 表格开始+const TABLE_ROW_START = '\x1B'; // 表格行开始+const TABLE_CELL_START = '\x1C'; // 表格单元格开始+const TABLE_CELL_END = '\x1D'; // 表格单元格结束+const TABLE_ROW_END = '\x0E'; // 表格行结束+const TABLE_END = '\x0F'; // 表格结束++function createTableDataStream(tables: string[][]) {+ const row = tables.length;+ const col = tables[0].length;+ let dataStream = TABLE_START;++ for (let i = 0; i < row; i++) {+ dataStream += TABLE_ROW_START;+ for (let j = 0; j < col; j++) {+ dataStream += `${TABLE_CELL_START + tables[i][j]}\r\n${TABLE_CELL_END}`;+ }+ dataStream += TABLE_ROW_END;+ }++ return dataStream + TABLE_END;+}++const exampleTables = [+ ['姓名\r这是一个段落\r这是二个段落\r这是三个段落\r这是四个段落', '语文', '数学', '英语', '总分'],+ ['张三', '80', '90', '70', '240'],+ ['李四', '80', '90', '70', '240'],+ ['王五', '80', '90', '70', '240'],+ ['赵六', '80', '90', '70', '240'],+];++const dataStream = `这是一个表格的用例\r${createTableDataStream(exampleTables)}班级成绩统计\r\n`;++const startIndex = dataStream.indexOf(TABLE_START);+const endIndex = dataStream.indexOf(TABLE_END);++function createParagraphAndSectionBreaks(dataStream: string) {+ const paragraphs: IParagraph[] = [];+ const sectionBreaks: ISectionBreak[] = [];+ for (let i = 0; i < dataStream.length; i++) {+ const char = dataStream[i];+ if (char === '\r') {+ paragraphs.push({+ startIndex: i,+ paragraphStyle: {+ spaceAbove: { v: 5 },+ lineSpacing: 2,+ spaceBelow: { v: 0 },+ horizontalAlign: HorizontalAlign.LEFT,+ },+ });+ }++ if (char === '\n') {+ sectionBreaks.push({+ startIndex: i,+ });+ }+ }++ return { paragraphs, sectionBreaks };+}++const { paragraphs, sectionBreaks } = createParagraphAndSectionBreaks(dataStream);++const tableCell: ITableCell = {+ rowSpan: 1,+ columnSpan: 1,+ margin: {+ start: {+ v: 10,+ },+ end: {+ v: 10,+ },+ top: {+ v: 5,+ },+ bottom: {+ v: 5,+ },+ },+};++const tableRow: ITableRow = {+ tableCells: [...new Array(exampleTables[0].length).fill(Tools.deepClone(tableCell))],+ trHeight: {+ val: { v: 30 },+ hRule: TableCellHeightRule.AUTO,+ },+};++const tableColumn: ITableColumn = {+ size: {+ type: TableSizeType.SPECIFIED,+ width: {+ v: 100,+ },+ },+};++const tableRows = [...new Array(exampleTables.length).fill(null).map(() => Tools.deepClone(tableRow))];+const tableColumns = [...new Array(exampleTables[0].length).fill(null).map(() => Tools.deepClone(tableColumn))];++tableColumns[0].size.width.v = 250;++const table: ITable = {+ tableRows,+ tableColumns,+ tableId: 'table-id',+ align: TableAlignmentType.START,+ indent: {+ v: 0,+ },+ textWrap: TableTextWrapType.NONE,+ position: {+ positionH: {+ relativeFrom: ObjectRelativeFromH.PAGE,+ posOffset: 0,+ },+ positionV: {+ relativeFrom: ObjectRelativeFromV.PAGE,+ posOffset: 0,+ },+ },+ dist: {+ distB: 0,+ distL: 0,+ distR: 0,+ distT: 0,+ },+ cellMargin: {+ start: {+ v: 10,+ },+ end: {+ v: 10,+ },+ top: {+ v: 5,+ },+ bottom: {+ v: 5,+ },+ },+ size: {+ type: TableSizeType.UNSPECIFIED,+ width: {+ v: 1000,+ },+ },+};export const DEFAULT_DOCUMENT_DATA_SIMPLE: IDocumentData = {id: 'default-document-id',+ tableSource: {+ 'table-id': table,+ },+ headers: {},+ footers: {},+ drawings: {},+ drawingsOrder: [],body: {- dataStream: '荷塘𠮷\r作者:朱自清 👨👩👧👦 Today Office\r\n',+ dataStream,+ customBlocks: [],textRuns: [{st: 0,- ed: 4,+ ed: 9,ts: {fs: 24,ff: 'Microsoft YaHei',@@ -38,10 +200,10 @@ export const DEFAULT_DOCUMENT_DATA_SIMPLE: IDocumentData = {},},{- st: 5,- ed: 36,+ st: 9,+ ed: 12,ts: {- fs: 18,+ fs: 14,ff: 'Times New Roman',cl: {rgb: 'rgb(30, 30, 30)',@@ -49,54 +211,62 @@ export const DEFAULT_DOCUMENT_DATA_SIMPLE: IDocumentData = {bl: BooleanNumber.FALSE,},},- ],- paragraphs: [{- startIndex: 4,- paragraphStyle: {- spaceAbove: { v: 10 },- lineSpacing: 2,- spaceBelow: { v: 0 },+ st: 13,+ ed: 15,+ ts: {+ fs: 14,+ ff: 'Times New Roman',+ cl: {+ rgb: 'rgb(130, 30, 30)',+ },+ bl: BooleanNumber.TRUE,},},{- startIndex: 36,- paragraphStyle: {- spaceAbove: { v: 10 },- lineSpacing: 2,- spaceBelow: { v: 0 },+ st: 16,+ ed: dataStream.length - 2,+ ts: {+ fs: 14,+ ff: 'Times New Roman',+ cl: {+ rgb: 'rgb(30, 30, 30)',+ },+ bl: BooleanNumber.FALSE,},},],- sectionBreaks: [- {- startIndex: 37,- // columnProperties: [- // {- // width: 250,- // paddingEnd: 15,- // },- // ],- // columnSeparatorType: ColumnSeparatorType.NONE,- // sectionType: SectionType.SECTION_TYPE_UNSPECIFIED,- // textDirection: textDirectionDocument,- // contentDirection: textDirection!,- },- ],+ paragraphs,+ tables: [{+ startIndex,+ endIndex,+ tableId: 'table-id',+ }],+ sectionBreaks,},documentStyle: {pageSize: {- width: 595,- height: 842,+ width: ptToPixel(595),+ height: ptToPixel(842),},documentFlavor: DocumentFlavor.TRADITIONAL,- marginTop: 50,- marginBottom: 50,- marginRight: 40,- marginLeft: 40,+ marginTop: ptToPixel(50),+ marginBottom: ptToPixel(50),+ marginRight: ptToPixel(50),+ marginLeft: ptToPixel(50),renderConfig: {- vertexAngle: 90,+ vertexAngle: 0,centerAngle: 0,},+ defaultHeaderId: '',+ defaultFooterId: '',+ evenPageHeaderId: '',+ evenPageFooterId: '',+ firstPageHeaderId: '',+ firstPageFooterId: '',+ evenAndOddHeaders: BooleanNumber.FALSE,+ useFirstPageHeaderFooter: BooleanNumber.FALSE,+ marginHeader: 30,+ marginFooter: 30,},};diff --git a/examples/src/docs/main.ts b/examples/src/docs/main.tsindex 6b04182e36..6e777a0ee2 100644--- a/examples/src/docs/main.ts+++ b/examples/src/docs/main.ts@@ -30,6 +30,8 @@ import { UniverDocsMentionUIPlugin } from '@univerjs/docs-mention-ui';import { DEFAULT_DOCUMENT_DATA_CN } from '../data';import { enUS, ruRU, zhCN } from '../locales';+// const IS_E2E: boolean = !!process.env.IS_E2E;+// package info// eslint-disable-next-line no-consoleconsole.table({@@ -74,6 +76,7 @@ univer.registerPlugin(UniverDocsDrawingUIPlugin);univer.registerPlugin(UniverDocsThreadCommentUIPlugin);univer.registerPlugin(UniverDocsHyperLinkUIPlugin);univer.registerPlugin(UniverDocsMentionUIPlugin);+univer.createUnit(UniverInstanceType.UNIVER_DOC, DEFAULT_DOCUMENT_DATA_CN);// use for console testdiff --git a/packages/core/package.json b/packages/core/package.jsonindex 9f00c2c29f..269ec0f594 100644--- a/packages/core/package.json+++ b/packages/core/package.json@@ -60,6 +60,7 @@"sync:cnpm": "cnpm sync"},"peerDependencies": {+ "@univerjs/core": "workspace:*","react": "^16.9.0 || ^17.0.0 || ^18.0.0","rxjs": ">=7.0.0"},diff --git a/packages/core/src/docs/data-model/json-x/json-x.ts b/packages/core/src/docs/data-model/json-x/json-x.tsindex 9f762334e7..cab2168022 100644--- a/packages/core/src/docs/data-model/json-x/json-x.ts+++ b/packages/core/src/docs/data-model/json-x/json-x.ts@@ -47,7 +47,8 @@ export class JSONX {private static _subTypes: Map<string, ISubType> = new Map();static registerSubtype(subType: ISubType) {- if (this._subTypes.has(subType.name) && this._subTypes.get(subType.name)?.id !== TextX.id) {+ // Add `subType == null` just use to pass tests.+ if (subType == null || (this._subTypes.has(subType.name) && this._subTypes.get(subType.name)?.id !== TextX.id)) {return;}@@ -67,9 +68,17 @@ export class JSONX {return json1.type.compose(thisActions, otherActions);}- // Do not use transform in JsonX, pls use transform in JsonXPro.- static transform(_thisActions: JSONOp, _otherActions: JSONOp, _priority: TPriority) {- throw new Error('transform is not implemented in JsonX');+ static transform(thisActions: JSONOp, otherActions: JSONOp, priority: TPriority) {+ return json1.type.transform(thisActions, otherActions, priority);+ }++ // Use to transform cursor position, just call TextXPro.transformPosition.+ static transformPosition(thisActions: JSONOp, index: number, priority: TPriority = 'right'): number {+ if (thisActions && thisActions.length === 2 && thisActions[0] === 'body' && (thisActions[1] as any).et === TextX.name) {+ return TextX.transformPosition((thisActions[1] as any).e, index, priority === 'left');+ }++ return index;}static invertWithDoc(actions: JSONOp, doc: IDocumentData) {diff --git a/packages/core/src/docs/data-model/text-x/__tests__/transform-position.spec.ts b/packages/core/src/docs/data-model/text-x/__tests__/transform-position.spec.tsnew file mode 100644index 0000000000..f763e38abe--- /dev/null+++ b/packages/core/src/docs/data-model/text-x/__tests__/transform-position.spec.ts@@ -0,0 +1,202 @@+/**+ * 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 { TextXAction } from '@univerjs/core';+import { TextXActionType } from '@univerjs/core';+import { describe, expect, it } from 'vitest';++import { TextX } from '../text-x';++describe('transformPosition()', () => {+ it('insert before position', () => {+ const actions = [+ {+ t: TextXActionType.INSERT,+ len: 1,+ line: 0,+ body: {+ dataStream: 'h',+ },+ },+ ];+ expect(TextX.transformPosition(actions, 2)).toEqual(3);+ });++ it('insert after position', () => {+ const actions: TextXAction[] = [+ {+ t: TextXActionType.RETAIN,+ segmentId: '',+ len: 1,+ },+ {+ t: TextXActionType.INSERT,+ len: 1,+ line: 0,+ body: {+ dataStream: 'h',+ },+ },+ ];+ expect(TextX.transformPosition(actions, 0)).toEqual(0);+ });++ it('insert at position', () => {+ const actions: TextXAction[] = [+ {+ t: TextXActionType.RETAIN,+ segmentId: '',+ len: 1,+ },+ {+ t: TextXActionType.INSERT,+ len: 1,+ line: 0,+ body: {+ dataStream: 'h',+ },+ },+ ];++ expect(TextX.transformPosition(actions, 1, true)).toEqual(1);+ expect(TextX.transformPosition(actions, 1, false)).toEqual(2);+ });++ it('delete before position', () => {+ const actions: TextXAction[] = [+ {+ t: TextXActionType.DELETE,+ segmentId: '',+ len: 1,+ line: 0,+ },+ ];++ expect(TextX.transformPosition(actions, 3)).toEqual(2);+ });++ it('delete after position', () => {+ const actions: TextXAction[] = [+ {+ t: TextXActionType.RETAIN,+ segmentId: '',+ len: 5,+ },+ {+ t: TextXActionType.DELETE,+ segmentId: '',+ len: 1,+ line: 0,+ },+ ];++ expect(TextX.transformPosition(actions, 3)).toEqual(3);+ });++ it('delete across position', () => {+ const actions: TextXAction[] = [+ {+ t: TextXActionType.RETAIN,+ segmentId: '',+ len: 1,+ },+ {+ t: TextXActionType.DELETE,+ segmentId: '',+ len: 5,+ line: 0,+ },+ ];++ expect(TextX.transformPosition(actions, 3)).toEqual(1);+ });++ it('insert and delete before position', () => {+ const actions: TextXAction[] = [+ {+ t: TextXActionType.RETAIN,+ segmentId: '',+ len: 2,+ },+ {+ t: TextXActionType.INSERT,+ len: 1,+ line: 0,+ body: {+ dataStream: 'h',+ },+ },+ {+ t: TextXActionType.DELETE,+ segmentId: '',+ len: 2,+ line: 0,+ },+ ];++ expect(TextX.transformPosition(actions, 4)).toEqual(3);+ });++ it('insert before and delete across position', () => {+ const actions: TextXAction[] = [+ {+ t: TextXActionType.RETAIN,+ segmentId: '',+ len: 2,+ },+ {+ t: TextXActionType.INSERT,+ len: 1,+ line: 0,+ body: {+ dataStream: 'h',+ },+ },+ {+ t: TextXActionType.DELETE,+ segmentId: '',+ len: 4,+ line: 0,+ },+ ];++ expect(TextX.transformPosition(actions, 4)).toEqual(3);+ });++ it('delete before and delete across position', () => {+ const actions: TextXAction[] = [+ {+ t: TextXActionType.DELETE,+ segmentId: '',+ len: 1,+ line: 0,+ },+ {+ t: TextXActionType.RETAIN,+ segmentId: '',+ len: 1,+ },+ {+ t: TextXActionType.DELETE,+ segmentId: '',+ len: 4,+ line: 0,+ },+ ];++ expect(TextX.transformPosition(actions, 4)).toEqual(1);+ });+});diff --git a/packages/core/src/docs/data-model/text-x/__tests__/transform.spec.ts b/packages/core/src/docs/data-model/text-x/__tests__/transform.spec.tsnew file mode 100644index 0000000000..717d64d9cd--- /dev/null+++ b/packages/core/src/docs/data-model/text-x/__tests__/transform.spec.ts@@ -0,0 +1,675 @@+/**+ * 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 { TextXAction } from '@univerjs/core';+import { BooleanNumber, TextXActionType } from '@univerjs/core';+import { describe, expect, it } from 'vitest';++import { TextX } from '../text-x';++describe('transform()', () => {+ it('insert + insert', () => {+ const actionsA: TextXAction[] = [+ {+ t: TextXActionType.INSERT,+ len: 1,+ line: 0,+ body: {+ dataStream: 'h',+ customRanges: [],+ customDecorations: [],+ },+ },+ ];+ const actionsB: TextXAction[] = [+ {+ t: TextXActionType.INSERT,+ len: 1,+ line: 0,+ body: {+ dataStream: 'e',+ },+ },+ ];++ const expectedActionsWithPriorityTrue: TextXAction[] = [+ {+ t: TextXActionType.RETAIN,+ segmentId: '',+ len: 1,+ },+ {+ t: TextXActionType.INSERT,+ len: 1,+ line: 0,+ body: {+ dataStream: 'e',+ customRanges: [],+ customDecorations: [],+ },+ },+ ];++ const expectedActionsWithPriorityFalse: TextXAction[] = [+ {+ t: TextXActionType.INSERT,+ len: 1,+ line: 0,+ body: {+ dataStream: 'e',+ customRanges: [],+ customDecorations: [],+ },+ },+ ];++ expect(TextX._transform(actionsA, actionsB, 'left')).toEqual(expectedActionsWithPriorityTrue);+ expect(TextX._transform(actionsA, actionsB, 'right')).toEqual(expectedActionsWithPriorityFalse);+ });++ it('insert + retain', () => {+ const actionsA: TextXAction[] = [+ {+ t: TextXActionType.INSERT,+ len: 1,+ line: 0,+ body: {+ dataStream: 'h',+ },+ },+ ];+ const actionsB: TextXAction[] = [+ {+ t: TextXActionType.RETAIN,+ len: 1,+ body: {+ dataStream: '',+ textRuns: [+ {+ st: 0,+ ed: 1,+ ts: {+ bl: BooleanNumber.TRUE,+ },+ },+ ],+ },+ segmentId: '',+ },+ ];+ const expectedActionsWithPriorityTrue = [+ {+ t: TextXActionType.RETAIN,+ segmentId: '',+ len: 1,+ },+ {+ t: TextXActionType.RETAIN,+ len: 1,+ body: {+ dataStream: '',+ customRanges: [],+ customDecorations: [],+ textRuns: [+ {+ st: 0,+ ed: 1,+ ts: {+ bl: BooleanNumber.TRUE,+ },+ },+ ],+ },+ segmentId: '',+ },+ ];++ const expectedActionsWithPriorityFalse: TextXAction[] = [+ {+ t: TextXActionType.RETAIN,+ segmentId: '',+ len: 1,+ },+ {+ t: TextXActionType.RETAIN,+ len: 1,+ body: {+ dataStream: '',+ customRanges: [],+ customDecorations: [],+ textRuns: [+ {+ st: 0,+ ed: 1,+ ts: {+ bl: BooleanNumber.TRUE,+ },+ },+ ],+ },+ segmentId: '',+ },+ ];++ expect(TextX._transform(actionsA, actionsB, 'left')).toEqual(expectedActionsWithPriorityTrue);+ expect(TextX._transform(actionsA, actionsB, 'right')).toEqual(expectedActionsWithPriorityFalse);+ });++ it('insert + delete', () => {+ const actionsA: TextXAction[] = [+ {+ t: TextXActionType.INSERT,+ len: 1,+ line: 0,+ body: {+ dataStream: 'h',+ },+ },+ ];+ const actionsB: TextXAction[] = [+ {+ t: TextXActionType.DELETE,+ len: 1,+ line: 0,+ segmentId: '',+ },+ ];+ const expectedActionsWithPriorityTrue = [+ {+ t: TextXActionType.RETAIN,+ segmentId: '',+ len: 1,+ },+ {+ t: TextXActionType.DELETE,+ len: 1,+ line: 0,+ segmentId: '',+ },+ ];++ expect(TextX._transform(actionsA, actionsB, 'left')).toEqual(expectedActionsWithPriorityTrue);+ });++ it('delete + insert', () => {+ const actionsA: TextXAction[] = [+ {+ t: TextXActionType.DELETE,+ len: 1,+ line: 0,+ },+ ];+ const actionsB: TextXAction[] = [+ {+ t: TextXActionType.INSERT,+ len: 1,+ body: {+ dataStream: 'h',+ },+ line: 0,+ segmentId: '',+ },+ ];+ const expectedActionsWithPriorityTrue: TextXAction[] = [+ {+ t: TextXActionType.INSERT,+ len: 1,+ body: {+ dataStream: 'h',+ customRanges: [],+ customDecorations: [],+ },+ line: 0,+ segmentId: '',+ },+ ];++ expect(TextX._transform(actionsA, actionsB, 'left')).toEqual(expectedActionsWithPriorityTrue);+ });++ it('delete + retain', () => {+ const actionsA: TextXAction[] = [+ {+ t: TextXActionType.DELETE,+ len: 1,+ line: 0,+ },+ ];+ const actionsB: TextXAction[] = [+ {+ t: TextXActionType.RETAIN,+ len: 1,+ segmentId: '',+ },+ ];+ const expectedActionsWithPriorityTrue: TextXAction[] = [];++ expect(TextX._transform(actionsA, actionsB, 'left')).toEqual(expectedActionsWithPriorityTrue);+ });++ it('delete + delete', () => {+ const actionsA: TextXAction[] = [+ {+ t: TextXActionType.DELETE,+ len: 1,+ line: 0,+ },+ ];+ const actionsB: TextXAction[] = [+ {+ t: TextXActionType.DELETE,+ len: 1,+ line: 0,+ },+ ];+ const expectedActionsWithPriorityTrue: TextXAction[] = [];++ expect(TextX._transform(actionsA, actionsB, 'left')).toEqual(expectedActionsWithPriorityTrue);+ });++ it('retain + insert', () => {+ const actionsA: TextXAction[] = [+ {+ t: TextXActionType.RETAIN,+ len: 1,+ segmentId: '',+ },+ ];+ const actionsB: TextXAction[] = [+ {+ t: TextXActionType.INSERT,+ body: {+ dataStream: 'h',+ },+ len: 1,+ line: 0,+ },+ ];+ const expectedActionsWithPriorityTrue: TextXAction[] = [+ {+ t: TextXActionType.INSERT,+ body: {+ dataStream: 'h',+ customRanges: [],+ customDecorations: [],+ },+ len: 1,+ line: 0,+ },+ ];++ expect(TextX._transform(actionsA, actionsB, 'left')).toEqual(expectedActionsWithPriorityTrue);+ });++ it('retain + retain', () => {+ const actionsA1: TextXAction[] = [+ {+ t: TextXActionType.RETAIN,+ len: 1,+ segmentId: '',+ body: {+ dataStream: '',+ textRuns: [+ {+ st: 0,+ ed: 1,+ ts: {+ cl: { rgb: 'blue' },+ },+ },+ ],+ },+ },+ ];++ const actionsA2: TextXAction[] = [+ {+ t: TextXActionType.RETAIN,+ len: 1,+ segmentId: '',+ body: {+ dataStream: '',+ textRuns: [+ {+ st: 0,+ ed: 1,+ ts: {+ cl: { rgb: 'blue' },+ },+ },+ ],+ },+ },+ ];++ const actionsB1: TextXAction[] = [+ {+ t: TextXActionType.RETAIN,+ len: 1,+ segmentId: '',+ body: {+ dataStream: '',+ textRuns: [+ {+ st: 0,+ ed: 1,+ ts: {+ cl: { rgb: 'red' },+ bl: BooleanNumber.TRUE,+ },+ },+ ],+ },+ },+ ];+ const actionsB2: TextXAction[] = [+ {+ t: TextXActionType.RETAIN,+ len: 1,+ segmentId: '',+ body: {+ dataStream: '',+ textRuns: [+ {+ st: 0,+ ed: 1,+ ts: {+ cl: { rgb: 'red' },+ bl: BooleanNumber.TRUE,+ },+ },+ ],+ },+ },+ ];+ const expectedActions1: TextXAction[] = [+ {+ t: TextXActionType.RETAIN,+ len: 1,+ segmentId: '',+ body: {+ dataStream: '',+ textRuns: [+ {+ st: 0,+ ed: 1,+ ts: {+ bl: BooleanNumber.TRUE,+ },+ },+ ],+ },+ },+ ];++ const expectedActions2: TextXAction[] = [];++ expect(TextX._transform(actionsA1, actionsB1, 'left')).toEqual(expectedActions1);+ expect(TextX._transform(actionsB2, actionsA2, 'left')).toEqual(expectedActions2);+ });++ it('retain + retain without priority', () => {+ const actionsA1: TextXAction[] = [+ {+ t: TextXActionType.RETAIN,+ len: 1,+ segmentId: '',+ body: {+ dataStream: '',+ textRuns: [+ {+ st: 0,+ ed: 1,+ ts: {+ cl: { rgb: 'blue' },+ },+ },+ ],+ },+ },+ ];++ const actionsA2: TextXAction[] = [+ {+ t: TextXActionType.RETAIN,+ len: 1,+ segmentId: '',+ body: {+ dataStream: '',+ textRuns: [+ {+ st: 0,+ ed: 1,+ ts: {+ cl: { rgb: 'blue' },+ },+ },+ ],+ },+ },+ ];++ const actionsB1: TextXAction[] = [+ {+ t: TextXActionType.RETAIN,+ len: 1,+ segmentId: '',+ body: {+ dataStream: '',+ textRuns: [+ {+ st: 0,+ ed: 1,+ ts: {+ cl: { rgb: 'red' },+ bl: BooleanNumber.TRUE,+ },+ },+ ],+ },+ },+ ];+ const actionsB2: TextXAction[] = [+ {+ t: TextXActionType.RETAIN,+ len: 1,+ segmentId: '',+ body: {+ dataStream: '',+ textRuns: [+ {+ st: 0,+ ed: 1,+ ts: {+ cl: { rgb: 'red' },+ bl: BooleanNumber.TRUE,+ },+ },+ ],+ },+ },+ ];+ const expectedActions1: TextXAction[] = [+ {+ t: TextXActionType.RETAIN,+ len: 1,+ segmentId: '',+ body: {+ dataStream: '',+ textRuns: [+ {+ st: 0,+ ed: 1,+ ts: {+ bl: BooleanNumber.TRUE,+ cl: { rgb: 'red' },+ },+ },+ ],+ },+ },+ ];++ // TODO: @jocs, fix this case after univer normalizeTextRuns are updated.+ const expectedActions2: TextXAction[] = [+ {+ t: TextXActionType.RETAIN,+ len: 1,+ segmentId: '',+ body: {+ dataStream: '',+ textRuns: [+ {+ st: 0,+ ed: 1,+ ts: {+ cl: { rgb: 'blue' },+ },+ },+ ],+ },+ },+ ];++ expect(TextX._transform(actionsA1, actionsB1, 'right')).toEqual(expectedActions1);+ expect(TextX._transform(actionsB2, actionsA2, 'right')).toEqual(expectedActions2);+ });++ it('retain + delete', () => {+ const actionsA: TextXAction[] = [+ {+ t: TextXActionType.RETAIN,+ len: 1,+ segmentId: '',+ body: {+ dataStream: '',+ textRuns: [+ {+ st: 0,+ ed: 1,+ ts: {+ cl: { rgb: 'blue' },+ },+ },+ ],+ },+ },+ ];++ const actionsB: TextXAction[] = [+ {+ t: TextXActionType.DELETE,+ len: 1,+ line: 0,+ segmentId: '',+ },+ ];++ const expectedActions: TextXAction[] = [+ {+ t: TextXActionType.DELETE,+ len: 1,+ line: 0,+ segmentId: '',+ },+ ];++ expect(TextX._transform(actionsA, actionsB, 'right')).toEqual(expectedActions);+ });++ it('retain + retain with paragraph', () => {+ const actionsA: TextXAction[] = [+ {+ t: TextXActionType.RETAIN,+ len: 1,+ segmentId: '',+ body: {+ dataStream: '',+ paragraphs: [+ {+ startIndex: 0,+ paragraphStyle: {+ lineSpacing: 1,+ },+ },+ ],+ },+ },+ ];++ const actionsB: TextXAction[] = [+ {+ t: TextXActionType.RETAIN,+ len: 1,+ segmentId: '',+ body: {+ dataStream: '',+ paragraphs: [+ {+ startIndex: 0,+ paragraphStyle: {+ lineSpacing: 5,+ spaceBelow: { v: 6 },+ },+ },+ ],+ },+ },+ ];++ const expectedActionsWithPriorityTrue: TextXAction[] = [+ {+ t: TextXActionType.RETAIN,+ len: 1,+ segmentId: '',+ body: {+ dataStream: '',+ paragraphs: [+ {+ startIndex: 0,+ paragraphStyle: {+ spaceBelow: { v: 6 },+ },+ },+ ],+ },+ },+ ];++ const expectedActionsWithPriorityFalse: TextXAction[] = [+ {+ t: TextXActionType.RETAIN,+ len: 1,+ segmentId: '',+ body: {+ dataStream: '',+ paragraphs: [+ {+ startIndex: 0,+ paragraphStyle: {+ lineSpacing: 5,+ spaceBelow: { v: 6 },+ },+ },+ ],+ },+ },+ ];++ expect(TextX._transform(actionsA, actionsB, 'right')).toEqual(expectedActionsWithPriorityFalse);+ expect(TextX._transform(actionsA, actionsB, 'left')).toEqual(expectedActionsWithPriorityTrue);+ });+});diff --git a/packages/core/src/docs/data-model/text-x/apply-utils/common.ts b/packages/core/src/docs/data-model/text-x/apply-utils/common.tsindex 3b3fbc8341..9410e7ee63 100644--- a/packages/core/src/docs/data-model/text-x/apply-utils/common.ts+++ b/packages/core/src/docs/data-model/text-x/apply-utils/common.ts@@ -21,10 +21,10 @@ import type {ICustomBlock,ICustomDecoration,ICustomRange,+ ICustomTable,IDocumentBody,IParagraph,ISectionBreak,- ITable,ITextRun,} from '../../../../types/interfaces';import { DataStreamTreeTokenType } from '../../types';@@ -338,10 +338,11 @@ export function insertTables(body: IDocumentBody, insertBody: IDocumentBody, texfor (let i = 0, len = tables.length; i < len; i++) {const table = tables[i];const { startIndex, endIndex } = table;+if (startIndex > currentIndex) {table.startIndex += textLength;table.endIndex += textLength;- } else if (endIndex >= currentIndex - 1) {+ } else if (endIndex > currentIndex) {table.endIndex += textLength;}}@@ -735,12 +736,13 @@ export function deleteTables(body: IDocumentBody, textLength: number, currentIndconst startIndex = currentIndex;const endIndex = currentIndex + textLength - 1;- const removeTables: ITable[] = [];+ const removeTables: ICustomTable[] = [];if (tables) {const newTables = [];for (let i = 0, len = tables.length; i < len; i++) {const table = tables[i];const { startIndex: st, endIndex: ed } = table;+if (startIndex <= st && endIndex >= ed) {removeTables.push({...table,@@ -753,6 +755,11 @@ export function deleteTables(body: IDocumentBody, textLength: number, currentIndtable.startIndex = segments[0];table.endIndex = segments[1];++ // FIXME: @JOCS, why startIndex will equal to endIndex here?+ if (table.startIndex === table.endIndex) {+ continue;+ }} else if (endIndex < st) {table.startIndex -= textLength;table.endIndex -= textLength;diff --git a/packages/core/src/docs/data-model/text-x/apply-utils/update-apply.ts b/packages/core/src/docs/data-model/text-x/apply-utils/update-apply.tsindex 7bbc4bcfbd..26205037c9 100644--- a/packages/core/src/docs/data-model/text-x/apply-utils/update-apply.ts+++ b/packages/core/src/docs/data-model/text-x/apply-utils/update-apply.ts@@ -20,10 +20,10 @@ import type {ICustomBlock,ICustomDecoration,ICustomRange,+ ICustomTable,IDocumentBody,IParagraph,ISectionBreak,- ITable,ITextRun,} from '../../../../types/interfaces';import { PresetListType } from '../../preset-list-type';@@ -406,10 +406,10 @@ function updateTables(const removeTables = deleteTables(body, textLength, currentIndex);if (coverType !== UpdateDocsAttributeType.REPLACE) {- const newUpdateTables: ITable[] = [];+ const newUpdateTables: ICustomTable[] = [];for (const updateTable of updateDataTables) {const { startIndex: updateStartIndex, endIndex: updateEndIndex } = updateTable;- let splitUpdateTables: ITable[] = [];+ let splitUpdateTables: ICustomTable[] = [];for (const removeTable of removeTables) {const { startIndex: removeStartIndex, endIndex: removeEndIndex } = removeTable;if (removeStartIndex >= updateStartIndex && removeEndIndex <= updateEndIndex) {diff --git a/packages/core/src/docs/data-model/text-x/apply.ts b/packages/core/src/docs/data-model/text-x/apply.tsindex ad083a5fb0..c56229a85a 100644--- a/packages/core/src/docs/data-model/text-x/apply.ts+++ b/packages/core/src/docs/data-model/text-x/apply.ts@@ -67,11 +67,11 @@ export function textXApply(doc: IDocumentBody, actions: TextXAction[]): IDocumen// FIXME: @JOCS Since updateApply modifies the action(used in undo/redo),// so make a deep copy here, does updateApply need to// be modified to have no side effects in the future?- action = Tools.deepClone(action);+ const clonedAction = Tools.deepClone(action);- switch (action.t) {+ switch (clonedAction.t) {case TextXActionType.RETAIN: {- const { coverType, body, len } = action;+ const { coverType, body, len } = clonedAction;if (body != null) {updateApply(doc, body, len, memoryCursor.cursor, coverType);}@@ -81,7 +81,7 @@ export function textXApply(doc: IDocumentBody, actions: TextXAction[]): IDocumen}case TextXActionType.INSERT: {- const { body, len } = action;+ const { body, len } = clonedAction;insertApply(doc, body!, len, memoryCursor.cursor);memoryCursor.moveCursor(len);@@ -89,12 +89,12 @@ export function textXApply(doc: IDocumentBody, actions: TextXAction[]): IDocumen}case TextXActionType.DELETE: {- const { len } = action;+ const { len } = clonedAction;deleteApply(doc, len, memoryCursor.cursor);break;}default:- throw new Error(`Unknown action type for action: ${action}.`);+ throw new Error(`Unknown action type for action: ${clonedAction}.`);}});diff --git a/packages/core/src/docs/data-model/text-x/text-x.ts b/packages/core/src/docs/data-model/text-x/text-x.tsindex f1220728ef..7dd93b5a25 100644--- a/packages/core/src/docs/data-model/text-x/text-x.ts+++ b/packages/core/src/docs/data-model/text-x/text-x.ts@@ -21,6 +21,7 @@ import { type IDeleteAction, type IInsertAction, type IRetainAction, type TextXAimport { ActionIterator } from './action-iterator';import { composeBody, getBodySlice, isUselessRetainAction } from './utils';import { textXApply } from './apply';+import { transformBody } from './transform-utils';function onlyHasDataStream(body: IDocumentBody) {return Object.keys(body).length === 1;@@ -92,9 +93,108 @@ export class TextX {return textX.serialize();}- // `transform` is implemented in univer-pro in class TextXPro. do not use this method in TextX.- static transform(_thisActions: TextXAction[], _otherActions: TextXAction[], _priority: TPriority): TextXAction[] {- throw new Error('transform is not implemented in TextX');+ /**+ * |(this↓ \| other→) | **insert** | **retain** | **delete** |+ * | ---------------- | ---------- | ---------- | ---------- |+ * | **insert** | Case 1 | Case 2 | Case 2 |+ * | **retain** | Case 1 | Case 5 | Case 4 |+ * | **delete** | Case 1 | Case 3 | Case 3 |+ *+ * Case 1: When the other action type is an insert operation,+ * the insert operation is retained regardless of the type of action this action+ * Case 2: When this action type is an insert operation and the other action type is a+ * non-insert operation, you need to retain the length of this action insert+ * Case 3: When this action is a delete operation, there are two scenarios:+ * 1) When other is a delete operation, since it is a delete operation, this has+ * already been deleted, so the target does not need to be in delete, and it can+ * be continued directly+ * 2) When other is the retain operation, although this action delete occurs first,+ * the delete priority is higher, so the delete operation is retained, and the origin+ * delete has been applied, so it is directly continued+ * Case 4: other is the delete operation, this is the retain operation, and the target delete operation+ * is kept+ * Case 5: When both other and this are retain operations+ * 1) If the other body attribute does not exist, directly retain length+ * 2) If the other body property exists, then execute the TransformBody logic to override it+ */+ // priority - if true, this actions takes priority over other, that is, this actions are considered to happen "first".+ static transform(thisActions: TextXAction[], otherActions: TextXAction[], priority: TPriority = 'right'): TextXAction[] {+ return this._transform(otherActions, thisActions, priority === 'left' ? 'right' : 'left');+ }++ static _transform(thisActions: TextXAction[], otherActions: TextXAction[], priority: TPriority = 'right'): TextXAction[] {+ const thisIter = new ActionIterator(thisActions);++ const otherIter = new ActionIterator(otherActions);++ const textX = new TextX();++ while (thisIter.hasNext() || otherIter.hasNext()) {+ if (+ thisIter.peekType() === TextXActionType.INSERT &&+ (priority === 'left' || otherIter.peekType() !== TextXActionType.INSERT)+ ) {+ const thisAction = thisIter.next();+ textX.retain(thisAction.len, thisAction.segmentId ?? '');+ } else if (otherIter.peekType() === TextXActionType.INSERT) {+ textX.push(otherIter.next());+ } else {+ const length = Math.min(thisIter.peekLength(), otherIter.peekLength());+ const thisAction = thisIter.next(length);+ const otherAction = otherIter.next(length);++ // handle this-delete case.+ if (thisAction.t === TextXActionType.DELETE) {+ continue;+ }++ // handle other-delete case.+ if (otherAction.t === TextXActionType.DELETE) {+ textX.push(otherAction);+ continue;+ }++ // handle this-retain + other-retain case.+ if (thisAction.body == null || otherAction.body == null) {+ textX.push(otherAction);+ } else {+ textX.push({+ ...otherAction,+ body: transformBody(thisAction as IRetainAction, otherAction as IRetainAction, priority === 'left'),+ });+ }+ }+ }++ textX.trimEndUselessRetainAction();++ return textX.serialize();+ }++ /**+ * Used to transform selection. Why not named transformSelection?+ * Because Univer Doc supports multiple Selections in one document, user need to encapsulate transformSelections at the application layer.+ */+ static transformPosition(thisActions: TextXAction[], index: number, priority = false): number {+ const thisIter = new ActionIterator(thisActions);++ let offset = 0;++ while (thisIter.hasNext() && offset <= index) {+ const length = thisIter.peekLength();+ const nextType = thisIter.peekType();+ thisIter.next();++ if (nextType === TextXActionType.DELETE) {+ index -= Math.min(length, index - offset);+ continue;+ } else if (nextType === TextXActionType.INSERT && (offset < index || !priority)) {+ index += length;+ }+ offset += length;+ }++ return index;}static isNoop(actions: TextXAction[]) {diff --git a/packages/core/src/docs/data-model/text-x/transform-utils.ts b/packages/core/src/docs/data-model/text-x/transform-utils.tsnew file mode 100644index 0000000000..a127a43207--- /dev/null+++ b/packages/core/src/docs/data-model/text-x/transform-utils.ts@@ -0,0 +1,276 @@+/**+ * 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 {+ IDocumentBody,+ IParagraph,+ IParagraphStyle,+ IRetainAction,+ ITextRun,+ ITextStyle,+ Nullable,+} from '@univerjs/core';+import { normalizeTextRuns, Tools } from '@univerjs/core';++enum TextXTransformType {+ // The properties on the target are always retained, and the properties on the origin are ignored.+ COVER,+ // Only properties that do not exist on the origin object and that exist on the target are kept.+ COVER_ONLY_NOT_EXISTED,+}++// eslint-disable-next-line max-lines-per-function, complexity+function transformTextRuns(originTextRuns: ITextRun[], targetTextRuns: ITextRun[], transformType: TextXTransformType) {+ if (originTextRuns.length === 0) {+ return targetTextRuns;+ }++ targetTextRuns = Tools.deepClone(targetTextRuns);+ originTextRuns = Tools.deepClone(originTextRuns);++ const newUpdateTextRuns: ITextRun[] = [];+ const updateLength = targetTextRuns.length;+ const removeLength = originTextRuns.length;+ let updateIndex = 0;+ let removeIndex = 0;+ let pending: Nullable<ITextRun> = null;++ function pushPendingAndReturnStatus() {+ if (pending) {+ newUpdateTextRuns.push(pending);+ pending = null;+ return true;+ }++ return false;+ }++ while (updateIndex < updateLength && removeIndex < removeLength) {+ const { st: updateSt, ed: updateEd, ts: targetStyle } = targetTextRuns[updateIndex];+ const { st: removeSt, ed: removeEd, ts: originStyle, sId } = originTextRuns[removeIndex];+ let newTs: ITextStyle = {};++ if (transformType === TextXTransformType.COVER) {+ newTs = { ...targetStyle };+ } else {+ newTs = { ...targetStyle };++ if (originStyle) {+ const keys = Object.keys(originStyle);++ for (const key of keys) {+ if (newTs[key as keyof ITextStyle]) {+ delete newTs[key as keyof ITextStyle];+ }+ }+ }+ }++ if (updateEd < removeSt) {+ if (!pushPendingAndReturnStatus()) {+ newUpdateTextRuns.push(targetTextRuns[updateIndex]);+ }++ updateIndex++;+ } else if (removeEd < updateSt) {+ if (!pushPendingAndReturnStatus()) {+ newUpdateTextRuns.push(originTextRuns[removeIndex]);+ }++ removeIndex++;+ } else {+ const newTextRun = {+ st: Math.min(updateSt, removeSt),+ ed: Math.max(updateSt, removeSt),+ ts: updateSt < removeSt ? { ...targetStyle } : { ...originStyle },+ sId: updateSt < removeSt ? undefined : sId,+ };+ if (newTextRun.ed > newTextRun.st) {+ newUpdateTextRuns.push();+ }++ newUpdateTextRuns.push({+ st: Math.max(updateSt, removeSt),+ ed: Math.min(updateEd, removeEd),+ ts: newTs,+ sId,+ });++ if (updateEd < removeEd) {+ updateIndex++;+ originTextRuns[removeIndex].st = updateEd;+ if (originTextRuns[removeIndex].st === originTextRuns[removeIndex].ed) {+ removeIndex++;+ }+ } else {+ removeIndex++;+ targetTextRuns[updateIndex].st = removeEd;+ if (targetTextRuns[updateIndex].st === targetTextRuns[updateIndex].ed) {+ updateIndex++;+ }+ }++ const pendingTextRun = {+ st: Math.min(updateEd, removeEd),+ ed: Math.max(updateEd, removeEd),+ ts: updateEd < removeEd ? { ...originStyle } : { ...targetStyle },+ sId: updateEd < removeEd ? sId : undefined,+ };++ pending = pendingTextRun.ed > pendingTextRun.st ? pendingTextRun : null;+ }+ }++ pushPendingAndReturnStatus();++ // If the last textRun is also disjoint, then the last textRun needs to be pushed in `newUpdateTextRun`+ const tempTopTextRun = newUpdateTextRuns[newUpdateTextRuns.length - 1];+ const updateLastTextRun = targetTextRuns[updateLength - 1];+ const removeLastTextRun = originTextRuns[removeLength - 1];++ if (tempTopTextRun.ed !== Math.max(updateLastTextRun.ed, removeLastTextRun.ed)) {+ if (updateLastTextRun.ed > removeLastTextRun.ed) {+ newUpdateTextRuns.push(updateLastTextRun);+ } else {+ newUpdateTextRuns.push(removeLastTextRun);+ }+ }++ return normalizeTextRuns(newUpdateTextRuns);+}++// At present, only the two properties of paragraphStyle and bullet are handled,+// paragraphStyle is treated separately, while bullet is treated as a whole because+// the properties in bullet are related+function transformParagraph(+ originParagraph: IParagraph,+ targetParagraph: IParagraph,+ transformType: TextXTransformType+): IParagraph {+ const paragraph: IParagraph = {+ startIndex: targetParagraph.startIndex,+ };++ if (targetParagraph.paragraphStyle) {+ if (originParagraph.paragraphStyle == null) {+ paragraph.paragraphStyle = {+ ...targetParagraph.paragraphStyle,+ };+ } else {+ paragraph.paragraphStyle = {+ ...targetParagraph.paragraphStyle,+ };++ if (transformType === TextXTransformType.COVER_ONLY_NOT_EXISTED) {+ const keys = Object.keys(originParagraph.paragraphStyle);++ for (const key of keys) {+ if (paragraph.paragraphStyle[key as keyof IParagraphStyle]) {+ delete paragraph.paragraphStyle[key as keyof IParagraphStyle];+ }+ }+ }+ }+ }++ if (targetParagraph.bullet) {+ if (originParagraph.bullet == null || transformType === TextXTransformType.COVER) {+ paragraph.bullet = {+ ...targetParagraph.bullet,+ };+ }+ }++ return paragraph;+}++export function transformBody(+ thisAction: IRetainAction,+ otherAction: IRetainAction,+ priority: boolean = false+): IDocumentBody {+ const { body: thisBody } = thisAction;+ const { body: otherBody } = otherAction;+ if (thisBody == null || thisBody.dataStream !== '' || otherBody == null || otherBody.dataStream !== '') {+ throw new Error('Data stream is not supported in transform.');+ }++ const retBody: IDocumentBody = {+ dataStream: '',+ };++ const { textRuns: thisTextRuns = [], paragraphs: thisParagraphs = [] } = thisBody;+ const { textRuns: otherTextRuns = [], paragraphs: otherParagraphs = [] } = otherBody;++ let textRuns: ITextRun[] = [];+ if (priority) {+ textRuns = transformTextRuns(thisTextRuns, otherTextRuns, TextXTransformType.COVER_ONLY_NOT_EXISTED);+ } else {+ textRuns = transformTextRuns(thisTextRuns, otherTextRuns, TextXTransformType.COVER);+ }+ if (textRuns.length) {+ retBody.textRuns = textRuns;+ }++ const paragraphs: IParagraph[] = [];++ let thisIndex = 0;+ let otherIndex = 0;++ while (thisIndex < thisParagraphs.length && otherIndex < otherParagraphs.length) {+ const thisParagraph = thisParagraphs[thisIndex];+ const otherParagraph = otherParagraphs[otherIndex];++ const { startIndex: thisStart } = thisParagraph;+ const { startIndex: otherStart } = otherParagraph;++ if (thisStart === otherStart) {+ let paragraph: IParagraph = {+ startIndex: thisStart,+ };++ if (priority) {+ paragraph = transformParagraph(+ thisParagraph,+ otherParagraph,+ TextXTransformType.COVER_ONLY_NOT_EXISTED+ );+ } else {+ paragraph = transformParagraph(thisParagraph, otherParagraph, TextXTransformType.COVER);+ }++ paragraphs.push(paragraph);+ thisIndex++;+ otherIndex++;+ } else if (thisStart < otherStart) {+ // paragraphs.push(Tools.deepClone(thisParagraph));+ thisIndex++;+ } else {+ paragraphs.push(Tools.deepClone(otherParagraph));+ otherIndex++;+ }+ }++ if (otherIndex < otherParagraphs.length) {+ paragraphs.push(...otherParagraphs.slice(otherIndex));+ }++ if (paragraphs.length) {+ retBody.paragraphs = paragraphs;+ }++ return retBody;+}diff --git a/packages/core/src/docs/data-model/text-x/utils.ts b/packages/core/src/docs/data-model/text-x/utils.tsindex 68f1ee466b..88f62ccfba 100644--- a/packages/core/src/docs/data-model/text-x/utils.ts+++ b/packages/core/src/docs/data-model/text-x/utils.ts@@ -27,7 +27,7 @@ export enum SliceBodyType {}// TODO: Support other properties like custom ranges, tables, etc.-// eslint-disable-next-line max-lines-per-function+// eslint-disable-next-line max-lines-per-function, complexityexport function getBodySlice(body: IDocumentBody,startOffset: number,@@ -35,7 +35,7 @@ export function getBodySlice(returnEmptyTextRun = false,type = SliceBodyType.cut): IDocumentBody {- const { dataStream, textRuns = [], paragraphs = [], customBlocks = [] } = body;+ const { dataStream, textRuns = [], paragraphs = [], customBlocks = [], tables = [] } = body;const docBody: IDocumentBody = {dataStream: dataStream.slice(startOffset, endOffset),@@ -85,6 +85,25 @@ export function getBodySlice(}];}+ const newTables = [];++ for (const table of tables) {+ const clonedTable = Tools.deepClone(table);+ const { startIndex, endIndex } = clonedTable;++ if (startIndex >= startOffset && endIndex <= endOffset) {+ newTables.push({+ ...clonedTable,+ startIndex: startIndex - startOffset,+ endIndex: endIndex - startOffset,+ });+ }+ }++ if (newTables.length) {+ docBody.tables = newTables;+ }+const newParagraphs: IParagraph[] = [];for (const paragraph of paragraphs) {@@ -126,7 +145,7 @@ export function getBodySlice(}export function normalizeBody(body: IDocumentBody): IDocumentBody {- const { dataStream, textRuns, paragraphs, customRanges, customDecorations } = body;+ const { dataStream, textRuns, paragraphs, customRanges, customDecorations, tables } = body;let leftOffset = 0;let rightOffset = 0;@@ -170,6 +189,11 @@ export function normalizeBody(body: IDocumentBody): IDocumentBody {d.endIndex += rightOffset;});+ tables?.forEach((table) => {+ table.startIndex += leftOffset;+ table.endIndex += rightOffset;+ });+return {...body,dataStream: newData,@@ -177,6 +201,7 @@ export function normalizeBody(body: IDocumentBody): IDocumentBody {paragraphs,customRanges,customDecorations,+ tables,};}diff --git a/packages/core/src/docs/data-model/types.ts b/packages/core/src/docs/data-model/types.tsindex 11b9ed44e6..c03da36684 100644--- a/packages/core/src/docs/data-model/types.ts+++ b/packages/core/src/docs/data-model/types.ts@@ -19,31 +19,25 @@ export enum DataStreamTreeNodeType {// PAGE_BREAK, // \f 换页// DOCS_END, // \0 文档结尾// TAB, // \t 制表符- PARAGRAPH, // \r 段落- SECTION_BREAK, // \n 章节- TABLE,- TABLE_ROW,- TABLE_CELL,- CUSTOM_BLOCK, // \b 图片 mention 等不参与文档流的场景- // TABLE_START, // \x1A 表格开始- // TABLE_ROW_START, // \x1B 表格开始- // TABLE_CELL_START, // \x1C 表格开始- // TABLE_CELL_END, //* \x1D 表格开始- // TABLE_ROW_END, // \x1E 表格开始- // TABLE_END, // \x1F 表格结束- // CUSTOM_RANGE_START, // \x1F 自定义范围开始- // CUSTOM_RANGE_END, // \x1E 自定义范围结束+ PARAGRAPH = 'PARAGRAPH', // \r 段落+ SECTION_BREAK = 'SECTION_BREAK', // \n 章节+ TABLE = 'TABLE',+ TABLE_ROW = 'TABLE_ROW',+ TABLE_CELL = 'TABLE_CELL',+ CUSTOM_BLOCK = 'CUSTOM_BLOCK', // \b 图片 mention 等不参与文档流的场景}export enum DataStreamTreeTokenType {PARAGRAPH = '\r', // 段落SECTION_BREAK = '\n', // 章节+ // table.TABLE_START = '\x1A', // 表格开始- TABLE_ROW_START = '\x1B', // 表格开始- TABLE_CELL_START = '\x1C', // 表格开始- TABLE_CELL_END = '\x1D', // 表格开始- TABLE_ROW_END = '\x0E', // 表格开始+ TABLE_ROW_START = '\x1B', // 表格行开始+ TABLE_CELL_START = '\x1C', // 表格单元格开始+ TABLE_CELL_END = '\x1D', // 表格单元格结束+ TABLE_ROW_END = '\x0E', // 表格行结束TABLE_END = '\x0F', // 表格结束+CUSTOM_RANGE_START = '\x1F', // 自定义范围开始CUSTOM_RANGE_END = '\x1E', // 自定义范围结束@@ -54,6 +48,5 @@ export enum DataStreamTreeTokenType {CUSTOM_BLOCK = '\b', // 图片 mention 等不参与文档流的场景LETTER = '',-SPACE = ' ',}diff --git a/packages/core/src/types/interfaces/i-document-data.ts b/packages/core/src/types/interfaces/i-document-data.tsindex 312152146d..998fd0cdb1 100644--- a/packages/core/src/types/interfaces/i-document-data.ts+++ b/packages/core/src/types/interfaces/i-document-data.ts@@ -31,7 +31,7 @@ export interface IDocumentData extends IReferenceSource, IExtraModelData {rev?: number;locale?: LocaleType;title?: string;- body?: IDocumentBody;+ body?: IDocumentBody; // Rich text.documentStyle: IDocumentStyle;settings?: IDocumentSettings;// The type of data depends on how the plug-in is defined@@ -40,6 +40,7 @@ export interface IDocumentData extends IReferenceSource, IExtraModelData {}export interface IReferenceSource {+ tableSource?: ITables; // Tablefooters?: IFooters;headers?: IHeaders;lists?: ILists;@@ -66,6 +67,10 @@ export interface IFooters {[footerId: string]: IFooterData;}+export interface ITables {+ [tableId: string]: ITable;+}+/*** Set of lists*/@@ -124,7 +129,7 @@ export interface IDocumentBody {customBlocks?: ICustomBlock[]; // customBlock user-defined block through plug-in- tables?: ITable[]; // Table+ tables?: ICustomTable[]; // Table// tableOfContents?: { [index: number]: ITableOfContent }; // tableOfContents// links?: { [index: number]: IHyperlink }; // links@@ -814,70 +819,131 @@ export interface IShading {backgroundColor: IColorStyle; // backgroundColor}-/**- * Type of width- */-export enum WidthType {- EVENLY_DISTRIBUTED = '0',- FIXED_WIDTH = '1',+export interface IDistFromText {+ distT: number; // distance between top text and table.+ distB: number; // distance between bottom text and table.+ distL: number; // distance between left text and table.+ distR: number; // distance between right text and table.+}++export interface ITableAnchor {+ positionH: IObjectPositionH; // horzAnchor (Table Horizontal Anchor)+ positionV: IObjectPositionV;+}++export enum TableSizeType {+ UNSPECIFIED,+ SPECIFIED,+}+export interface IWidthInTableSize {+ type: TableSizeType;+ width: INumberUnit;+}++// 17.18.45 ST_JcTable (Table Alignment Type)+export enum TableAlignmentType {+ START,+ CENTER,+ END,+}++// 17.18.87 ST_TblLayoutType (Table Layout Type)+export enum TableLayoutType {+ AUTO_FIT,+ FIXED,+}++export enum TableTextWrapType {+ NONE,+ WRAP,+}++export interface ICustomTable {+ startIndex: number;+ endIndex: number;+ // A unique ID associated with a table.+ tableId: string;}/*** Properties of table*/export interface ITable {- startIndex: number;- endIndex: number;- rows: number; // rows- columns: number; // columnstableRows: ITableRow[]; // tableRows- tableStyle: WidthType; // tableStyle- width: number; // width+ tableColumns: ITableColumn[]; // tableColumns+ align: TableAlignmentType; // 17.4.28 jc (Table Alignment)+ indent: INumberUnit; // left align only. leftIndent+ textWrap: TableTextWrapType; // 17.4.57 tblpPr (Floating Table Positioning)+ position: ITableAnchor; // 17.4.57 tblpPr (Floating Table Positioning)+ dist: IDistFromText; // 17.4.57 tblpPr (Floating Table Positioning)+ size: IWidthInTableSize;+ tableId: string;+ cellMargin?: ITableCellMargin; // cellMargin+ layout?: TableLayoutType; // 17.4.52 tblLayout (Table Layout)+ overlap?: BooleanNumber; // 17.4.56 tblOverlap (Floating Table Allows Other Tables to Overlap)+ description?: string; // 17.4.46 tblDescription (Table Description)+}++// Specifies the meaning of the height specified for this table row+// The meaning of the value of the val attribute is defined based on the value of the hRule+// attribute for this table row as follows:+// If the value of hRule is auto, then the table row's height should be automatically+// determined based on the height of its contents. The h value is ignored.+// If the value of hRule is atLeast, then the table row's height should be at least+// the value the h attribute.+// If the value of hRule is exact, then the table row's height should be exactly the+// value of the h attribute.+export enum TableCellHeightRule {+ AUTO,+ AT_LEAST,+ EXACT,+}++export interface ITableColumn { // 合并拆分列,HTML 合并单元格+ size: IWidthInTableSize;+}++export interface ITableRowSize {+ val: INumberUnit;+ hRule: TableCellHeightRule;}/*** Properties of row of table*/export interface ITableRow {- st: number; // startIndex- ed: number; // endIndextableCells: ITableCell[]; // tableCells- tableRowStyle: ITableRowStyle; // tableRowStyle-}--/**- * Properties of style table row- */-export interface ITableRowStyle {- minRowHeight: number; // minRowHeight+ // If omitted, then the table row shall automatically resize its height to the height required by its contents+ // (the equivalent of an hRule value of auto)+ trHeight: ITableRowSize; // 17.4.80 trHeight (Table Row Height)+ cantSplit?: BooleanNumber; // allowBreakAcrossPages, the default is true.+ isFirstRow?: BooleanNumber; // isFirstRow.+ repeatHeaderRow?: BooleanNumber; // Show header row in different pages. only for the first row.}/*** Properties of table cell*/export interface ITableCell {- // st: number; // startIndex- // ed: number; // endIndex- // content: IBlockElement[]; // content- tableCellStyle: ITableCellStyle; // tableCellStyle-}--/**- * Properties of style of table cell- */-export interface ITableCellStyle {- rowSpan: number; // rowSpan- columnSpan: number; // columnSpan- backgroundColor: IColorStyle; // backgroundColor- borderLeft: ITableCellBorder; // borderLeft- borderRight: ITableCellBorder; // borderRight- borderTop: ITableCellBorder; // borderTop- borderBottom: ITableCellBorder; // borderBottom- paddingLeft: number; // paddingLeft- paddingRight: number; // paddingRight- paddingTop: number; // paddingTop- paddingBottom: number; // paddingBottom- contentAlignment: ContentAlignment; // contentAlignment+ margin?: ITableCellMargin; // margin+ rowSpan?: number; // rowSpan+ columnSpan?: number; // columnSpan+ backgroundColor?: IColorStyle; // backgroundColor+ borderLeft?: ITableCellBorder; // borderLeft+ borderRight?: ITableCellBorder; // borderRight+ borderTop?: ITableCellBorder; // borderTop+ borderBottom?: ITableCellBorder; // borderBottom+ size?: IWidthInTableSize; // size+ tcFitText?: BooleanNumber; // 17.4.67 tcFitText (Fit Text Within Cell)+ // hAlign: use paragraph align to instead.+ vAlign?: VerticalAlignmentType; // 17.4.83 vAlign (Table Cell Vertical Alignment)+}++export interface ITableCellMargin {+ start: INumberUnit; // start+ end: INumberUnit; // end+ top: INumberUnit; // top+ bottom: INumberUnit; // bottom}/**@@ -885,17 +951,19 @@ export interface ITableCellStyle {*/export interface ITableCellBorder {color: IColorStyle; // color- width: number; // width+ width: INumberUnit; // widthdashStyle: DashStyleType; // dashStyle}++// 17.18.101ST_VerticalJc (Vertical Alignment Type)/*** The content alignments for a Shape or TableCell. The supported alignments correspond to predefined text anchoring types from the ECMA-376 standard.*/-export enum ContentAlignment {+export enum VerticalAlignmentType {CONTENT_ALIGNMENT_UNSPECIFIED, // An unspecified content alignment. The content alignment is inherited from the parent if one exists.- CONTENT_ALIGNMENT_UNSUPPORTED, // An unsupported content alignment.+ BOTH,TOP, // An alignment that aligns the content to the top of the content holder. Corresponds to ECMA-376 ST_TextAnchoringType 't'.- MIDDLE, // An alignment that aligns the content to the middle of the content holder. Corresponds to ECMA-376 ST_TextAnchoringType 'ctr'.+ CENTER, // An alignment that aligns the content to the middle of the content holder. Corresponds to ECMA-376 ST_TextAnchoringType 'ctr'.BOTTOM, // An alignment that aligns the content to the bottom of the content holder. Corresponds to ECMA-376 ST_TextAnchoringType 'b'.}@@ -957,6 +1025,7 @@ export enum NumberUnitType {LINE,CHARACTER,PIXEL,+ PERCENT,}// 20.4.3.1 ST_AlignH (Relative Horizontal Alignment Positions)diff --git a/packages/debugger/package.json b/packages/debugger/package.jsonindex f5d7e6e32e..c96ca06c5d 100644--- a/packages/debugger/package.json+++ b/packages/debugger/package.json@@ -65,7 +65,7 @@"rxjs": ">=7.0.0"},"optionalDependencies": {- "vue": "^3.4.35"+ "vue": ">=3.0.0"},"devDependencies": {"@univerjs/core": "workspace:*",diff --git a/packages/debugger/src/controllers/e2e/data/default-doc.ts b/packages/debugger/src/controllers/e2e/data/default-doc.tsindex 5ab4ad8d5a..99eadc790a 100644--- a/packages/debugger/src/controllers/e2e/data/default-doc.ts+++ b/packages/debugger/src/controllers/e2e/data/default-doc.ts@@ -15,190 +15,620 @@*/import type { IDocumentData } from '@univerjs/core';-import { BaselineOffset, BooleanNumber, ColumnSeparatorType, DocumentFlavor, DrawingTypeEnum, ObjectRelativeFromH, ObjectRelativeFromV, PositionedObjectLayoutType, PresetListType, SectionType, WrapTextType } from '@univerjs/core';+import { BooleanNumber, DocumentFlavor } from '@univerjs/core';+import { ptToPixel } from '@univerjs/engine-render';// eslint-disable-next-line max-lines-per-functionexport function getDefaultDocData(): IDocumentData {- return {+ const DEFAULT_DOCUMENT_DATA_CN: IDocumentData = {id: 'd',- drawings: {- shapeTest1: {- unitId: 'd',- subUnitId: 'd',- drawingType: DrawingTypeEnum.DRAWING_SHAPE,- drawingId: 'shapeTest1',- title: 'test shape',- description: 'test shape',- docTransform: {- size: {- width: 100,- height: 400,- },- positionH: {- relativeFrom: ObjectRelativeFromH.COLUMN,- posOffset: 100,- },- positionV: {- relativeFrom: ObjectRelativeFromV.PARAGRAPH,- posOffset: 160,- },- angle: 0,- // imageProperties: {- // contentUrl: 'https://cnbabylon.com/assets/img/agents.png',- // },- },- layoutType: PositionedObjectLayoutType.WRAP_SQUARE,- behindDoc: BooleanNumber.FALSE,- wrapText: WrapTextType.BOTH_SIDES,- },- },+ tableSource: {},+ drawings: {},+ drawingsOrder: [],+ headers: {},+ footers: {},body: {- dataStream: '在“第1题”工作表中完成以下操作\b上标日期列单元格数据验证,限制只能输入日期(介于1949年1月1日至2099年1月1日)\r细化埋点上报链路和指标方案梳理目前通过每日定时任务发送报告\r自2018年首届进博会举办以来,进博会已经成为全球新品的首发地、前沿技术的首选地、创新服务的首推地。中国这十年”对外开放成就展湖北展区主要以图文、图表、数据、视频、企业展品、实物模型、光电科技等体现湖北十年开放成就、重大开放平台及产业。湖北省共计17家企业、机构的展品将在这一展区展示\r国家主席习近平以视频方式出席在上海举行的第五届中国国际进口博览会开幕式并发表题为《共创开放繁荣的美好未来》的致辞中国将推动各国各方共享深化国际合作机遇,全面深入参与世界贸易组织改革谈判\r中国男排两名现役国手彭世坤和张秉龙分别效力的三得利太阳鸟和东京大熊本轮遭遇。双方经过激战,主场作战的卫冕冠军三得利技高一筹3-2逆转击败对手,力夺第3场胜利\r\n',+ dataStream:+ '荷塘月色\r\r作者:朱自清\r\r这几天心里颇不宁静。今晚在院子里坐着乘凉,忽然想起日日走过的荷塘,在这满月的光里,总该另有一番样子吧。月亮渐渐地升高了,墙外马路上孩子们的欢笑,已经听不见了;妻在屋里拍着闰儿,迷迷糊糊地哼着眠歌。我悄悄地披了大衫,带上门出去。\r\r沿着荷塘,是一条曲折的小煤屑路。这是一条幽僻的路;白天也少人走,夜晚更加寂寞。荷塘四面,长着许多树,蓊蓊郁郁的。路图片一片是些杨柳,和一些不知道名字的树。没有月光的晚上,这路上阴森森的,有些怕人。今晚却很好,虽然月光也还是淡淡的。\r\r路上只我一个人,背着手踱着。这一片天地好像是我的;我也像超出了平常的自己,到了另一个世界里。我爱热闹,也爱冷静;爱群居,也爱独处。像今晚上,一个人在这苍茫的月下,什么都可以想,什么都可以不想,便觉是个自由的人。白天里一定要做的事,一定要说的话是现在都可不理。这是独处的妙处,我且受用这无边的荷香月色好了。\r\r曲曲折折的荷塘上面,弥望的是田田的叶子。叶子出水很高,像亭亭的舞女的裙。层层的叶子中间,零星地点缀着些白花,有袅娜地开着的,有羞涩地打着朵儿的;正如一粒粒的明珠,又如碧天里的星星,又如刚出浴的美人。微风过处,送来缕缕清香,仿佛远处高楼上渺茫的歌声似的。这时候叶子与花也有一丝的颤动,像闪电般,霎时传过荷塘的那边去了。叶子本是肩并肩密密地挨着,这便宛然有了一道凝碧的波痕。叶子底下是脉脉的流水,遮住了,不能见一些颜色;而叶子却更见风致了。\r\r月光如流水一般,静静地泻在这一片叶子和花上。薄薄的青雾浮起在荷塘里。叶子和花仿佛在牛乳中洗过一样,又像笼着轻纱的梦。虽然是满月,天上却有一层淡淡的云,所以不能朗照;但我以为这恰是到了好处——酣眠固不可少,小睡也别有风味的。月光是隔了树照过来的,高处丛生的灌木,落下参差的斑驳的黑影,峭楞楞如鬼一般;弯弯的杨柳的稀疏的倩影,却又像是画在荷叶上。塘中的月色并不均匀;但光与影有着和谐的旋律,如梵婀玲上奏着的名曲。\r\r荷塘的四面,远远近近,高高低低都是树,而杨柳最多。这些树将一片荷塘重重围住;只在小路一旁,漏着几段空隙,像是特为月光留下的。树色一例是阴阴的,乍看像一团烟雾;但杨柳的丰姿,便在烟雾里也辨得出。树梢上隐隐约约的是一带远山,只有些大意罢了。树缝里也漏着一两点路灯光,没精打采的,是渴睡人的眼。这时候最热闹的,要数树上的蝉声与水里的蛙声;但热闹是它们的,我什么也没有。\r\r忽然想起采莲的事情来了。采莲是江南的旧俗,似乎很早就有,而六朝时为盛;从诗歌里可以约略知道。采莲的是少年的女子,她们是荡着小船,唱着艳歌去的。采莲人不用说很多,还有看采莲的人。那是一个热闹的季节,也是一个风流的季节。梁元帝《采莲赋》里说得好:\r\r于是妖童女,荡舟心许;鷁首徐回,兼传羽杯;櫂将移而藻挂,船欲动而萍开。尔其纤腰束素,迁延顾步;夏始春余,叶嫩花初,恐沾裳而浅笑,畏倾船而敛裾。\r\r可见当时嬉游的光景了。这真是有趣的事,可惜我们现在早已无福消受了。\r\r于是又记起,《西洲曲》里的句子:\r\r采莲南塘秋,莲花过人头;低头弄莲子,莲子清如水。\r\r今晚若有采莲人,这儿的莲花也算得“过人头”了;只不见一些流水的影子,是不行的。这令我到底惦着江南了。——这样想着,猛一抬头,不觉已是自己的门前;轻轻地推门进去,什么声息也没有,妻已睡熟好久了。\r\r一九二七年七月,北京清华园。\r\r\r\r《荷塘月色》语言朴素典雅,准确生动,贮满诗意,满溢着朱自清的散文语言一贯有朴素的美,不用浓墨重彩,画的是淡墨水彩。\r\r朱自清先生一笔写景一笔说情,看起来松散不知所云,可仔细体会下,就能感受到先生在字里行间表述出的苦闷,而随之读者也被先生的文字所感染,被带进了他当时那苦闷而无法明喻的心情。这就是优异散文的必须品质之一。\r\r扩展资料:\r一首长诗《毁灭》奠定了朱自清在文坛新诗人的地位,而《桨声灯影里的秦淮河》则被公认为白话美文的典范。朱自清用白话美文向复古派宣战,有力地回击了复古派“白话不能作美文”之说,他是“五四”新文学运动的开拓者之一。\r\r朱自清的美文影响了一代又一代人。作家贾平凹说:来到扬州,第一个想到的人是朱自清,他是知识分子中最最了不起的人物。\r\r实际上,朱自清的写作路程是非常曲折的,他早期的时候大多数作品都是诗歌,但是他的诗歌和我国古代诗人的诗有很大区别,他的诗是用白话文写的,这其实也是他写作的惯用风格。\r\r后来,朱自清开始写一些关于社会的文章,因为那个时候社会比较混乱,这时候的作品大多抨击社会的黑暗面,文体风格大多硬朗,基调伉俪。到了后期,大多是写关于山水的文章,这类文章的写作格调大多以清丽雅致为主。\r\r朱自清的写作风格虽然在不同的时期随着他的人生阅历和社会形态的不同而发生着变化,但是他文章的主基调是没有变的,他这一生,所写的所有文章风格上都有一个非常显著的特点,那就是简约平淡,他不是类似古代花间词派的诗人们,不管是他的诗词还是他的文章从来都不用过于华丽的辞藻,他崇尚的是平淡。\r\r英国友人戴立克试过英译朱自清几篇散文,译完一读显得单薄,远远不如原文流利。他不服气,改用稍微古奥的英文重译,好多了:“那是说,朱先生外圆内方,文字尽管浅白,心思却很深沉,译笔只好朝深处经营。”朱自清的很多文章,譬如《背影》《祭亡妇》,读来自有一番只可意会不可言传的东西。\r\r平淡就是朱自清的写作风格。他不是豪放派的作家,他在创作的时候钟情于清新的风格,给人耳目一新的感觉。在他的文章中包含了他对生活的向往,由此可见他的写作风格和他待人处事的态度也是有几分相似的。他的文章非常优美,但又不会让人觉得狭隘,给人一种豁达渊博的感觉,这就是朱自清的写作风格,更是朱自清的为人品质。\r\r写有《荷塘月色》《背影》等名篇的著名散文家朱自清先生,不仅自己一生风骨正气,还用无形的家风涵养子孙。良好的家风家规意蕴深远,催人向善,是凝聚情感、涵养德行、砥砺成才的人生信条。“北有朱自清,南有朱物华,一文一武,一南一北,双星闪耀”,这是中国知识界、教育界对朱家两兄弟的赞誉。\r\r朱自清性格温和,为人和善,对待年轻人平易近人,是个平和的人。他取字“佩弦”,意思要像弓弦那样将自己绷紧,给人的感觉是自我要求高,偶尔有呆气。朱自清教学负责,对学生要求严格,修他的课的学生都受益不少。\r\r1948 年 6 月,患胃病多年的朱自清,在《抗议美国扶日政策并拒绝领取美援面粉宣言》上,一丝不苟地签下了自己的名字。随后,朱自清还将面粉配购证以及面粉票退了回去。1948 年 8 月 12 日,朱自清因不堪胃病折磨,离开人世。在新的时代即将到来时,朱自清却匆匆地离人们远去。他为人们留下了无数经典的诗歌和文字,还有永不屈服的精神。\r\r朱自清没有豪言壮语,他只是用坚定的行动、朴实的语言,向世人展示了中国知识分子在祖国危难之际坚定的革命性,体现了中国人的骨气,表现了无比高贵的民族气节,呈现了人生最有价值的一面,谱就了生命中最华丽的乐章。\r\r他以“自清”为名,自勉在困境中不丧志;他身患重病,至死拒领美援面粉,其气节令世人感佩;他的《背影》《荷塘月色》《匆匆》脍炙人口;他的文字追求“真”,没有半点矫饰,却蕴藏着动人心弦的力量。\r\r朱自清不但在文学创作方面有很高的造诣,也是一名革命民主主义战士,在反饥饿、反内战的斗争中,他始终保持着一个正直的爱国知识分子的气节和情操。毛泽东对朱自清宁肯饿死不领美国“救济粉”的精神给予称赞,赞扬他“表现了我们民族的英雄气概”。\r\n',textRuns: [{st: 0,- ed: 15,+ ed: 4,ts: {- fs: 12,+ fs: 20,+ ff: 'Microsoft YaHei',+ cl: {+ rgb: 'rgb(255, 255, 255)',+ },+ bl: BooleanNumber.TRUE,bg: {- rgb: 'rgb(200,0,90)',+ rgb: '#FF6670',},+ it: BooleanNumber.TRUE,+ },+ },+ {+ st: 6,+ ed: 9,+ ts: {+ fs: 16,+ ff: 'Microsoft YaHei',cl: {- rgb: 'rgb(255,130,0)',+ rgb: 'rgb(30, 30, 30)',},+ bl: BooleanNumber.FALSE,},},{- st: 17,- ed: 18,+ st: 9,+ ed: 12,ts: {- fs: 14,- bg: {- rgb: 'rgb(2,128,2)',- },+ fs: 16,+ ff: 'Microsoft YaHei',cl: {- rgb: 'rgb(0,1,55)',+ rgb: 'rgb(30, 30, 30)',},- va: BaselineOffset.SUPERSCRIPT,+ bl: BooleanNumber.TRUE,},},{- st: 19,- ed: 60,+ st: 14,+ ed: 3064,ts: {- fs: 14,- bg: {- rgb: 'rgb(90,128,255)',- },+ fs: 12,+ ff: 'Microsoft YaHei',cl: {- rgb: 'rgb(0,1,255)',+ rgb: 'rgb(30, 30, 30)',},+ bl: BooleanNumber.FALSE,},},-+ ],+ paragraphs: [{- st: 62,- ed: 90,+ startIndex: 4,+ paragraphStyle: {+ spaceAbove: { v: 0 },+ lineSpacing: 2,+ spaceBelow: { v: 0 },+ },},-{- st: 92,- ed: 233,+ startIndex: 5,+ paragraphStyle: {+ spaceAbove: { v: 10 },+ lineSpacing: 2,+ spaceBelow: { v: 0 },+ },},-{- st: 235,- ed: 326,+ startIndex: 12,+ paragraphStyle: {+ spaceAbove: { v: 10 },+ lineSpacing: 2,+ spaceBelow: { v: 0 },+ },+ },+ {+ startIndex: 13,+ paragraphStyle: {+ spaceAbove: { v: 10 },+ lineSpacing: 2,+ spaceBelow: { v: 0 },+ },},-{- st: 328,- ed: 405,+ startIndex: 127,+ paragraphStyle: {+ spaceAbove: { v: 10 },+ lineSpacing: 2,+ spaceBelow: { v: 0 },+ // hanging: 20,+ // indentStart: 50,+ // indentEnd: 50,+ // indentFirstLine: 50,+ },},- ],- paragraphs: [{- startIndex: 60,- bullet: {- listType: PresetListType.ORDER_LIST,- listId: 'a',- nestingLevel: 0,- textStyle: {- fs: 20,- },+ startIndex: 128,+ paragraphStyle: {+ spaceAbove: { v: 10 },+ lineSpacing: 2,+ spaceBelow: { v: 0 },},},{- startIndex: 91,- bullet: {- listType: PresetListType.ORDER_LIST,- listId: 'a',- nestingLevel: 1,- textStyle: {- fs: 20,- },+ startIndex: 244,+ paragraphStyle: {+ spaceAbove: { v: 10 },+ lineSpacing: 2,+ spaceBelow: { v: 0 },},},{- startIndex: 234,- bullet: {- listType: PresetListType.ORDER_LIST,- listId: 'a',- nestingLevel: 1,- textStyle: {- fs: 20,- },+ startIndex: 245,+ paragraphStyle: {+ spaceAbove: { v: 10 },+ lineSpacing: 2,+ spaceBelow: { v: 0 },},},{- startIndex: 327,- bullet: {- listType: PresetListType.ORDER_LIST,- listId: 'a',- nestingLevel: 1,- textStyle: {- fs: 20,- },+ startIndex: 398,+ paragraphStyle: {+ spaceAbove: { v: 10 },+ lineSpacing: 2,+ spaceBelow: { v: 0 },},},{- startIndex: 406,- bullet: {- listType: PresetListType.ORDER_LIST,- listId: 'a',- nestingLevel: 2,- textStyle: {- fs: 20,- },+ startIndex: 399,+ paragraphStyle: {+ spaceAbove: { v: 10 },+ lineSpacing: 2,+ spaceBelow: { v: 0 },+ },+ },+ {+ startIndex: 618,+ paragraphStyle: {+ spaceAbove: { v: 10 },+ lineSpacing: 2,+ spaceBelow: { v: 0 },+ },+ },+ {+ startIndex: 619,+ paragraphStyle: {+ spaceAbove: { v: 10 },+ lineSpacing: 2,+ spaceBelow: { v: 0 },+ },+ },+ {+ startIndex: 824,+ paragraphStyle: {+ spaceAbove: { v: 10 },+ lineSpacing: 2,+ spaceBelow: { v: 0 },+ },+ },+ {+ startIndex: 825,+ paragraphStyle: {+ spaceAbove: { v: 10 },+ lineSpacing: 2,+ spaceBelow: { v: 0 },+ },+ },+ {+ startIndex: 1007,+ paragraphStyle: {+ spaceAbove: { v: 10 },+ lineSpacing: 2,+ spaceBelow: { v: 0 },+ },+ },+ {+ startIndex: 1008,+ paragraphStyle: {+ spaceAbove: { v: 10 },+ lineSpacing: 2,+ spaceBelow: { v: 0 },+ },+ },+ {+ startIndex: 1130,+ paragraphStyle: {+ spaceAbove: { v: 10 },+ lineSpacing: 2,+ spaceBelow: { v: 0 },+ },+ },+ {+ startIndex: 1131,+ paragraphStyle: {+ spaceAbove: { v: 10 },+ lineSpacing: 2,+ spaceBelow: { v: 0 },+ },+ },+ {+ startIndex: 1203,+ paragraphStyle: {+ spaceAbove: { v: 10 },+ lineSpacing: 2,+ spaceBelow: { v: 0 },+ },+ },+ {+ startIndex: 1204,+ paragraphStyle: {+ spaceAbove: { v: 10 },+ lineSpacing: 2,+ spaceBelow: { v: 0 },+ },+ },+ {+ startIndex: 1238,+ paragraphStyle: {+ spaceAbove: { v: 10 },+ lineSpacing: 2,+ spaceBelow: { v: 0 },+ },+ },+ {+ startIndex: 1239,+ paragraphStyle: {+ spaceAbove: { v: 10 },+ lineSpacing: 2,+ spaceBelow: { v: 0 },+ },+ },+ {+ startIndex: 1256,+ paragraphStyle: {+ spaceAbove: { v: 10 },+ lineSpacing: 2,+ spaceBelow: { v: 0 },+ },+ },+ {+ startIndex: 1257,+ paragraphStyle: {+ spaceAbove: { v: 10 },+ lineSpacing: 2,+ spaceBelow: { v: 0 },+ },+ },+ {+ startIndex: 1282,+ paragraphStyle: {+ spaceAbove: { v: 10 },+ lineSpacing: 2,+ spaceBelow: { v: 0 },+ },+ },+ {+ startIndex: 1283,+ paragraphStyle: {+ spaceAbove: { v: 10 },+ lineSpacing: 2,+ spaceBelow: { v: 0 },+ },+ },+ {+ startIndex: 1380,+ paragraphStyle: {+ spaceAbove: { v: 10 },+ lineSpacing: 2,+ spaceBelow: { v: 0 },+ },+ },+ {+ startIndex: 1381,+ paragraphStyle: {+ spaceAbove: { v: 10 },+ lineSpacing: 2,+ spaceBelow: { v: 0 },+ },+ },+ {+ startIndex: 1396,+ paragraphStyle: {+ spaceAbove: { v: 10 },+ lineSpacing: 2,+ spaceBelow: { v: 0 },+ },+ },+ {+ startIndex: 1397,+ paragraphStyle: {+ spaceAbove: { v: 10 },+ lineSpacing: 2,+ spaceBelow: { v: 0 },+ },+ },+ {+ startIndex: 1398,+ paragraphStyle: {+ spaceAbove: { v: 10 },+ lineSpacing: 2,+ spaceBelow: { v: 0 },+ },+ },+ {+ startIndex: 1399,+ paragraphStyle: {+ spaceAbove: { v: 10 },+ lineSpacing: 2,+ spaceBelow: { v: 0 },+ },+ },+ {+ startIndex: 1457,+ paragraphStyle: {+ spaceAbove: { v: 10 },+ lineSpacing: 2,+ spaceBelow: { v: 0 },+ },+ },+ {+ startIndex: 1458,+ paragraphStyle: {+ spaceAbove: { v: 10 },+ lineSpacing: 2,+ spaceBelow: { v: 0 },+ },+ },+ {+ startIndex: 1559,+ paragraphStyle: {+ spaceAbove: { v: 10 },+ lineSpacing: 2,+ spaceBelow: { v: 0 },+ },+ },+ {+ startIndex: 1560,+ paragraphStyle: {+ spaceAbove: { v: 10 },+ lineSpacing: 2,+ spaceBelow: { v: 0 },+ },+ },+ {+ startIndex: 1566,+ paragraphStyle: {+ spaceAbove: { v: 10 },+ lineSpacing: 2,+ spaceBelow: { v: 0 },+ },+ },+ {+ startIndex: 1670,+ paragraphStyle: {+ spaceAbove: { v: 10 },+ lineSpacing: 2,+ spaceBelow: { v: 0 },+ },+ },+ {+ startIndex: 1671,+ paragraphStyle: {+ spaceAbove: { v: 10 },+ lineSpacing: 2,+ spaceBelow: { v: 0 },+ },+ },+ {+ startIndex: 1728,+ paragraphStyle: {+ spaceAbove: { v: 10 },+ lineSpacing: 2,+ spaceBelow: { v: 0 },+ },+ },+ {+ startIndex: 1729,+ paragraphStyle: {+ spaceAbove: { v: 10 },+ lineSpacing: 2,+ spaceBelow: { v: 0 },+ },+ },+ {+ startIndex: 1811,+ paragraphStyle: {+ spaceAbove: { v: 10 },+ lineSpacing: 2,+ spaceBelow: { v: 0 },+ },+ },+ {+ startIndex: 1812,+ paragraphStyle: {+ spaceAbove: { v: 10 },+ lineSpacing: 2,+ spaceBelow: { v: 0 },+ },+ },+ {+ startIndex: 1912,+ paragraphStyle: {+ spaceAbove: { v: 10 },+ lineSpacing: 2,+ spaceBelow: { v: 0 },+ },+ },+ {+ startIndex: 1913,+ paragraphStyle: {+ spaceAbove: { v: 10 },+ lineSpacing: 2,+ spaceBelow: { v: 0 },+ },+ },+ {+ startIndex: 2053,+ paragraphStyle: {+ spaceAbove: { v: 10 },+ lineSpacing: 2,+ spaceBelow: { v: 0 },+ },+ },+ {+ startIndex: 2054,+ paragraphStyle: {+ spaceAbove: { v: 10 },+ lineSpacing: 2,+ spaceBelow: { v: 0 },+ },+ },+ {+ startIndex: 2190,+ paragraphStyle: {+ spaceAbove: { v: 10 },+ lineSpacing: 2,+ spaceBelow: { v: 0 },+ },+ },+ {+ startIndex: 2191,+ paragraphStyle: {+ spaceAbove: { v: 10 },+ lineSpacing: 2,+ spaceBelow: { v: 0 },+ },+ },+ {+ startIndex: 2341,+ paragraphStyle: {+ spaceAbove: { v: 10 },+ lineSpacing: 2,+ spaceBelow: { v: 0 },+ },+ },+ {+ startIndex: 2342,+ paragraphStyle: {+ spaceAbove: { v: 10 },+ lineSpacing: 2,+ spaceBelow: { v: 0 },+ },+ },+ {+ startIndex: 2481,+ paragraphStyle: {+ spaceAbove: { v: 10 },+ lineSpacing: 2,+ spaceBelow: { v: 0 },+ },+ },+ {+ startIndex: 2482,+ paragraphStyle: {+ spaceAbove: { v: 10 },+ lineSpacing: 2,+ spaceBelow: { v: 0 },+ },+ },+ {+ startIndex: 2582,+ paragraphStyle: {+ spaceAbove: { v: 10 },+ lineSpacing: 2,+ spaceBelow: { v: 0 },+ },+ },+ {+ startIndex: 2583,+ paragraphStyle: {+ spaceAbove: { v: 10 },+ lineSpacing: 2,+ spaceBelow: { v: 0 },+ },+ },+ {+ startIndex: 2750,+ paragraphStyle: {+ spaceAbove: { v: 10 },+ lineSpacing: 2,+ spaceBelow: { v: 0 },+ },+ },+ {+ startIndex: 2751,+ paragraphStyle: {+ spaceAbove: { v: 10 },+ lineSpacing: 2,+ spaceBelow: { v: 0 },+ },+ },+ {+ startIndex: 2853,+ paragraphStyle: {+ spaceAbove: { v: 10 },+ lineSpacing: 2,+ spaceBelow: { v: 0 },+ },+ },+ {+ startIndex: 2854,+ paragraphStyle: {+ spaceAbove: { v: 10 },+ lineSpacing: 2,+ spaceBelow: { v: 0 },+ },+ },+ {+ startIndex: 2948,+ paragraphStyle: {+ spaceAbove: { v: 10 },+ lineSpacing: 2,+ spaceBelow: { v: 0 },+ },+ },+ {+ startIndex: 2949,+ paragraphStyle: {+ spaceAbove: { v: 10 },+ lineSpacing: 2,+ spaceBelow: { v: 0 },+ },+ },+ {+ startIndex: 3065,+ paragraphStyle: {+ spaceAbove: { v: 10 },+ lineSpacing: 2,+ spaceBelow: { v: 0 },},},],sectionBreaks: [{- startIndex: 407,- columnProperties: [- {- width: 200,- paddingEnd: 20,- },- ],- columnSeparatorType: ColumnSeparatorType.NONE,- sectionType: SectionType.SECTION_TYPE_UNSPECIFIED,- // textDirection: textDirectionDocument,- // contentDirection: textDirection!,+ startIndex: 3066,+ // columnProperties: [+ // {+ // width: ptToPixel(240),+ // paddingEnd: ptToPixel(15),+ // },+ // ],+ // columnSeparatorType: ColumnSeparatorType.NONE,+ // sectionType: SectionType.SECTION_TYPE_UNSPECIFIED,+ // textDirection: textDirectionDocument,+ // contentDirection: textDirection!,},],+ customBlocks: [],+ tables: [],},documentStyle: {pageSize: {- width: 594.3,- height: 840.51,+ width: ptToPixel(595),+ height: ptToPixel(842),},documentFlavor: DocumentFlavor.TRADITIONAL,- marginTop: 72,- marginBottom: 72,- marginRight: 90,- marginLeft: 90,+ marginTop: ptToPixel(50),+ marginBottom: ptToPixel(50),+ marginRight: ptToPixel(50),+ marginLeft: ptToPixel(50),+ renderConfig: {+ vertexAngle: 0,+ centerAngle: 0,+ },+ defaultHeaderId: '',+ defaultFooterId: '',+ evenPageHeaderId: '',+ evenPageFooterId: '',+ firstPageHeaderId: '',+ firstPageFooterId: '',+ evenAndOddHeaders: BooleanNumber.FALSE,+ useFirstPageHeaderFooter: BooleanNumber.FALSE,+ marginHeader: 30,+ marginFooter: 30,},};+ return DEFAULT_DOCUMENT_DATA_CN;}diff --git a/packages/docs-drawing-ui/src/commands/commands/insert-doc-drawing.command.ts b/packages/docs-drawing-ui/src/commands/commands/insert-doc-drawing.command.tsindex f50e1507e8..ce40768b25 100644--- a/packages/docs-drawing-ui/src/commands/commands/insert-doc-drawing.command.ts+++ b/packages/docs-drawing-ui/src/commands/commands/insert-doc-drawing.command.ts@@ -45,7 +45,7 @@ export const InsertDocDrawingCommand: ICommand = {const textSelectionManagerService = accessor.get(TextSelectionManagerService);const univerInstanceService = accessor.get(IUniverInstanceService);- const activeTextRange = textSelectionManagerService.getActiveRange();+ const activeTextRange = textSelectionManagerService.getActiveTextRangeWithStyle();const documentDataModel = univerInstanceService.getCurrentUniverDocInstance();if (activeTextRange == null || documentDataModel == null) {return false;diff --git a/packages/docs-drawing-ui/src/commands/commands/update-doc-drawing.command.ts b/packages/docs-drawing-ui/src/commands/commands/update-doc-drawing.command.tsindex f88eda27b8..abb7665d0c 100644--- a/packages/docs-drawing-ui/src/commands/commands/update-doc-drawing.command.ts+++ b/packages/docs-drawing-ui/src/commands/commands/update-doc-drawing.command.ts@@ -652,6 +652,7 @@ export interface IMoveInlineDrawingParams {offset: number;segmentId: string;segmentPage: number;+ needRefreshDrawings?: boolean;}/**@@ -662,7 +663,7 @@ export const IMoveInlineDrawingCommand: ICommand = {type: CommandType.COMMAND,- handler: (accessor: IAccessor, params?: IMoveInlineDrawingParams) => {+ handler: (accessor: IAccessor, params: IMoveInlineDrawingParams) => {if (params == null) {return false;}@@ -686,7 +687,14 @@ export const IMoveInlineDrawingCommand: ICommand = {return false;}- const { drawing, unitId, offset, segmentId: newSegmentId, segmentPage } = params;+ const { drawing, unitId, offset, segmentId: newSegmentId, segmentPage, needRefreshDrawings } = params;++ // Need to refresh drawings if not find the anchor position.+ if (needRefreshDrawings) {+ docRefreshDrawingsService.refreshDrawings(skeleton);+ transformer.refreshControls();+ return true;+ }const rawActions: JSONXActions = [];diff --git a/packages/docs-drawing-ui/src/controllers/doc-drawing-transformer-update.controller.ts b/packages/docs-drawing-ui/src/controllers/doc-drawing-transformer-update.controller.tsindex ee6fe79b75..ac73d6b4b0 100644--- a/packages/docs-drawing-ui/src/controllers/doc-drawing-transformer-update.controller.ts+++ b/packages/docs-drawing-ui/src/controllers/doc-drawing-transformer-update.controller.ts@@ -23,7 +23,7 @@ import {} from '@univerjs/core';import { DocSkeletonManagerService, getDocObject } from '@univerjs/docs';import { IDrawingManagerService } from '@univerjs/drawing';-import type { BaseObject, Documents, IDocumentSkeletonGlyph, IDocumentSkeletonPage, Image, IPoint, Viewport } from '@univerjs/engine-render';+import type { BaseObject, Documents, IDocumentSkeletonGlyph, IDocumentSkeletonPage, Image, INodeSearch, IPoint, Viewport } from '@univerjs/engine-render';import { DocumentSkeletonPageType, getAnchorBounding, getColor, getOneTextSelectionRange, IRenderManagerService, ITextSelectionRenderManager, Liquid, NodePositionConvertToCursor, PageLayoutType, Rect, TEXT_RANGE_LAYER_INDEX, Vector2 } from '@univerjs/engine-render';import type { IDrawingDocTransform } from '../commands/commands/update-doc-drawing.command';import { IMoveInlineDrawingCommand, ITransformNonInlineDrawingCommand, UpdateDrawingDocTransformCommand } from '../commands/commands/update-doc-drawing.command';@@ -47,6 +47,12 @@ interface IDrawingAnchor {contentBoxPointGroup?: IPoint[][];}+function isInTableCell(nodePosition: INodeSearch) {+ const { path } = nodePosition;++ return path.some((p) => p === 'cells');+}+// Listen doc drawing transformer change, and update drawing data.@OnLifecycle(LifecycleStages.Rendered, DocDrawingTransformerController)@@ -408,6 +414,11 @@ export class DocDrawingTransformerController extends Disposable {return;}+ // TODO: @JOCS, table cell do not support drawings now. so need to disable it.+ if (isInTableCell(nodePosition)) {+ return;+ }+const positionWithIsBack = {...nodePosition,isBack,@@ -600,6 +611,11 @@ export class DocDrawingTransformerController extends Disposable {return;}+ // TODO: @JOCS, table cell do not support drawings now. so need to disable it.+ if (isInTableCell(nodePosition)) {+ return;+ }+const positionWithIsBack = {...nodePosition,isBack,@@ -663,10 +679,6 @@ export class DocDrawingTransformerController extends Disposable {const anchor = this._getInlineDrawingAnchor(drawing, offsetX, offsetY);const { offset, segmentId, segmentPage } = anchor ?? {};- if (offset == null) {- return;- }-return this._commandService.executeCommand(IMoveInlineDrawingCommand.id, {unitId: drawing.unitId,subUnitId: drawing.unitId,@@ -674,6 +686,7 @@ export class DocDrawingTransformerController extends Disposable {offset,segmentId,segmentPage,+ needRefreshDrawings: offset == null,});}diff --git a/packages/docs-drawing-ui/src/views/menu/image.menu.ts b/packages/docs-drawing-ui/src/views/menu/image.menu.tsindex 2a37be0d57..14ef448ce5 100644--- a/packages/docs-drawing-ui/src/views/menu/image.menu.ts+++ b/packages/docs-drawing-ui/src/views/menu/image.menu.ts@@ -15,15 +15,49 @@*/import { getMenuHiddenObservable, type IMenuItem, MenuGroup, MenuItemType, MenuPosition } from '@univerjs/ui';-import { UniverInstanceType } from '@univerjs/core';+import { IUniverInstanceService, UniverInstanceType } from '@univerjs/core';import type { IAccessor } from '@univerjs/core';+import { TextSelectionManagerService } from '@univerjs/docs';+import { combineLatest, Observable } from 'rxjs';import { COMPONENT_DOC_UPLOAD_FILE_MENU } from '../upload-component/component-name';export const ImageUploadIcon = 'addition-and-subtraction-single';const IMAGE_MENU_ID = 'doc.menu.image';const IMAGE_MENU_UPLOAD_FLOAT_ID = 'doc.menu.image.upload.float';+// TODO: @Jocs, remove this when cell support drawing.+const getDisableWhenSelectionInTableObservable = (accessor: IAccessor) => {+ const textSelectionManagerService = accessor.get(TextSelectionManagerService);+ const univerInstanceService = accessor.get(IUniverInstanceService);++ return new Observable<boolean>((subscriber) => {+ const observable = textSelectionManagerService.textSelection$.subscribe(() => {+ const activeRange = textSelectionManagerService.getActiveTextRangeWithStyle();++ if (activeRange) {+ const { segmentId, startOffset, endOffset } = activeRange;+ const docDataModel = univerInstanceService.getCurrentUniverDocInstance();+ const tables = docDataModel?.getSelfOrHeaderFooterModel(segmentId).getBody()?.tables;++ if (tables && tables.length) {+ if (tables.some((table) => {+ const { startIndex, endIndex } = table;+ return (startOffset >= startIndex && startOffset <= endIndex) || (endOffset >= startIndex && endOffset <= endIndex);+ })) {+ subscriber.next(true);+ return;+ }+ }+ }++ subscriber.next(false);+ });++ return () => observable.unsubscribe();+ });+};+export function ImageMenuFactory(accessor: IAccessor): IMenuItem {return {id: IMAGE_MENU_ID,@@ -32,7 +66,9 @@ export function ImageMenuFactory(accessor: IAccessor): IMenuItem {group: MenuGroup.TOOLBAR_LAYOUT,icon: ImageUploadIcon,tooltip: 'docImage.title',- hidden$: getMenuHiddenObservable(accessor, UniverInstanceType.UNIVER_DOC),+ hidden$: combineLatest(getDisableWhenSelectionInTableObservable(accessor), getMenuHiddenObservable(accessor, UniverInstanceType.UNIVER_DOC), (one, two) => {+ return one || two;+ }),};}diff --git a/packages/docs-hyper-link-ui/src/commands/operations/popup.operation.ts b/packages/docs-hyper-link-ui/src/commands/operations/popup.operation.tsindex 7023c18ce4..9f0431377e 100644--- a/packages/docs-hyper-link-ui/src/commands/operations/popup.operation.ts+++ b/packages/docs-hyper-link-ui/src/commands/operations/popup.operation.ts@@ -23,7 +23,7 @@ import { DocHyperLinkPopupService } from '../../services/hyper-link-popup.servicexport const shouldDisableAddLink = (accessor: IAccessor) => {const textSelectionService = accessor.get(TextSelectionManagerService);const univerInstanceService = accessor.get(IUniverInstanceService);- const activeRange = textSelectionService.getActiveRange();+ const activeRange = textSelectionService.getActiveTextRangeWithStyle();const renderManagerService = accessor.get(IRenderManagerService);const render = renderManagerService.getCurrent();const skeleton = render?.with(DocSkeletonManagerService).getSkeleton();diff --git a/packages/docs-hyper-link-ui/src/controllers/doc-hyper-link-clipboard.controller.ts b/packages/docs-hyper-link-ui/src/controllers/doc-hyper-link-clipboard.controller.tsindex c9ec597c4d..0ff2e6e101 100644--- a/packages/docs-hyper-link-ui/src/controllers/doc-hyper-link-clipboard.controller.ts+++ b/packages/docs-hyper-link-ui/src/controllers/doc-hyper-link-clipboard.controller.ts@@ -42,7 +42,7 @@ export class DocHyperLinkClipboardController extends Disposable {if (!doc) {return body;}- const activeRange = this._textSelectionManagerService.getActiveRange();+ const activeRange = this._textSelectionManagerService.getActiveTextRangeWithStyle();const customRanges = doc.getBody()?.customRanges;const matchedRange = activeRange ?diff --git a/packages/docs-hyper-link-ui/src/services/hyper-link-popup.service.ts b/packages/docs-hyper-link-ui/src/services/hyper-link-popup.service.tsindex 2ce50c815e..9c044d512d 100644--- a/packages/docs-hyper-link-ui/src/services/hyper-link-popup.service.ts+++ b/packages/docs-hyper-link-ui/src/services/hyper-link-popup.service.ts@@ -69,7 +69,7 @@ export class DocHyperLinkPopupService extends Disposable {this._editPopup.dispose();}this._editingLink$.next(linkInfo);- let activeRange: Nullable<ITextRange> = this._textSelectionManagerService.getActiveRange();+ let activeRange: Nullable<ITextRange> = this._textSelectionManagerService.getActiveTextRangeWithStyle();if (linkInfo) {const { unitId, rangeIndex } = linkInfo;const doc = this._univerInstanceService.getUnit<DocumentDataModel>(unitId, UniverInstanceType.UNIVER_DOC);diff --git a/packages/docs-hyper-link-ui/src/views/hyper-link-edit/index.tsx b/packages/docs-hyper-link-ui/src/views/hyper-link-edit/index.tsxindex 40070df3da..47b55acbc6 100644--- a/packages/docs-hyper-link-ui/src/views/hyper-link-edit/index.tsx+++ b/packages/docs-hyper-link-ui/src/views/hyper-link-edit/index.tsx@@ -63,7 +63,7 @@ export const DocHyperLinkEdit = () => {setLink(linkDetail?.payload ?? '');return;}- const activeRange = textSelectionManagerService.getActiveRange();+ const activeRange = textSelectionManagerService.getActiveTextRangeWithStyle();if (!activeRange) {return;}diff --git a/packages/docs-mention-ui/src/controllers/doc-mention-trigger.controller.ts b/packages/docs-mention-ui/src/controllers/doc-mention-trigger.controller.tsindex 6c2c035273..1f8551f6d3 100644--- a/packages/docs-mention-ui/src/controllers/doc-mention-trigger.controller.ts+++ b/packages/docs-mention-ui/src/controllers/doc-mention-trigger.controller.ts@@ -39,7 +39,7 @@ export class DocMentionTriggerController extends Disposable {this._commandService.onCommandExecuted((commandInfo) => {if (commandInfo.id === InsertCommand.id) {const params = commandInfo.params as IInsertCommandParams;- const activeRange = this._textSelectionManagerService.getActiveRange();+ const activeRange = this._textSelectionManagerService.getActiveTextRangeWithStyle();if (params.body.dataStream === '@' && activeRange && !Tools.isDefine(this._docMentionService.editing)) {this._commandService.executeCommand(ShowMentionEditPopupOperation.id, {startIndex: activeRange.startOffset - 1,@@ -55,7 +55,7 @@ export class DocMentionTriggerController extends Disposable {if (this._docMentionPopupService.editPopup == null) {return;}- const activeRange = this._textSelectionManagerService.getActiveRange();+ const activeRange = this._textSelectionManagerService.getActiveTextRangeWithStyle();if (activeRange && activeRange.endOffset <= this._docMentionPopupService.editPopup.anchor) {this._commandService.executeCommand(CloseMentionEditPopupOperation.id);}diff --git a/packages/docs-mention/src/commands/commands/doc-mention.command.ts b/packages/docs-mention/src/commands/commands/doc-mention.command.tsindex 270bfb8c2f..90f8a8ea87 100644--- a/packages/docs-mention/src/commands/commands/doc-mention.command.ts+++ b/packages/docs-mention/src/commands/commands/doc-mention.command.ts@@ -38,7 +38,7 @@ export const AddDocMentionCommand: ICommand<IAddDocMentionCommandParams> = {const { mention, unitId, startIndex } = params;const commandService = accessor.get(ICommandService);const textSelectionManagerService = accessor.get(TextSelectionManagerService);- const activeRange = textSelectionManagerService.getActiveRange();+ const activeRange = textSelectionManagerService.getActiveTextRangeWithStyle();if (!activeRange) {return false;}diff --git a/packages/docs-thread-comment-ui/src/commands/operations/show-comment-panel.operation.ts b/packages/docs-thread-comment-ui/src/commands/operations/show-comment-panel.operation.tsindex 42efeb849a..23865d461c 100644--- a/packages/docs-thread-comment-ui/src/commands/operations/show-comment-panel.operation.ts+++ b/packages/docs-thread-comment-ui/src/commands/operations/show-comment-panel.operation.ts@@ -91,7 +91,7 @@ export const StartAddCommentOperation: ICommand = {const commandService = accessor.get(ICommandService);const sidebarService = accessor.get(ISidebarService);- const textRange = textSelectionManagerService.getActiveRange();+ const textRange = textSelectionManagerService.getActiveTextRangeWithStyle();if (!doc || !textRange) {return false;}diff --git a/packages/docs-thread-comment-ui/src/controllers/menu.ts b/packages/docs-thread-comment-ui/src/controllers/menu.tsindex be6ad121ae..a92f240884 100644--- a/packages/docs-thread-comment-ui/src/controllers/menu.ts+++ b/packages/docs-thread-comment-ui/src/controllers/menu.ts@@ -33,7 +33,7 @@ export const shouldDisableAddComment = (accessor: IAccessor) => {return true;}- const range = textSelectionManagerService.getActiveRange();+ const range = textSelectionManagerService.getActiveTextRangeWithStyle();if (!range || range.collapsed) {return true;}diff --git a/packages/docs-thread-comment-ui/src/views/doc-thread-comment-panel/index.tsx b/packages/docs-thread-comment-ui/src/views/doc-thread-comment-panel/index.tsxindex 0cfa499abd..6baf3c054d 100644--- a/packages/docs-thread-comment-ui/src/views/doc-thread-comment-panel/index.tsx+++ b/packages/docs-thread-comment-ui/src/views/doc-thread-comment-panel/index.tsx@@ -72,7 +72,7 @@ export const DocThreadCommentPanel = () => {return null;}- const activeRange = textSelectionManagerService.getActiveRange();+ const activeRange = textSelectionManagerService.getActiveTextRangeWithStyle();const isInValidSelection = Boolean(activeRange &&(activeRange.endOffset === activeRange.startOffset || activeRange.segmentId)diff --git a/packages/docs-ui/src/commands/commands/clipboard.command.ts b/packages/docs-ui/src/commands/commands/clipboard.command.tsindex 5cd5121b70..9529d6fa52 100644--- a/packages/docs-ui/src/commands/commands/clipboard.command.ts+++ b/packages/docs-ui/src/commands/commands/clipboard.command.ts@@ -64,7 +64,6 @@ export const DocPasteCommand: IMultiCommand = {handler: async (accessor: IAccessor) => {const docClipboardService = accessor.get(IDocClipboardService);const clipboardInterfaceService = accessor.get(IClipboardInterfaceService);-const clipboardItems = await clipboardInterfaceService.read();if (clipboardItems.length === 0) {return false;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 b2d1ef78fe..e8998a5162 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@@ -17,7 +17,7 @@import type { DocumentDataModel, IAccessor, ICommand, IMutationInfo, IParagraphStyle } from '@univerjs/core';import { CommandType, ICommandService, IUniverInstanceService, JSONX, MemoryCursor, TextX, TextXActionType, UniverInstanceType, UpdateDocsAttributeType } from '@univerjs/core';import type { IRichTextEditingMutationParams } from '@univerjs/docs';-import { getParagraphsInRange, getRichTextEditPath, RichTextEditingMutation, serializeTextRange, TextSelectionManagerService } 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 const DocParagraphSettingCommand: ICommand<IDocParagraphSettingCommandParams> = {@@ -30,20 +30,20 @@ export const DocParagraphSettingCommand: ICommand<IDocParagraphSettingCommandParconst commandService = accessor.get(ICommandService);const docDataModel = univerInstanceService.getCurrentUnitForType<DocumentDataModel>(UniverInstanceType.UNIVER_DOC);- const activeRange = textSelectionManagerService.getActiveRange();+ const docRanges = textSelectionManagerService.getDocRanges();- if (!docDataModel || !activeRange || !config) {+ if (!docDataModel || docRanges.length === 0 || !config) {return false;}- const segmentId = activeRange.segmentId;+ const segmentId = docRanges[0].segmentId;+const unitId = docDataModel.getUnitId();const allParagraphs = docDataModel.getSelfOrHeaderFooterModel(segmentId).getBody()?.paragraphs ?? [];- const paragraphs = getParagraphsInRange(activeRange, allParagraphs) ?? [];+ const paragraphs = getParagraphsInRanges(docRanges, allParagraphs) ?? [];- const selections = textSelectionManagerService.getCurrentSelections() ?? [];- const serializedSelections = selections.map(serializeTextRange);+ const serializedSelections = docRanges.map(serializeDocRange);const doMutation: IMutationInfo<IRichTextEditingMutationParams> = {id: RichTextEditingMutation.id,@@ -99,6 +99,7 @@ export const DocParagraphSettingCommand: ICommand<IDocParagraphSettingCommandParIRichTextEditingMutationParams,IRichTextEditingMutationParams>(doMutation.id, doMutation.params);+return !!result;},};diff --git a/packages/docs-ui/src/commands/commands/doc-tab.command.ts b/packages/docs-ui/src/commands/commands/doc-tab.command.tsnew file mode 100644index 0000000000..c21b014b63--- /dev/null+++ b/packages/docs-ui/src/commands/commands/doc-tab.command.ts@@ -0,0 +1,69 @@+/**+ * 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 { CommandType, type ICommand, ICommandService } from '@univerjs/core';+import { DocTableShiftTabCommand, DocTableTabCommand, TextSelectionManagerService } from '@univerjs/docs';+import { isInSameTableCell } from '@univerjs/engine-render';++export interface IDocTabCommandParams { }++export const DocTabCommand: ICommand<IDocTabCommandParams> = {+ id: 'doc.tab.tab-in-doc',+ type: CommandType.COMMAND,+ handler: async (accessor) => {+ const textSelectionManagerService = accessor.get(TextSelectionManagerService);+ const commandService = accessor.get(ICommandService);++ const activeTextRange = textSelectionManagerService.getActiveTextRangeWithStyle();++ if (activeTextRange == null) {+ return false;+ }++ const { startNodePosition, endNodePosition } = activeTextRange;++ if (startNodePosition && endNodePosition && isInSameTableCell(startNodePosition, endNodePosition)) {+ return commandService.executeCommand(DocTableTabCommand.id);+ }++ return false;+ },+};++export interface IDocShiftTabCommandParams { }++export const DocShiftTabCommand: ICommand<IDocShiftTabCommandParams> = {+ id: 'doc.tab.shift-tab-in-doc',+ type: CommandType.COMMAND,+ handler: async (accessor) => {+ const textSelectionManagerService = accessor.get(TextSelectionManagerService);+ const commandService = accessor.get(ICommandService);++ const activeTextRange = textSelectionManagerService.getActiveTextRangeWithStyle();++ if (activeTextRange == null) {+ return false;+ }++ const { startNodePosition, endNodePosition } = activeTextRange;++ if (startNodePosition && endNodePosition && isInSameTableCell(startNodePosition, endNodePosition)) {+ return commandService.executeCommand(DocTableShiftTabCommand.id);+ }++ return false;+ },+};diff --git a/packages/docs-ui/src/commands/operations/doc-create-table.operation.ts b/packages/docs-ui/src/commands/operations/doc-create-table.operation.tsnew file mode 100644index 0000000000..442523e200--- /dev/null+++ b/packages/docs-ui/src/commands/operations/doc-create-table.operation.ts@@ -0,0 +1,68 @@+/**+ * 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 { IAccessor, ICommand } from '@univerjs/core';+import { CommandType, ICommandService, LocaleService } from '@univerjs/core';+import { IConfirmService } from '@univerjs/ui';+import { CreateDocTableCommand } from '@univerjs/docs';+import { COMPONENT_DOC_CREATE_TABLE_CONFIRM } from '../../views/table/create/component-name';++const COMPONENT_DOC_CREATE_TABLE_CONFIRM_ID = 'doc.component.create-table-confirm';++export const DocCreateTableOperation: ICommand = {+ id: 'doc.operation.create-table',+ type: CommandType.COMMAND,+ handler: async (accessor: IAccessor) => {+ const localeService = accessor.get(LocaleService);+ const confirmService = accessor.get(IConfirmService);+ const commandService = accessor.get(ICommandService);++ const tableCreateParams = {+ rowCount: 3,+ colCount: 5,+ };++ const handleRowColChange = (rowCount: number, colCount: number) => {+ tableCreateParams.rowCount = rowCount;+ tableCreateParams.colCount = colCount;+ };++ await confirmService.open({+ id: COMPONENT_DOC_CREATE_TABLE_CONFIRM_ID,+ children: {+ label: {+ name: COMPONENT_DOC_CREATE_TABLE_CONFIRM,+ props: {+ handleRowColChange,+ tableCreateParams,+ },+ },+ },+ width: 400,+ title: { title: localeService.t('toolbar.table.insert') },+ onConfirm: () => {+ commandService.executeCommand(CreateDocTableCommand.id, tableCreateParams);+ confirmService.close(COMPONENT_DOC_CREATE_TABLE_CONFIRM_ID);+ },+ onClose: () => {+ confirmService.close(COMPONENT_DOC_CREATE_TABLE_CONFIRM_ID);+ },+ });++ return true;+ },+};+diff --git a/packages/docs-ui/src/controllers/doc-editor-bridge.controller.ts b/packages/docs-ui/src/controllers/doc-editor-bridge.controller.tsindex b68f5ae57b..bb0a4e29c9 100644--- a/packages/docs-ui/src/controllers/doc-editor-bridge.controller.ts+++ b/packages/docs-ui/src/controllers/doc-editor-bridge.controller.ts@@ -157,7 +157,7 @@ export class DocEditorBridgeController extends Disposable {private _initialBlur() {this.disposeWithMe(this._editorService.blur$.subscribe(() => {- this._textSelectionRenderManager.removeAllTextRanges();+ this._textSelectionRenderManager.removeAllRanges();this._textSelectionRenderManager.blur();})@@ -186,8 +186,8 @@ export class DocEditorBridgeController extends Disposable {private _initialFocus() {this.disposeWithMe(this._editorService.focus$.subscribe((textRange) => {- this._textSelectionRenderManager.removeAllTextRanges();- this._textSelectionRenderManager.addTextRanges([textRange]);+ this._textSelectionRenderManager.removeAllRanges();+ this._textSelectionRenderManager.addDocRanges([textRange]);}));diff --git a/packages/docs-ui/src/controllers/doc-table.controller.ts b/packages/docs-ui/src/controllers/doc-table.controller.tsnew file mode 100644index 0000000000..971906f385--- /dev/null+++ b/packages/docs-ui/src/controllers/doc-table.controller.ts@@ -0,0 +1,53 @@+/**+ * 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 { Disposable, ICommandService, Inject, LifecycleStages, OnLifecycle } from '@univerjs/core';++import { ComponentManager } from '@univerjs/ui';+import { COMPONENT_DOC_CREATE_TABLE_CONFIRM } from '../views/table/create/component-name';+import { DocCreateTableConfirm } from '../views/table/create/TableCreate';+import { DocCreateTableOperation } from '../commands/operations/doc-create-table.operation';++@OnLifecycle(LifecycleStages.Rendered, DocTableController)+export class DocTableController extends Disposable {+ constructor(+ @ICommandService private readonly _commandService: ICommandService,+ @Inject(ComponentManager) private readonly _componentManager: ComponentManager+ ) {+ super();++ this._initialize();+ }++ private _initialize() {+ this._init();+ this._registerCommands();+ this._initCustomComponents();+ }++ private _registerCommands() {+ [+ DocCreateTableOperation,+ ].forEach((command) => this.disposeWithMe(this._commandService.registerCommand(command)));+ }++ private _initCustomComponents(): void {+ const componentManager = this._componentManager;+ this.disposeWithMe(componentManager.register(COMPONENT_DOC_CREATE_TABLE_CONFIRM, DocCreateTableConfirm));+ }++ private _init() {}+}diff --git a/packages/docs-ui/src/controllers/doc-ui.controller.ts b/packages/docs-ui/src/controllers/doc-ui.controller.tsindex cf30b1e595..17c8c2c923 100644--- a/packages/docs-ui/src/controllers/doc-ui.controller.ts+++ b/packages/docs-ui/src/controllers/doc-ui.controller.ts@@ -56,16 +56,18 @@ import {FontFamilySelectorMenuItemFactory,FontSizeSelectorMenuItemFactory,HeaderFooterMenuItemFactory,+ InsertTableMenuFactory,ItalicMenuItemFactory,OrderListMenuItemFactory,ResetBackgroundColorMenuItemFactory,StrikeThroughMenuItemFactory,SubscriptMenuItemFactory,SuperscriptMenuItemFactory,+ TableMenuFactory,TextColorSelectorMenuItemFactory,UnderlineMenuItemFactory,} from './menu/menu';-import { CopyMenuFactory, CutMenuFactory, DeleteMenuFactory, ParagraphSettingMenuFactory, PasteMenuFactory } from './menu/context-menu';+import { CopyMenuFactory, CutMenuFactory, DeleteColumnsMenuItemFactory, DeleteMenuFactory, DeleteRowsMenuItemFactory, DeleteTableMenuItemFactory, InsertColumnLeftMenuItemFactory, InsertColumnRightMenuItemFactory, InsertRowAfterMenuItemFactory, InsertRowBeforeMenuItemFactory, ParagraphSettingMenuFactory, PasteMenuFactory, TableDeleteMenuItemFactory, TableInsertMenuItemFactory } from './menu/context-menu';// FIXME: LifecycleStages.Rendered must be used, otherwise the menu cannot be added to the DOM, but the sheet ui plug-in can be added in LifecycleStages.Ready@OnLifecycle(LifecycleStages.Rendered, DocUIController)@@ -118,6 +120,8 @@ export class DocUIController extends Disposable {FontFamilySelectorMenuItemFactory,TextColorSelectorMenuItemFactory,HeaderFooterMenuItemFactory,+ TableMenuFactory,+ InsertTableMenuFactory,AlignLeftMenuItemFactory,AlignCenterMenuItemFactory,AlignRightMenuItemFactory,@@ -131,13 +135,22 @@ export class DocUIController extends Disposable {this.disposeWithMe(this._menuService.addMenuItem(this._injector.invoke(factory), menu));});- [+ ([CopyMenuFactory,CutMenuFactory,PasteMenuFactory,DeleteMenuFactory,ParagraphSettingMenuFactory,- ].forEach((factory) => {+ TableInsertMenuItemFactory,+ InsertRowBeforeMenuItemFactory,+ InsertRowAfterMenuItemFactory,+ InsertColumnLeftMenuItemFactory,+ InsertColumnRightMenuItemFactory,+ TableDeleteMenuItemFactory,+ DeleteRowsMenuItemFactory,+ DeleteColumnsMenuItemFactory,+ DeleteTableMenuItemFactory,+ ] as IMenuItemFactory[]).forEach((factory) => {try {this.disposeWithMe(this._menuService.addMenuItem(this._injector.invoke(factory), menu));} catch (error) {diff --git a/packages/docs-ui/src/controllers/menu/context-menu.ts b/packages/docs-ui/src/controllers/menu/context-menu.tsindex 5815e66a12..1d9f4884c4 100644--- a/packages/docs-ui/src/controllers/menu/context-menu.ts+++ b/packages/docs-ui/src/controllers/menu/context-menu.ts@@ -15,19 +15,20 @@*/import type { IAccessor } from '@univerjs/core';-import { UniverInstanceType } from '@univerjs/core';-import type { IMenuButtonItem } from '@univerjs/ui';+import { IUniverInstanceService, UniverInstanceType } from '@univerjs/core';+import type { IMenuButtonItem, IMenuSelectorItem } from '@univerjs/ui';import { getMenuHiddenObservable, MenuGroup, MenuItemType, MenuPosition } from '@univerjs/ui';-import { Observable } from 'rxjs';-import { DeleteLeftCommand, TextSelectionManagerService } from '@univerjs/docs';+import { combineLatest, Observable } from 'rxjs';+import { DeleteLeftCommand, DocTableDeleteColumnsCommand, DocTableDeleteRowsCommand, DocTableDeleteTableCommand, DocTableInsertColumnLeftCommand, DocTableInsertColumnRightCommand, DocTableInsertRowAboveCommand, DocTableInsertRowBellowCommand, TextSelectionManagerService } from '@univerjs/docs';+import type { RectRange } from '@univerjs/engine-render';import { DocCopyCommand, DocCutCommand, DocPasteCommand } from '../../commands/commands/clipboard.command';import { DocParagraphSettingPanelOperation } from '../../commands/operations/doc-paragraph-setting-panel.operation';const getDisableOnCollapsedObservable = (accessor: IAccessor) => {const textSelectionManagerService = accessor.get(TextSelectionManagerService);return new Observable<boolean>((subscriber) => {- const observable = textSelectionManagerService.textSelection$.subscribe((selections) => {- const range = textSelectionManagerService.getActiveRange();+ const observable = textSelectionManagerService.textSelection$.subscribe(() => {+ const range = textSelectionManagerService.getActiveTextRangeWithStyle();if (range && !range.collapsed) {subscriber.next(false);} else {@@ -39,6 +40,51 @@ const getDisableOnCollapsedObservable = (accessor: IAccessor) => {});};+function inSameTable(rectRanges: Readonly<RectRange[]>) {+ if (rectRanges.length < 2) {+ return true;+ }++ const tableIds = rectRanges.map((rectRange) => rectRange.tableId);+ return tableIds.every((tableId) => tableId === tableIds[0]);+}++const getDisableWhenSelectionNotInTableObservable = (accessor: IAccessor) => {+ const textSelectionManagerService = accessor.get(TextSelectionManagerService);+ const univerInstanceService = accessor.get(IUniverInstanceService);++ return new Observable<boolean>((subscriber) => {+ const observable = textSelectionManagerService.textSelection$.subscribe(() => {+ const rectRanges = textSelectionManagerService.getCurrentRectRanges();+ const activeRange = textSelectionManagerService.getActiveTextRangeWithStyle();+ if (rectRanges && rectRanges.length && inSameTable(rectRanges)) {+ subscriber.next(false);+ return;+ }++ if (activeRange && (rectRanges == null || rectRanges.length === 0)) {+ const { segmentId, startOffset, endOffset } = activeRange;+ const docDataModel = univerInstanceService.getCurrentUniverDocInstance();+ const tables = docDataModel?.getSelfOrHeaderFooterModel(segmentId).getBody()?.tables;++ if (tables && tables.length) {+ if (tables.some((table) => {+ const { startIndex, endIndex } = table;+ return (startOffset >= startIndex && startOffset <= endIndex) || (endOffset >= startIndex && endOffset <= endIndex);+ })) {+ subscriber.next(false);+ return;+ }+ }+ }++ subscriber.next(true);+ });++ return () => observable.unsubscribe();+ });+};+export const CopyMenuFactory = (accessor: IAccessor): IMenuButtonItem => {return {id: DocCopyCommand.id,@@ -59,7 +105,6 @@ export const ParagraphSettingMenuFactory = (accessor: IAccessor): IMenuButtonIteicon: 'MenuSingle24',title: 'doc.menu.paragraphSetting',positions: [MenuPosition.CONTEXT_MENU],- disabled$: getDisableOnCollapsedObservable(accessor),hidden$: getMenuHiddenObservable(accessor, UniverInstanceType.UNIVER_DOC),};};@@ -101,3 +146,117 @@ export const DeleteMenuFactory = (accessor: IAccessor): IMenuButtonItem => {hidden$: getMenuHiddenObservable(accessor, UniverInstanceType.UNIVER_DOC),};};++const TABLE_INSERT_MENU_ID = 'doc.menu.table-insert';+export function TableInsertMenuItemFactory(accessor: IAccessor): IMenuSelectorItem<string> {+ return {+ id: TABLE_INSERT_MENU_ID,+ group: MenuGroup.CONTEXT_MENU_LAYOUT,+ type: MenuItemType.SUBITEMS,+ title: 'table.insert',+ icon: 'Insert',+ positions: [MenuPosition.CONTEXT_MENU],+ hidden$: combineLatest(getMenuHiddenObservable(accessor, UniverInstanceType.UNIVER_DOC), getDisableWhenSelectionNotInTableObservable(accessor), (one, two) => {+ return one || two;+ }),+ };+}++export function InsertRowBeforeMenuItemFactory(accessor: IAccessor): IMenuButtonItem {+ return {+ id: DocTableInsertRowAboveCommand.id,+ type: MenuItemType.BUTTON,+ title: 'table.insertRowAbove',+ icon: 'InsertRowAbove',+ positions: [TABLE_INSERT_MENU_ID],+ disabled$: getDisableWhenSelectionNotInTableObservable(accessor),+ hidden$: getMenuHiddenObservable(accessor, UniverInstanceType.UNIVER_DOC),+ };+}++export function InsertRowAfterMenuItemFactory(accessor: IAccessor): IMenuButtonItem {+ return {+ id: DocTableInsertRowBellowCommand.id,+ type: MenuItemType.BUTTON,+ positions: [TABLE_INSERT_MENU_ID],+ title: 'table.insertRowBelow',+ icon: 'InsertRowBelow',+ disabled$: getDisableWhenSelectionNotInTableObservable(accessor),+ hidden$: getMenuHiddenObservable(accessor, UniverInstanceType.UNIVER_DOC),+ };+}++export function InsertColumnLeftMenuItemFactory(accessor: IAccessor): IMenuButtonItem {+ return {+ id: DocTableInsertColumnLeftCommand.id,+ type: MenuItemType.BUTTON,+ title: 'table.insertColumnLeft',+ icon: 'LeftInsertColumn',+ positions: [TABLE_INSERT_MENU_ID],+ disabled$: getDisableWhenSelectionNotInTableObservable(accessor),+ hidden$: getMenuHiddenObservable(accessor, UniverInstanceType.UNIVER_DOC),+ };+}++export function InsertColumnRightMenuItemFactory(accessor: IAccessor): IMenuButtonItem {+ return {+ id: DocTableInsertColumnRightCommand.id,+ type: MenuItemType.BUTTON,+ positions: [TABLE_INSERT_MENU_ID],+ title: 'table.insertColumnRight',+ icon: 'RightInsertColumn',+ disabled$: getDisableWhenSelectionNotInTableObservable(accessor),+ hidden$: getMenuHiddenObservable(accessor, UniverInstanceType.UNIVER_DOC),+ };+}++const TABLE_DELETE_MENU_ID = 'doc.menu.table-delete';+export function TableDeleteMenuItemFactory(accessor: IAccessor): IMenuSelectorItem<string> {+ return {+ id: TABLE_DELETE_MENU_ID,+ group: MenuGroup.CONTEXT_MENU_LAYOUT,+ type: MenuItemType.SUBITEMS,+ title: 'table.delete',+ icon: 'Reduce',+ positions: [MenuPosition.CONTEXT_MENU],+ hidden$: combineLatest(getMenuHiddenObservable(accessor, UniverInstanceType.UNIVER_DOC), getDisableWhenSelectionNotInTableObservable(accessor), (one, two) => {+ return one || two;+ }),+ };+}++export function DeleteRowsMenuItemFactory(accessor: IAccessor): IMenuButtonItem {+ return {+ id: DocTableDeleteRowsCommand.id,+ type: MenuItemType.BUTTON,+ title: 'table.deleteRows',+ icon: 'DeleteRow',+ positions: [TABLE_DELETE_MENU_ID],+ disabled$: getDisableWhenSelectionNotInTableObservable(accessor),+ hidden$: getMenuHiddenObservable(accessor, UniverInstanceType.UNIVER_DOC),+ };+}++export function DeleteColumnsMenuItemFactory(accessor: IAccessor): IMenuButtonItem {+ return {+ id: DocTableDeleteColumnsCommand.id,+ type: MenuItemType.BUTTON,+ positions: [TABLE_DELETE_MENU_ID],+ title: 'table.deleteColumns',+ icon: 'DeleteColumn',+ disabled$: getDisableWhenSelectionNotInTableObservable(accessor),+ hidden$: getMenuHiddenObservable(accessor, UniverInstanceType.UNIVER_DOC),+ };+}++export function DeleteTableMenuItemFactory(accessor: IAccessor): IMenuButtonItem {+ return {+ id: DocTableDeleteTableCommand.id,+ type: MenuItemType.BUTTON,+ positions: [TABLE_DELETE_MENU_ID],+ title: 'table.deleteTable',+ icon: 'GridSingle',+ disabled$: getDisableWhenSelectionNotInTableObservable(accessor),+ hidden$: getMenuHiddenObservable(accessor, UniverInstanceType.UNIVER_DOC),+ };+}diff --git a/packages/docs-ui/src/controllers/menu/menu.ts b/packages/docs-ui/src/controllers/menu/menu.tsindex e293e4a2ff..4ab629408d 100644--- a/packages/docs-ui/src/controllers/menu/menu.ts+++ b/packages/docs-ui/src/controllers/menu/menu.ts@@ -30,6 +30,7 @@ import {AlignOperationCommand,AlignRightCommand,BulletListCommand,+ DocSkeletonManagerService,getParagraphsInRange,OrderListCommand,ResetInlineFormatTextBackgroundColorCommand,@@ -46,7 +47,7 @@ import {SetInlineFormatUnderlineCommand,SetTextSelectionsOperation,TextSelectionManagerService } from '@univerjs/docs';-import type { IMenuButtonItem, IMenuSelectorItem } from '@univerjs/ui';+import type { IMenuButtonItem, IMenuItem, IMenuSelectorItem } from '@univerjs/ui';import {FONT_FAMILY_LIST,FONT_SIZE_LIST,@@ -60,11 +61,97 @@ import type { IAccessor, PresetListType } from '@univerjs/core';import type { Subscription } from 'rxjs';import { combineLatest, map, Observable } from 'rxjs';+import { DocumentEditArea, IRenderManagerService } from '@univerjs/engine-render';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';import { OpenHeaderFooterPanelCommand } from '../../commands/commands/doc-header-footer.command';import { BULLET_LIST_TYPE_COMPONENT, ORDER_LIST_TYPE_COMPONENT } from '../../components/list-type-picker';+import { DocCreateTableOperation } from '../../commands/operations/doc-create-table.operation';++function getInsertTableHiddenObservable(+ accessor: IAccessor+): Observable<boolean> {+ const univerInstanceService = accessor.get(IUniverInstanceService);+ const renderManagerService = accessor.get(IRenderManagerService);++ return new Observable((subscriber) => {+ const subscription = univerInstanceService.focused$.subscribe((unitId) => {+ if (unitId == null) {+ return subscriber.next(true);+ }+ const univerType = univerInstanceService.getUnitType(unitId);++ if (univerType !== UniverInstanceType.UNIVER_DOC) {+ return subscriber.next(true);+ }++ const currentRender = renderManagerService.getRenderById(unitId);+ if (currentRender == null) {+ return subscriber.next(true);+ }++ const viewModel = currentRender.with(DocSkeletonManagerService).getViewModel();++ viewModel.editAreaChange$.subscribe((editArea) => {+ subscriber.next(editArea === DocumentEditArea.HEADER || editArea === DocumentEditArea.FOOTER);+ });+ });++ const currentRender = renderManagerService.getCurrentTypeOfRenderer(UniverInstanceType.UNIVER_DOC);+ if (currentRender == null) {+ return subscriber.next(true);+ }++ const viewModel = currentRender.with(DocSkeletonManagerService).getViewModel();++ subscriber.next(viewModel.getEditArea() !== DocumentEditArea.BODY);++ return () => subscription.unsubscribe();+ });+}++function getTableDisabledObservable(accessor: IAccessor): Observable<boolean> {+ const textSelectionManagerService = accessor.get(TextSelectionManagerService);++ return new Observable((subscriber) => {+ const subscription = textSelectionManagerService.textSelection$.subscribe((selection) => {+ if (selection == null) {+ subscriber.next(true);+ return;+ }++ const { textRanges } = selection;++ if (textRanges.length !== 1) {+ subscriber.next(true);+ return;+ }++ const textRange = textRanges[0];+ const { collapsed, anchorNodePosition } = textRange;++ if (!collapsed) {+ subscriber.next(true);+ return;+ }++ if (anchorNodePosition != null) {+ const { path } = anchorNodePosition;++ // TODO: Not support insert table in table cell now.+ if (path.indexOf('cells') !== -1) {+ subscriber.next(true);+ return;+ }+ }++ subscriber.next(false);+ });++ return () => subscription.unsubscribe();+ });+}export function BoldMenuItemFactory(accessor: IAccessor): IMenuButtonItem {const commandService = accessor.get(ICommandService);@@ -420,6 +507,35 @@ export function HeaderFooterMenuItemFactory(accessor: IAccessor): IMenuButtonIte};}+export const TableIcon = 'GridSingle';+const TABLE_MENU_ID = 'doc.menu.table';++export function TableMenuFactory(accessor: IAccessor): IMenuItem {+ return {+ id: TABLE_MENU_ID,+ type: MenuItemType.SUBITEMS,+ positions: [MenuPosition.TOOLBAR_START],+ group: MenuGroup.TOOLBAR_LAYOUT,+ icon: TableIcon,+ tooltip: 'toolbar.table.main',+ disabled$: getTableDisabledObservable(accessor),+ // Do not show header footer menu and insert table at zen mode.+ hidden$: combineLatest(getMenuHiddenObservable(accessor, UniverInstanceType.UNIVER_DOC), getInsertTableHiddenObservable(accessor), getHeaderFooterMenuHiddenObservable(accessor), (one, two, three) => {+ return one || two || three;+ }),+ };+}++export function InsertTableMenuFactory(_accessor: IAccessor): IMenuButtonItem {+ return {+ id: DocCreateTableOperation.id,+ title: 'toolbar.table.insert',+ type: MenuItemType.BUTTON,+ positions: [TABLE_MENU_ID],+ hidden$: getMenuHiddenObservable(_accessor, UniverInstanceType.UNIVER_DOC),+ };+}+export function AlignLeftMenuItemFactory(accessor: IAccessor): IMenuButtonItem {const commandService = accessor.get(ICommandService);@@ -577,7 +693,7 @@ const listValueFactory$ = (accessor: IAccessor) => {}textSubscription = textSelectionManagerService.textSelection$.subscribe(() => {- const range = textSelectionManagerService.getActiveRange();+ const range = textSelectionManagerService.getActiveTextRangeWithStyle();if (range) {const doc = docDataModel.getSelfOrHeaderFooterModel(range?.segmentId);const paragraphs = getParagraphsInRange(range, doc.getBody()?.paragraphs ?? []);@@ -698,7 +814,7 @@ function getFontStyleAtCursor(accessor: IAccessor) {const univerInstanceService = accessor.get(IUniverInstanceService);const textSelectionService = accessor.get(TextSelectionManagerService);const docDataModel = univerInstanceService.getCurrentUniverDocInstance();- const activeTextRange = textSelectionService.getActiveRange();+ const activeTextRange = textSelectionService.getActiveTextRangeWithStyle();if (docDataModel == null || activeTextRange == null) {return;@@ -736,7 +852,7 @@ function getParagraphStyleAtCursor(accessor: IAccessor) {const univerInstanceService = accessor.get(IUniverInstanceService);const textSelectionService = accessor.get(TextSelectionManagerService);const docDataModel = univerInstanceService.getCurrentUniverDocInstance();- const activeTextRange = textSelectionService.getActiveRange();+ const activeTextRange = textSelectionService.getActiveTextRangeWithStyle();if (docDataModel == null || activeTextRange == null) {return;diff --git a/packages/docs-ui/src/controllers/render-controllers/back-scroll.render-controller.ts b/packages/docs-ui/src/controllers/render-controllers/back-scroll.render-controller.tsindex 9a70837152..6ad9609eff 100644--- a/packages/docs-ui/src/controllers/render-controllers/back-scroll.render-controller.ts+++ b/packages/docs-ui/src/controllers/render-controllers/back-scroll.render-controller.ts@@ -123,7 +123,7 @@ export class DocBackScrollRenderController extends RxDisposable implements IRend// Let the selection show on the current screen.private _scrollToSelection(unitId: string) {- const activeTextRange = this._textSelectionManagerService.getActiveRange();+ const activeTextRange = this._textSelectionManagerService.getActiveTextRangeWithStyle();if (activeTextRange == null) {return;}diff --git a/packages/docs-ui/src/controllers/render-controllers/text-selection.render-controller.ts b/packages/docs-ui/src/controllers/render-controllers/text-selection.render-controller.tsindex cdb3c194d8..2e96aeb7ea 100644--- a/packages/docs-ui/src/controllers/render-controllers/text-selection.render-controller.ts+++ b/packages/docs-ui/src/controllers/render-controllers/text-selection.render-controller.ts@@ -111,7 +111,7 @@ export class DocTextSelectionRenderController extends Disposable implements IRen}}- this._textSelectionRenderManager.eventTrigger(evt);+ this._textSelectionRenderManager.onPointDown(evt);if (this._editorService.getEditor(unitId)) {/**diff --git a/packages/docs-ui/src/docs-ui-plugin.ts b/packages/docs-ui/src/docs-ui-plugin.tsindex 561028e62b..39186ce30b 100644--- a/packages/docs-ui/src/docs-ui-plugin.ts+++ b/packages/docs-ui/src/docs-ui-plugin.ts@@ -14,6 +14,8 @@* limitations under the License.*/+import type {+ Dependency } from '@univerjs/core';import {ICommandService,ILogService,@@ -21,10 +23,7 @@ import {Injector,IUniverInstanceService,Plugin,- Tools,- UniverInstanceType,-} from '@univerjs/core';-import type { Dependency } from '@univerjs/core';+ Tools, UniverInstanceType } from '@univerjs/core';import { IEditorService, IShortcutService } from '@univerjs/ui';import { IRenderManagerService } from '@univerjs/engine-render';import { DocInterceptorService, DocSkeletonManagerService } from '@univerjs/docs';@@ -66,6 +65,8 @@ import { DocParagraphSettingController } from './controllers/doc-paragraph-settiimport { DocParagraphSettingPanelOperation } from './commands/operations/doc-paragraph-setting-panel.operation';import { DocParagraphSettingCommand } from './commands/commands/doc-paragraph-setting.command';+import { DocTableController } from './controllers/doc-table.controller';+import { DocShiftTabCommand, DocTabCommand } from './commands/commands/doc-tab.command';export class UniverDocsUIPlugin extends Plugin {static override pluginName = DOC_UI_PLUGIN_NAME;@@ -84,6 +85,7 @@ export class UniverDocsUIPlugin extends Plugin {this._initDependencies(_injector);this._initializeShortcut();this._initCommand();+ this._registerCommands();}override onReady(): void {@@ -117,11 +119,20 @@ export class UniverDocsUIPlugin extends Plugin {DeleteRightShortcut,BreakLineShortcut,ShiftTabShortCut,+ // TabShortcut,+ // ShiftTabShortcut,].forEach((shortcut) => {this._injector.get(IShortcutService).registerShortcut(shortcut);});}+ private _registerCommands() {+ [+ DocTabCommand,+ DocShiftTabCommand,+ ].forEach((command) => this.disposeWithMe(this._commandService.registerCommand(command)));+ }+private _initDependencies(injector: Injector) {const dependencies: Dependency[] = [[DocUIController, { useFactory: () => this._injector.createInstance(DocUIController, this._config) }],@@ -129,6 +140,7 @@ export class UniverDocsUIPlugin extends Plugin {[DocEditorBridgeController],[DocAutoFormatController],+ [DocTableController],[DocsRenderService],[AppUIController, { useFactory: () => this._injector.createInstance(AppUIController, this._config) }],[IDocClipboardService, { useClass: DocClipboardService }],diff --git a/packages/docs-ui/src/locale/en-US.ts b/packages/docs-ui/src/locale/en-US.tsindex f694e2b435..81319a7fc0 100644--- a/packages/docs-ui/src/locale/en-US.ts+++ b/packages/docs-ui/src/locale/en-US.ts@@ -36,6 +36,12 @@ const locale: typeof zhCN = {main: 'Text Background color',right: 'Choose color',},+ table: {+ main: 'Table',+ insert: 'Insert Table',+ colCount: 'Column count',+ rowCount: 'Row count',+ },resetColor: 'Reset',order: 'Ordered list',unorder: 'Unordered list',@@ -45,6 +51,17 @@ const locale: typeof zhCN = {alignJustify: 'Justify',headerFooter: 'Header & Footer',},+ table: {+ insert: 'Insert',+ insertRowAbove: 'Insert row above',+ insertRowBelow: 'Insert row below',+ insertColumnLeft: 'Insert column left',+ insertColumnRight: 'Insert column right',+ delete: 'Table delete',+ deleteRows: 'Delete row',+ deleteColumns: 'Delete column',+ deleteTable: 'Delete table',+ },headerFooter: {header: 'Header',footer: 'Footer',diff --git a/packages/docs-ui/src/locale/ru-RU.ts b/packages/docs-ui/src/locale/ru-RU.tsindex f43b6f203e..a4651ef29e 100644--- a/packages/docs-ui/src/locale/ru-RU.ts+++ b/packages/docs-ui/src/locale/ru-RU.ts@@ -36,6 +36,12 @@ const locale: typeof zhCN = {main: 'Цвет фона текста',right: 'Выбрать цвет',},+ table: {+ main: 'Table',+ insert: 'Insert Table',+ colCount: 'Column count',+ rowCount: 'Row count',+ },resetColor: 'Сбросить',order: 'Упорядоченный список',unorder: 'Неупорядоченный список',@@ -45,6 +51,17 @@ const locale: typeof zhCN = {alignJustify: 'Выровнять по ширине',headerFooter: 'Header & Footer',},+ table: {+ insert: 'Insert',+ insertRowAbove: 'Insert row above',+ insertRowBelow: 'Insert row below',+ insertColumnLeft: 'Insert column left',+ insertColumnRight: 'Insert column right',+ delete: 'Table delete',+ deleteRows: 'Delete row',+ deleteColumns: 'Delete column',+ deleteTable: 'Delete table',+ },headerFooter: {header: 'Header',footer: 'Footer',diff --git a/packages/docs-ui/src/locale/vi-VN.ts b/packages/docs-ui/src/locale/vi-VN.tsindex 5d836d1ff0..8e17ff9c5d 100644--- a/packages/docs-ui/src/locale/vi-VN.ts+++ b/packages/docs-ui/src/locale/vi-VN.ts@@ -36,6 +36,12 @@ const locale: typeof zhCN = {main: 'Màu nền văn bản',right: 'Chọn màu nền',},+ table: {+ main: 'Table',+ insert: 'Insert Table',+ colCount: 'Column count',+ rowCount: 'Row count',+ },resetColor: 'Đặt lại màu',order: 'Danh sách có thứ tự',unorder: 'Danh sách không thứ tự',@@ -45,6 +51,17 @@ const locale: typeof zhCN = {alignJustify: 'Căn đều hai bên',headerFooter: 'Đầu trang và chân trang',},+ table: {+ insert: 'Insert',+ insertRowAbove: 'Insert row above',+ insertRowBelow: 'Insert row below',+ insertColumnLeft: 'Insert column left',+ insertColumnRight: 'Insert column right',+ delete: 'Table delete',+ deleteRows: 'Delete row',+ deleteColumns: 'Delete column',+ deleteTable: 'Delete table',+ },headerFooter: {header: 'Đầu trang',footer: 'Chân trang',diff --git a/packages/docs-ui/src/locale/zh-CN.ts b/packages/docs-ui/src/locale/zh-CN.tsindex 4399367de2..3a45b3b287 100644--- a/packages/docs-ui/src/locale/zh-CN.ts+++ b/packages/docs-ui/src/locale/zh-CN.ts@@ -34,6 +34,12 @@ const locale = {main: '文本背景色',right: '背景色选择',},+ table: {+ main: '表格',+ insert: '插入表格',+ colCount: '列数',+ rowCount: '行数',+ },resetColor: '重置颜色',order: '有序列表',unorder: '无序列表',@@ -43,6 +49,17 @@ const locale = {alignJustify: '两端对齐',headerFooter: '页眉页脚',},+ table: {+ insert: '插入',+ insertRowAbove: '上方插入行',+ insertRowBelow: '下方插入行',+ insertColumnLeft: '左方插入列',+ insertColumnRight: '右方插入列',+ delete: '表格删除',+ deleteRows: '删除行',+ deleteColumns: '删除列',+ deleteTable: '删除表格',+ },headerFooter: {header: '页眉',footer: '页脚',diff --git a/packages/docs-ui/src/locale/zh-TW.ts b/packages/docs-ui/src/locale/zh-TW.tsindex 38e8e5c578..7b937f48f0 100644--- a/packages/docs-ui/src/locale/zh-TW.ts+++ b/packages/docs-ui/src/locale/zh-TW.ts@@ -36,6 +36,12 @@ const locale: typeof zhCN = {main: '文字背景色',right: '背景色選擇',},+ table: {+ main: 'Table',+ insert: 'Insert Table',+ colCount: 'Column count',+ rowCount: 'Row count',+ },resetColor: '重置顏色',order: '有序列表',unorder: '無序列表',@@ -45,6 +51,17 @@ const locale: typeof zhCN = {alignJustify: '兩端對齊',headerFooter: '頁眉頁腳',},+ table: {+ insert: 'Insert',+ insertRowAbove: 'Insert row above',+ insertRowBelow: 'Insert row below',+ insertColumnLeft: 'Insert column left',+ insertColumnRight: 'Insert column right',+ delete: 'Table delete',+ deleteRows: 'Delete row',+ deleteColumns: 'Delete column',+ deleteTable: 'Delete table',+ },headerFooter: {header: '頁眉',footer: '頁腳',diff --git a/packages/docs-ui/src/services/clipboard/__test__/html-and-udm-convert.spec.ts b/packages/docs-ui/src/services/clipboard/__test__/html-and-udm-convert.spec.tsindex 7d077b38fa..8ef84250a5 100644--- a/packages/docs-ui/src/services/clipboard/__test__/html-and-udm-convert.spec.ts+++ b/packages/docs-ui/src/services/clipboard/__test__/html-and-udm-convert.spec.ts@@ -116,7 +116,7 @@ describe('test case in html and udm convert', () => {const convertor = new HtmlToUDMService();const udm = await convertor.convert(html);- expect(udm.dataStream).toBe('hello\rworld');+ expect(udm.body!.dataStream).toBe('hello\rworld');});});@@ -125,7 +125,7 @@ describe('test case in html and udm convert', () => {const convertor = new UDMToHtmlService();const html = await convertor.convert([body!]);- expect(html).toBe('<strong>hello</strong><strong><i>world</i></strong>');+ expect(html).toBe('<p class="UniverNormal" ><strong>hello</strong><strong><i>world</i></strong></p>');});});});diff --git a/packages/docs-ui/src/services/clipboard/clipboard.service.ts b/packages/docs-ui/src/services/clipboard/clipboard.service.tsindex b4ab4b2256..131c32a98a 100644--- a/packages/docs-ui/src/services/clipboard/clipboard.service.ts+++ b/packages/docs-ui/src/services/clipboard/clipboard.service.ts@@ -14,11 +14,13 @@* limitations under the License.*/-import type { DocumentDataModel, ICustomRange, IDisposable, IDocumentBody, IParagraph } from '@univerjs/core';-import { createIdentifier, CustomRangeType, DataStreamTreeTokenType, Disposable, ICommandService, ILogService, Inject, IUniverInstanceService, normalizeBody, SliceBodyType, toDisposable, Tools, UniverInstanceType } from '@univerjs/core';+import type { DocumentDataModel, ICustomRange, IDisposable, IDocumentBody, IDocumentData, IParagraph } from '@univerjs/core';+import { createIdentifier, CustomRangeType, DataStreamTreeTokenType, Disposable, getBodySlice, ICommandService, ILogService, Inject, IUniverInstanceService, normalizeBody, SliceBodyType, toDisposable, Tools, UniverInstanceType } from '@univerjs/core';import { HTML_CLIPBOARD_MIME_TYPE, IClipboardInterfaceService, PLAIN_TEXT_CLIPBOARD_MIME_TYPE } from '@univerjs/ui';-import { CutContentCommand, DocCustomRangeService, getDeleteSelection, InnerPasteCommand, TextSelectionManagerService } from '@univerjs/docs';+import { CutContentCommand, DocCustomRangeService, getCursorWhenDelete, getDeleteSelection, InnerPasteCommand, TextSelectionManagerService } from '@univerjs/docs';+import type { RectRange, TextRange } from '@univerjs/engine-render';+import { DOC_RANGE_TYPE } from '@univerjs/engine-render';import { copyContentCache, extractId, genId } from './copy-content-cache';import { HtmlToUDMService } from './html-to-udm/converter';import PastePluginLark from './html-to-udm/paste-plugins/plugin-lark';@@ -46,6 +48,38 @@ export interface IDocClipboardService {addClipboardHook(hook: IDocClipboardHook): IDisposable;}+function getTableSlice(body: IDocumentBody, start: number, end: number): IDocumentBody {+ const bodySlice = getBodySlice(body, start, end + 2); // +2 for '\r\n in last cell'++ const dataStream = DataStreamTreeTokenType.TABLE_START ++ DataStreamTreeTokenType.TABLE_ROW_START ++ DataStreamTreeTokenType.TABLE_CELL_START ++ bodySlice.dataStream ++ DataStreamTreeTokenType.TABLE_CELL_END ++ DataStreamTreeTokenType.TABLE_ROW_END ++ DataStreamTreeTokenType.TABLE_END;++ bodySlice.dataStream = dataStream;+ bodySlice.textRuns?.forEach((textRun) => {+ const { st, ed } = textRun;+ textRun.st = st + 3;+ textRun.ed = ed + 3;+ });++ bodySlice.tables?.forEach((table) => {+ const { startIndex, endIndex } = table;+ table.startIndex = startIndex + 3;+ table.endIndex = endIndex + 3;+ });++ bodySlice.paragraphs?.forEach((paragraph) => {+ const { startIndex } = paragraph;+ paragraph.startIndex = startIndex + 3;+ });++ return bodySlice;+}+export const IDocClipboardService = createIdentifier<IDocClipboardService>('doc.clipboard-service');export class DocClipboardService extends Disposable implements IDocClipboardService {@@ -66,16 +100,17 @@ export class DocClipboardService extends Disposable implements IDocClipboardServ}async copy(sliceType: SliceBodyType = SliceBodyType.copy): Promise<boolean> {- const documentBodyList = this._getDocumentBodyInRanges(sliceType);+ const { bodyList, needCache } = this._getDocumentBodyInRanges(sliceType);- if (documentBodyList.length === 0) {+ if (bodyList.length === 0) {return false;}try {- const activeRange = this._textSelectionManagerService.getActiveRange();+ const activeRange = this._textSelectionManagerService.getActiveTextRangeWithStyle();const isCopyInHeaderFooter = !!activeRange?.segmentId;- this._setClipboardData(documentBodyList, !isCopyInHeaderFooter);++ this._setClipboardData(bodyList, !isCopyInHeaderFooter && needCache);} catch (e) {this._logService.error('[DocClipboardService] copy failed', e);return false;@@ -89,15 +124,15 @@ export class DocClipboardService extends Disposable implements IDocClipboardServ}async paste(items: ClipboardItem[]): Promise<boolean> {- const body = await this._generateBodyFromClipboardItems(items);+ const partDocData = await this._genDocDataFromClipboardItems(items);- return this._paste(body);+ return this._paste(partDocData);}async legacyPaste(html?: string, text?: string): Promise<boolean> {- const body = this._generateBodyFromHtmlAndText(html, text);+ const partDocData = this._genDocDataFromHtmlAndText(html, text);- return this._paste(body);+ return this._paste(partDocData);}private async _cut(): Promise<boolean> {@@ -105,14 +140,15 @@ export class DocClipboardService extends Disposable implements IDocClipboardServsegmentId,endOffset: activeEndOffset,style,- } = this._textSelectionManagerService.getActiveRange() ?? {};- const ranges = this._textSelectionManagerService.getCurrentSelections();+ } = this._textSelectionManagerService.getActiveTextRangeWithStyle() ?? {};+ const textRanges = this._textSelectionManagerService.getCurrentTextRanges() ?? [];+ const rectRanges = this._textSelectionManagerService.getCurrentRectRanges() ?? [];if (segmentId == null) {this._logService.error('[DocClipboardController] segmentId is not existed');}- if (activeEndOffset == null || ranges == null) {+ if (textRanges.length === 0 && rectRanges.length === 0) {return false;}@@ -120,20 +156,25 @@ export class DocClipboardService extends Disposable implements IDocClipboardServthis.copy(SliceBodyType.cut);try {- let cursor = activeEndOffset;- for (const range of ranges) {- const { startOffset, endOffset } = range;+ let cursor = 0;- if (startOffset == null || endOffset == null) {- continue;- }+ if (rectRanges.length > 0) {+ cursor = getCursorWhenDelete(textRanges as Readonly<TextRange[]>, rectRanges);+ } else if (activeEndOffset != null) {+ for (const range of textRanges) {+ const { startOffset, endOffset } = range;- if (endOffset <= activeEndOffset) {- cursor -= endOffset - startOffset;+ if (startOffset == null || endOffset == null) {+ continue;+ }++ if (endOffset <= activeEndOffset) {+ cursor -= endOffset - startOffset;+ }}}- const textRanges = [+ const newTextRanges = [{startOffset: cursor,endOffset: cursor,@@ -141,14 +182,20 @@ export class DocClipboardService extends Disposable implements IDocClipboardServ},];- return this._commandService.executeCommand(CutContentCommand.id, { segmentId, textRanges });+ return this._commandService.executeCommand(CutContentCommand.id, { segmentId, textRanges: newTextRanges });} catch (e) {this._logService.error('[DocClipboardController] cut content failed');return false;}}- private async _paste(_body: IDocumentBody): Promise<boolean> {+ private async _paste(docData: Partial<IDocumentData>): Promise<boolean> {+ const { body: _body } = docData;++ if (_body == null) {+ return false;+ }+let body = normalizeBody(_body);const unitId = this._univerInstanceService.getCurrentUnitForType(UniverInstanceType.UNIVER_DOC)?.getUnitId();@@ -163,9 +210,9 @@ export class DocClipboardService extends Disposable implements IDocClipboardServ});body.customRanges = body.customRanges?.map((range) => this._docCustomRangeService.copyCustomRange(unitId, range));- const activeRange = this._textSelectionManagerService.getActiveRange();+ const activeRange = this._textSelectionManagerService.getActiveTextRangeWithStyle();const { segmentId, endOffset: activeEndOffset, style } = activeRange || {};- const ranges = this._textSelectionManagerService.getCurrentSelections();+ const ranges = this._textSelectionManagerService.getCurrentTextRanges();if (segmentId == null) {this._logService.error('[DocClipboardController] segmentId does not exist!');@@ -198,7 +245,12 @@ export class DocClipboardService extends Disposable implements IDocClipboardServ},];- return this._commandService.executeCommand(InnerPasteCommand.id, { body, segmentId, textRanges });+ return this._commandService.executeCommand(InnerPasteCommand.id, {+ doc: {+ ...docData,+ body,+ }, segmentId, textRanges,+ });} catch (_e) {this._logService.error('[DocClipboardController]', 'clipboard is empty.');return false;@@ -213,10 +265,10 @@ export class DocClipboardService extends Disposable implements IDocClipboardServ: documentBodyList[0].dataStream;let html = this._umdToHtml.convert(documentBodyList);- // Only cache copy content when the range is 1.+ // Only cache copy content when the range is 1.if (documentBodyList.length === 1 && needCache) {html = html.replace(/(<[a-z]+)/, (_p0, p1) => `${p1} data-copy-id="${copyId}"`);- copyContentCache.set(copyId, documentBodyList[0]);+ copyContentCache.set(copyId, { body: documentBodyList[0] });}return this._clipboardInterfaceService.write(text, html);@@ -234,33 +286,58 @@ export class DocClipboardService extends Disposable implements IDocClipboardServ});}- private _getDocumentBodyInRanges(sliceType: SliceBodyType): IDocumentBody[] {- const ranges = this._textSelectionManagerService.getCurrentSelections();- const activeRange = this._textSelectionManagerService.getActiveRange();+ // eslint-disable-next-line max-lines-per-function+ private _getDocumentBodyInRanges(sliceType: SliceBodyType): {+ bodyList: IDocumentBody[];+ needCache: boolean;+ } {const docDataModel = this._univerInstanceService.getCurrentUniverDocInstance();+ const allRanges = this._textSelectionManagerService.getDocRanges();+const results: IDocumentBody[] = [];- const body = docDataModel?.getBody();+ let needCache = true;- if (ranges == null || docDataModel == null || body == null) {- return results;+ if (docDataModel == null || allRanges.length === 0) {+ return {+ bodyList: results,+ needCache,+ };}- if (activeRange == null) {- return results;- }+ const segmentId = allRanges[0].segmentId;- const { segmentId } = activeRange;+ const body = docDataModel?.getSelfOrHeaderFooterModel(segmentId)?.getBody();++ if (body == null) {+ return {+ bodyList: results,+ needCache,+ };+ }- for (const range of ranges) {- const { startOffset, endOffset, collapsed } = range;+ for (const range of allRanges) {+ const { startOffset, endOffset, collapsed, rangeType } = range;- if (collapsed) {+ if (collapsed || startOffset == null || endOffset == null) {continue;}- if (startOffset == null || endOffset == null) {+ if (rangeType === DOC_RANGE_TYPE.RECT) {+ needCache = false;++ const { spanEntireRow } = range as unknown as RectRange;+ let bodySlice: IDocumentBody;+ if (!spanEntireRow) {+ bodySlice = getTableSlice(body, startOffset, endOffset);+ } else {+ bodySlice = getTableSlice(body, startOffset, endOffset);+ }++ results.push(bodySlice);+continue;}+const deleteRange = getDeleteSelection({ startOffset, endOffset, collapsed }, body);const docBody = docDataModel.getSelfOrHeaderFooterModel(segmentId).sliceBody(deleteRange.startOffset, deleteRange.endOffset, sliceType);@@ -268,6 +345,7 @@ export class DocClipboardService extends Disposable implements IDocClipboardServcontinue;}+ // TODO: @zhangwei, should be delete?if (docBody.customRanges) {const deleteRange: ICustomRange[] = [];docBody.customRanges.forEach((range) => {@@ -290,10 +368,13 @@ export class DocClipboardService extends Disposable implements IDocClipboardServresults.push(docBody);}- return results;+ return {+ bodyList: results,+ needCache,+ };}- private async _generateBodyFromClipboardItems(items: ClipboardItem[]): Promise<IDocumentBody> {+ private async _genDocDataFromClipboardItems(items: ClipboardItem[]): Promise<Partial<IDocumentData>> {try {// TODO: support paste image.@@ -310,7 +391,7 @@ export class DocClipboardService extends Disposable implements IDocClipboardServ}}- return this._generateBodyFromHtmlAndText(html, text);+ return this._genDocDataFromHtmlAndText(html, text);} catch (e) {return Promise.reject(e);}@@ -355,10 +436,12 @@ export class DocClipboardService extends Disposable implements IDocClipboardServ};}- private _generateBodyFromHtmlAndText(html?: string, text?: string): IDocumentBody {+ private _genDocDataFromHtmlAndText(html?: string, text?: string): Partial<IDocumentData> {if (!html) {if (text) {- return this._generateBody(text);+ const body = this._generateBody(text);++ return { body };} else {throw new Error('[DocClipboardService] html and text cannot be both empty!');}@@ -372,6 +455,8 @@ export class DocClipboardService extends Disposable implements IDocClipboardServ}}- return this._htmlToUDM.convert(html);+ const doc = this._htmlToUDM.convert(html);++ return doc;}}diff --git a/packages/docs-ui/src/services/clipboard/copy-content-cache.ts b/packages/docs-ui/src/services/clipboard/copy-content-cache.tsindex 1003a64d1c..21aa1d6e1d 100644--- a/packages/docs-ui/src/services/clipboard/copy-content-cache.ts+++ b/packages/docs-ui/src/services/clipboard/copy-content-cache.ts@@ -14,7 +14,7 @@* limitations under the License.*/-import type { IDocumentBody } from '@univerjs/core';+import type { IDocumentData } from '@univerjs/core';import { LRUMap, Tools } from '@univerjs/core';const COPY_CONTENT_CACHE_LIMIT = 10;@@ -35,9 +35,9 @@ export function extractId(html: string) {}export class CopyContentCache {- private _cache = new LRUMap<string, IDocumentBody>(COPY_CONTENT_CACHE_LIMIT);+ private _cache = new LRUMap<string, Partial<IDocumentData>>(COPY_CONTENT_CACHE_LIMIT);- set(id: string, clipboardData: IDocumentBody) {+ set(id: string, clipboardData: Partial<IDocumentData>) {this._cache.set(id, clipboardData);}diff --git a/packages/docs-ui/src/services/clipboard/html-to-udm/converter.ts b/packages/docs-ui/src/services/clipboard/html-to-udm/converter.tsindex 8c27b9fedf..b2e129c683 100644--- a/packages/docs-ui/src/services/clipboard/html-to-udm/converter.ts+++ b/packages/docs-ui/src/services/clipboard/html-to-udm/converter.ts@@ -14,8 +14,10 @@* limitations under the License.*/-import { CustomRangeType, DataStreamTreeTokenType, type IDocumentBody, type ITextStyle, type Nullable, skipParseTagNames, Tools } from '@univerjs/core';+import type { IDocumentBody, IDocumentData, ITable, ITextStyle, Nullable } from '@univerjs/core';+import { CustomRangeType, DataStreamTreeTokenType, skipParseTagNames, Tools } from '@univerjs/core';+import { genTableSource, getEmptyTableCell, getEmptyTableRow, getTableColumn } from '@univerjs/docs';import { extractNodeStyle } from './parse-node-style';import parseToDom from './parse-to-dom';import type { IAfterProcessRule, IPastePlugin, IStyleRule } from './paste-plugins/type';@@ -34,6 +36,14 @@ function matchFilter(node: HTMLElement, filter: IStyleRule['filter']) {return filter(node);}+// TODO: get from page width.+const DEFAULT_TABLE_WIDTH = 600;++interface ITableCache {+ table: ITable;+ startIndex: number;+}+/*** Convert html strings into data structures in univer, IDocumentBody.* Support plug-in, add custom rules,@@ -49,36 +59,46 @@ export class HtmlToUDMService {this._pluginList.push(plugin);}+ private _tableCache: ITableCache[] = [];+private _styleCache: Map<ChildNode, ITextStyle> = new Map();private _styleRules: IStyleRule[] = [];private _afterProcessRules: IAfterProcessRule[] = [];- convert(html: string): IDocumentBody {+ convert(html: string): Partial<IDocumentData> {const pastePlugin = HtmlToUDMService._pluginList.find((plugin) => plugin.checkPasteType(html));- const dom = parseToDom(html);+ const dom = parseToDom(html)!;- const newDocBody: IDocumentBody = {+ const body: IDocumentBody = {dataStream: '',textRuns: [],};+ const docData: Partial<IDocumentData> = {+ body,+ tableSource: {},+ };+if (pastePlugin) {this._styleRules = [...pastePlugin.stylesRules];this._afterProcessRules = [...pastePlugin.afterProcessRules];}+ this._tableCache = [];this._styleCache.clear();- this._process(null, dom?.childNodes!, newDocBody);+ this._process(null, dom.childNodes, docData);this._styleCache.clear();this._styleRules = [];this._afterProcessRules = [];- return newDocBody;+ return docData;}- private _process(parent: Nullable<ChildNode>, nodes: NodeListOf<ChildNode>, doc: IDocumentBody) {+ private _process(parent: Nullable<ChildNode>, nodes: NodeListOf<ChildNode>, doc: Partial<IDocumentData>) {+ const body = doc.body!;+for (const node of nodes) {if (node.nodeType === Node.TEXT_NODE) {if (node.nodeValue?.trim() === '') {@@ -93,17 +113,17 @@ export class HtmlToUDMService {if ((parent as Element).tagName.toUpperCase() === 'A') {const id = Tools.generateRandomId();text = `${DataStreamTreeTokenType.CUSTOM_RANGE_START}${text}${DataStreamTreeTokenType.CUSTOM_RANGE_END}`;- doc.customRanges = [- ...(doc.customRanges ?? []),+ body.customRanges = [+ ...(body.customRanges ?? []),{- startIndex: doc.dataStream.length,- endIndex: doc.dataStream.length + text.length - 1,+ startIndex: body.dataStream.length,+ endIndex: body.dataStream.length + text.length - 1,rangeId: id,rangeType: CustomRangeType.HYPERLINK,},];- doc.payloads = {- ...doc.payloads,+ body.payloads = {+ ...body.payloads,[id]: (parent as HTMLAnchorElement).href,};}@@ -113,12 +133,12 @@ export class HtmlToUDMService {style = this._styleCache.get(parent);}- doc.dataStream += text;+ body.dataStream += text;if (style && Object.getOwnPropertyNames(style).length) {- doc.textRuns!.push({- st: doc.dataStream.length - text!.length,- ed: doc.dataStream.length,+ body.textRuns!.push({+ st: body.dataStream.length - text!.length,+ ed: body.dataStream.length,ts: style,});}@@ -135,8 +155,12 @@ export class HtmlToUDMService {const { childNodes } = node;+ this._processBeforeTable(node as HTMLElement, doc);+this._process(node, childNodes, doc);+ this._processAfterTable(node as HTMLElement, doc);+const afterProcessRule = this._afterProcessRules.find(({ filter }) =>matchFilter(node as HTMLElement, filter));@@ -147,4 +171,114 @@ export class HtmlToUDMService {}}}++ private _processBeforeTable(node: HTMLElement, doc: Partial<IDocumentData>) {+ const tagName = node.tagName.toUpperCase();+ const body = doc.body!;++ switch (tagName) {+ case 'TABLE': {+ if (body.dataStream[body.dataStream.length - 1] !== '\r') {+ body.dataStream += '\r';+ body.paragraphs?.push({+ startIndex: body.dataStream.length - 1,+ });+ }++ const table = genTableSource(0, 0, DEFAULT_TABLE_WIDTH);++ this._tableCache.push({+ table,+ startIndex: body.dataStream.length,+ });++ body.dataStream += DataStreamTreeTokenType.TABLE_START;++ break;+ }++ case 'TR': {+ const row = getEmptyTableRow(0);+ const lastTable = this._tableCache[this._tableCache.length - 1].table;++ lastTable.tableRows.push(row);++ body.dataStream += DataStreamTreeTokenType.TABLE_ROW_START;++ break;+ }++ case 'TD': {+ const cell = getEmptyTableCell();+ const lastTable = this._tableCache[this._tableCache.length - 1].table;+ const lastRow = lastTable.tableRows[lastTable.tableRows.length - 1];++ lastRow.tableCells.push(cell);++ body.dataStream += DataStreamTreeTokenType.TABLE_CELL_START;++ break;+ }+ }+ }++ private _processAfterTable(node: HTMLElement, doc: Partial<IDocumentData>) {+ const tagName = node.tagName.toUpperCase();+ const body = doc.body!;++ if (doc.tableSource == null) {+ doc.tableSource = {};+ }++ if (body.tables == null) {+ body.tables = [];+ }++ if (body.sectionBreaks == null) {+ body.sectionBreaks = [];+ }++ const { tableSource } = doc;++ switch (tagName) {+ case 'TABLE': {+ const tableCache = this._tableCache.pop()!;++ const { startIndex, table } = tableCache;++ const colCount = table.tableRows[0].tableCells.length!;+ const tableColumn = getTableColumn(DEFAULT_TABLE_WIDTH / colCount);+ const tableColumns = [...new Array(colCount).fill(null).map(() => Tools.deepClone(tableColumn))];++ table.tableColumns = tableColumns;++ tableSource[table.tableId] = table;++ body.dataStream += DataStreamTreeTokenType.TABLE_END;++ body.tables.push({+ startIndex,+ endIndex: body.dataStream.length - 1,+ tableId: table.tableId,+ });++ break;+ }++ case 'TR': {+ body.dataStream += DataStreamTreeTokenType.TABLE_ROW_END;++ break;+ }++ case 'TD': {+ body.sectionBreaks?.push({+ startIndex: body.dataStream.length,+ });+ body.dataStream += `\n${DataStreamTreeTokenType.TABLE_CELL_END}`;++ break;+ }+ }+ }}diff --git a/packages/docs-ui/src/services/clipboard/html-to-udm/parse-node-style.ts b/packages/docs-ui/src/services/clipboard/html-to-udm/parse-node-style.tsindex 58033bb354..85a18b1c67 100644--- a/packages/docs-ui/src/services/clipboard/html-to-udm/parse-node-style.ts+++ b/packages/docs-ui/src/services/clipboard/html-to-udm/parse-node-style.ts@@ -18,6 +18,7 @@ import type { ITextStyle } from '@univerjs/core';import { BaselineOffset, BooleanNumber, ColorKit } from '@univerjs/core';import { pixelToPt } from '@univerjs/engine-render';+// eslint-disable-next-line max-lines-per-function, complexityexport function extractNodeStyle(node: HTMLElement): ITextStyle {const styles = node.style;const docStyles: ITextStyle = {};diff --git a/packages/docs-ui/src/services/clipboard/html-to-udm/paste-plugins/plugin-lark.ts b/packages/docs-ui/src/services/clipboard/html-to-udm/paste-plugins/plugin-lark.tsindex 5c1acefd2f..1461296a5d 100644--- a/packages/docs-ui/src/services/clipboard/html-to-udm/paste-plugins/plugin-lark.ts+++ b/packages/docs-ui/src/services/clipboard/html-to-udm/paste-plugins/plugin-lark.ts@@ -47,14 +47,15 @@ const wordPastePlugin: IPastePlugin = {return el.tagName === 'DIV' && /ace-line/i.test(el.className);},handler(doc) {- if (doc.paragraphs == null) {- doc.paragraphs = [];+ const body = doc.body!;+ if (body.paragraphs == null) {+ body.paragraphs = [];}- doc.paragraphs.push({- startIndex: doc.dataStream.length,+ body.paragraphs.push({+ startIndex: body.dataStream.length,});- doc.dataStream += '\r';+ body.dataStream += '\r';},},],diff --git a/packages/docs-ui/src/services/clipboard/html-to-udm/paste-plugins/plugin-univer.ts b/packages/docs-ui/src/services/clipboard/html-to-udm/paste-plugins/plugin-univer.tsindex 38a711526e..edfa894e8c 100644--- a/packages/docs-ui/src/services/clipboard/html-to-udm/paste-plugins/plugin-univer.ts+++ b/packages/docs-ui/src/services/clipboard/html-to-udm/paste-plugins/plugin-univer.ts@@ -32,12 +32,13 @@ const univerPastePlugin: IPastePlugin = {return el.tagName === 'P' && /UniverNormal/i.test(el.className);},handler(doc, el) {- if (doc.paragraphs == null) {- doc.paragraphs = [];+ const body = doc.body!;+ if (body.paragraphs == null) {+ body.paragraphs = [];}const paragraph: IParagraph = {- startIndex: doc.dataStream.length,+ startIndex: body.dataStream.length,};const paragraphStyle = getParagraphStyle(el);@@ -46,8 +47,8 @@ const univerPastePlugin: IPastePlugin = {paragraph.paragraphStyle = paragraphStyle;}- doc.paragraphs.push(paragraph);- doc.dataStream += '\r';+ body.paragraphs.push(paragraph);+ body.dataStream += '\r';},},],diff --git a/packages/docs-ui/src/services/clipboard/html-to-udm/paste-plugins/plugin-word.ts b/packages/docs-ui/src/services/clipboard/html-to-udm/paste-plugins/plugin-word.tsindex 82951cebfb..381678389d 100644--- a/packages/docs-ui/src/services/clipboard/html-to-udm/paste-plugins/plugin-word.ts+++ b/packages/docs-ui/src/services/clipboard/html-to-udm/paste-plugins/plugin-word.ts@@ -44,12 +44,13 @@ const wordPastePlugin: IPastePlugin = {return el.tagName === 'P';},handler(doc, el) {- if (doc.paragraphs == null) {- doc.paragraphs = [];+ const body = doc.body!;+ if (body.paragraphs == null) {+ body.paragraphs = [];}const paragraph: IParagraph = {- startIndex: doc.dataStream.length,+ startIndex: body.dataStream.length,};const paragraphStyle = getParagraphStyle(el);@@ -58,8 +59,8 @@ const wordPastePlugin: IPastePlugin = {paragraph.paragraphStyle = paragraphStyle;}- doc.paragraphs.push(paragraph);- doc.dataStream += '\r';+ body.paragraphs.push(paragraph);+ body.dataStream += '\r';},},],diff --git a/packages/docs-ui/src/services/clipboard/html-to-udm/paste-plugins/type.ts b/packages/docs-ui/src/services/clipboard/html-to-udm/paste-plugins/type.tsindex 25f3568c95..34a100d4a8 100644--- a/packages/docs-ui/src/services/clipboard/html-to-udm/paste-plugins/type.ts+++ b/packages/docs-ui/src/services/clipboard/html-to-udm/paste-plugins/type.ts@@ -14,7 +14,7 @@* limitations under the License.*/-import type { IDocumentBody, ITextStyle } from '@univerjs/core';+import type { IDocumentData, ITextStyle } from '@univerjs/core';export interface IStyleRule {filter: string | string[] | ((node: HTMLElement) => boolean);@@ -23,7 +23,7 @@ export interface IStyleRule {export interface IAfterProcessRule {filter: string | string[] | ((node: HTMLElement) => boolean);- handler(doc: IDocumentBody, node: HTMLElement): void;+ handler(doc: Partial<IDocumentData>, node: HTMLElement): void;}export interface IPastePlugin {diff --git a/packages/docs-ui/src/services/clipboard/html-to-udm/utils.ts b/packages/docs-ui/src/services/clipboard/html-to-udm/utils.tsindex 84c836f1d0..01e954be3c 100644--- a/packages/docs-ui/src/services/clipboard/html-to-udm/utils.ts+++ b/packages/docs-ui/src/services/clipboard/html-to-udm/utils.ts@@ -42,7 +42,10 @@ export function getParagraphStyle(el: HTMLElement): Nullable<IParagraphStyle> {}case 'line-height': {- const lineHeightValue = Number.parseFloat(cssValue);+ let lineHeightValue = Number.parseFloat(cssValue);+ if (cssValue.endsWith('%')) {+ lineHeightValue /= 100;+ }paragraphStyle.lineSpacing = lineHeightValue;break;diff --git a/packages/docs-ui/src/services/clipboard/udm-to-html/convertor.ts b/packages/docs-ui/src/services/clipboard/udm-to-html/convertor.tsindex c838134232..c15ea824dd 100644--- a/packages/docs-ui/src/services/clipboard/udm-to-html/convertor.ts+++ b/packages/docs-ui/src/services/clipboard/udm-to-html/convertor.ts@@ -14,8 +14,10 @@* limitations under the License.*/-import type { IDocumentBody, ITextRun } from '@univerjs/core';-import { BaselineOffset, BooleanNumber, Tools } from '@univerjs/core';+import type { IDocumentBody, IParagraph, ITextRun } from '@univerjs/core';+import { BaselineOffset, BooleanNumber, DataStreamTreeNodeType, Tools } from '@univerjs/core';+import type { DataStreamTreeNode } from '@univerjs/engine-render';+import { parseDataStreamToTree } from '@univerjs/engine-render';export function covertTextRunToHtml(dataStream: string, textRun: ITextRun): string {const { st: start, ed, ts = {} } = textRun;@@ -113,13 +115,56 @@ export function getBodySliceHtml(body: IDocumentBody, startIndex: number, endIndreturn spanList.join('');}-export function convertBodyToHtml(body: IDocumentBody, withParagraphInfo: boolean = true): string {- if (withParagraphInfo && body.paragraphs?.length) {- const { dataStream, paragraphs = [] } = body;- let result = '';- let cursorIndex = -1;- for (const paragraph of paragraphs) {- const { startIndex, paragraphStyle = {} } = paragraph;+interface IHtmlResult {+ html: string;+}++export function convertBodyToHtml(body: IDocumentBody): string {+ const { paragraphs = [], sectionBreaks = [] } = body;+ let { dataStream } = body;++ if (!dataStream.endsWith('\r\n')) {+ dataStream += '\r\n';++ paragraphs.push({+ startIndex: dataStream.length - 2,+ });++ sectionBreaks.push({+ startIndex: dataStream.length - 1,+ });++ body.dataStream = dataStream;+ body.paragraphs = paragraphs;+ body.sectionBreaks = sectionBreaks;+ }++ const result: IHtmlResult = { html: '' };++ const nodeList = parseDataStreamToTree(dataStream);++ for (const node of nodeList) {+ processNode(node, body, result);+ }++ return result.html;+}++// eslint-disable-next-line max-lines-per-function+function processNode(node: DataStreamTreeNode, body: IDocumentBody, result: IHtmlResult) {+ switch (node.nodeType) {+ case DataStreamTreeNodeType.SECTION_BREAK: {+ for (const n of node.children) {+ processNode(n, body, result);+ }++ break;+ }++ case DataStreamTreeNodeType.PARAGRAPH: {+ const { children, startIndex, endIndex } = node;+ const paragraph = body.paragraphs!.find((p) => p.startIndex === endIndex) ?? {} as IParagraph;+ const { paragraphStyle = {} } = paragraph;const { spaceAbove, spaceBelow, lineSpacing } = paragraphStyle;const style = [];@@ -143,26 +188,59 @@ export function convertBodyToHtml(body: IDocumentBody, withParagraphInfo: booleastyle.push(`line-height: ${lineSpacing}`);}- if (startIndex > cursorIndex + 1) {- result += `<p class="UniverNormal" ${- style.length ? `style="${style.join('; ')};"` : ''- }>${getBodySliceHtml(body, cursorIndex + 1, startIndex)}</p>`;- } else {- result += `<p class="UniverNormal" ${- style.length ? `style="${style.join('; ')};"` : ''- }></p>`;+ result.html += `<p class="UniverNormal" ${style.length ? `style="${style.join('; ')};"` : ''}>`;++ if (children.length) {+ for (const table of children) {+ processNode(table, body, result);+ }}- cursorIndex = startIndex;+ result.html += `${getBodySliceHtml(body, startIndex, endIndex)}</p>`;++ break;}- if (cursorIndex !== dataStream.length) {- result += getBodySliceHtml(body, cursorIndex, dataStream.length);+ case DataStreamTreeNodeType.TABLE: {+ const { children } = node;++ result.html += '<table class="UniverTable" style="width: 100%; border-collapse: collapse;"><tbody>';++ for (const row of children) {+ processNode(row, body, result);+ }++ result.html += '</tbody></table>';++ break;}- return result;- } else {- return getBodySliceHtml(body, 0, body.dataStream.length);+ case DataStreamTreeNodeType.TABLE_ROW: {+ const { children } = node;++ result.html += '<tr class="UniverTableRow">';+ for (const cell of children) {+ processNode(cell, body, result);+ }+ result.html += '</tr>';++ break;+ }++ case DataStreamTreeNodeType.TABLE_CELL: {+ const { children } = node;++ result.html += '<td class="UniverTableCell">';+ for (const n of children) {+ processNode(n, body, result);+ }+ result.html += '</td>';+ break;+ }++ default: {+ throw new Error(`Unknown node type: ${node.nodeType}`);+ }}}@@ -172,19 +250,10 @@ export class UDMToHtmlService {throw new Error('The bodyList length at least to be 1');}- // If only one selection range of content is copied, the paragraph information will be used,- // otherwise, the paragraph information will be discarded and a paragraph- // will be generated for each body- if (bodyList.length === 1) {- return convertBodyToHtml(bodyList[0]);- }-let html = '';- for (const body of bodyList) {- html += '<p className="UniverNormal">';- html += convertBodyToHtml(body, false);- html += '</p>';+ for (const body of Tools.deepClone(bodyList)) {+ html += convertBodyToHtml(body);}return html;diff --git a/packages/docs-ui/src/shortcuts/core-editing.shortcut.ts b/packages/docs-ui/src/shortcuts/core-editing.shortcut.tsindex 876c933495..5b34634061 100644--- a/packages/docs-ui/src/shortcuts/core-editing.shortcut.ts+++ b/packages/docs-ui/src/shortcuts/core-editing.shortcut.ts@@ -37,3 +37,15 @@ export const DeleteRightShortcut: IShortcutItem = {preconditions: whenDocAndEditorFocused,binding: KeyCode.DELETE,};++// export const TabShortcut: IShortcutItem = {+// id: DocTabCommand.id,+// preconditions: whenDocAndEditorFocused,+// binding: KeyCode.TAB,+// };++// export const ShiftTabShortcut: IShortcutItem = {+// id: DocShiftTabCommand.id,+// preconditions: whenDocAndEditorFocused,+// binding: KeyCode.TAB | MetaKeys.SHIFT,+// };diff --git a/packages/docs-ui/src/views/header-footer/panel/DocHeaderFooterOptions.tsx b/packages/docs-ui/src/views/header-footer/panel/DocHeaderFooterOptions.tsxindex 5b8d454a56..c53713801b 100644--- a/packages/docs-ui/src/views/header-footer/panel/DocHeaderFooterOptions.tsx+++ b/packages/docs-ui/src/views/header-footer/panel/DocHeaderFooterOptions.tsx@@ -121,7 +121,7 @@ export const DocHeaderFooterOptions = (props: IDocHeaderFooterOptionsProps) => {});// To make sure input always has focus.- textSelectionRenderService.removeAllTextRanges();+ textSelectionRenderService.removeAllRanges();textSelectionRenderService.blur();};diff --git a/packages/docs-ui/src/views/paragraph-setting/Setting.tsx b/packages/docs-ui/src/views/paragraph-setting/Setting.tsxindex 129d2c09ed..d0e855811a 100644--- a/packages/docs-ui/src/views/paragraph-setting/Setting.tsx+++ b/packages/docs-ui/src/views/paragraph-setting/Setting.tsx@@ -64,8 +64,8 @@ export function ParagraphSetting() {const alignmentOptions = useMemo(() => [{ label: localeService.t('toolbar.alignLeft'), value: String(HorizontalAlign.LEFT), icon: <LeftJustifyingSingle /> },- { label: localeService.t('toolbar.alignRight'), value: String(HorizontalAlign.RIGHT), icon: <HorizontallySingle /> },- { label: localeService.t('toolbar.alignCenter'), value: String(HorizontalAlign.CENTER), icon: <RightJustifyingSingle /> },+ { label: localeService.t('toolbar.alignCenter'), value: String(HorizontalAlign.CENTER), icon: <HorizontallySingle /> },+ { label: localeService.t('toolbar.alignRight'), value: String(HorizontalAlign.RIGHT), icon: <RightJustifyingSingle /> },{ label: localeService.t('toolbar.alignJustify'), value: String(HorizontalAlign.JUSTIFIED), icon: <AlignTextBothSingle /> }],[]);diff --git a/packages/docs-ui/src/views/paragraph-setting/hook/utils.ts b/packages/docs-ui/src/views/paragraph-setting/hook/utils.tsindex da591e0b3c..ca3a901595 100644--- a/packages/docs-ui/src/views/paragraph-setting/hook/utils.ts+++ b/packages/docs-ui/src/views/paragraph-setting/hook/utils.ts@@ -16,7 +16,7 @@import type { DocumentDataModel, IParagraph } from '@univerjs/core';import { ICommandService, IUniverInstanceService, UniverInstanceType, useDependency } from '@univerjs/core';-import { getParagraphsInRange, TextSelectionManagerService } from '@univerjs/docs';+import { getParagraphsInRanges, TextSelectionManagerService } from '@univerjs/docs';import { useState } from 'react';import { getNumberUnitValue } from '@univerjs/engine-render';import type { IDocParagraphSettingCommandParams } from '../../../commands/commands/doc-paragraph-setting.command';@@ -26,12 +26,17 @@ export const useCurrentParagraph = () => {const textSelectionManagerService = useDependency(TextSelectionManagerService);const univerInstanceService = useDependency(IUniverInstanceService);const docDataModel = univerInstanceService.getCurrentUnitForType<DocumentDataModel>(UniverInstanceType.UNIVER_DOC);- const activeRange = textSelectionManagerService.getActiveRange();- if (!docDataModel || !activeRange) {+ const docRanges = textSelectionManagerService.getDocRanges();++ if (!docDataModel || docRanges.length === 0) {return [];}- const paragraphs = docDataModel.getSelfOrHeaderFooterModel(activeRange.segmentId).getBody()?.paragraphs ?? [];- const currentParagraphs = getParagraphsInRange(activeRange, paragraphs) ?? [];++ const segmentId = docRanges[0].segmentId;++ const paragraphs = docDataModel.getSelfOrHeaderFooterModel(segmentId).getBody()?.paragraphs ?? [];+ const currentParagraphs = getParagraphsInRanges(docRanges, paragraphs) ?? [];+return currentParagraphs;};diff --git a/packages/docs-ui/src/views/table/create/TableCreate.tsx b/packages/docs-ui/src/views/table/create/TableCreate.tsxnew file mode 100644index 0000000000..9228d5737e--- /dev/null+++ b/packages/docs-ui/src/views/table/create/TableCreate.tsx@@ -0,0 +1,78 @@+/**+ * 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 React, { useEffect, useState } from 'react';+import { LocaleService, useDependency } from '@univerjs/core';++import { InputNumber } from '@univerjs/design';+import styles from './index.module.less';++interface IDocCreateTableConfirmProps {+ handleRowColChange: (rowCount: number, colCount: number) => void;+ tableCreateParams: {+ rowCount: number;+ colCount: number;+ };+}++export const DocCreateTableConfirm = ({+ handleRowColChange,+ tableCreateParams,+}: IDocCreateTableConfirmProps) => {+ const localeService = useDependency(LocaleService);++ const [rowCount, setRowCount] = useState(3);+ const [colCount, setColCount] = useState(5);++ function handleInputChange(rowCount: number, colCount: number) {+ setRowCount(rowCount);+ setColCount(colCount);+ handleRowColChange(rowCount, colCount);+ }++ useEffect(() => {+ setRowCount(tableCreateParams.rowCount);+ setColCount(tableCreateParams.colCount);+ }, [tableCreateParams]);++ return (+ <div className={styles.create}>+ <div className={styles.createItem}>+ <span className={styles.createLabel}>{localeService.t('toolbar.table.rowCount')}</span>+ <InputNumber+ min={1}+ max={100}+ precision={0}+ value={rowCount}+ onChange={(val) => { handleInputChange(val as number, colCount); }}+ className={styles.createInput}+ />+ </div>+ <div className={styles.createItem}>+ <span className={styles.createLabel}>{localeService.t('toolbar.table.colCount')}</span>+ <InputNumber+ min={1}+ max={100}+ precision={0}+ value={colCount}+ onChange={(val) => { handleInputChange(rowCount, val as number); }}+ className={styles.createInput}+ />+ </div>+ </div>+ );+};+diff --git a/packages/docs-ui/src/views/table/create/component-name.ts b/packages/docs-ui/src/views/table/create/component-name.tsnew file mode 100644index 0000000000..9a419e6f34--- /dev/null+++ b/packages/docs-ui/src/views/table/create/component-name.ts@@ -0,0 +1,17 @@+/**+ * 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.+ */++export const COMPONENT_DOC_CREATE_TABLE_CONFIRM = 'COMPONENT_DOC_CREATE_TABLE_CONFIRM';diff --git a/packages/docs-ui/src/views/table/create/index.module.less b/packages/docs-ui/src/views/table/create/index.module.lessnew file mode 100644index 0000000000..e3089a5f7b--- /dev/null+++ b/packages/docs-ui/src/views/table/create/index.module.less@@ -0,0 +1,19 @@+.create {+ padding: 20px auto;+ display: flex;+ align-content: center;+ justify-content: space-between;++ &-item {+ display: flex;+ align-items: center;+ }++ &-label {+ margin-right: 5px;+ }++ &-input {+ width: 110px;+ }+}diff --git a/packages/docs/package.json b/packages/docs/package.jsonindex 56088ed906..9e521c8028 100644--- a/packages/docs/package.json+++ b/packages/docs/package.json@@ -61,6 +61,7 @@},"peerDependencies": {"@univerjs/core": "workspace:*",+ "@univerjs/docs": "workspace:*","@univerjs/engine-render": "workspace:*","rxjs": ">=7.0.0"},diff --git a/packages/docs/src/basics/custom-decoration-factory.ts b/packages/docs/src/basics/custom-decoration-factory.tsindex 727c9f93f1..6d0c1bd76b 100644--- a/packages/docs/src/basics/custom-decoration-factory.ts+++ b/packages/docs/src/basics/custom-decoration-factory.ts@@ -82,7 +82,7 @@ export function addCustomDecorationBySelectionFactory(accessor: IAccessor, paramconst textSelectionManagerService = accessor.get(TextSelectionManagerService);const univerInstanceService = accessor.get(IUniverInstanceService);- const selection = textSelectionManagerService.getActiveRange();+ const selection = textSelectionManagerService.getActiveTextRangeWithStyle();if (!selection) {return false;}diff --git a/packages/docs/src/basics/custom-range-factory.ts b/packages/docs/src/basics/custom-range-factory.tsindex 27d9e05c21..568c294c0c 100644--- a/packages/docs/src/basics/custom-range-factory.ts+++ b/packages/docs/src/basics/custom-range-factory.ts@@ -117,7 +117,7 @@ export function addCustomRangeBySelectionFactory(accessor: IAccessor, param: IAdconst textSelectionManagerService = accessor.get(TextSelectionManagerService);const univerInstanceService = accessor.get(IUniverInstanceService);- const selection = textSelectionManagerService.getActiveRange();+ const selection = textSelectionManagerService.getActiveTextRangeWithStyle();if (!selection) {return false;}diff --git a/packages/docs/src/basics/replace.ts b/packages/docs/src/basics/replace.tsindex cba4f295d0..154b67ef43 100644--- a/packages/docs/src/basics/replace.ts+++ b/packages/docs/src/basics/replace.ts@@ -127,7 +127,7 @@ export function replaceSelectionFactory(accessor: IAccessor, params: IReplaceSel}const body = docDataModel.getBody();- const selection = params.selection ?? textSelectionManagerService.getActiveRange();+ const selection = params.selection ?? textSelectionManagerService.getActiveTextRangeWithStyle();if (!selection || !body) {return false;}diff --git a/packages/docs/src/basics/table.ts b/packages/docs/src/basics/table.tsnew file mode 100644index 0000000000..0051988f2f--- /dev/null+++ b/packages/docs/src/basics/table.ts@@ -0,0 +1,163 @@+/**+ * 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 { Nullable } from '@univerjs/core';+import type { IDocumentSkeletonCached, IDocumentSkeletonLine, IDocumentSkeletonPage, IDocumentSkeletonRow, IDocumentSkeletonTable } from '@univerjs/engine-render';+import { DocumentSkeletonPageType, getLastLine, lineIterator } from '@univerjs/engine-render';++export function firstLineInTable(table: IDocumentSkeletonTable) {+ const firstRow = table.rows[0];+ const firstCell = firstRow.cells[0];+ const firstLine = firstCell.sections[0].columns[0].lines[0];++ return firstLine;+}++export function lastLineInTable(table: IDocumentSkeletonTable) {+ const lastRow = table.rows[table.rows.length - 1];+ const lastCell = lastRow.cells[lastRow.cells.length - 1];+ const lastLine = getLastLine(lastCell);++ return lastLine;+}++export function findTableAfterLine(line: IDocumentSkeletonLine, page: IDocumentSkeletonPage) {+ const { ed } = line;+ const { skeTables } = page;++ let table = null;++ for (const t of skeTables.values()) {+ if (t.st === ed + 1) {+ table = t;+ break;+ }+ }++ return table;+}++export function findLineBeforeAndAfterTable(table: Nullable<IDocumentSkeletonTable>) {+ const tablePage = table?.parent as IDocumentSkeletonPage;+ let lineBeforeTable = null;+ let lineAfterTable = null;++ if (table == null || tablePage == null) {+ return {+ lineBeforeTable,+ lineAfterTable,+ };+ }++ const { st, ed } = table;++ const pages = tablePage.type === DocumentSkeletonPageType.CELL ? [tablePage] : (tablePage.parent as IDocumentSkeletonCached).pages;++ lineIterator(pages, (l) => {+ if (l.st === ed + 1) {+ lineAfterTable = l;+ } else if (l.ed === st - 1) {+ lineBeforeTable = l;+ }+ });++ return {+ lineBeforeTable,+ lineAfterTable,+ };+}++export function findBellowCell(cell: IDocumentSkeletonPage) {+ const row = cell.parent as IDocumentSkeletonRow;+ const table = row?.parent as IDocumentSkeletonTable;++ if (row == null || table == null) {+ return;+ }++ const bellowRow = table.rows[table.rows.indexOf(row) + 1];++ if (bellowRow == null) {+ return;+ }++ const col = row.cells.indexOf(cell);++ return bellowRow.cells[col];+}++export function findAboveCell(cell: IDocumentSkeletonPage) {+ const row = cell.parent as IDocumentSkeletonRow;+ const table = row?.parent as IDocumentSkeletonTable;++ if (row == null || table == null) {+ return;+ }++ const aboveRow = table.rows[table.rows.indexOf(row) - 1];++ if (aboveRow == null) {+ return;+ }++ const col = row.cells.indexOf(cell);++ return aboveRow.cells[col];+}++export function findNextCell(cell: IDocumentSkeletonPage) {}++export function findPrevCell(cell: IDocumentSkeletonPage) {}++export function findTableBeforeLine(line: IDocumentSkeletonLine, page: IDocumentSkeletonPage) {+ const { st } = line;+ const { skeTables } = page;++ let table = null;++ for (const t of skeTables.values()) {+ if (t.ed === st - 1) {+ table = t;+ break;+ }+ }++ return table;+}++export function firstLineInCell(cell: IDocumentSkeletonPage) {+ const firstLine = cell.sections[0].columns[0].lines[0];++ return firstLine;+}++export function lastLineInCell(cell: IDocumentSkeletonPage) {+ const lastLine = getLastLine(cell);++ return lastLine;+}++export function isFirstLineInCell(line: IDocumentSkeletonLine, cell: IDocumentSkeletonPage) {+ const firstLine = firstLineInCell(cell);++ return line === firstLine;+}++export function isLastLineInCell(line: IDocumentSkeletonLine, cell: IDocumentSkeletonPage) {+ const lastLine = lastLineInCell(cell);++ return line === lastLine;+}diff --git a/packages/docs/src/commands/commands/__tests__/clipboard.command.spec.ts b/packages/docs/src/commands/commands/__tests__/clipboard.command.spec.tsindex 498f263b10..f5f51f007a 100644--- a/packages/docs/src/commands/commands/__tests__/clipboard.command.spec.ts+++ b/packages/docs/src/commands/commands/__tests__/clipboard.command.spec.ts@@ -168,17 +168,19 @@ describe('test cases in clipboard', () => {const commandParams: IInnerPasteCommandParams = {segmentId: '',- body: {- dataStream: 'univer',- textRuns: [- {- st: 0,- ed: 6,- ts: {- bl: BooleanNumber.TRUE,+ doc: {+ body: {+ dataStream: 'univer',+ textRuns: [+ {+ st: 0,+ ed: 6,+ ts: {+ bl: BooleanNumber.TRUE,+ },},- },- ],+ ],+ },},textRanges: [], // only used to eliminate TS type check error.};diff --git a/packages/docs/src/commands/commands/__tests__/inline-format.command.spec.ts b/packages/docs/src/commands/commands/__tests__/inline-format.command.spec.tsindex 6598e487d8..b6f577d1fe 100644--- a/packages/docs/src/commands/commands/__tests__/inline-format.command.spec.ts+++ b/packages/docs/src/commands/commands/__tests__/inline-format.command.spec.ts@@ -82,7 +82,7 @@ describe('Test inline format commands', () => {selectionManager.setCurrentSelection({unitId: 'test-doc',- subUnitId: '',+ subUnitId: 'test-doc',});selectionManager.add([diff --git a/packages/docs/src/commands/commands/__tests__/mock-text-selection-render-manager.ts b/packages/docs/src/commands/commands/__tests__/mock-text-selection-render-manager.tsindex 0ea5313a00..f9420a064d 100644--- a/packages/docs/src/commands/commands/__tests__/mock-text-selection-render-manager.ts+++ b/packages/docs/src/commands/commands/__tests__/mock-text-selection-render-manager.ts@@ -24,11 +24,11 @@ export class TextSelectionRenderManager {readonly textSelectionInner$ = this._textSelectionInner$.asObservable();- removeAllTextRanges() {+ removeAllRanges() {// empty}- addTextRanges() {+ addDocRanges() {// empty}}diff --git a/packages/docs/src/commands/commands/break-line.command.ts b/packages/docs/src/commands/commands/break-line.command.tsindex 1dd0acc80f..d0b584963d 100644--- a/packages/docs/src/commands/commands/break-line.command.ts+++ b/packages/docs/src/commands/commands/break-line.command.ts@@ -22,7 +22,7 @@ import { getInsertSelection } from '../../basics/selection';import { DocCustomRangeService } from '../../services/doc-custom-range.service';import { InsertCommand } from './core-editing.command';-function generateParagraphs(dataStream: string, prevParagraph?: IParagraph): IParagraph[] {+export function generateParagraphs(dataStream: string, prevParagraph?: IParagraph): IParagraph[] {const paragraphs: IParagraph[] = [];for (let i = 0, len = dataStream.length; i < len; i++) {@@ -61,11 +61,24 @@ export const BreakLineCommand: ICommand = {const commandService = accessor.get(ICommandService);const customRangeService = accessor.get(DocCustomRangeService);- const activeRange = textSelectionManagerService.getActiveRange();- if (activeRange == null) {+ const activeTextRange = textSelectionManagerService.getActiveTextRangeWithStyle();+ const rectRanges = textSelectionManagerService.getCurrentRectRanges();+ if (activeTextRange == null) {return false;}- const { segmentId } = activeRange;++ // Just reset the cursor to the active text range start when select both text range and rect range.+ if (rectRanges && rectRanges.length) {+ const { startOffset } = activeTextRange;++ textSelectionManagerService.replaceTextRanges([{+ startOffset,+ endOffset: startOffset,+ }]);+ return true;+ }++ const { segmentId } = activeTextRange;const docDataModel = univerInstanceService.getCurrentUniverDocInstance();const body = docDataModel?.getSelfOrHeaderFooterModel(segmentId).getBody();if (!docDataModel || !body) {@@ -73,7 +86,7 @@ export const BreakLineCommand: ICommand = {}const unitId = docDataModel.getUnitId();- const { startOffset, endOffset } = getInsertSelection(activeRange, body);+ const { startOffset, endOffset } = getInsertSelection(activeTextRange, body);const paragraphs = body.paragraphs ?? [];const prevParagraph = paragraphs.find((p) => p.startIndex >= startOffset);@@ -114,7 +127,7 @@ export const BreakLineCommand: ICommand = {dataStream: DataStreamTreeTokenType.PARAGRAPH,paragraphs: generateParagraphs(DataStreamTreeTokenType.PARAGRAPH, prevParagraph),},- range: activeRange,+ range: activeTextRange,segmentId,});diff --git a/packages/docs/src/commands/commands/clipboard.inner.command.ts b/packages/docs/src/commands/commands/clipboard.inner.command.tsindex cec9889fad..60ef3c1d7e 100644--- a/packages/docs/src/commands/commands/clipboard.inner.command.ts+++ b/packages/docs/src/commands/commands/clipboard.inner.command.ts@@ -15,34 +15,45 @@*/import type {+ DocumentDataModel,ICommand,IDocumentBody,+ IDocumentData,IMutationInfo,ITextRange,JSONXActions,} from '@univerjs/core';import {CommandType,- getDocsUpdateBody,ICommandService,IUniverInstanceService,JSONX,MemoryCursor,TextX,TextXActionType,+ Tools,} from '@univerjs/core';-import type { ITextRangeWithStyle } from '@univerjs/engine-render';+import type { DocumentViewModel, ITextRangeWithStyle, RectRange, TextRange } from '@univerjs/engine-render';import { getRetainAndDeleteFromReplace } from '../../basics/retain-delete-params';import { TextSelectionManagerService } from '../../services/text-selection-manager.service';import type { IRichTextEditingMutationParams } from '../mutations/core-editing.mutation';import { RichTextEditingMutation } from '../mutations/core-editing.mutation';-import { getRichTextEditPath } from '../util';+import { getCommandSkeleton, getRichTextEditPath } from '../util';import { getRetainAndDeleteAndExcludeLineBreak } from '../../basics/replace';+import { getDeleteRowContentActionParams, getDeleteRowsActionsParams, getDeleteTableActionParams } from './table/table';++function hasRangeInTable(ranges: TextRange[]) {+ return ranges.some((range) => {+ const { anchorNodePosition } = range;++ return anchorNodePosition ? anchorNodePosition?.path.indexOf('cells') > -1 : false;+ });+}export interface IInnerPasteCommandParams {segmentId: string;- body: IDocumentBody;+ doc: Partial<IDocumentData>;textRanges: ITextRangeWithStyle[];}@@ -51,14 +62,15 @@ export const InnerPasteCommand: ICommand<IInnerPasteCommandParams> = {id: 'doc.command.inner-paste',type: CommandType.COMMAND,+ // eslint-disable-next-line max-lines-per-functionhandler: async (accessor, params: IInnerPasteCommandParams) => {- const { segmentId, textRanges, body } = params;+ const { segmentId, textRanges, doc } = params;const commandService = accessor.get(ICommandService);const textSelectionManagerService = accessor.get(TextSelectionManagerService);const univerInstanceService = accessor.get(IUniverInstanceService);-- const selections = textSelectionManagerService.getCurrentSelections();- if (!Array.isArray(selections) || selections.length === 0) {+ const selections = textSelectionManagerService.getCurrentTextRanges();+ const { body, tableSource } = doc;+ if (!Array.isArray(selections) || selections.length === 0 || body == null) {return false;}@@ -84,12 +96,45 @@ export const InnerPasteCommand: ICommand<IInnerPasteCommandParams> = {const textX = new TextX();const jsonX = JSONX.getInstance();+ const rawActions: JSONXActions = [];++ const hasTable = !!body.tables?.length;++ // TODO: @JOCS A feature that has not yet been implemented,+ // and it is currently not possible to paste tables in the header and footer.+ if (hasTable && segmentId) {+ return false;+ }++ // TODO: @JOCS A feature that has not yet been implemented.+ // Can not paste tables into table cell now.+ if (hasTable && hasRangeInTable(selections)) {+ return false;+ }for (const selection of selections) {const { startOffset, endOffset, collapsed } = selection;const len = startOffset - memoryCursor.cursor;+ const cloneBody = Tools.deepClone(body);++ if (hasTable) {+ for (const t of cloneBody.tables!) {+ const { tableId: oldTableId } = t;+ const tableId = Tools.generateRandomId(6);++ t.tableId = tableId;++ const table = Tools.deepClone(tableSource![oldTableId]);++ table.tableId = tableId;++ const action = jsonX.insertOp(['tableSource', tableId], table);+ rawActions.push(action!);+ }+ }+if (collapsed) {textX.push({t: TextXActionType.RETAIN,@@ -103,7 +148,7 @@ export const InnerPasteCommand: ICommand<IInnerPasteCommandParams> = {textX.push({t: TextXActionType.INSERT,- body,+ body: cloneBody,len: body.dataStream.length,line: 0,segmentId,@@ -114,7 +159,12 @@ export const InnerPasteCommand: ICommand<IInnerPasteCommandParams> = {}const path = getRichTextEditPath(docDataModel, segmentId);- doMutation.params.actions = jsonX.editOp(textX.serialize(), path);++ rawActions.push(jsonX.editOp(textX.serialize(), path)!);++ doMutation.params.actions = rawActions.reduce((acc, cur) => {+ return JSONX.compose(acc, cur as JSONXActions);+ }, null as JSONXActions);const result = commandService.syncExecuteCommand<IRichTextEditingMutationParams,@@ -125,27 +175,232 @@ export const InnerPasteCommand: ICommand<IInnerPasteCommandParams> = {},};+function getCutActionsFromTextRanges(+ selections: ITextRange[],+ docDataModel: DocumentDataModel,+ segmentId: string+) {+ const originBody = docDataModel.getSelfOrHeaderFooterModel(segmentId).getBody();++ const textX = new TextX();+ const jsonX = JSONX.getInstance();+ const rawActions: JSONXActions = [];++ if (originBody == null) {+ return rawActions;+ }++ const memoryCursor = new MemoryCursor();+ memoryCursor.reset();++ for (const selection of selections) {+ const { startOffset, endOffset, collapsed } = selection;++ if (startOffset == null || endOffset == null) {+ continue;+ }++ const len = startOffset - memoryCursor.cursor;++ if (collapsed) {+ textX.push({+ t: TextXActionType.RETAIN,+ len,+ segmentId,+ });+ } else {+ textX.push(...getRetainAndDeleteAndExcludeLineBreak(selection, originBody, segmentId, memoryCursor.cursor));+ }++ memoryCursor.reset();+ memoryCursor.moveCursor(endOffset);+ }++ const path = getRichTextEditPath(docDataModel, segmentId);+ rawActions.push(jsonX.editOp(textX.serialize(), path)!);++ const removedCustomBlockIds = getCustomBlockIdsInSelections(originBody, selections);+ const drawings = docDataModel.getDrawings() ?? {};+ const drawingOrder = docDataModel.getDrawingsOrder() ?? [];+ const sortedRemovedCustomBlockIds = removedCustomBlockIds.sort((a, b) => {+ if (drawingOrder.indexOf(a) > drawingOrder.indexOf(b)) {+ return -1;+ } else if (drawingOrder.indexOf(a) < drawingOrder.indexOf(b)) {+ return 1;+ }++ return 0;+ });++ if (sortedRemovedCustomBlockIds.length > 0) {+ for (const blockId of sortedRemovedCustomBlockIds) {+ const drawing = drawings[blockId];+ const drawingIndex = drawingOrder.indexOf(blockId);+ if (drawing == null || drawingIndex < 0) {+ continue;+ }++ const removeDrawingAction = jsonX.removeOp(['drawings', blockId], drawing);+ const removeDrawingOrderAction = jsonX.removeOp(['drawingsOrder', drawingIndex], blockId);++ rawActions.push(removeDrawingAction!);+ rawActions.push(removeDrawingOrderAction!);+ }+ }++ return rawActions.reduce((acc, cur) => {+ return JSONX.compose(acc, cur as JSONXActions);+ }, null as JSONXActions);+}++// eslint-disable-next-line max-lines-per-function+function getCutActionsFromRectRanges(+ ranges: RectRange[],+ docDataModel: DocumentDataModel,+ viewModel: DocumentViewModel,+ segmentId: string+): JSONXActions {+ const rawActions: JSONXActions = [];+ const segmentBody = docDataModel.getSelfOrHeaderFooterModel(segmentId).getBody();++ if (segmentBody == null) {+ return rawActions;+ }++ const textX = new TextX();+ const jsonX = JSONX.getInstance();+ const memoryCursor = new MemoryCursor();+ memoryCursor.reset();++ for (const range of ranges) {+ const { startOffset, endOffset, spanEntireRow, spanEntireTable } = range;++ if (startOffset == null || endOffset == null) {+ continue;+ }++ if (spanEntireTable) {+ // Remove entire table.+ const actionParams = getDeleteTableActionParams({ startOffset, endOffset, segmentId }, viewModel);+ if (actionParams == null) {+ continue;+ }++ const { offset, len, tableId } = actionParams;+ if (offset - memoryCursor.cursor > 0) {+ textX.push({+ t: TextXActionType.RETAIN,+ len: offset - memoryCursor.cursor,+ segmentId,+ });+ }++ textX.push({+ t: TextXActionType.DELETE,+ len,+ line: 0,+ segmentId,+ });++ const action = jsonX.removeOp(['tableSource', tableId]);+ rawActions.push(action!);++ memoryCursor.moveCursorTo(offset + len);+ } else if (spanEntireRow) {+ // Remove selected rows.+ const actionParams = getDeleteRowsActionsParams({ startOffset, endOffset, segmentId }, viewModel);+ if (actionParams == null) {+ continue;+ }++ const { offset, rowIndexes, len, tableId } = actionParams;++ if (offset - memoryCursor.cursor > 0) {+ textX.push({+ t: TextXActionType.RETAIN,+ len: offset - memoryCursor.cursor,+ segmentId,+ });+ }++ textX.push({+ t: TextXActionType.DELETE,+ len,+ line: 0,+ segmentId,+ });++ // Step 3: delete table rows;+ for (const index of rowIndexes.reverse()) {+ const action = jsonX.removeOp(['tableSource', tableId, 'tableRows', index]);+ rawActions.push(action!);+ }++ memoryCursor.moveCursorTo(offset + len);+ } else {+ // Only delete content in rect range.+ const actionParams = getDeleteRowContentActionParams({ startOffset, endOffset, segmentId }, viewModel);+ if (actionParams == null) {+ continue;+ }++ const { offsets } = actionParams;++ for (const offset of offsets) {+ const { retain, delete: delLen } = offset;+ if (retain - memoryCursor.cursor > 0) {+ textX.push({+ t: TextXActionType.RETAIN,+ len: retain - memoryCursor.cursor,+ segmentId,+ });+ }++ textX.push({+ t: TextXActionType.DELETE,+ len: delLen,+ line: 0,+ segmentId,+ });++ memoryCursor.moveCursorTo(retain + delLen);+ }+ }+ }++ const path = getRichTextEditPath(docDataModel, segmentId);+ rawActions.push(jsonX.editOp(textX.serialize(), path)!);++ return rawActions.reduce((acc, cur) => {+ return JSONX.compose(acc, cur as JSONXActions);+ }, null as JSONXActions);+}+export interface IInnerCutCommandParams {segmentId: string;textRanges: ITextRangeWithStyle[];selections?: ITextRange[];}-export const CutContentCommand: ICommand<IInnerCutCommandParams> = {- id: 'doc.command.inner-cut',+const INNER_CUT_COMMAND_ID = 'doc.command.inner-cut';+export const CutContentCommand: ICommand<IInnerCutCommandParams> = {+ id: INNER_CUT_COMMAND_ID,type: CommandType.COMMAND,- // eslint-disable-next-line max-lines-per-functionhandler: async (accessor, params: IInnerCutCommandParams) => {const { segmentId, textRanges } = params;const commandService = accessor.get(ICommandService);const textSelectionManagerService = accessor.get(TextSelectionManagerService);const univerInstanceService = accessor.get(IUniverInstanceService);- const selections = params.selections ?? textSelectionManagerService.getCurrentSelections();+ const selections = params.selections ?? textSelectionManagerService.getCurrentTextRanges();+ const rectRanges = textSelectionManagerService.getCurrentRectRanges();- if (!Array.isArray(selections) || selections.length === 0) {+ if (+ (!Array.isArray(selections) || selections.length === 0)+ && (!Array.isArray(rectRanges) || rectRanges.length === 0)+ ) {return false;}@@ -155,11 +410,18 @@ export const CutContentCommand: ICommand<IInnerCutCommandParams> = {}const docDataModel = univerInstanceService.getUniverDocInstance(unitId);- const originBody = getDocsUpdateBody(docDataModel!.getSnapshot(), segmentId);- if (docDataModel == null || originBody == null) {+ if (docDataModel == null) {return false;}+ const docSkeletonManagerService = getCommandSkeleton(accessor, unitId);++ if (docSkeletonManagerService == null) {+ return false;+ }++ const viewModel = docSkeletonManagerService.getViewModel();+const doMutation: IMutationInfo<IRichTextEditingMutationParams> = {id: RichTextEditingMutation.id,params: {@@ -169,73 +431,22 @@ export const CutContentCommand: ICommand<IInnerCutCommandParams> = {},};- const memoryCursor = new MemoryCursor();-- memoryCursor.reset();-- const textX = new TextX();- const jsonX = JSONX.getInstance();- const rawActions: JSONXActions = [];-- for (const selection of selections) {- const { startOffset, endOffset, collapsed } = selection;-- if (startOffset == null || endOffset == null) {- continue;- }-- const len = startOffset - memoryCursor.cursor;-- if (collapsed) {- textX.push({- t: TextXActionType.RETAIN,- len,- segmentId,- });- } else {- textX.push(...getRetainAndDeleteAndExcludeLineBreak(selection, originBody, segmentId, memoryCursor.cursor));- }-- memoryCursor.reset();- memoryCursor.moveCursor(endOffset);+ if (Array.isArray(selections) && selections?.length !== 0) {+ doMutation.params.actions = getCutActionsFromTextRanges(selections, docDataModel, segmentId);}- const path = getRichTextEditPath(docDataModel, segmentId);- rawActions.push(jsonX.editOp(textX.serialize(), path)!);-- const removedCustomBlockIds = getCustomBlockIdsInSelections(originBody, selections);- const drawings = docDataModel.getDrawings() ?? {};- const drawingOrder = docDataModel.getDrawingsOrder() ?? [];- const sortedRemovedCustomBlockIds = removedCustomBlockIds.sort((a, b) => {- if (drawingOrder.indexOf(a) > drawingOrder.indexOf(b)) {- return -1;- } else if (drawingOrder.indexOf(a) < drawingOrder.indexOf(b)) {- return 1;- }-- return 0;- });-- if (sortedRemovedCustomBlockIds.length > 0) {- for (const blockId of sortedRemovedCustomBlockIds) {- const drawing = drawings[blockId];- const drawingIndex = drawingOrder.indexOf(blockId);- if (drawing == null || drawingIndex < 0) {- continue;- }-- const removeDrawingAction = jsonX.removeOp(['drawings', blockId], drawing);- const removeDrawingOrderAction = jsonX.removeOp(['drawingsOrder', drawingIndex], blockId);-- rawActions.push(removeDrawingAction!);- rawActions.push(removeDrawingOrderAction!);+ if (Array.isArray(rectRanges) && rectRanges?.length !== 0) {+ const actions = getCutActionsFromRectRanges(rectRanges, docDataModel, viewModel, segmentId);+ if (doMutation.params.actions?.length === 0 || doMutation.params.actions == null) {+ doMutation.params.actions = actions;+ } else {+ doMutation.params.actions = JSONX.compose(+ doMutation.params.actions,+ JSONX.transform(actions, doMutation.params.actions, 'right')!+ ) as JSONXActions;}}- doMutation.params.actions = rawActions.reduce((acc, cur) => {- return JSONX.compose(acc, cur as JSONXActions);- }, null as JSONXActions);-const result = commandService.syncExecuteCommand<IRichTextEditingMutationParams,IRichTextEditingMutationParamsdiff --git a/packages/docs/src/commands/commands/core-editing.command.ts b/packages/docs/src/commands/commands/core-editing.command.tsindex 99d9fc0d40..6ee69d52ab 100644--- a/packages/docs/src/commands/commands/core-editing.command.ts+++ b/packages/docs/src/commands/commands/core-editing.command.ts@@ -65,7 +65,7 @@ export const InsertCommand: ICommand<IInsertCommandParams> = {return false;}- const activeRange = textSelectionManagerService.getActiveRange();+ const activeRange = textSelectionManagerService.getActiveTextRangeWithStyle();const originBody = docDataModel.getSelfOrHeaderFooterModel(activeRange?.segmentId ?? '').getBody();if (!originBody) {diff --git a/packages/docs/src/commands/commands/delete.command.ts b/packages/docs/src/commands/commands/delete.command.tsindex 450dbda96d..3d157262d8 100644--- a/packages/docs/src/commands/commands/delete.command.ts+++ b/packages/docs/src/commands/commands/delete.command.ts@@ -14,9 +14,10 @@* limitations under the License.*/-import type { IAccessor, ICommand, ICustomBlock, IDocumentBody, IMutationInfo, IParagraph, ITextRange, ITextRun, JSONXActions } from '@univerjs/core';+import type { IAccessor, ICommand, ICustomBlock, IDocumentBody, IMutationInfo, IParagraph, ITextRange, ITextRun, JSONXActions, Nullable } from '@univerjs/core';import {CommandType,+ DataStreamTreeTokenType,getCustomDecorationSlice,getCustomRangeSlice,ICommandService,@@ -27,7 +28,7 @@ import {TextXActionType,UpdateDocsAttributeType,} from '@univerjs/core';-import type { IActiveTextRange, ITextRangeWithStyle } from '@univerjs/engine-render';+import type { IActiveTextRange, ITextRangeWithStyle, RectRange, TextRange } from '@univerjs/engine-render';import { getParagraphByGlyph, hasListGlyph, isFirstGlyph, isIndentByGlyph } from '@univerjs/engine-render';import type { ITextActiveRange } from '../../services/text-selection-manager.service';@@ -57,7 +58,7 @@ export const DeleteCustomBlockCommand: ICommand<IDeleteCustomBlockParams> = {const univerInstanceService = accessor.get(IUniverInstanceService);const commandService = accessor.get(ICommandService);- const activeRange = textSelectionManagerService.getActiveRange();+ const activeRange = textSelectionManagerService.getActiveTextRangeWithStyle();const documentDataModel = univerInstanceService.getCurrentUniverDocInstance();if (activeRange == null || documentDataModel == null) {@@ -150,8 +151,8 @@ export const MergeTwoParagraphCommand: ICommand<IMergeTwoParagraphParams> = {const { direction, range } = params;- const activeRange = textSelectionManagerService.getActiveRange();- const ranges = textSelectionManagerService.getCurrentSelections();+ const activeRange = textSelectionManagerService.getActiveTextRangeWithStyle();+ const ranges = textSelectionManagerService.getCurrentTextRanges();if (activeRange == null || ranges == null) {return false;@@ -239,6 +240,54 @@ export const MergeTwoParagraphCommand: ICommand<IMergeTwoParagraphParams> = {},};+export function getCursorWhenDelete(textRanges: Readonly<Nullable<TextRange[]>>, rectRanges: readonly RectRange[]): number {+ let cursor = 0;++ if (textRanges == null || textRanges.length === 0) {+ if (typeof rectRanges[0].startOffset === 'number') {+ // Put the cursor at the first rect range start.+ const rectRange = rectRanges[0]!;+ const { spanEntireRow, spanEntireTable } = rectRange;++ if (spanEntireTable) {+ // Put the cursor at the first line of deleted table paragraph.+ cursor = rectRange.startOffset! - 3; // 3 is TABLE START, ROW START, CELL START.+ } else if (spanEntireRow) {+ // Put the cursor at the last row's end cell before deleted rows.+ if (rectRange.startRow > 0) {+ cursor = rectRange.startOffset! - 6; // 6 is ROW START, CELL START, CELL END, ROW END, \r, \n.+ } else {+ cursor = rectRange.startOffset!;+ }+ } else {+ cursor = rectRanges[0].startOffset;+ }+ }+ } else if (textRanges.length > 0 && rectRanges.length > 0) {+ const textRange = textRanges[0]!;+ const rectRange = rectRanges[0]!;++ if (textRange.startOffset != null && rectRange.startOffset != null) {+ if (textRange.startOffset < rectRange.startOffset) {+ // Put the cursor at the first text range start.+ cursor = textRange.startOffset;+ } else if (textRange.startOffset >= rectRange.startOffset) {+ const { spanEntireRow, spanEntireTable } = rectRange;++ if (spanEntireTable) {+ // Put the cursor at the first line of deleted table paragraph.+ cursor = rectRange.startOffset - 3; // 3 is TABLE START, ROW START, CELL START.+ } else if (spanEntireRow) {+ // Put the cursor at the last row's end cell before deleted rows.+ cursor = rectRange.startOffset - 6; // 6 is ROW START, CELL START, CELL END, ROW END, \r, \n.+ }+ }+ }+ }++ return cursor;+}+// Handle BACKSPACE key.export const DeleteLeftCommand: ICommand = {id: 'doc.command.delete-left',@@ -258,14 +307,36 @@ export const DeleteLeftCommand: ICommand = {const unitId = docDataModel.getUnitId();const docSkeletonManagerService = getCommandSkeleton(accessor, unitId);- const activeRange = textSelectionManagerService.getActiveRange();- const ranges = textSelectionManagerService.getCurrentSelections();+ const activeRange = textSelectionManagerService.getActiveTextRangeWithStyle();+ const rectRanges = textSelectionManagerService.getCurrentRectRanges();+ const ranges = textSelectionManagerService.getCurrentTextRanges();const skeleton = docSkeletonManagerService?.getSkeleton();- if (activeRange == null || skeleton == null || ranges == null) {++ if (skeleton == null) {+ return false;+ }++ if (rectRanges?.length) {+ const cursor = getCursorWhenDelete(ranges, rectRanges);+ const segmentId = rectRanges[0].segmentId;+ const textRanges = [+ {+ startOffset: cursor,+ endOffset: cursor,+ },+ ];+ return commandService.executeCommand(CutContentCommand.id, {+ segmentId,+ textRanges,+ });+ }++ if (activeRange == null || ranges == null) {return false;}const { segmentId, style, segmentPage } = activeRange;+const body = docDataModel.getSelfOrHeaderFooterModel(segmentId).getBody();if (body == null) {@@ -451,9 +522,26 @@ export const DeleteRightCommand: ICommand = {const docSkeletonManagerService = getCommandSkeleton(accessor, docDataModel.getUnitId());const commandService = accessor.get(ICommandService);- const activeRange = textSelectionManagerService.getActiveRange();- const ranges = textSelectionManagerService.getCurrentSelections();+ const activeRange = textSelectionManagerService.getActiveTextRangeWithStyle();+ const rectRanges = textSelectionManagerService.getCurrentRectRanges();+ const ranges = textSelectionManagerService.getCurrentTextRanges();const skeleton = docSkeletonManagerService?.getSkeleton();++ if (rectRanges?.length) {+ const cursor = getCursorWhenDelete(ranges, rectRanges);+ const segmentId = rectRanges[0].segmentId;+ const textRanges = [+ {+ startOffset: cursor,+ endOffset: cursor,+ },+ ];+ return commandService.executeCommand(CutContentCommand.id, {+ segmentId,+ textRanges,+ });+ }+if (activeRange == null || skeleton == null || ranges == null) {return false;}@@ -477,6 +565,11 @@ export const DeleteRightCommand: ICommand = {const needDeleteGlyph = skeleton.findNodeByCharIndex(startOffset, segmentId, segmentPage)!;const nextGlyph = skeleton.findNodeByCharIndex(startOffset + 1);+ // Handle delete key at cell content end.+ if (needDeleteGlyph.streamType === DataStreamTreeTokenType.PARAGRAPH && nextGlyph?.streamType === DataStreamTreeTokenType.SECTION_BREAK) {+ return false;+ }+if (needDeleteGlyph.content === '\r') {result = await commandService.executeCommand(MergeTwoParagraphCommand.id, {direction: DeleteDirection.RIGHT,diff --git a/packages/docs/src/commands/commands/inline-format.command.ts b/packages/docs/src/commands/commands/inline-format.command.tsindex 826d032a50..5f53dd7c54 100644--- a/packages/docs/src/commands/commands/inline-format.command.ts+++ b/packages/docs/src/commands/commands/inline-format.command.ts@@ -23,8 +23,8 @@ import {JSONX, MemoryCursor,TextX, TextXActionType,} from '@univerjs/core';-import type { TextRange } from '@univerjs/engine-render';-import { serializeTextRange, TextSelectionManagerService } from '../../services/text-selection-manager.service';+import type { IDocRange } from '@univerjs/engine-render';+import { serializeDocRange, TextSelectionManagerService } from '../../services/text-selection-manager.service';import type { IRichTextEditingMutationParams } from '../mutations/core-editing.mutation';import { RichTextEditingMutation } from '../mutations/core-editing.mutation';import { getRichTextEditPath } from '../util';@@ -32,25 +32,16 @@ import { getRichTextEditPath } from '../util';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-definereturn commandService.executeCommand(SetInlineFormatCommand.id, {- segmentId,preCommandId,...(params ?? {}),});}export interface ISetInlineFormatCommandParams {- segmentId: string;preCommandId: string;value?: string;}@@ -61,12 +52,10 @@ export const SetInlineFormatBoldCommand: ICommand = {type: CommandType.COMMAND,handler: async (accessor, params) => {const commandService = accessor.get(ICommandService);- const textSelectionManagerService = accessor.get(TextSelectionManagerService);return handleInlineFormat(SetInlineFormatBoldCommandId,params,- textSelectionManagerService,commandService);},@@ -78,12 +67,10 @@ export const SetInlineFormatItalicCommand: ICommand = {type: CommandType.COMMAND,handler: async (accessor, params) => {const commandService = accessor.get(ICommandService);- const textSelectionManagerService = accessor.get(TextSelectionManagerService);return handleInlineFormat(SetInlineFormatItalicCommandId,params,- textSelectionManagerService,commandService);},@@ -95,12 +82,10 @@ export const SetInlineFormatUnderlineCommand: ICommand = {type: CommandType.COMMAND,handler: async (accessor, params) => {const commandService = accessor.get(ICommandService);- const textSelectionManagerService = accessor.get(TextSelectionManagerService);return handleInlineFormat(SetInlineFormatUnderlineCommandId,params,- textSelectionManagerService,commandService);},@@ -112,12 +97,10 @@ export const SetInlineFormatStrikethroughCommand: ICommand = {type: CommandType.COMMAND,handler: async (accessor, params) => {const commandService = accessor.get(ICommandService);- const textSelectionManagerService = accessor.get(TextSelectionManagerService);return handleInlineFormat(SetInlineFormatStrikethroughCommandId,params,- textSelectionManagerService,commandService);},@@ -129,12 +112,10 @@ export const SetInlineFormatSubscriptCommand: ICommand = {type: CommandType.COMMAND,handler: async (accessor, params) => {const commandService = accessor.get(ICommandService);- const textSelectionManagerService = accessor.get(TextSelectionManagerService);return handleInlineFormat(SetInlineFormatSubscriptCommandId,params,- textSelectionManagerService,commandService);},@@ -146,12 +127,10 @@ export const SetInlineFormatSuperscriptCommand: ICommand = {type: CommandType.COMMAND,handler: async (accessor, params) => {const commandService = accessor.get(ICommandService);- const textSelectionManagerService = accessor.get(TextSelectionManagerService);return handleInlineFormat(SetInlineFormatSuperscriptCommandId,params,- textSelectionManagerService,commandService);},@@ -163,12 +142,10 @@ export const SetInlineFormatFontSizeCommand: ICommand = {type: CommandType.COMMAND,handler: async (accessor, params) => {const commandService = accessor.get(ICommandService);- const textSelectionManagerService = accessor.get(TextSelectionManagerService);return handleInlineFormat(SetInlineFormatFontSizeCommandId,params,- textSelectionManagerService,commandService);},@@ -180,12 +157,10 @@ export const SetInlineFormatFontFamilyCommand: ICommand = {type: CommandType.COMMAND,handler: async (accessor, params) => {const commandService = accessor.get(ICommandService);- const textSelectionManagerService = accessor.get(TextSelectionManagerService);return handleInlineFormat(SetInlineFormatFontFamilyCommandId,params,- textSelectionManagerService,commandService);},@@ -197,12 +172,10 @@ export const SetInlineFormatTextColorCommand: ICommand = {type: CommandType.COMMAND,handler: async (accessor, params) => {const commandService = accessor.get(ICommandService);- const textSelectionManagerService = accessor.get(TextSelectionManagerService);return handleInlineFormat(SetInlineFormatTextColorCommandId,params,- textSelectionManagerService,commandService);},@@ -214,12 +187,10 @@ export const SetInlineFormatTextBackgroundColorCommand: ICommand = {type: CommandType.COMMAND,handler: async (accessor, params) => {const commandService = accessor.get(ICommandService);- const textSelectionManagerService = accessor.get(TextSelectionManagerService);return handleInlineFormat(SetInlineFormatTextBackgroundColorCommandId,params,- textSelectionManagerService,commandService);},@@ -231,12 +202,10 @@ export const ResetInlineFormatTextBackgroundColorCommand: ICommand = {type: CommandType.COMMAND,handler: async (accessor, params) => {const commandService = accessor.get(ICommandService);- const textSelectionManagerService = accessor.get(TextSelectionManagerService);return handleInlineFormat(ResetInlineFormatTextBackgroundColorCommandId,params,- textSelectionManagerService,commandService);},@@ -261,17 +230,19 @@ export const SetInlineFormatCommand: ICommand<ISetInlineFormatCommandParams> = {type: CommandType.COMMAND,// eslint-disable-next-line max-lines-per-functionhandler: async (accessor, params: ISetInlineFormatCommandParams) => {- const { segmentId, value, preCommandId } = params;+ const { value, preCommandId } = params;const commandService = accessor.get(ICommandService);const textSelectionManagerService = accessor.get(TextSelectionManagerService);const univerInstanceService = accessor.get(IUniverInstanceService);- const selections = textSelectionManagerService.getCurrentSelections();+ const docRanges = textSelectionManagerService.getDocRanges();- if (!Array.isArray(selections) || selections.length === 0) {+ if (docRanges.length === 0) {return false;}+ const segmentId = docRanges[0].segmentId;+const docDataModel = univerInstanceService.getCurrentUniverDocInstance();if (docDataModel == null) {return false;@@ -291,7 +262,7 @@ export const SetInlineFormatCommand: ICommand<ISetInlineFormatCommandParams> = {formatValue = getReverseFormatValueInSelection(docDataModel.getSelfOrHeaderFooterModel(segmentId).getBody()!.textRuns!,preCommandId,- selections+ docRanges);break;@@ -328,7 +299,7 @@ export const SetInlineFormatCommand: ICommand<ISetInlineFormatCommandParams> = {params: {unitId,actions: [],- textRanges: selections.map(serializeTextRange),+ textRanges: docRanges.map(serializeDocRange),},};@@ -338,8 +309,12 @@ export const SetInlineFormatCommand: ICommand<ISetInlineFormatCommandParams> = {const memoryCursor = new MemoryCursor();memoryCursor.reset();- for (const selection of selections) {- const { startOffset, endOffset } = selection;+ for (const range of docRanges) {+ const { startOffset, endOffset } = range;++ if (startOffset == null || endOffset == null) {+ continue;+ }const body: IDocumentBody = {dataStream: '',@@ -399,14 +374,14 @@ function isTextDecoration(value: unknown | ITextDecoration): value is ITextDecorfunction getReverseFormatValueInSelection(textRuns: ITextRun[],preCommandId: string,- selections: TextRange[]+ docRanges: IDocRange[]): BooleanNumber | ITextDecoration | BaselineOffset {let ti = 0;let si = 0;const key: keyof IStyleBase = COMMAND_ID_TO_FORMAT_KEY_MAP[preCommandId];- while (ti !== textRuns.length && si !== selections.length) {- const { startOffset, endOffset } = selections[si];+ while (ti !== textRuns.length && si !== docRanges.length) {+ const { startOffset, endOffset } = docRanges[si];// TODO: @jocs handle sid in textRunconst { st, ed, ts } = textRuns[ti];diff --git a/packages/docs/src/commands/commands/list.command.ts b/packages/docs/src/commands/commands/list.command.tsindex 6a750dadc9..0de509acc3 100644--- a/packages/docs/src/commands/commands/list.command.ts+++ b/packages/docs/src/commands/commands/list.command.ts@@ -30,9 +30,10 @@ import {Tools,UpdateDocsAttributeType,} from '@univerjs/core';-import { getCharSpaceApply, getNumberUnitValue, type IActiveTextRange } from '@univerjs/engine-render';+import type { IActiveTextRange, IDocRange } from '@univerjs/engine-render';+import { getCharSpaceApply, getNumberUnitValue } from '@univerjs/engine-render';-import { serializeTextRange, TextSelectionManagerService } from '../../services/text-selection-manager.service';+import { serializeDocRange, TextSelectionManagerService } from '../../services/text-selection-manager.service';import type { IRichTextEditingMutationParams } from '../mutations/core-editing.mutation';import { RichTextEditingMutation } from '../mutations/core-editing.mutation';import { getRichTextEditPath } from '../util';@@ -55,16 +56,16 @@ export const ListOperationCommand: ICommand<IListOperationCommandParams> = {let listType: string = params.listType;const docDataModel = univerInstanceService.getCurrentUniverDocInstance();- const activeRange = textSelectionManagerService.getActiveRange();+ const activeRange = textSelectionManagerService.getActiveTextRangeWithStyle();if (docDataModel == null || activeRange == null) {return false;}const { segmentId } = activeRange;- const selections = textSelectionManagerService.getCurrentSelections() ?? [];+ const selections = textSelectionManagerService.getCurrentTextRanges() ?? [];const paragraphs = docDataModel.getSelfOrHeaderFooterModel(segmentId).getBody()?.paragraphs;- const serializedSelections = selections.map(serializeTextRange);+ const serializedSelections = selections.map(serializeDocRange);if (paragraphs == null) {return false;@@ -205,16 +206,16 @@ export const ChangeListTypeCommand: ICommand<IChangeListTypeCommandParams> = {const commandService = accessor.get(ICommandService);const { listType } = params;const docDataModel = univerInstanceService.getCurrentUniverDocInstance();- const activeRange = textSelectionManagerService.getActiveRange();+ const activeRange = textSelectionManagerService.getActiveTextRangeWithStyle();if (docDataModel == null || activeRange == null) {return false;}const { segmentId } = activeRange;- const selections = textSelectionManagerService.getCurrentSelections() ?? [];+ const selections = textSelectionManagerService.getDocRanges() ?? [];const paragraphs = docDataModel.getSelfOrHeaderFooterModel(segmentId).getBody()?.paragraphs;- const serializedSelections = selections.map(serializeTextRange);+ const serializedSelections = selections.map(serializeDocRange);if (paragraphs == null) {return false;@@ -336,16 +337,16 @@ export const ChangeListNestingLevelCommand: ICommand<IChangeListNestingLevelCommconst univerInstanceService = accessor.get(IUniverInstanceService);const commandService = accessor.get(ICommandService);const docDataModel = univerInstanceService.getCurrentUniverDocInstance();- const activeRange = textSelectionManagerService.getActiveRange();+ const activeRange = textSelectionManagerService.getActiveTextRangeWithStyle();if (docDataModel == null || activeRange == null) {return false;}const { segmentId } = activeRange;- const selections = textSelectionManagerService.getCurrentSelections() ?? [];+ const selections = textSelectionManagerService.getDocRanges() ?? [];const paragraphs = docDataModel.getSelfOrHeaderFooterModel(segmentId).getBody()?.paragraphs;- const serializedSelections = selections.map(serializeTextRange);+ const serializedSelections = selections.map(serializeDocRange);if (paragraphs == null) {return false;@@ -529,6 +530,18 @@ export function getParagraphsRelative(activeRange: IActiveTextRange, paragraphs:return selectionParagraphs;}+export function getParagraphsInRanges(ranges: IDocRange[], paragraphs: IParagraph[]) {+ const results: IParagraph[] = [];++ for (const range of ranges) {+ const ps = getParagraphsInRange(range as unknown as IActiveTextRange, paragraphs);++ results.push(...ps);+ }++ return results;+}+export function findNearestSectionBreak(currentIndex: number, sectionBreaks: ISectionBreak[]) {const sortedSectionBreaks = sectionBreaks.sort(sortRulesFactory('startIndex'));for (let i = 0; i < sortedSectionBreaks.length; i++) {diff --git a/packages/docs/src/commands/commands/paragraph-align.command.ts b/packages/docs/src/commands/commands/paragraph-align.command.tsindex 8da6660335..c292c9d6ba 100644--- a/packages/docs/src/commands/commands/paragraph-align.command.ts+++ b/packages/docs/src/commands/commands/paragraph-align.command.ts@@ -26,18 +26,18 @@ import {UpdateDocsAttributeType,} from '@univerjs/core';-import { serializeTextRange, TextSelectionManagerService } from '../../services/text-selection-manager.service';+import { serializeDocRange, TextSelectionManagerService } from '../../services/text-selection-manager.service';import type { IRichTextEditingMutationParams } from '../mutations/core-editing.mutation';import { RichTextEditingMutation } from '../mutations/core-editing.mutation';import { getRichTextEditPath } from '../util';-import { getParagraphsInRange } from './list.command';+import { getParagraphsInRanges } from './list.command';interface IAlignOperationCommandParams {alignType: HorizontalAlign;}export const AlignOperationCommand: ICommand<IAlignOperationCommandParams> = {- id: 'doc.command.align-operation',+ id: 'doc.command.align-action',type: CommandType.COMMAND,@@ -50,20 +50,26 @@ export const AlignOperationCommand: ICommand<IAlignOperationCommandParams> = {const { alignType } = params;const docDataModel = univerInstanceService.getCurrentUniverDocInstance();- const activeRange = textSelectionManagerService.getActiveRange();- if (docDataModel == null || activeRange == null) {+ if (docDataModel == null) {return false;}- const { segmentId } = activeRange;- const selections = textSelectionManagerService.getCurrentSelections() ?? [];++ const allRanges = textSelectionManagerService.getDocRanges();+ if (allRanges.length === 0) {+ return false;+ }++ const segmentId = allRanges[0].segmentId;+const paragraphs = docDataModel.getSelfOrHeaderFooterModel(segmentId).getBody()?.paragraphs;- const serializedSelections = selections.map(serializeTextRange);+ const serializedSelections = allRanges.map(serializeDocRange);if (paragraphs == null) {return false;}- const currentParagraphs = getParagraphsInRange(activeRange, paragraphs);+ const currentParagraphs = getParagraphsInRanges(allRanges, paragraphs);+const unitId = docDataModel.getUnitId();const isAlreadyAligned = currentParagraphs.every((paragraph) => paragraph.paragraphStyle?.horizontalAlign === alignType);diff --git a/packages/docs/src/commands/commands/replace-content.command.ts b/packages/docs/src/commands/commands/replace-content.command.tsindex 95384ae813..77b6e2256c 100644--- a/packages/docs/src/commands/commands/replace-content.command.ts+++ b/packages/docs/src/commands/commands/replace-content.command.ts@@ -46,7 +46,7 @@ export const ReplaceContentCommand: ICommand<IReplaceContentCommandParams> = {const docDataModel = univerInstanceService.getUniverDocInstance(unitId);const prevBody = docDataModel?.getSnapshot().body;- const selections = textSelectionManagerService.getCurrentSelections();+ const selections = textSelectionManagerService.getCurrentTextRanges();if (docDataModel == null || prevBody == null) {return false;@@ -176,7 +176,7 @@ export const ReplaceSelectionCommand: ICommand<IReplaceSelectionCommandParams> =}const body = docDataModel.getBody();- const selection = params.selection ?? textSelectionManagerService.getActiveRange();+ const selection = params.selection ?? textSelectionManagerService.getActiveTextRangeWithStyle();if (!selection || !body) {return false;}diff --git a/packages/docs/src/commands/commands/table/doc-table-create.command.ts b/packages/docs/src/commands/commands/table/doc-table-create.command.tsnew file mode 100644index 0000000000..9d7f5522ee--- /dev/null+++ b/packages/docs/src/commands/commands/table/doc-table-create.command.ts@@ -0,0 +1,167 @@+/**+ * 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, JSONXActions } from '@univerjs/core';+import { CommandType, DataStreamTreeTokenType, ICommandService, IUniverInstanceService, JSONX, TextX, TextXActionType } from '@univerjs/core';+import type { IRichTextEditingMutationParams } from '@univerjs/docs';+import { generateParagraphs, getCommandSkeleton, getInsertSelection, getRichTextEditPath, RichTextEditingMutation, TextSelectionManagerService } from '@univerjs/docs';+import type { ITextRangeWithStyle } from '@univerjs/engine-render';+import { genEmptyTable, genTableSource } from './table';++export const CreateDocTableCommandId = 'doc.command.create-table';++export interface ICreateDocTableCommandParams {+ rowCount: number;+ colCount: number;+}+/**+ * The command to create a table at cursor point.+ */+export const CreateDocTableCommand: ICommand<ICreateDocTableCommandParams> = {+ id: CreateDocTableCommandId,+ type: CommandType.COMMAND,++ // eslint-disable-next-line max-lines-per-function+ handler: async (accessor, params: ICreateDocTableCommandParams) => {+ const { rowCount, colCount } = params;+ const textSelectionManagerService = accessor.get(TextSelectionManagerService);+ const univerInstanceService = accessor.get(IUniverInstanceService);+ const commandService = accessor.get(ICommandService);++ const activeRange = textSelectionManagerService.getActiveTextRangeWithStyle();+ if (activeRange == null) {+ return false;+ }+ const { segmentId, segmentPage } = activeRange;+ const docDataModel = univerInstanceService.getCurrentUniverDocInstance();+ const body = docDataModel?.getSelfOrHeaderFooterModel(segmentId).getBody();+ if (docDataModel == null || body == null) {+ return false;+ }++ const unitId = docDataModel.getUnitId();+ const docSkeletonManagerService = getCommandSkeleton(accessor, unitId);+ const skeleton = docSkeletonManagerService?.getSkeleton();++ if (skeleton == null) {+ return false;+ }+ const { startOffset } = getInsertSelection(activeRange, body);++ const paragraphs = body.paragraphs ?? [];+ const prevParagraph = paragraphs.find((p) => p.startIndex >= startOffset);+ const curGlyph = skeleton.findNodeByCharIndex(startOffset, segmentId, segmentPage);+ const line = curGlyph?.parent?.parent;+ const preGlyph = skeleton.findNodeByCharIndex(startOffset - 1, segmentId, segmentPage);+ const isInParagraph = preGlyph && preGlyph.content !== '\r';++ if (curGlyph == null || line == null) {+ return false;+ }++ // Also need to create new paragraph when there is already a table in paragraph.+ const needCreateParagraph = isInParagraph || line.isBehindTable;++ const textX = new TextX();+ const jsonX = JSONX.getInstance();+ const rawActions: JSONXActions = [];++ // 4 is cal by `\r + TableStart + RowStart + CellStart`, 3 is cal by `TableStart + RowStart + CellStart`.+ const cursor = startOffset + (needCreateParagraph ? 4 : 3);+ const textRanges: ITextRangeWithStyle[] = [{+ startOffset: cursor,+ endOffset: cursor,+ collapsed: true,+ }];++ const doMutation: IMutationInfo<IRichTextEditingMutationParams> = {+ id: RichTextEditingMutation.id,+ params: {+ unitId,+ actions: [],+ textRanges,+ },+ };++ // Step 1: Break lines if necessary.+ if (startOffset > 0) {+ textX.push({+ t: TextXActionType.RETAIN,+ len: startOffset,+ segmentId,+ });+ }++ if (needCreateParagraph) {+ textX.push({+ t: TextXActionType.INSERT,+ body: {+ dataStream: DataStreamTreeTokenType.PARAGRAPH,+ paragraphs: generateParagraphs(DataStreamTreeTokenType.PARAGRAPH, prevParagraph),+ },+ len: 1,+ line: 0,+ segmentId,+ });+ }++ // Step 2: Insert table.+ const { dataStream: tableDataStream, paragraphs: tableParagraphs, sectionBreaks } = genEmptyTable(rowCount, colCount);+ const page = curGlyph.parent?.parent?.parent?.parent?.parent;+ if (page == null) {+ return false;+ }+ const { pageWidth, marginLeft, marginRight } = page;+ const tableSource = genTableSource(rowCount, colCount, pageWidth - marginLeft - marginRight);++ textX.push({+ t: TextXActionType.INSERT,+ body: {+ dataStream: tableDataStream,+ paragraphs: tableParagraphs,+ sectionBreaks,+ tables: [+ {+ startIndex: 0,+ endIndex: tableDataStream.length,+ tableId: tableSource.tableId,+ },+ ],+ },+ len: tableDataStream.length,+ line: 0,+ segmentId,+ });++ const path = getRichTextEditPath(docDataModel, segmentId);+ rawActions.push(jsonX.editOp(textX.serialize(), path)!);++ // Step 3: Insert table source;+ const insertTableSource = jsonX.insertOp(['tableSource', tableSource.tableId], tableSource);+ rawActions.push(insertTableSource!);++ doMutation.params.actions = rawActions.reduce((acc, cur) => {+ return JSONX.compose(acc, cur as JSONXActions);+ }, null as JSONXActions);++ const result = commandService.syncExecuteCommand<+ IRichTextEditingMutationParams,+ IRichTextEditingMutationParams+ >(doMutation.id, doMutation.params);++ return Boolean(result);+ },+};diff --git a/packages/docs/src/commands/commands/table/doc-table-delete.command.ts b/packages/docs/src/commands/commands/table/doc-table-delete.command.tsnew file mode 100644index 0000000000..f142faf373--- /dev/null+++ b/packages/docs/src/commands/commands/table/doc-table-delete.command.ts@@ -0,0 +1,345 @@+/**+ * 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, JSONXActions } from '@univerjs/core';+import { CommandType, ICommandService, IUniverInstanceService, JSONX, TextX, TextXActionType } from '@univerjs/core';+import type { IRichTextEditingMutationParams } from '@univerjs/docs';+import { getCommandSkeleton, getRichTextEditPath, RichTextEditingMutation, TextSelectionManagerService } from '@univerjs/docs';+import type { ITextRangeWithStyle } from '@univerjs/engine-render';+import { getDeleteColumnsActionParams, getDeleteRowsActionsParams, getDeleteTableActionParams, getRangeInfoFromRanges } from './table';++export interface IDocTableDeleteRowsCommandParams {}++export const DocTableDeleteRowsCommand: ICommand<IDocTableDeleteRowsCommandParams> = {+ id: 'doc.table.delete-rows',+ type: CommandType.COMMAND,+ // eslint-disable-next-line max-lines-per-function+ handler: async (accessor) => {+ const textSelectionManagerService = accessor.get(TextSelectionManagerService);+ const univerInstanceService = accessor.get(IUniverInstanceService);+ const commandService = accessor.get(ICommandService);++ const activeRectRanges = textSelectionManagerService.getCurrentRectRanges();+ const activeTextRange = textSelectionManagerService.getActiveTextRange();++ const rangeInfo = getRangeInfoFromRanges(activeTextRange, activeRectRanges);++ if (rangeInfo == null) {+ return false;+ }++ const { segmentId } = rangeInfo;++ const docDataModel = univerInstanceService.getCurrentUniverDocInstance();+ const body = docDataModel?.getSelfOrHeaderFooterModel(segmentId).getBody();++ if (docDataModel == null || body == null) {+ return false;+ }+ const docSkeletonManagerService = getCommandSkeleton(accessor, docDataModel.getUnitId());++ if (docSkeletonManagerService == null) {+ return false;+ }++ const viewModel = docSkeletonManagerService.getViewModel();+ const unitId = docDataModel?.getUnitId();+ const textX = new TextX();+ const jsonX = JSONX.getInstance();++ const actionParams = getDeleteRowsActionsParams(rangeInfo, viewModel);++ if (actionParams == null) {+ return false;+ }++ const { offset, rowIndexes, len, tableId, cursor, selectWholeTable } = actionParams;++ if (selectWholeTable) {+ // eslint-disable-next-line ts/no-use-before-define+ return commandService.executeCommand(DocTableDeleteTableCommand.id);+ }++ const rawActions: JSONXActions = [];++ const textRanges: ITextRangeWithStyle[] = [{+ startOffset: cursor,+ endOffset: cursor,+ collapsed: true,+ }];++ const doMutation: IMutationInfo<IRichTextEditingMutationParams> = {+ id: RichTextEditingMutation.id,+ params: {+ unitId,+ actions: [],+ textRanges,+ },+ };++ if (offset > 0) {+ textX.push({+ t: TextXActionType.RETAIN,+ len: offset,+ segmentId,+ });+ }++ textX.push({+ t: TextXActionType.DELETE,+ len,+ line: 0,+ segmentId,+ });++ const path = getRichTextEditPath(docDataModel, segmentId);+ rawActions.push(jsonX.editOp(textX.serialize(), path)!);++ // Step 3: delete table rows;+ for (const index of rowIndexes.reverse()) {+ const action = jsonX.removeOp(['tableSource', tableId, 'tableRows', index]);+ rawActions.push(action!);+ }++ doMutation.params.actions = rawActions.reduce((acc, cur) => {+ return JSONX.compose(acc, cur as JSONXActions);+ }, null as JSONXActions);++ const result = commandService.syncExecuteCommand<+ IRichTextEditingMutationParams,+ IRichTextEditingMutationParams+ >(doMutation.id, doMutation.params);++ return Boolean(result);+ },+};++export interface IDocTableDeleteColumnsCommandParams {}++export const DocTableDeleteColumnsCommand: ICommand<IDocTableDeleteColumnsCommandParams> = {+ id: 'doc.table.delete-columns',+ type: CommandType.COMMAND,+ // eslint-disable-next-line max-lines-per-function+ handler: async (accessor) => {+ const textSelectionManagerService = accessor.get(TextSelectionManagerService);+ const univerInstanceService = accessor.get(IUniverInstanceService);+ const commandService = accessor.get(ICommandService);++ const activeRectRanges = textSelectionManagerService.getCurrentRectRanges();+ const activeTextRange = textSelectionManagerService.getActiveTextRange();++ const rangeInfo = getRangeInfoFromRanges(activeTextRange, activeRectRanges);++ if (rangeInfo == null) {+ return false;+ }++ const { segmentId } = rangeInfo;++ const docDataModel = univerInstanceService.getCurrentUniverDocInstance();+ const body = docDataModel?.getSelfOrHeaderFooterModel(segmentId).getBody();++ if (docDataModel == null || body == null) {+ return false;+ }+ const docSkeletonManagerService = getCommandSkeleton(accessor, docDataModel.getUnitId());++ if (docSkeletonManagerService == null) {+ return false;+ }++ const viewModel = docSkeletonManagerService.getViewModel();+ const unitId = docDataModel?.getUnitId();+ const textX = new TextX();+ const jsonX = JSONX.getInstance();++ const actionParams = getDeleteColumnsActionParams(rangeInfo, viewModel);++ if (actionParams == null) {+ return false;+ }++ const { offsets, columnIndexes, tableId, cursor, rowCount, selectWholeTable } = actionParams;++ if (selectWholeTable) {+ // eslint-disable-next-line ts/no-use-before-define+ return commandService.executeCommand(DocTableDeleteTableCommand.id);+ }++ const rawActions: JSONXActions = [];++ const textRanges: ITextRangeWithStyle[] = [{+ startOffset: cursor,+ endOffset: cursor,+ collapsed: true,+ }];++ const doMutation: IMutationInfo<IRichTextEditingMutationParams> = {+ id: RichTextEditingMutation.id,+ params: {+ unitId,+ actions: [],+ textRanges,+ },+ };++ for (const offset of offsets) {+ const { retain, delete: deleteLen } = offset;+ if (retain > 0) {+ textX.push({+ t: TextXActionType.RETAIN,+ len: retain,+ segmentId,+ });+ }++ textX.push({+ t: TextXActionType.DELETE,+ len: deleteLen,+ line: 0,+ segmentId,+ });+ }++ const path = getRichTextEditPath(docDataModel, segmentId);+ rawActions.push(jsonX.editOp(textX.serialize(), path)!);++ // Step 3: delete table columns;+ columnIndexes.reverse();+ for (let i = 0; i < rowCount; i++) {+ for (const index of columnIndexes) {+ const action = jsonX.removeOp(['tableSource', tableId, 'tableRows', i, 'tableCells', index]);+ rawActions.push(action!);+ }+ }++ for (const index of columnIndexes) {+ const action = jsonX.removeOp(['tableSource', tableId, 'tableColumns', index]);+ rawActions.push(action!);+ }++ doMutation.params.actions = rawActions.reduce((acc, cur) => {+ return JSONX.compose(acc, cur as JSONXActions);+ }, null as JSONXActions);++ const result = commandService.syncExecuteCommand<+ IRichTextEditingMutationParams,+ IRichTextEditingMutationParams+ >(doMutation.id, doMutation.params);++ return Boolean(result);+ },+};++export interface IDocTableDeleteTableCommandParams {}++export const DocTableDeleteTableCommand: ICommand<IDocTableDeleteTableCommandParams> = {+ id: 'doc.table.delete-table',+ type: CommandType.COMMAND,+ // eslint-disable-next-line max-lines-per-function+ handler: async (accessor) => {+ const textSelectionManagerService = accessor.get(TextSelectionManagerService);+ const univerInstanceService = accessor.get(IUniverInstanceService);+ const commandService = accessor.get(ICommandService);++ const activeRectRanges = textSelectionManagerService.getCurrentRectRanges();+ const activeTextRange = textSelectionManagerService.getActiveTextRange();++ const rangeInfo = getRangeInfoFromRanges(activeTextRange, activeRectRanges);++ if (rangeInfo == null) {+ return false;+ }++ const { segmentId } = rangeInfo;++ const docDataModel = univerInstanceService.getCurrentUniverDocInstance();+ const body = docDataModel?.getSelfOrHeaderFooterModel(segmentId).getBody();++ if (docDataModel == null || body == null) {+ return false;+ }+ const docSkeletonManagerService = getCommandSkeleton(accessor, docDataModel.getUnitId());++ if (docSkeletonManagerService == null) {+ return false;+ }++ const viewModel = docSkeletonManagerService.getViewModel();+ const unitId = docDataModel?.getUnitId();+ const textX = new TextX();+ const jsonX = JSONX.getInstance();++ const actionParams = getDeleteTableActionParams(rangeInfo, viewModel);++ if (actionParams == null) {+ return false;+ }++ const { offset, len, tableId, cursor } = actionParams;++ const rawActions: JSONXActions = [];++ const textRanges: ITextRangeWithStyle[] = [{+ startOffset: cursor,+ endOffset: cursor,+ collapsed: true,+ }];++ const doMutation: IMutationInfo<IRichTextEditingMutationParams> = {+ id: RichTextEditingMutation.id,+ params: {+ unitId,+ actions: [],+ textRanges,+ },+ };++ if (offset > 0) {+ textX.push({+ t: TextXActionType.RETAIN,+ len: offset,+ segmentId,+ });+ }++ textX.push({+ t: TextXActionType.DELETE,+ len,+ line: 0,+ segmentId,+ });++ const path = getRichTextEditPath(docDataModel, segmentId);+ rawActions.push(jsonX.editOp(textX.serialize(), path)!);++ // Step 3: delete table;++ const action = jsonX.removeOp(['tableSource', tableId]);+ rawActions.push(action!);++ doMutation.params.actions = rawActions.reduce((acc, cur) => {+ return JSONX.compose(acc, cur as JSONXActions);+ }, null as JSONXActions);++ const result = commandService.syncExecuteCommand<+ IRichTextEditingMutationParams,+ IRichTextEditingMutationParams+ >(doMutation.id, doMutation.params);++ return Boolean(result);+ },+};diff --git a/packages/docs/src/commands/commands/table/doc-table-insert.command.ts b/packages/docs/src/commands/commands/table/doc-table-insert.command.tsnew file mode 100644index 0000000000..254e875e48--- /dev/null+++ b/packages/docs/src/commands/commands/table/doc-table-insert.command.ts@@ -0,0 +1,331 @@+/**+ * 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, JSONXActions } from '@univerjs/core';+import { CommandType, ICommandService, IUniverInstanceService, JSONX, TextX, TextXActionType } from '@univerjs/core';+import type { IRichTextEditingMutationParams } from '@univerjs/docs';+import { getCommandSkeleton, getRichTextEditPath, RichTextEditingMutation, TextSelectionManagerService } from '@univerjs/docs';+import type { ITextRangeWithStyle } from '@univerjs/engine-render';+import { getColumnWidths, getEmptyTableCell, getEmptyTableRow, getInsertColumnActionsParams, getInsertColumnBody, getInsertRowActionsParams, getInsertRowBody, getRangeInfoFromRanges, getTableColumn, INSERT_COLUMN_POSITION, INSERT_ROW_POSITION } from './table';++// Insert rows and columns are in this file.++export const DocTableInsertRowCommandId = 'doc.command.table-insert-row';++export const DocTableInsertColumnCommandId = 'doc.command.table-insert-column';++export const DocTableInsertRowAboveCommandId = 'doc.command.table-insert-row-above';++export const DocTableInsertRowBellowCommandId = 'doc.command.table-insert-row-bellow';++export const DocTableInsertColumnLeftCommandId = 'doc.command.table-insert-column-left';++export const DocTableInsertColumnRightCommandId = 'doc.command.table-insert-column-right';++export interface IDocTableInsertRowAboveCommandParams {}++export const DocTableInsertRowAboveCommand: ICommand<IDocTableInsertRowAboveCommandParams> = {+ id: DocTableInsertRowAboveCommandId,+ type: CommandType.COMMAND,+ handler: async (accessor) => {+ const commandService = accessor.get(ICommandService);++ return commandService.executeCommand(DocTableInsertRowCommandId, { position: INSERT_ROW_POSITION.ABOVE });+ },+};++export interface IDocTableInsertRowBellowCommandParams {}++export const DocTableInsertRowBellowCommand: ICommand<IDocTableInsertRowBellowCommandParams> = {+ id: DocTableInsertRowBellowCommandId,+ type: CommandType.COMMAND,+ handler: async (accessor) => {+ const commandService = accessor.get(ICommandService);++ return commandService.executeCommand(DocTableInsertRowCommandId, { position: INSERT_ROW_POSITION.BELLOW });+ },+};++export interface IDocTableInsertColumnLeftCommandParams {}++export const DocTableInsertColumnLeftCommand: ICommand<IDocTableInsertColumnLeftCommandParams> = {+ id: DocTableInsertColumnLeftCommandId,+ type: CommandType.COMMAND,+ handler: async (accessor) => {+ const commandService = accessor.get(ICommandService);++ return commandService.executeCommand(DocTableInsertColumnCommandId, { position: INSERT_COLUMN_POSITION.LEFT });+ },+};++export interface IDocTableInsertColumnRightCommandParams {}++export const DocTableInsertColumnRightCommand: ICommand<IDocTableInsertColumnRightCommandParams> = {+ id: DocTableInsertColumnRightCommandId,+ type: CommandType.COMMAND,+ handler: async (accessor) => {+ const commandService = accessor.get(ICommandService);++ return commandService.executeCommand(DocTableInsertColumnCommandId, { position: INSERT_COLUMN_POSITION.RIGHT });+ },+};++export interface IDocTableInsertRowCommandParams {+ position: INSERT_ROW_POSITION;+}+/**+ * The command to insert table row.+ */+export const DocTableInsertRowCommand: ICommand<IDocTableInsertRowCommandParams> = {+ id: DocTableInsertRowCommandId,+ type: CommandType.COMMAND,++ // eslint-disable-next-line max-lines-per-function+ handler: async (accessor, params: IDocTableInsertRowCommandParams) => {+ const { position } = params;+ const textSelectionManagerService = accessor.get(TextSelectionManagerService);+ const univerInstanceService = accessor.get(IUniverInstanceService);+ const commandService = accessor.get(ICommandService);++ const activeRectRanges = textSelectionManagerService.getCurrentRectRanges();+ const activeTextRange = textSelectionManagerService.getActiveTextRange();++ const rangeInfo = getRangeInfoFromRanges(activeTextRange, activeRectRanges);++ if (rangeInfo == null) {+ return false;+ }++ const { segmentId } = rangeInfo;++ const docDataModel = univerInstanceService.getCurrentUniverDocInstance();+ const body = docDataModel?.getSelfOrHeaderFooterModel(segmentId).getBody();++ if (docDataModel == null || body == null) {+ return false;+ }+ const docSkeletonManagerService = getCommandSkeleton(accessor, docDataModel.getUnitId());++ if (docSkeletonManagerService == null) {+ return false;+ }++ const viewModel = docSkeletonManagerService.getViewModel();+ const unitId = docDataModel?.getUnitId();+ const textX = new TextX();+ const jsonX = JSONX.getInstance();++ const actionParams = getInsertRowActionsParams(rangeInfo, position, viewModel);++ if (actionParams == null) {+ return false;+ }++ const { offset, colCount, tableId, insertRowIndex } = actionParams;++ const rawActions: JSONXActions = [];++ const cursor = offset + 2;++ const textRanges: ITextRangeWithStyle[] = [{+ startOffset: cursor,+ endOffset: cursor,+ collapsed: true,+ }];++ const doMutation: IMutationInfo<IRichTextEditingMutationParams> = {+ id: RichTextEditingMutation.id,+ params: {+ unitId,+ actions: [],+ textRanges,+ },+ };++ if (offset > 0) {+ textX.push({+ t: TextXActionType.RETAIN,+ len: offset,+ segmentId,+ });+ }++ const insertBody = getInsertRowBody(colCount);++ textX.push({+ t: TextXActionType.INSERT,+ body: insertBody,+ len: insertBody.dataStream.length,+ line: 0,+ segmentId,+ });++ const path = getRichTextEditPath(docDataModel, segmentId);+ rawActions.push(jsonX.editOp(textX.serialize(), path)!);++ // Step 3: Insert table row;+ const insertRow = getEmptyTableRow(colCount);+ const insertTableSource = jsonX.insertOp(['tableSource', tableId, 'tableRows', insertRowIndex], insertRow);+ rawActions.push(insertTableSource!);++ doMutation.params.actions = rawActions.reduce((acc, cur) => {+ return JSONX.compose(acc, cur as JSONXActions);+ }, null as JSONXActions);++ const result = commandService.syncExecuteCommand<+ IRichTextEditingMutationParams,+ IRichTextEditingMutationParams+ >(doMutation.id, doMutation.params);++ return Boolean(result);+ },+};++export interface IDocTableInsertColumnCommandParams {+ position: INSERT_COLUMN_POSITION;+}+/**+ * The command to insert table column.+ */+export const DocTableInsertColumnCommand: ICommand<IDocTableInsertColumnCommandParams> = {+ id: DocTableInsertColumnCommandId,+ type: CommandType.COMMAND,++ // eslint-disable-next-line max-lines-per-function+ handler: async (accessor, params: IDocTableInsertColumnCommandParams) => {+ const { position } = params;+ const textSelectionManagerService = accessor.get(TextSelectionManagerService);+ const univerInstanceService = accessor.get(IUniverInstanceService);+ const commandService = accessor.get(ICommandService);++ const activeRectRanges = textSelectionManagerService.getCurrentRectRanges();+ const activeTextRange = textSelectionManagerService.getActiveTextRange();++ const rangeInfo = getRangeInfoFromRanges(activeTextRange, activeRectRanges);++ if (rangeInfo == null) {+ return false;+ }++ const { segmentId } = rangeInfo;++ const docDataModel = univerInstanceService.getCurrentUniverDocInstance();+ const body = docDataModel?.getSelfOrHeaderFooterModel(segmentId).getBody();++ if (docDataModel == null || body == null) {+ return false;+ }+ const docSkeletonManagerService = getCommandSkeleton(accessor, docDataModel.getUnitId());++ if (docSkeletonManagerService == null) {+ return false;+ }++ const viewModel = docSkeletonManagerService.getViewModel();+ const unitId = docDataModel?.getUnitId();+ const textX = new TextX();+ const jsonX = JSONX.getInstance();++ const actionParams = getInsertColumnActionsParams(rangeInfo, position, viewModel);++ if (actionParams == null) {+ return false;+ }++ const { offsets, columnIndex, tableId, rowCount } = actionParams;++ const rawActions: JSONXActions = [];++ const cursor = offsets[0] + 1;++ const textRanges: ITextRangeWithStyle[] = [{+ startOffset: cursor,+ endOffset: cursor,+ collapsed: true,+ }];++ const doMutation: IMutationInfo<IRichTextEditingMutationParams> = {+ id: RichTextEditingMutation.id,+ params: {+ unitId,+ actions: [],+ textRanges,+ },+ };++ for (const offset of offsets) {+ textX.push({+ t: TextXActionType.RETAIN,+ len: offset,+ segmentId,+ });++ const insertBody = getInsertColumnBody();++ textX.push({+ t: TextXActionType.INSERT,+ body: insertBody,+ len: insertBody.dataStream.length,+ line: 0,+ segmentId,+ });+ }++ const path = getRichTextEditPath(docDataModel, segmentId);+ rawActions.push(jsonX.editOp(textX.serialize(), path)!);++ // Step 3: Insert table cell;+ for (let i = 0; i < rowCount; i++) {+ const insertCell = getEmptyTableCell();+ const insertTableSource = jsonX.insertOp(['tableSource', tableId, 'tableRows', i, 'tableCells', columnIndex], insertCell);+ rawActions.push(insertTableSource!);+ }++ const snapshot = docDataModel.getSnapshot();++ const documentStyle = snapshot.documentStyle;++ const { marginLeft = 0, marginRight = 0 } = documentStyle;++ const pageWidth = (documentStyle.pageSize?.width ?? 800) - marginLeft - marginRight;++ // eslint-disable-next-line ts/no-non-null-asserted-optional-chain+ const tableColumns = snapshot?.tableSource?.[tableId].tableColumns!;++ const { newColWidth, widths } = getColumnWidths(pageWidth, tableColumns, columnIndex);++ // Update pre columns width.+ for (let i = 0; i < widths.length; i++) {+ const action = jsonX.replaceOp(['tableSource', tableId, 'tableColumns', i, 'size', 'width', 'v'], tableColumns[i].size.width.v, widths[i]);+ rawActions.push(action!);+ }++ const insertCol = getTableColumn(newColWidth);+ const insertTableColumn = jsonX.insertOp(['tableSource', tableId, 'tableColumns', columnIndex], insertCol);+ rawActions.push(insertTableColumn!);++ doMutation.params.actions = rawActions.reduce((acc, cur) => {+ return JSONX.compose(acc, cur as JSONXActions);+ }, null as JSONXActions);++ const result = commandService.syncExecuteCommand<+ IRichTextEditingMutationParams,+ IRichTextEditingMutationParams+ >(doMutation.id, doMutation.params);++ return Boolean(result);+ },+};diff --git a/packages/docs/src/commands/commands/table/doc-table-tab.command.ts b/packages/docs/src/commands/commands/table/doc-table-tab.command.tsnew file mode 100644index 0000000000..96a7dbf6e5--- /dev/null+++ b/packages/docs/src/commands/commands/table/doc-table-tab.command.ts@@ -0,0 +1,42 @@+/**+ * 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 } from '@univerjs/core';+import { CommandType } from '@univerjs/core';++export interface IDocTableTabCommandParams {}++export const DocTableTabCommand: ICommand<IDocTableTabCommandParams> = {+ id: 'doc.table.tab-in-table',+ type: CommandType.COMMAND,++ handler: async () => {+ // TODO: implement tab in table+ return true;+ },+};++export interface IDocTableShiftTabCommandParams {}++export const DocTableShiftTabCommand: ICommand<IDocTableShiftTabCommandParams> = {+ id: 'doc.table.shift-tab-in-table',+ type: CommandType.COMMAND,++ handler: async () => {+ // TODO: implement tab in table+ return true;+ },+};diff --git a/packages/docs/src/commands/commands/table/table.ts b/packages/docs/src/commands/commands/table/table.tsnew file mode 100644index 0000000000..450b765290--- /dev/null+++ b/packages/docs/src/commands/commands/table/table.ts@@ -0,0 +1,687 @@+/**+ * 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, ISectionBreak, ITable, ITableCell, ITableColumn, ITableRow, Nullable } from '@univerjs/core';+import { DataStreamTreeTokenType, generateRandomId, ObjectRelativeFromH, ObjectRelativeFromV, TableAlignmentType, TableCellHeightRule, TableSizeType, TableTextWrapType, Tools } from '@univerjs/core';+import type { DataStreamTreeNode, DocumentViewModel, RectRange, TextRange } from '@univerjs/engine-render';++export enum INSERT_ROW_POSITION {+ ABOVE,+ BELLOW,+}++export enum INSERT_COLUMN_POSITION {+ LEFT,+ RIGHT,+}++export function genEmptyTable(rowCount: number, colCount: number) {+ let dataStream: string = DataStreamTreeTokenType.TABLE_START;+ const paragraphs: IParagraph[] = [];+ const sectionBreaks: ISectionBreak[] = [];++ for (let i = 0; i < rowCount; i++) {+ dataStream += DataStreamTreeTokenType.TABLE_ROW_START;++ for (let j = 0; j < colCount; j++) {+ dataStream += `${DataStreamTreeTokenType.TABLE_CELL_START}\r\n${DataStreamTreeTokenType.TABLE_CELL_END}`;+ paragraphs.push({+ startIndex: dataStream.length - 3,+ paragraphStyle: {+ spaceAbove: { v: 3 },+ lineSpacing: 2,+ spaceBelow: { v: 0 },+ },+ });+ sectionBreaks.push({+ startIndex: dataStream.length - 2,+ });+ }++ dataStream += DataStreamTreeTokenType.TABLE_ROW_END;+ }++ dataStream += DataStreamTreeTokenType.TABLE_END;++ return {+ dataStream,+ paragraphs,+ sectionBreaks,+ };+}++export function getEmptyTableCell() {+ const tableCell: ITableCell = {+ margin: {+ start: {+ v: 10,+ },+ end: {+ v: 10,+ },+ top: {+ v: 5,+ },+ bottom: {+ v: 5,+ },+ },+ };++ return tableCell;+}++export function getEmptyTableRow(col: number) {+ const tableCell = getEmptyTableCell();+ const tableRow: ITableRow = {+ tableCells: [...new Array(col).fill(null).map(() => Tools.deepClone(tableCell))],+ trHeight: {+ val: { v: 30 },+ hRule: TableCellHeightRule.AUTO,+ },+ };++ return tableRow;+}++export function getTableColumn(width: number) {+ const tableColumn: ITableColumn = {+ size: {+ type: TableSizeType.SPECIFIED,+ width: {+ v: width,+ },+ },+ };++ return tableColumn;+}++export function genTableSource(rowCount: number, colCount: number, pageContentWidth: number) {+ const tableColumn: ITableColumn = getTableColumn(pageContentWidth / colCount);+ const tableRow = getEmptyTableRow(colCount);+ const tableRows = [...new Array(rowCount).fill(null).map(() => Tools.deepClone(tableRow))];+ const tableColumns = [...new Array(colCount).fill(null).map(() => Tools.deepClone(tableColumn))];+ const tableId = generateRandomId(6);+ const table: ITable = {+ tableRows,+ tableColumns,+ tableId,+ align: TableAlignmentType.START,+ indent: {+ v: 0,+ },+ textWrap: TableTextWrapType.NONE,+ position: {+ positionH: {+ relativeFrom: ObjectRelativeFromH.PAGE,+ posOffset: 0,+ },+ positionV: {+ relativeFrom: ObjectRelativeFromV.PAGE,+ posOffset: 0,+ },+ },+ dist: {+ distB: 0,+ distL: 0,+ distR: 0,+ distT: 0,+ },+ cellMargin: {+ start: {+ v: 10,+ },+ end: {+ v: 10,+ },+ top: {+ v: 5,+ },+ bottom: {+ v: 5,+ },+ },+ size: {+ type: TableSizeType.UNSPECIFIED,+ width: {+ v: pageContentWidth,+ },+ },+ };++ return table;+}++interface IRangeInfo {+ startOffset: number;+ endOffset: number;+ segmentId: string;+}++export function getRangeInfoFromRanges(textRange: Nullable<TextRange>, rectRanges: Readonly<Nullable<RectRange[]>>): Nullable<IRangeInfo> {+ if (!textRange && !rectRanges) {+ return null;+ }++ if (rectRanges && rectRanges.length > 0) {+ let startOffset = Number.POSITIVE_INFINITY;+ let endOffset = Number.NEGATIVE_INFINITY;+ const segmentId = '';++ for (const rectRange of rectRanges) {+ const { startOffset: st, endOffset: ed, segmentId: sid } = rectRange;++ if (st == null || ed == null || sid == null) {+ continue;+ }+ startOffset = Math.min(startOffset, st);+ endOffset = Math.max(endOffset, ed);+ }++ if (Number.isFinite(startOffset) && Number.isFinite(endOffset)) {+ return {+ startOffset,+ endOffset,+ segmentId,+ };+ }+ } else if (textRange) {+ const { startOffset, endOffset, segmentId } = textRange;+ if (startOffset == null || endOffset == null || segmentId == null) {+ return null;+ }++ return {+ startOffset,+ endOffset,+ segmentId,+ };+ }+}++export function getInsertRowBody(col: number) {+ let dataStream: string = DataStreamTreeTokenType.TABLE_ROW_START;+ const paragraphs: IParagraph[] = [];+ const sectionBreaks: ISectionBreak[] = [];++ for (let i = 0; i < col; i++) {+ dataStream += `${DataStreamTreeTokenType.TABLE_CELL_START}\r\n${DataStreamTreeTokenType.TABLE_CELL_END}`;+ paragraphs.push({+ startIndex: dataStream.length - 2,+ paragraphStyle: {+ spaceAbove: { v: 3 },+ lineSpacing: 2,+ spaceBelow: { v: 0 },+ },+ });+ sectionBreaks.push({+ startIndex: dataStream.length - 1,+ });+ }++ dataStream += DataStreamTreeTokenType.TABLE_ROW_END;++ return {+ dataStream,+ paragraphs,+ sectionBreaks,+ };+}++export function getInsertColumnBody() {+ const dataStream = `${DataStreamTreeTokenType.TABLE_CELL_START}\r\n${DataStreamTreeTokenType.TABLE_CELL_END}`;+ const paragraphs: IParagraph[] = [];+ const sectionBreaks: ISectionBreak[] = [];++ paragraphs.push({+ startIndex: 1,+ paragraphStyle: {+ spaceAbove: { v: 3 },+ lineSpacing: 2,+ spaceBelow: { v: 0 },+ },+ });+ sectionBreaks.push({+ startIndex: 2,+ });++ return {+ dataStream,+ paragraphs,+ sectionBreaks,+ };+}++export function getInsertRowActionsParams(rangeInfo: IRangeInfo, position: INSERT_ROW_POSITION, viewModel: DocumentViewModel) {+ const { startOffset, endOffset, segmentId } = rangeInfo;+ const vm = viewModel.getSelfOrHeaderFooterViewModel(segmentId);+ const index = position === INSERT_ROW_POSITION.ABOVE ? startOffset : endOffset;++ let tableRow = null;+ const tableId = viewModel.getBody()?.tables?.find((t) => index >= t.startIndex && index <= t.endIndex)?.tableId;+ let rowIndex = 0;++ // TODO: handle nested tables+ for (const section of vm.children) {+ for (const paragraph of section.children) {+ const { children } = paragraph;+ const table = children[0];++ if (table) {+ for (const row of table.children) {+ if (row.startIndex <= index && index <= row.endIndex) {+ rowIndex = table.children.indexOf(row);+ tableRow = row;+ break;+ }+ }+ }++ if (tableRow) {+ break;+ }+ }++ if (tableRow) {+ break;+ }+ }++ if (tableRow == null || tableId == null) {+ return null;+ }++ return {+ offset: position === INSERT_ROW_POSITION.ABOVE ? tableRow.startIndex : tableRow.endIndex + 1,+ colCount: tableRow.children.length,+ tableId,+ insertRowIndex: position === INSERT_ROW_POSITION.ABOVE ? rowIndex : rowIndex + 1,+ };+}++export function getInsertColumnActionsParams(rangeInfo: IRangeInfo, position: INSERT_COLUMN_POSITION, viewModel: DocumentViewModel) {+ const { startOffset, endOffset, segmentId } = rangeInfo;+ const vm = viewModel.getSelfOrHeaderFooterViewModel(segmentId);+ const index = position === INSERT_COLUMN_POSITION.LEFT ? startOffset : endOffset;++ const tableId = viewModel.getBody()?.tables?.find((t) => index >= t.startIndex && index <= t.endIndex)?.tableId;+ const offsets: number[] = [];+ let table: Nullable<DataStreamTreeNode> = null;+ let columnIndex = -1;++ for (const section of vm.children) {+ for (const paragraph of section.children) {+ const { children } = paragraph;+ const tableNode = children[0];++ if (tableNode) {+ if (index < tableNode.startIndex || index > tableNode.endIndex) {+ continue;+ }++ table = tableNode;++ for (const row of tableNode.children) {+ for (const cell of row.children) {+ const cellIndex = row.children.indexOf(cell);++ if (index >= cell.startIndex && index <= cell.endIndex) {+ columnIndex = position === INSERT_COLUMN_POSITION.LEFT ? cellIndex : cellIndex + 1;+ break;+ }+ }++ if (columnIndex !== -1) {+ break;+ }+ }+ }++ if (table) {+ break;+ }+ }++ if (table) {+ break;+ }+ }++ if (table == null || tableId == null || columnIndex === -1) {+ return null;+ }++ let cursor = 0;++ for (const row of table.children) {+ const cell = row.children[columnIndex];+ offsets.push(cell.startIndex - cursor);++ cursor = cell.startIndex;+ }++ return {+ offsets,+ tableId,+ columnIndex,+ rowCount: table.children.length,+ };+}++export function getColumnWidths(pageWidth: number, tableColumns: ITableColumn[], insertColumnIndex: number) {+ const widths: number[] = [];+ let newColWidth = tableColumns[insertColumnIndex].size.width.v;+ let totalWidth = 0;++ for (let i = 0; i < tableColumns.length; i++) {+ totalWidth += tableColumns[i].size.width.v;+ }++ totalWidth += newColWidth;++ for (let i = 0; i < tableColumns.length; i++) {+ widths.push((tableColumns[i].size.width.v / totalWidth) * pageWidth);+ }++ newColWidth = (newColWidth / totalWidth) * pageWidth;++ return {+ widths,+ newColWidth,+ };+}++export function getDeleteRowsActionsParams(rangeInfo: IRangeInfo, viewModel: DocumentViewModel) {+ const { startOffset, endOffset, segmentId } = rangeInfo;+ const vm = viewModel.getSelfOrHeaderFooterViewModel(segmentId);+ const tableId = viewModel.getBody()?.tables?.find((t) => startOffset >= t.startIndex && endOffset <= t.endIndex)?.tableId;+ const rowIndexes: number[] = [];+ let offset = -1;+ let len = 0;+ let cursor = -1;+ let selectWholeTable = false;++ for (const section of vm.children) {+ for (const paragraph of section.children) {+ const { children } = paragraph;+ const table = children[0];++ if (table) {+ if (startOffset < table.startIndex || endOffset > table.endIndex) {+ continue;+ }++ cursor = table.startIndex + 3;++ for (const row of table.children) {+ const rowIndex = table.children.indexOf(row);+ const { startIndex, endIndex } = row;++ if (startOffset >= startIndex && startOffset <= endIndex) {+ offset = startIndex;+ rowIndexes.push(rowIndex);+ len += endIndex - startIndex + 1;+ } else if (startIndex > startOffset && endIndex < endOffset) {+ rowIndexes.push(rowIndex);+ len += endIndex - startIndex + 1;+ } else if (endOffset >= startIndex && endOffset <= endIndex) {+ rowIndexes.push(rowIndex);+ len += endIndex - startIndex + 1;+ }++ if (rowIndexes.length === table.children.length) {+ selectWholeTable = true;+ }+ }+ }++ if (rowIndexes.length) {+ break;+ }+ }++ if (rowIndexes.length) {+ break;+ }+ }++ if (tableId == null || rowIndexes.length === 0) {+ return null;+ }++ return {+ tableId,+ rowIndexes,+ offset,+ len,+ cursor,+ selectWholeTable,+ };+}++interface IRetainDeleteOffset {+ retain: number;+ delete: number;+}++// eslint-disable-next-line max-lines-per-function+export function getDeleteColumnsActionParams(rangeInfo: IRangeInfo, viewModel: DocumentViewModel) {+ const { startOffset, endOffset, segmentId } = rangeInfo;+ const vm = viewModel.getSelfOrHeaderFooterViewModel(segmentId);++ const tableId = viewModel.getBody()?.tables?.find((t) => startOffset >= t.startIndex && endOffset <= t.endIndex)?.tableId;+ const offsets: IRetainDeleteOffset[] = [];+ let table: Nullable<DataStreamTreeNode> = null;+ const columnIndexes: number[] = [];+ let cursor = -1;+ let startColumnIndex = -1;+ let endColumnIndex = -1;++ for (const section of vm.children) {+ for (const paragraph of section.children) {+ const { children } = paragraph;+ const tableNode = children[0];++ if (tableNode) {+ if (startOffset < tableNode.startIndex || endOffset > tableNode.endIndex) {+ continue;+ }++ table = tableNode;++ for (const row of tableNode.children) {+ for (const cell of row.children) {+ const cellIndex = row.children.indexOf(cell);++ if (startOffset >= cell.startIndex && startOffset <= cell.endIndex) {+ startColumnIndex = cellIndex;+ }++ if (endOffset >= cell.startIndex && endOffset <= cell.endIndex) {+ endColumnIndex = cellIndex;+ }+ }+ }+ }++ if (table) {+ break;+ }+ }++ if (table) {+ break;+ }+ }++ if (table == null || tableId == null) {+ return null;+ }++ for (let i = startColumnIndex; i <= endColumnIndex; i++) {+ columnIndexes.push(i);+ }++ let delta = 0;+ for (const row of table.children) {+ const startCell = row.children[startColumnIndex];+ const endCell = row.children[endColumnIndex];++ offsets.push({+ retain: startCell.startIndex - delta,+ delete: endCell.endIndex - startCell.startIndex + 1,+ });++ delta = endCell.endIndex + 1;+ }++ cursor = table.startIndex + 3;++ return {+ offsets,+ tableId,+ columnIndexes,+ cursor,+ selectWholeTable: columnIndexes.length === table.children[0].children.length,+ rowCount: table.children.length,+ };+}++export function getDeleteTableActionParams(rangeInfo: IRangeInfo, viewModel: DocumentViewModel) {+ const { startOffset, endOffset, segmentId } = rangeInfo;+ const vm = viewModel.getSelfOrHeaderFooterViewModel(segmentId);++ const tableId = viewModel.getBody()?.tables?.find((t) => startOffset >= t.startIndex && endOffset <= t.endIndex)?.tableId;+ let offset = -1;+ let len = 0;+ let cursor = -1;++ for (const section of vm.children) {+ for (const paragraph of section.children) {+ const { children } = paragraph;+ const table = children[0];++ if (table) {+ if (startOffset < table.startIndex || endOffset > table.endIndex) {+ continue;+ }++ offset = table.startIndex;+ len = table.endIndex - table.startIndex + 1;+ cursor = table.startIndex;+ }++ if (table) {+ break;+ }+ }++ if (len > 0) {+ break;+ }+ }++ if (tableId == null) {+ return null;+ }++ return {+ tableId,+ offset,+ len,+ cursor,+ };+}++export function getDeleteRowContentActionParams(rangeInfo: IRangeInfo, viewModel: DocumentViewModel) {+ const { startOffset, endOffset, segmentId } = rangeInfo;+ const vm = viewModel.getSelfOrHeaderFooterViewModel(segmentId);++ const tableId = viewModel.getBody()?.tables?.find((t) => startOffset >= t.startIndex && endOffset <= t.endIndex)?.tableId;+ const offsets: IRetainDeleteOffset[] = [];+ let table: Nullable<DataStreamTreeNode> = null;++ let cursor = -1;+ let rowIndex = -1;+ let startColumnIndex = -1;+ let endColumnIndex = -1;++ for (const section of vm.children) {+ for (const paragraph of section.children) {+ const { children } = paragraph;+ const tableNode = children[0];++ if (tableNode) {+ if (startOffset < tableNode.startIndex || endOffset > tableNode.endIndex) {+ continue;+ }++ table = tableNode;++ for (const row of tableNode.children) {+ const rIndex = tableNode.children.indexOf(row);++ for (const cell of row.children) {+ const cellIndex = row.children.indexOf(cell);++ if (startOffset >= cell.startIndex && startOffset <= cell.endIndex) {+ rowIndex = rIndex;+ startColumnIndex = cellIndex;+ }++ if (endOffset >= cell.startIndex && endOffset <= cell.endIndex) {+ // StartOffset and endOffset are in the same row.+ endColumnIndex = cellIndex;+ }+ }+ }+ }++ if (table) {+ break;+ }+ }++ if (table) {+ break;+ }+ }++ if (table == null || tableId == null || rowIndex === -1) {+ return null;+ }++ const row = table.children[rowIndex];++ for (let i = startColumnIndex; i <= endColumnIndex; i++) {+ const cell = row.children[i];++ offsets.push({+ retain: cell.startIndex + 1,+ delete: cell.endIndex - cell.startIndex - 3,+ });+ }++ cursor = table.startIndex + 3;++ return {+ offsets,+ tableId,+ cursor,+ rowCount: table.children.length,+ };+}diff --git a/packages/docs/src/commands/mutations/core-editing.mutation.ts b/packages/docs/src/commands/mutations/core-editing.mutation.tsindex 02fa779936..332aefeccb 100644--- a/packages/docs/src/commands/mutations/core-editing.mutation.ts+++ b/packages/docs/src/commands/mutations/core-editing.mutation.ts@@ -17,7 +17,7 @@import { CommandType, IUniverInstanceService, JSONX } from '@univerjs/core';import type { IMutation, IMutationCommonParams, JSONXActions, Nullable } from '@univerjs/core';import { IRenderManagerService, type ITextRangeWithStyle } from '@univerjs/engine-render';-import { serializeTextRange, TextSelectionManagerService } from '../../services/text-selection-manager.service';+import { serializeDocRange, TextSelectionManagerService } from '../../services/text-selection-manager.service';import type { IDocStateChangeParams } from '../../services/doc-state-change-manager.service';import { DocStateChangeManagerService } from '../../services/doc-state-change-manager.service';import { IMEInputManagerService } from '../../services/ime-input-manager.service';@@ -72,9 +72,10 @@ export const RichTextEditingMutation: IMutation<IRichTextEditingMutationParams,}const textSelectionManagerService = accessor.get(TextSelectionManagerService);- const selections = textSelectionManagerService.getCurrentSelections() ?? [];+ const selections = textSelectionManagerService.getCurrentTextRanges() ?? [];+ const rectRanges = textSelectionManagerService.getCurrentRectRanges() ?? [];- const serializedSelections = selections.map(serializeTextRange);+ const serializedSelections = [...selections, ...rectRanges].map(serializeDocRange);const docStateChangeManagerService = accessor.get(DocStateChangeManagerService);@@ -95,10 +96,7 @@ export const RichTextEditingMutation: IMutation<IRichTextEditingMutationParams,// Step 1: Update Doc Data Model.const undoActions = JSONX.invertWithDoc(actions, documentDataModel.getSnapshot());- // console.log('undoActions', undoActions);documentDataModel.apply(actions);- // console.log('===redoActions', { actions, undoActions, noHistory });- // console.log('===body', documentDataModel);// Step 2: Update Doc View Model.documentViewModel.reset(documentDataModel);diff --git a/packages/docs/src/commands/operations/select-all.operation.ts b/packages/docs/src/commands/operations/select-all.operation.tsindex 59486a438a..f796b524b1 100644--- a/packages/docs/src/commands/operations/select-all.operation.ts+++ b/packages/docs/src/commands/operations/select-all.operation.ts@@ -28,7 +28,7 @@ export const SelectAllOperation: ICommand<ISelectAllOperationParams> = {const univerInstanceService = accessor.get(IUniverInstanceService);const textSelectionManagerService = accessor.get(TextSelectionManagerService);const docDataModel = univerInstanceService.getCurrentUniverDocInstance();- const activeTextRange = textSelectionManagerService.getActiveRange();+ const activeTextRange = textSelectionManagerService.getActiveTextRangeWithStyle();if (docDataModel == null || activeTextRange == null) {return false;}diff --git a/packages/docs/src/controllers/ime-input.controller.ts b/packages/docs/src/controllers/ime-input.controller.tsindex aa097756c7..558cab87d1 100644--- a/packages/docs/src/controllers/ime-input.controller.ts+++ b/packages/docs/src/controllers/ime-input.controller.ts@@ -31,6 +31,7 @@ import type { Subscription } from 'rxjs';import { IMEInputCommand } from '../commands/commands/ime-input.command';import { DocSkeletonManagerService } from '../services/doc-skeleton-manager.service';import { IMEInputManagerService } from '../services/ime-input-manager.service';+import { TextSelectionManagerService } from '../services/text-selection-manager.service';@OnLifecycle(LifecycleStages.Rendered, IMEInputController)export class IMEInputController extends Disposable {@@ -48,6 +49,7 @@ export class IMEInputController extends Disposable {@IUniverInstanceService private readonly _univerInstanceService: IUniverInstanceService,@IRenderManagerService private readonly _renderManagerSrv: IRenderManagerService,@ITextSelectionRenderManager private readonly _textSelectionRenderManager: ITextSelectionRenderManager,+ @Inject(TextSelectionManagerService) private readonly _textSelectionManagerService: TextSelectionManagerService,@Inject(IMEInputManagerService) private readonly _imeInputManagerService: IMEInputManagerService,@ICommandService private readonly _commandService: ICommandService) {diff --git a/packages/docs/src/controllers/move-cursor.controller.ts b/packages/docs/src/controllers/move-cursor.controller.tsindex 553d78f099..6e508331c2 100644--- a/packages/docs/src/controllers/move-cursor.controller.ts+++ b/packages/docs/src/controllers/move-cursor.controller.ts@@ -27,12 +27,15 @@ import {} from '@univerjs/core';import type {DocumentSkeleton,+ IDocumentSkeletonCached,IDocumentSkeletonGlyph,IDocumentSkeletonLine,+ IDocumentSkeletonPage,+ IDocumentSkeletonTable,INodePosition,INodeSearch,} from '@univerjs/engine-render';-import { IRenderManagerService, NodePositionConvertToCursor, RANGE_DIRECTION } from '@univerjs/engine-render';+import { DocumentSkeletonPageType, IRenderManagerService, NodePositionConvertToCursor, RANGE_DIRECTION } from '@univerjs/engine-render';import type { Subscription } from 'rxjs';import { getDocObject } from '../basics/component-tools';@@ -40,6 +43,7 @@ import type { IMoveCursorOperationParams } from '../commands/operations/cursor.oimport { MoveCursorOperation, MoveSelectionOperation } from '../commands/operations/cursor.operation';import { DocSkeletonManagerService } from '../services/doc-skeleton-manager.service';import { TextSelectionManagerService } from '../services/text-selection-manager.service';+import { findAboveCell, findBellowCell, findLineBeforeAndAfterTable, findTableAfterLine, findTableBeforeLine, firstLineInCell, firstLineInTable, lastLineInCell, lastLineInTable } from '../basics/table';@OnLifecycle(LifecycleStages.Rendered, MoveCursorController)export class MoveCursorController extends Disposable {@@ -92,10 +96,10 @@ export class MoveCursorController extends Disposable {// eslint-disable-next-line max-lines-per-function, complexityprivate _handleShiftMoveSelection(direction: Direction) {- const activeRange = this._textSelectionManagerService.getActiveRange();- const allRanges = this._textSelectionManagerService.getCurrentSelections()!;+ const activeRange = this._textSelectionManagerService.getActiveTextRangeWithStyle();+ const allRanges = this._textSelectionManagerService.getCurrentTextRanges()!;const docDataModel = this._univerInstanceService.getCurrentUniverDocInstance();- if (!docDataModel) {+ if (docDataModel == null) {return;}@@ -138,7 +142,11 @@ export class MoveCursorController extends Disposable {? startOffset: endOffset;- let focusOffset = collapsed ? endOffset : rangeDirection === RANGE_DIRECTION.FORWARD ? endOffset : startOffset;+ let focusOffset = collapsed+ ? endOffset+ : rangeDirection === RANGE_DIRECTION.FORWARD+ ? endOffset+ : startOffset;const dataStreamLength = docDataModel.getSelfOrHeaderFooterModel(segmentId).getBody()!.dataStream.length ?? Number.POSITIVE_INFINITY;if (direction === Direction.LEFT || direction === Direction.RIGHT) {@@ -162,7 +170,7 @@ export class MoveCursorController extends Disposable {const documentOffsetConfig = docObject.document.getOffsetConfig();const focusNodePosition = collapsed ? startNodePosition : rangeDirection === RANGE_DIRECTION.FORWARD ? endNodePosition : startNodePosition;- const newPos = this._getTopOrBottomPosition(skeleton, focusGlyph, focusNodePosition, direction === Direction.DOWN);+ const newPos = this._getTopOrBottomPosition(skeleton, focusGlyph, focusNodePosition, direction === Direction.DOWN, true);if (newPos == null) {// move selection@@ -201,24 +209,28 @@ export class MoveCursorController extends Disposable {// eslint-disable-next-line max-lines-per-function, complexityprivate _handleMoveCursor(direction: Direction) {- const activeRange = this._textSelectionManagerService.getActiveRange();- const allRanges = this._textSelectionManagerService.getCurrentSelections();+ const activeRange = this._textSelectionManagerService.getActiveTextRangeWithStyle();+ const allRanges = this._textSelectionManagerService.getCurrentTextRanges();const docDataModel = this._univerInstanceService.getCurrentUniverDocInstance();- if (!docDataModel) {+ if (docDataModel == null) {return false;}const skeleton = this._renderManagerService.getRenderById(docDataModel.getUnitId())?.with(DocSkeletonManagerService).getSkeleton();const docObject = this._getDocObject();- const body = docDataModel.getBody();- if (activeRange == null || skeleton == null || docObject == null || allRanges == null || body == null) {+ if (activeRange == null || skeleton == null || docObject == null || allRanges == null) {return;}const { startOffset, endOffset, style, collapsed, segmentId, startNodePosition, endNodePosition, segmentPage } = activeRange;+ const body = docDataModel.getSelfOrHeaderFooterModel(segmentId).getBody();- const dataStreamLength = docDataModel.getSelfOrHeaderFooterModel(segmentId).getBody()!.dataStream.length ?? Number.POSITIVE_INFINITY;+ if (body == null) {+ return;+ }++ const dataStreamLength = body.dataStream.length ?? Number.POSITIVE_INFINITY;const customRanges = docDataModel.getCustomRanges() ?? [];if (direction === Direction.LEFT || direction === Direction.RIGHT) {@@ -237,21 +249,32 @@ export class MoveCursorController extends Disposable {} else {const preSpan = skeleton.findNodeByCharIndex(startOffset - 1, segmentId, segmentPage);const curSpan = skeleton.findNodeByCharIndex(startOffset, segmentId, segmentPage)!;+ const nextGlyph = skeleton.findNodeByCharIndex(startOffset + 1, segmentId, segmentPage);if (direction === Direction.LEFT) {- cursor = Math.max(0, startOffset - (preSpan?.count ?? 0));+ cursor = Math.max(0, startOffset - (preSpan?.count ?? 1));} else {// -1 because the length of the string will be 1 larger than the index, and the reason for subtracting another 1 is because it ends in \n- cursor = Math.min(dataStreamLength - 2, endOffset + curSpan.count);+ cursor = Math.min(dataStreamLength - 2, endOffset + curSpan.count + (nextGlyph?.streamType === DataStreamTreeTokenType.SECTION_BREAK ? 1 : 0));}}- const skipTokens: string[] = [DataStreamTreeTokenType.CUSTOM_RANGE_START, DataStreamTreeTokenType.CUSTOM_RANGE_END];+ const skipTokens: string[] = [+ DataStreamTreeTokenType.CUSTOM_RANGE_START,+ DataStreamTreeTokenType.CUSTOM_RANGE_END,+ DataStreamTreeTokenType.TABLE_START,+ DataStreamTreeTokenType.TABLE_END,+ DataStreamTreeTokenType.TABLE_ROW_START,+ DataStreamTreeTokenType.TABLE_ROW_END,+ DataStreamTreeTokenType.TABLE_CELL_START,+ DataStreamTreeTokenType.TABLE_CELL_END,+ DataStreamTreeTokenType.SECTION_BREAK,+ ];if (direction === Direction.LEFT) {while (skipTokens.includes(body.dataStream[cursor])) {cursor--;}} else {- while (skipTokens.includes(body.dataStream[cursor - 1])) {+ while (skipTokens.includes(body.dataStream[cursor])) {cursor++;}}@@ -327,7 +350,8 @@ export class MoveCursorController extends Disposable {docSkeleton: DocumentSkeleton,glyph: Nullable<IDocumentSkeletonGlyph>,nodePosition: Nullable<INodePosition>,- direction: boolean+ direction: boolean,+ skipCellContent = false): Nullable<INodePosition> {if (glyph == null || nodePosition == null) {return;@@ -335,7 +359,7 @@ export class MoveCursorController extends Disposable {const offsetLeft = this._getGlyphLeftOffsetInLine(glyph);- const line = this._getNextOrPrevLine(glyph, direction);+ const line = this._getNextOrPrevLine(glyph, direction, skipCellContent);if (line == null) {return;@@ -377,6 +401,9 @@ export class MoveCursorController extends Disposable {const divideLeft = divide.left;for (const glyph of divide.glyphGroup) {+ if (glyph.streamType === DataStreamTreeTokenType.SECTION_BREAK) {+ continue;+ }const { left } = glyph;const leftSide = divideLeft + left;@@ -398,20 +425,15 @@ export class MoveCursorController extends Disposable {return docSkeleton.findPositionByGlyph(nearestNode.glyph, segmentPage);}- // eslint-disable-next-line max-lines-per-function- private _getNextOrPrevLine(glyph: IDocumentSkeletonGlyph, direction: boolean) {+ // eslint-disable-next-line max-lines-per-function, complexity+ private _getNextOrPrevLine(glyph: IDocumentSkeletonGlyph, direction: boolean, skipCellContent = false) {const divide = glyph.parent;- if (divide == null) {- return;- }-- const line = divide.parent;- if (line == null) {- return;- }+ const line = divide?.parent;+ const column = line?.parent;+ const section = column?.parent;+ const page = section?.parent;- const column = line.parent;- if (column == null) {+ if (divide == null || line == null || column == null || section == null || page == null) {return;}@@ -423,22 +445,40 @@ export class MoveCursorController extends Disposable {let newLine: IDocumentSkeletonLine;+ if (page.type === DocumentSkeletonPageType.CELL && skipCellContent) {+ const nLine = findAboveOrBellowCellLine(page, direction);++ if (nLine) {+ return nLine;+ }+ }+if (direction === true) {newLine = column.lines[currentLineIndex + 1];+ const tableAfterLine = findTableAfterLine(line, page);++ if (tableAfterLine) {+ const firstLine = firstLineInTable(tableAfterLine);+ if (firstLine) {+ newLine = firstLine;+ }+ }} else {newLine = column.lines[currentLineIndex - 1];+ // If the previous line is behind the table, find the last line of the table.+ const tableBeforeLine = findTableBeforeLine(line, page);+ if (tableBeforeLine) {+ const lastLine = lastLineInTable(tableBeforeLine);+ if (lastLine) {+ newLine = lastLine;+ }+ }}if (newLine != null) {return newLine;}- const section = column.parent;-- if (section == null) {- return;- }-const currentColumnIndex = section.columns.indexOf(column);if (currentColumnIndex === -1) {@@ -456,12 +496,6 @@ export class MoveCursorController extends Disposable {return newLine;}- const page = section.parent;-- if (page == null) {- return;- }-const currentSectionIndex = page.sections.indexOf(section);if (currentSectionIndex === -1) {@@ -481,7 +515,11 @@ export class MoveCursorController extends Disposable {return newLine;}- const skeleton = page.parent;+ if (page.type === DocumentSkeletonPageType.CELL) {+ return findAboveOrBellowCellLine(page, direction);+ }++ const skeleton: Nullable<IDocumentSkeletonCached> = page.parent as IDocumentSkeletonCached;if (skeleton == null) {return;@@ -515,3 +553,41 @@ export class MoveCursorController extends Disposable {return getDocObject(this._univerInstanceService, this._renderManagerService);}}++function findAboveOrBellowCellLine(+ page: IDocumentSkeletonPage,+ direction: boolean+) {+ let newLine = null;+ if (direction === true) {+ const bellowCell = findBellowCell(page);+ if (bellowCell) {+ newLine = firstLineInCell(bellowCell);+ } else {+ const table = page.parent?.parent as IDocumentSkeletonTable;+ const { lineAfterTable } = findLineBeforeAndAfterTable(table);++ if (lineAfterTable) {+ newLine = lineAfterTable;+ }+ }+ } else {+ const aboveCell = findAboveCell(page);+ if (aboveCell) {+ newLine = lastLineInCell(aboveCell)!;+ } else {+ const table = page.parent?.parent as IDocumentSkeletonTable;+ const { lineBeforeTable } = findLineBeforeAndAfterTable(table);++ if (lineBeforeTable) {+ newLine = lineBeforeTable;+ }+ }+ }++ if (newLine != null) {+ return newLine;+ }++ return newLine;+}diff --git a/packages/docs/src/doc-plugin.ts b/packages/docs/src/doc-plugin.tsindex 04f7d1c4de..02e85016db 100644--- a/packages/docs/src/doc-plugin.ts+++ b/packages/docs/src/doc-plugin.ts@@ -61,6 +61,10 @@ import { DocCustomRangeController } from './controllers/custom-range.controller'import { DocsRenameMutation } from './commands/mutations/docs-rename.mutation';import { DocAutoFormatService } from './services/doc-auto-format.service';import { EnterCommand, SpaceCommand, TabCommand } from './commands/commands/auto-format.command';+import { CreateDocTableCommand } from './commands/commands/table/doc-table-create.command';+import { DocTableDeleteColumnsCommand, DocTableDeleteRowsCommand, DocTableDeleteTableCommand } from './commands/commands/table/doc-table-delete.command';+import { DocTableInsertColumnCommand, DocTableInsertColumnLeftCommand, DocTableInsertColumnRightCommand, DocTableInsertRowAboveCommand, DocTableInsertRowBellowCommand, DocTableInsertRowCommand } from './commands/commands/table/doc-table-insert.command';+import { DocTableShiftTabCommand, DocTableTabCommand } from './commands/commands/table/doc-table-tab.command';export interface IUniverDocsConfig {hasScroll?: boolean;@@ -123,6 +127,18 @@ export class UniverDocsPlugin extends Plugin {AlignRightCommand,AlignOperationCommand,AlignJustifyCommand,+ CreateDocTableCommand,+ DocTableInsertRowCommand,+ DocTableInsertRowAboveCommand,+ DocTableInsertRowBellowCommand,+ DocTableInsertColumnCommand,+ DocTableInsertColumnLeftCommand,+ DocTableInsertColumnRightCommand,+ DocTableDeleteRowsCommand,+ DocTableDeleteColumnsCommand,+ DocTableDeleteTableCommand,+ DocTableTabCommand,+ DocTableShiftTabCommand,DocsRenameMutation,TabCommand,SpaceCommand,diff --git a/packages/docs/src/index.ts b/packages/docs/src/index.tsindex fcb50e1bb7..8063916357 100644--- a/packages/docs/src/index.ts+++ b/packages/docs/src/index.ts@@ -23,7 +23,7 @@ export * from './basics/docs-view-key';export { type IUniverDocsConfig, UniverDocsPlugin } from './doc-plugin';export { DocSkeletonManagerService } from './services/doc-skeleton-manager.service';-export { TextSelectionManagerService, serializeTextRange } from './services/text-selection-manager.service';+export { TextSelectionManagerService, serializeDocRange } from './services/text-selection-manager.service';export { DocStateChangeManagerService, type IDocStateChangeParams } from './services/doc-state-change-manager.service';export { IMEInputManagerService } from './services/ime-input-manager.service';export { DocCustomRangeService, type ICustomRangeHook } from './services/doc-custom-range.service';@@ -58,7 +58,7 @@ export {ResetInlineFormatTextBackgroundColorCommand,SetInlineFormatCommand,} from './commands/commands/inline-format.command';-export { ListOperationCommand, BulletListCommand, OrderListCommand, ChangeListNestingLevelCommand, ChangeListTypeCommand } from './commands/commands/list.command';+export { ListOperationCommand, BulletListCommand, OrderListCommand, ChangeListNestingLevelCommand, ChangeListTypeCommand, getParagraphsInRanges } from './commands/commands/list.command';export {AlignOperationCommand,AlignLeftCommand,@@ -92,3 +92,16 @@ export { DocInterceptorService } from './services/doc-interceptor/doc-interceptoexport { DOC_INTERCEPTOR_POINT } from './services/doc-interceptor/interceptor-const';export { DocAutoFormatService } from './services/doc-auto-format.service';export { ChangeListNestingLevelType } from './commands/commands/list.command';+export { getCommandSkeleton } from './commands/util';+export { generateParagraphs } from './commands/commands/break-line.command';+export type { IInnerCutCommandParams } from './commands/commands/clipboard.inner.command';+export { CreateDocTableCommand, type ICreateDocTableCommandParams } from './commands/commands/table/doc-table-create.command';+export { DocTableDeleteRowsCommand, DocTableDeleteColumnsCommand, DocTableDeleteTableCommand } from './commands/commands/table/doc-table-delete.command';+export type { IDocTableDeleteRowsCommandParams, IDocTableDeleteColumnsCommandParams, IDocTableDeleteTableCommandParams } from './commands/commands/table/doc-table-delete.command';+export type { IDocTableInsertColumnCommandParams, IDocTableInsertRowCommandParams, IDocTableInsertColumnRightCommandParams, IDocTableInsertRowAboveCommandParams, IDocTableInsertRowBellowCommandParams, IDocTableInsertColumnLeftCommandParams } from './commands/commands/table/doc-table-insert.command';+export { DocTableInsertColumnCommand, DocTableInsertRowCommand, DocTableInsertColumnRightCommand, DocTableInsertRowAboveCommand, DocTableInsertRowBellowCommand, DocTableInsertColumnLeftCommand } from './commands/commands/table/doc-table-insert.command';+export type { IDocTableShiftTabCommandParams, IDocTableTabCommandParams } from './commands/commands/table/doc-table-tab.command';+export { DocTableTabCommand, DocTableShiftTabCommand } from './commands/commands/table/doc-table-tab.command';++export { genTableSource, getEmptyTableRow, getEmptyTableCell, getTableColumn } from './commands/commands/table/table';+export { getCursorWhenDelete } from './commands/commands/delete.command';diff --git a/packages/docs/src/services/doc-auto-format.service.ts b/packages/docs/src/services/doc-auto-format.service.tsindex cab07b4107..838863bed6 100644--- a/packages/docs/src/services/doc-auto-format.service.ts+++ b/packages/docs/src/services/doc-auto-format.service.ts@@ -112,7 +112,7 @@ export class DocAutoFormatService extends Disposable {onAutoFormat(id: string, params: Nullable<object>): ICommandInfo[] {const autoForamts = this._matches.get(id) ?? [];const unit = this._univerInstanceService.getCurrentUnitForType<DocumentDataModel>(UniverInstanceType.UNIVER_DOC);- const selection = this._textSelectionManagerService.getActiveRange();+ const selection = this._textSelectionManagerService.getActiveTextRangeWithStyle();if (unit && selection) {const doc = unit.getSelfOrHeaderFooterModel(selection.segmentId);diff --git a/packages/docs/src/services/text-selection-manager.service.ts b/packages/docs/src/services/text-selection-manager.service.tsindex 1e358734cb..29bf68b9c4 100644--- a/packages/docs/src/services/text-selection-manager.service.ts+++ b/packages/docs/src/services/text-selection-manager.service.ts@@ -17,12 +17,14 @@import type { Nullable } from '@univerjs/core';import { ICommandService, RxDisposable } from '@univerjs/core';import type {+ IDocRange,INodePosition,- ISuccinctTextRangeParam,+ ISuccinctDocRangeParam,ITextRangeWithStyle,ITextSelectionInnerParam,ITextSelectionStyle,RANGE_DIRECTION,+ RectRange,TextRange,} from '@univerjs/engine-render';import { ITextSelectionRenderManager, NORMAL_TEXT_SELECTION_PLUGIN_STYLE } from '@univerjs/engine-render';@@ -30,7 +32,7 @@ import { BehaviorSubject, takeUntil } from 'rxjs';import { SetTextSelectionsOperation } from '../commands/operations/text-selection.operation';-interface ITextSelectionManagerSearchParam {+interface IDocSelectionManagerSearchParam {unitId: string;subUnitId: string;}@@ -47,11 +49,11 @@ export interface ITextActiveRange {segmentPage: number;}-interface ITextSelectionManagerInsertParam extends ITextSelectionManagerSearchParam, ITextSelectionInnerParam {}+interface ITextSelectionManagerInsertParam extends IDocSelectionManagerSearchParam, ITextSelectionInnerParam {}type ITextSelectionInfo = Map<string, Map<string, ITextSelectionInnerParam>>;-export function serializeTextRange(textRange: TextRange): ITextRangeWithStyle {+export function serializeDocRange(textRange: IDocRange): ITextRangeWithStyle {const { startOffset, endOffset, collapsed } = textRange;const serializedTextRange: ITextRangeWithStyle = {@@ -71,7 +73,7 @@ export function serializeTextRange(textRange: TextRange): ITextRangeWithStyle {* This service is for text selection.*/export class TextSelectionManagerService extends RxDisposable {- private _currentSelection: Nullable<ITextSelectionManagerSearchParam> = null;+ private _currentSelection: Nullable<IDocSelectionManagerSearchParam> = null;private readonly _textSelectionInfo: ITextSelectionInfo = new Map();@@ -109,19 +111,42 @@ export class TextSelectionManagerService extends RxDisposable {}// **Only used in test case** because this does not go through the render layer.- setCurrentSelection(param: ITextSelectionManagerSearchParam) {+ setCurrentSelection(param: IDocSelectionManagerSearchParam) {this._currentSelection = param;this._refresh(param);}- setCurrentSelectionNotRefresh(param: ITextSelectionManagerSearchParam) {+ setCurrentSelectionNotRefresh(param: IDocSelectionManagerSearchParam) {this._currentSelection = param;}- getCurrentSelections(): Readonly<Nullable<TextRange[]>> {+ getCurrentTextRanges(): Readonly<Nullable<TextRange[]>> {return this._getTextRanges(this._currentSelection)?.textRanges;}+ getCurrentRectRanges(): Readonly<Nullable<RectRange[]>> {+ return this._getTextRanges(this._currentSelection)?.rectRanges;+ }++ getDocRanges() {+ const textRanges = this.getCurrentTextRanges() ?? [];+ const rectRanges = this.getCurrentRectRanges() ?? [];+ // Sort ranges by startOffset in ascending order.+ const allRanges = [...textRanges, ...rectRanges]+ .filter((range) => range.startOffset != null && range.endOffset != null)+ .sort((a, b) => {+ if (a.startOffset! > b.startOffset!) {+ return 1;+ } else if (a.startOffset! < b.startOffset!) {+ return -1;+ } else {+ return 0;+ }+ });++ return allRanges;+ }+getActiveTextRange(): Nullable<TextRange> {const selectionInfo = this._getTextRanges(this._currentSelection);if (selectionInfo == null) {@@ -132,7 +157,17 @@ export class TextSelectionManagerService extends RxDisposable {return textRanges.find((textRange) => textRange.isActive());}- getActiveRange(): Nullable<ITextActiveRange> {+ getActiveRectRange(): Nullable<RectRange> {+ const selectionInfo = this._getTextRanges(this._currentSelection);+ if (selectionInfo == null) {+ return;+ }++ const { rectRanges } = selectionInfo;+ return rectRanges.find((rectRange) => rectRange.isActive());+ }++ getActiveTextRangeWithStyle(): Nullable<ITextActiveRange> {const selectionInfo = this._getTextRanges(this._currentSelection);if (selectionInfo == null) {return;@@ -165,7 +200,7 @@ export class TextSelectionManagerService extends RxDisposable {}// **Only used in test case** because this does not go through the render layer.- add(textRanges: ISuccinctTextRangeParam[], isEditing = true) {+ add(textRanges: ISuccinctDocRangeParam[], isEditing = true) {if (this._currentSelection == null) {return;}@@ -173,6 +208,7 @@ export class TextSelectionManagerService extends RxDisposable {this._addByParam({...this._currentSelection,textRanges: textRanges as TextRange[],+ rectRanges: [],segmentId: '',segmentPage: -1,isEditing,@@ -180,15 +216,15 @@ export class TextSelectionManagerService extends RxDisposable {});}- replaceTextRanges(textRanges: ISuccinctTextRangeParam[], isEditing = true, options?: { [key: string]: boolean }) {+ replaceTextRanges(docRanges: ISuccinctDocRangeParam[], isEditing = true, options?: { [key: string]: boolean }) {if (this._currentSelection == null) {return;}// Remove all textRanges.- this._textSelectionRenderManager.removeAllTextRanges();+ this._textSelectionRenderManager.removeAllRanges();// Add new textRanges.- this._textSelectionRenderManager.addTextRanges(textRanges, isEditing, options);+ this._textSelectionRenderManager.addDocRanges(docRanges, isEditing, options);}// All textRanges should be synchronized from the render layer.@@ -229,11 +265,11 @@ export class TextSelectionManagerService extends RxDisposable {segmentId,style,isEditing,- ranges: textRanges.map(serializeTextRange),+ ranges: textRanges.map(serializeDocRange),});}- private _getTextRanges(param: Nullable<ITextSelectionManagerSearchParam>) {+ private _getTextRanges(param: Nullable<IDocSelectionManagerSearchParam>) {if (param == null) {return;}@@ -243,23 +279,27 @@ export class TextSelectionManagerService extends RxDisposable {return this._textSelectionInfo.get(unitId)?.get(subUnitId);}- private _refresh(param: ITextSelectionManagerSearchParam): void {+ private _refresh(param: IDocSelectionManagerSearchParam): void {const allTextSelectionInfo = this._getTextRanges(param);// Remove all textRanges.- this._textSelectionRenderManager.removeAllTextRanges();-- if (- allTextSelectionInfo &&- Array.isArray(allTextSelectionInfo.textRanges) &&- allTextSelectionInfo.textRanges.length- ) {- this._textSelectionRenderManager.addTextRanges(allTextSelectionInfo.textRanges.map(serializeTextRange));+ this._textSelectionRenderManager.removeAllRanges();++ if (allTextSelectionInfo == null) {+ return;+ }++ const { textRanges, rectRanges } = allTextSelectionInfo;++ const docRanges = [...textRanges, ...rectRanges];++ if (docRanges.length > 0) {+ this._textSelectionRenderManager.addDocRanges(docRanges.map(serializeDocRange));}}private _replaceByParam(insertParam: ITextSelectionManagerInsertParam) {- const { unitId, subUnitId, style, segmentId, textRanges, isEditing, segmentPage } = insertParam;+ const { unitId, subUnitId, style, segmentId, textRanges, rectRanges, isEditing, segmentPage } = insertParam;if (!this._textSelectionInfo.has(unitId)) {this._textSelectionInfo.set(unitId, new Map());@@ -267,11 +307,11 @@ export class TextSelectionManagerService extends RxDisposable {const unitTextRange = this._textSelectionInfo.get(unitId)!;- unitTextRange.set(subUnitId, { textRanges, style, segmentId, isEditing, segmentPage });+ unitTextRange.set(subUnitId, { textRanges, rectRanges, style, segmentId, isEditing, segmentPage });}private _addByParam(insertParam: ITextSelectionManagerInsertParam): void {- const { unitId, subUnitId, textRanges, style, segmentId, isEditing, segmentPage } = insertParam;+ const { unitId, subUnitId, textRanges, rectRanges, style, segmentId, isEditing, segmentPage } = insertParam;if (!this._textSelectionInfo.has(unitId)) {this._textSelectionInfo.set(unitId, new Map());@@ -280,7 +320,7 @@ export class TextSelectionManagerService extends RxDisposable {const unitTextRange = this._textSelectionInfo.get(unitId)!;if (!unitTextRange.has(subUnitId)) {- unitTextRange.set(subUnitId, { textRanges, style, segmentId, isEditing, segmentPage });+ unitTextRange.set(subUnitId, { textRanges, rectRanges, style, segmentId, isEditing, segmentPage });} else {const OldTextRanges = unitTextRange.get(subUnitId)!;OldTextRanges.textRanges.push(...textRanges);diff --git a/packages/engine-render/src/basics/i-document-skeleton-cached.ts b/packages/engine-render/src/basics/i-document-skeleton-cached.tsindex 4434fc4a90..2d13f6ab16 100644--- a/packages/engine-render/src/basics/i-document-skeleton-cached.ts+++ b/packages/engine-render/src/basics/i-document-skeleton-cached.ts@@ -22,6 +22,7 @@ import type {IDocumentRenderConfig,INestingLevel,IParagraphProperties,+ ITable,ITextStyle,PageOrientType,} from '@univerjs/core';@@ -33,6 +34,7 @@ export interface IDocumentSkeletonCached extends ISkeletonResourceReference {top: number;st: number; // startIndex 文本开始索引ed?: number; // endIndex 文本结束索引+ parent?: unknown;}export interface ISkeletonResourceReference {@@ -62,6 +64,7 @@ export enum DocumentSkeletonPageType {BODY,HEADER,FOOTER,+ CELL,};export interface IDocumentSkeletonPage {@@ -79,6 +82,8 @@ export interface IDocumentSkeletonPage {originMarginBottom: number; // The margin bottom in document style config, used to draw margin identifier.marginBottom: number;+ left: number; // Only use for cell.+pageNumber: number; // page页数pageNumberStart: number; // page开始页序号verticalAlign: boolean; // 垂直对齐,仅对一页生效@@ -90,10 +95,11 @@ export interface IDocumentSkeletonPage {st: number; // startIndex 文本开始索引ed: number; // endIndex 文本结束索引skeDrawings: Map<string, IDocumentSkeletonDrawing>;- segmentId: string; // 如果是页眉、页脚,就是页眉页脚的id,如果是正文页面,为空字符串- type: DocumentSkeletonPageType; // 页面类型,页眉、页脚或正文+ skeTables: Map<string, IDocumentSkeletonTable>; // 页面中表格的 skeletons+ segmentId: string; // 如果是页眉、页脚,就是页眉页脚的 id,如果是正文页面,为空字符串+ type: DocumentSkeletonPageType; // 页面类型,页眉、页脚或正文、单元格renderConfig?: IDocumentRenderConfig;- parent?: IDocumentSkeletonCached;+ parent?: IDocumentSkeletonCached | IDocumentSkeletonRow;}export interface IDocumentSkeletonHeaderFooter extends IDocumentSkeletonPage {}@@ -109,6 +115,29 @@ export interface IDocumentSkeletonSection {parent?: IDocumentSkeletonPage;}+export interface IDocumentSkeletonTable {+ rows: IDocumentSkeletonRow[];+ width: number; // 根据表格设置或者 columns 的宽度计算表格的宽度+ height: number; // 根据行数及行高计算整个表格高度+ top: number; // 根据表格所在段落,计算表格的 top+ left: number; // 根据表格外围容器的宽度、align、及indent 计算 left 值+ st: number; // startIndex 开始索引+ ed: number; // endIndex 结束索引+ tableId: string; // 表格的id+ tableSource: ITable;+ parent?: IDocumentSkeletonPage;+}++export interface IDocumentSkeletonRow {+ cells: IDocumentSkeletonPage[];+ index: number; // 行号+ height: number; // 实际的高度+ top: number; // top 相对于表格上沿+ st: number; // startIndex 文本开始索引+ ed: number; // endIndex 文本结束索引+ parent?: IDocumentSkeletonTable;+}+export interface IDocumentSkeletonColumn {lines: IDocumentSkeletonLine[];// column坐标系相对于section@@ -149,6 +178,9 @@ export interface IDocumentSkeletonLine {bullet?: IDocumentSkeletonBullet; // 无序和有序列表标题paragraphStart: boolean; // Paragraph start 默认 false+ isBehindTable: boolean; // 在 DataStream 中,如果段落包含 table,那么段落第一行 isBehindTable 为 true, 并且 tableId 不为空,主要用来计算 st\ed.+ tableId: string; // tableId 如果段落包含 table,那么 tableId 不为空,主要用来计算 st\ed.+// dtId: string[]; // drawingTBIds 影响行的元素id集合,会切割divide,影响上下// bmt: number; // benchmarkTop, drawing的位置是根据paragraph的位置进行相对定位的,段落跨页后,需要一个校准parent?: IDocumentSkeletonColumn;diff --git a/packages/engine-render/src/basics/interfaces.ts b/packages/engine-render/src/basics/interfaces.tsindex c5871d2ad6..f29ac8a31d 100644--- a/packages/engine-render/src/basics/interfaces.ts+++ b/packages/engine-render/src/basics/interfaces.ts@@ -39,6 +39,7 @@ import type {IDocumentSkeletonFontStyle,IDocumentSkeletonGlyph,IDocumentSkeletonHeaderFooter,+ IDocumentSkeletonTable,} from './i-document-skeleton-cached';import type { Vector2 } from './vector2';import type { ITransformerConfig } from './transformer-config';@@ -106,10 +107,17 @@ export interface ISectionBreakConfig extends IDocStyleBase, ISectionBreakBase, IevenAndOddHeaders?: BooleanNumber;}+export interface IParagraphTableCache {+ tableId: string;+ table: IDocumentSkeletonTable;+ hasPositioned: boolean;+}+export interface IParagraphConfig {paragraphIndex: number;paragraphAffectSkeDrawings?: Map<string, IDocumentSkeletonDrawing>;paragraphInlineSkeDrawings?: Map<string, IDocumentSkeletonDrawing>;+ skeTablesInParagraph?: IParagraphTableCache[];// headerAndFooterAffectSkeDrawings?: Map<string, IDocumentSkeletonDrawing>;bulletSkeleton?: IDocumentSkeletonBullet;// pageContentWidth: number;@@ -158,6 +166,7 @@ export interface INodeSearch {page: number;segmentPage: number; // The index of the page where the header and footer reside.pageType: DocumentSkeletonPageType;+ path: (string | number)[];}export interface INodePosition extends INodeSearch {diff --git a/packages/engine-render/src/basics/range.ts b/packages/engine-render/src/basics/range.tsindex 47cb9ef0a4..e14c75c39b 100644--- a/packages/engine-render/src/basics/range.ts+++ b/packages/engine-render/src/basics/range.ts@@ -35,7 +35,7 @@ export interface ITextRangeWithStyle extends ITextRangeParam {}// Only use in add/replaceTextRanges methods.-export interface ISuccinctTextRangeParam {+export interface ISuccinctDocRangeParam {startOffset: number;endOffset: number;segmentId?: string; // Header of footer id.diff --git a/packages/engine-render/src/components/docs/document.ts b/packages/engine-render/src/components/docs/document.tsindex d99fe641f5..179a765a61 100644--- a/packages/engine-render/src/components/docs/document.ts+++ b/packages/engine-render/src/components/docs/document.ts@@ -20,7 +20,7 @@ import { CellValueType, HorizontalAlign, VerticalAlign, WrapStrategy } from '@unimport type { IDocumentRenderConfig, IScale, Nullable } from '@univerjs/core';import { Subject } from 'rxjs';import { calculateRectRotate, getRotateOffsetAndFarthestHypotenuse } from '../../basics/draw';-import type { IDocumentSkeletonGlyph, IDocumentSkeletonLine, IDocumentSkeletonPage } from '../../basics/i-document-skeleton-cached';+import type { IDocumentSkeletonGlyph, IDocumentSkeletonLine, IDocumentSkeletonPage, IDocumentSkeletonTable } from '../../basics/i-document-skeleton-cached';import { LineType } from '../../basics/i-document-skeleton-cached';import { degToRad } from '../../basics/tools';import type { Transform } from '../../basics/transform';@@ -31,6 +31,7 @@ import type { Scene } from '../../scene';import type { ComponentExtension, IExtensionConfig } from '../extension';import { DocumentsSpanAndLineExtensionRegistry } from '../extension';import { VERTICAL_ROTATE_ANGLE } from '../../basics/text-rotation';+import { BORDER_TYPE, drawLineByBorderType } from '../../basics';import { Liquid } from './liquid';import type { IDocumentsConfig, IPageMarginLayout } from './doc-component';import { DocComponent } from './doc-component';@@ -153,6 +154,7 @@ export class Documents extends DocComponent {headerId,footerId,renderConfig = {},+ skeTables,} = page;const {verticalAlign = VerticalAlign.TOP, // Do not make changes, otherwise the document will not render.@@ -163,7 +165,6 @@ export class Documents extends DocComponent {cellValueType,// isRotateNonEastAsian = BooleanNumber.FALSE,} = renderConfig;-const horizontalOffsetNoAngle = this._horizontalHandler(actualWidth,pagePaddingLeft,@@ -173,20 +174,15 @@ export class Documents extends DocComponent {centerAngleDeg,cellValueType);-const verticalOffsetNoAngle = this._verticalHandler(actualHeight,pagePaddingTop,pagePaddingBottom,verticalAlign);-const alignOffsetNoAngle = Vector2.create(horizontalOffsetNoAngle, verticalOffsetNoAngle);-const centerAngle = degToRad(centerAngleDeg);-const vertexAngle = degToRad(vertexAngleDeg);-const finalAngle = vertexAngle - centerAngle;if (this.isSkipByDiffBounds(page, pageTop, pageLeft, bounds)) {@@ -202,6 +198,22 @@ export class Documents extends DocComponent {continue;}+ if (skeTables.size > 0) {+ this._drawTable(+ ctx,+ page,+ skeTables,+ extensions,+ backgroundExtension,+ glyphExtensionsExcludeBackground,+ alignOffsetNoAngle,+ centerAngle,+ vertexAngle,+ renderConfig,+ parentScale+ );+ }+const headerSkeletonPage = skeHeaders.get(headerId)?.get(pageWidth);const headerAlignOffsetNoAngle = Vector2.create(@@ -467,6 +479,266 @@ export class Documents extends DocComponent {}}+ private _drawTable(+ ctx: UniverRenderingContext,+ page: IDocumentSkeletonPage,+ skeTables: Map<string, IDocumentSkeletonTable>,+ extensions: ComponentExtension<IDocumentSkeletonGlyph | IDocumentSkeletonLine, DOCS_EXTENSION_TYPE, IBoundRectNoAngle[]>[],+ backgroundExtension: Nullable<ComponentExtension<IDocumentSkeletonGlyph | IDocumentSkeletonLine, DOCS_EXTENSION_TYPE, IBoundRectNoAngle[]>>,+ glyphExtensionsExcludeBackground: ComponentExtension<IDocumentSkeletonGlyph | IDocumentSkeletonLine, DOCS_EXTENSION_TYPE, IBoundRectNoAngle[]>[],+ alignOffsetNoAngle: Vector2,+ centerAngle: number,+ vertexAngle: number,+ renderConfig: IDocumentRenderConfig,+ parentScale: IScale+ ) {+ for (const [_tableId, tableSkeleton] of skeTables) {+ const { top: tableTop, left: tableLeft, rows } = tableSkeleton;+ this._drawLiquid?.translateSave();+ this._drawLiquid?.translate(tableLeft, tableTop);++ for (const row of rows) {+ const { top: rowTop, cells } = row;+ this._drawLiquid?.translateSave();+ this._drawLiquid?.translate(0, rowTop);++ for (const cell of cells) {+ const { left: cellLeft } = cell;+ this._drawLiquid?.translateSave();+ this._drawLiquid?.translate(cellLeft, 0);++ this._drawTableCell(+ ctx,+ page,+ cell,+ extensions,+ backgroundExtension,+ glyphExtensionsExcludeBackground,+ alignOffsetNoAngle,+ centerAngle,+ vertexAngle,+ renderConfig,+ parentScale+ );++ this._drawLiquid?.translateRestore();+ }++ this._drawLiquid?.translateRestore();+ }++ this._drawLiquid?.translateRestore();+ }+ }++ // TODO: @JOCS, DRY!!!+ private _drawTableCell(+ ctx: UniverRenderingContext,+ page: IDocumentSkeletonPage,+ cell: IDocumentSkeletonPage,+ extensions: ComponentExtension<IDocumentSkeletonGlyph | IDocumentSkeletonLine, DOCS_EXTENSION_TYPE, IBoundRectNoAngle[]>[],+ backgroundExtension: Nullable<ComponentExtension<IDocumentSkeletonGlyph | IDocumentSkeletonLine, DOCS_EXTENSION_TYPE, IBoundRectNoAngle[]>>,+ glyphExtensionsExcludeBackground: ComponentExtension<IDocumentSkeletonGlyph | IDocumentSkeletonLine, DOCS_EXTENSION_TYPE, IBoundRectNoAngle[]>[],+ alignOffsetNoAngle: Vector2,+ centerAngle: number,+ vertexAngle: number,+ renderConfig: IDocumentRenderConfig,+ parentScale: IScale+ ) {+ if (this._drawLiquid == null) {+ return;+ }+ this._drawTableCellBorders(ctx, page, cell);+ const { sections, marginLeft, marginTop } = cell;++ alignOffsetNoAngle = Vector2.create(alignOffsetNoAngle.x + marginLeft, alignOffsetNoAngle.y + marginTop);++ for (const section of sections) {+ const { columns } = section;++ this._drawLiquid.translateSave();+ this._drawLiquid.translateSection(section);++ for (const column of columns) {+ const { lines } = column;++ this._drawLiquid.translateSave();+ this._drawLiquid.translateColumn(column);++ const linesCount = lines.length;++ const alignOffset = alignOffsetNoAngle;++ for (let i = 0; i < linesCount; i++) {+ const line = lines[i];+ const { divides, asc = 0, type, lineHeight = 0 } = line;++ const maxLineAsc = asc;++ const maxLineAscSin = maxLineAsc * Math.sin(centerAngle);+ const maxLineAscCos = maxLineAsc * Math.cos(centerAngle);++ if (type === LineType.BLOCK) {+ for (const extension of extensions) {+ if (extension.type === DOCS_EXTENSION_TYPE.LINE) {+ extension.extensionOffset = {+ alignOffset,+ renderConfig,+ };+ extension.draw(ctx, parentScale, line);+ }+ }+ } else {+ this._drawLiquid.translateSave();+ this._drawLiquid.translateLine(line, true);++ const divideLength = divides.length;++ for (let i = 0; i < divideLength; i++) {+ const divide = divides[i];+ const { glyphGroup } = divide;++ this._drawLiquid.translateSave();+ this._drawLiquid.translateDivide(divide);++ // Draw text background.+ for (const glyph of glyphGroup) {+ if (!glyph.content || glyph.content.length === 0) {+ continue;+ }++ const { width: spanWidth, left: spanLeft } = glyph;++ const { x: translateX, y: translateY } = this._drawLiquid;++ const originTranslate = Vector2.create(translateX, translateY);++ const centerPoint = Vector2.create(spanWidth / 2, lineHeight / 2);++ const spanStartPoint = calculateRectRotate(+ originTranslate.addByPoint(spanLeft, 0),+ centerPoint,+ centerAngle,+ vertexAngle,+ alignOffset+ );++ const extensionOffset: IExtensionConfig = {+ spanStartPoint,+ };++ if (backgroundExtension) {+ backgroundExtension.extensionOffset = extensionOffset;+ backgroundExtension.draw(ctx, parentScale, glyph);+ }+ }++ // Draw text\border\lines etc.+ for (const glyph of glyphGroup) {+ if (!glyph.content || glyph.content.length === 0) {+ continue;+ }++ const { width: spanWidth, left: spanLeft, xOffset } = glyph;++ const { x: translateX, y: translateY } = this._drawLiquid;++ const originTranslate = Vector2.create(translateX, translateY);++ const centerPoint = Vector2.create(spanWidth / 2, lineHeight / 2);++ const spanStartPoint = calculateRectRotate(+ originTranslate.addByPoint(spanLeft + xOffset, 0),+ centerPoint,+ centerAngle,+ vertexAngle,+ alignOffset+ );++ const spanPointWithFont = calculateRectRotate(+ originTranslate.addByPoint(+ spanLeft + maxLineAscSin + xOffset,+ maxLineAscCos+ ),+ centerPoint,+ centerAngle,+ vertexAngle,+ alignOffset+ );++ const extensionOffset: IExtensionConfig = {+ originTranslate,+ spanStartPoint,+ spanPointWithFont,+ centerPoint,+ alignOffset,+ renderConfig,+ };++ for (const extension of glyphExtensionsExcludeBackground) {+ extension.extensionOffset = extensionOffset;+ extension.draw(ctx, parentScale, glyph);+ }+ }++ this._drawLiquid.translateRestore();+ }++ this._drawLiquid.translateRestore();+ }+ }++ this._drawLiquid.translateRestore();+ }++ this._drawLiquid.translateRestore();+ }+ }++ private _drawTableCellBorders(+ ctx: UniverRenderingContext,+ page: IDocumentSkeletonPage,+ cell: IDocumentSkeletonPage+ ) {+ const { marginLeft, marginTop } = page;+ const { pageWidth, pageHeight } = cell;+ if (this._drawLiquid == null) {+ return;+ }+ let { x, y } = this._drawLiquid;++ x += marginLeft;+ y += marginTop;++ drawLineByBorderType(ctx, BORDER_TYPE.LEFT, 0, {+ startX: x,+ startY: y,+ endX: x + pageWidth,+ endY: y + pageHeight,+ });++ drawLineByBorderType(ctx, BORDER_TYPE.TOP, 0, {+ startX: x,+ startY: y,+ endX: x + pageWidth,+ endY: y + pageHeight,+ });++ drawLineByBorderType(ctx, BORDER_TYPE.RIGHT, 0, {+ startX: x,+ startY: y,+ endX: x + pageWidth,+ endY: y + pageHeight,+ });++ drawLineByBorderType(ctx, BORDER_TYPE.BOTTOM, 0, {+ startX: x,+ startY: y,+ endX: x + pageWidth,+ endY: y + pageHeight,+ });+ }+private _drawHeaderFooter(page: IDocumentSkeletonPage,ctx: UniverRenderingContext,@@ -640,10 +912,6 @@ export class Documents extends DocComponent {this._drawLiquid.translateRestore();}-- // if (!isEditHeaderFooter) {- // ctx.restore();- // }}private _horizontalHandler(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 f1e4c43330..8b3e60cc2c 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@@ -15,7 +15,7 @@*/import type { INumberUnit, Nullable } from '@univerjs/core';-import { BooleanNumber, DataStreamTreeTokenType, GridType, ObjectRelativeFromV, PositionedObjectLayoutType, SpacingRule } from '@univerjs/core';+import { BooleanNumber, DataStreamTreeTokenType, GridType, ObjectRelativeFromV, PositionedObjectLayoutType, SpacingRule, TableTextWrapType } from '@univerjs/core';import type {IDocumentSkeletonColumn,IDocumentSkeletonDivide,@@ -23,9 +23,11 @@ import type {IDocumentSkeletonGlyph,IDocumentSkeletonLine,IDocumentSkeletonPage,+ IDocumentSkeletonSection,+ IDocumentSkeletonTable,} from '../../../../../basics/i-document-skeleton-cached';import { GlyphType, LineType } from '../../../../../basics/i-document-skeleton-cached';-import type { IParagraphConfig, ISectionBreakConfig } from '../../../../../basics/interfaces';+import type { IParagraphConfig, IParagraphTableCache, ISectionBreakConfig } from '../../../../../basics/interfaces';import {calculateLineTopByDrawings,collisionDetection,@@ -56,6 +58,7 @@ import {lineIterator,} from '../../tools';import { BreakPointType } from '../../line-breaker/break';+import { getNullTableSkeleton, getTableIdAndSliceIndex, getTableSliceId } from '../table';export function layoutParagraph(ctx: ILayoutContext,@@ -444,6 +447,7 @@ function _lineOperator(const {paragraphStyle = {},paragraphAffectSkeDrawings,+ skeTablesInParagraph,skeHeaders,skeFooters,pDrawingAnchor,@@ -451,30 +455,13 @@ function _lineOperator(} = paragraphConfig;const {- // namedStyleType = NamedStyleType.NAMED_STYLE_TYPE_UNSPECIFIED,- // horizontalAlign = HorizontalAlign.UNSPECIFIED,-// direction,spaceAbove,spaceBelow,-- // borderBetween,- // borderTop,- // borderBottom,- // borderLeft,- // borderRight,-indentFirstLine,hanging,indentStart,indentEnd,- // tabStops = [],-- // keepLines = BooleanNumber.FALSE,- // keepNext = BooleanNumber.FALSE,- // wordWrap = BooleanNumber.FALSE,- // widowControl = BooleanNumber.FALSE,- // shading,} = paragraphStyle;const { paragraphLineGapDefault, linePitch, lineSpacing, spacingRule, snapToGrid, gridType } = getLineHeightConfig(@@ -515,6 +502,8 @@ function _lineOperator(const headerPage = skeHeaders?.get(headerId)?.get(pageWidth);const footerPage = skeFooters?.get(footerId)?.get(pageWidth);+ let needOpenNewPageByTableLayout = false;+// Handle float object relative to line.// FIXME: @jocs, it will not update the last line's drawings.if (preLine) {@@ -538,15 +527,19 @@ function _lineOperator(__updateAndPositionDrawings(ctx, lineTop, lineHeight, column, targetDrawings, paragraphConfig.paragraphIndex, paragraphStart, pDrawingAnchor?.get(paragraphIndex)?.top);}+ if (skeTablesInParagraph != null && skeTablesInParagraph.length > 0) {+ needOpenNewPageByTableLayout = _updateAndPositionTable(lineTop, marginTop, lastPage, section, skeTablesInParagraph);+ }+const newLineTop = calculateLineTopByDrawings(lineHeight,lineTop,lastPage,headerPage,footerPage- ); // WRAP_TOP_AND_BOTTOM 的 drawing 会改变行的起始 top+ ); // WRAP_TOP_AND_BOTTOM 的 drawing 和 WRAP NONE 的 table 会改变行的起始 top- if (lineHeight + newLineTop > section.height && column.lines.length > 0 && lastPage.sections.length > 0) {+ if ((lineHeight + newLineTop > section.height && column.lines.length > 0 && lastPage.sections.length > 0) || needOpenNewPageByTableLayout) {// 行高超过Col高度,且列中已存在一行以上,且section大于一个;// console.log('_lineOperator', { glyphGroup, pages, lineHeight, newLineTop, sectionHeight: section.height, lastPage });setColumnFullState(column, true);@@ -599,6 +592,7 @@ function _lineOperator(column.width,lineIndex,paragraphStart,+ paragraphConfig,lastPage,headerPage,footerPage@@ -645,6 +639,137 @@ function __updateAndPositionDrawings();}+function _updateAndPositionTable(+ lineTop: number,+ marginTop: number,+ page: IDocumentSkeletonPage,+ section: IDocumentSkeletonSection,+ skeTablesInParagraph: IParagraphTableCache[]+): boolean {+ if (skeTablesInParagraph.length === 0) {+ return false;+ }++ // Paragraph will only have one table.+ const lastTable = skeTablesInParagraph[skeTablesInParagraph.length - 1];++ if (lastTable.hasPositioned) {+ return false;+ }++ const { tableId, table } = lastTable;+ const { tableSource } = table;++ switch (tableSource.textWrap) {+ case TableTextWrapType.NONE: {+ table.top = lineTop + marginTop;+ break;+ }+ case TableTextWrapType.WRAP: {+ // TODO: @JOCS, handle text wrap position.+ break;+ }+ default: {+ throw new Error(`Unsupported table text wrap type: ${tableSource.textWrap}`);+ }+ }++ const { top, height } = table;++ if (top + height > section.height) {+ // Need split table.+ skeTablesInParagraph.pop();+ const availableHeight = section.height - top;+ const [newTable, remainTable] = _splitTable(table, availableHeight);++ if (newTable != null) {+ page.skeTables.set(newTable.tableId, newTable);+ newTable.parent = page;+ skeTablesInParagraph.push({+ table: newTable,+ tableId: newTable.tableId,+ hasPositioned: true,+ });+ }++ if (remainTable != null) {+ skeTablesInParagraph.push({+ table: remainTable,+ tableId: remainTable.tableId,+ hasPositioned: false,+ });+ }+ return true;+ } else {+ page.skeTables.set(tableId, table);+ table.parent = page;+ lastTable.hasPositioned = true;++ return false;+ }+}++// FIXME: @JOCS 重新创建两个 table skeleton 比复用之前 table 更好?+function _splitTable(+ table: IDocumentSkeletonTable,+ availableHeight: number+): [+ Nullable<IDocumentSkeletonTable>,+ Nullable<IDocumentSkeletonTable>+ ] {+ // 处理极端情况,表格第一行高度都大于可用高度,那么表格从下一页开始排版+ if (table.rows[0].height > availableHeight) {+ return [null, table];+ }++ const { tableId: tableSliceId, tableSource } = table;+ const { tableId, sliceIndex } = getTableIdAndSliceIndex(tableSliceId);+ const newTable = getNullTableSkeleton(0, 0, tableSource);++ // Reset table id;+ newTable.tableId = getTableSliceId(tableId, sliceIndex);+ newTable.left = table.left;+ newTable.width = table.width;+ newTable.height = 0;+ newTable.top = table.top;+ table.top = 0;++ let remainHeight = availableHeight;++ while (table.rows.length && remainHeight >= table.rows[0].height) {+ const row = table.rows.shift()!;++ newTable.rows.push(row);++ table.height -= row.height;+ newTable.height += row.height;++ // Reset row's parent index.+ row.parent = newTable;++ remainHeight -= row.height;+ }++ table.tableId = getTableSliceId(tableId, sliceIndex + 1);++ // Reset st and ed.++ newTable.st = newTable.rows[0].st - 1;+ newTable.ed = newTable.rows[newTable.rows.length - 1].ed + 1;++ if (table.rows.length > 0) {+ table.st = table.rows[0].st - 1;+ table.ed = table.rows[table.rows.length - 1].ed + 1;++ // Reset row top.+ for (const row of table.rows) {+ row.top -= newTable.height;+ }+ }++ return [newTable, table.rows.length > 0 ? table : null];+}+function _getCustomBlockIdsInLine(line: IDocumentSkeletonLine) {const customBlockIds: string[] = [];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.tsindex 8ce4b136b6..97f5376288 100644--- 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.ts@@ -273,13 +273,14 @@ export function lineAdjustment(sectionBreakConfig: ISectionBreakConfig) {const { endIndex } = paragraphNode;- const paragraph = viewModel.getParagraph(endIndex) || { startIndex: 0 };+ const paragraph = viewModel.getParagraph(endIndex, true) || { startIndex: 0 };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.diff --git a/packages/engine-render/src/components/docs/layout/block/paragraph/linebreaking.ts b/packages/engine-render/src/components/docs/layout/block/paragraph/linebreaking.tsindex 0806a04263..99c839e971 100644--- a/packages/engine-render/src/components/docs/layout/block/paragraph/linebreaking.ts+++ b/packages/engine-render/src/components/docs/layout/block/paragraph/linebreaking.ts@@ -17,7 +17,7 @@import type { IBullet, IDocDrawingBase, IDrawings, Nullable } from '@univerjs/core';import { DataStreamTreeTokenType, PositionedObjectLayoutType } from '@univerjs/core';import { BreakType } from '../../../../../basics/i-document-skeleton-cached';-import type { IDocumentSkeletonBullet, IDocumentSkeletonDrawing, IDocumentSkeletonPage } from '../../../../../basics/i-document-skeleton-cached';+import type { IDocumentSkeletonBullet, IDocumentSkeletonDrawing, IDocumentSkeletonPage, IDocumentSkeletonTable } from '../../../../../basics/i-document-skeleton-cached';import { createSkeletonPage } from '../../model/page';import { setColumnFullState } from '../../model/section';import type { ILayoutContext } from '../../tools';@@ -121,7 +121,8 @@ export function lineBreaking(shapedTextList: IShapedText[],curPage: IDocumentSkeletonPage,paragraphNode: DataStreamTreeNode,- sectionBreakConfig: ISectionBreakConfig+ sectionBreakConfig: ISectionBreakConfig,+ tableSkeleton: Nullable<IDocumentSkeletonTable>): IDocumentSkeletonPage[] {const { skeletonResourceReference } = ctx;const {@@ -154,6 +155,7 @@ export function lineBreaking(paragraphStyle,paragraphAffectSkeDrawings,paragraphInlineSkeDrawings,+ skeTablesInParagraph: tableSkeleton ? [{ tableId: tableSkeleton.tableId, table: tableSkeleton, hasPositioned: false }] : undefined,skeHeaders,skeFooters,pDrawingAnchor: segmentDrawingAnchorCache,diff --git a/packages/engine-render/src/components/docs/layout/block/paragraph/layout.ts b/packages/engine-render/src/components/docs/layout/block/paragraph/paragraph-layout.tssimilarity index 66%rename from packages/engine-render/src/components/docs/layout/block/paragraph/layout.tsrename to packages/engine-render/src/components/docs/layout/block/paragraph/paragraph-layout.tsindex 1c97e9f6e7..47a88d02a3 100644--- a/packages/engine-render/src/components/docs/layout/block/paragraph/layout.ts+++ b/packages/engine-render/src/components/docs/layout/block/paragraph/paragraph-layout.ts@@ -14,12 +14,14 @@* limitations under the License.*/+import { DataStreamTreeNodeType } from '@univerjs/core';import type { IDocumentSkeletonPage } from '../../../../../basics/i-document-skeleton-cached';import type { ISectionBreakConfig } from '../../../../../basics/interfaces';import type { ILayoutContext } from '../../tools';import { clearFontCreateConfigCache } from '../../tools';import type { DataStreamTreeNode } from '../../../view-model/data-stream-tree-node';import type { DocumentViewModel } from '../../../view-model/document-view-model';+import { createTableSkeleton } from '../table';import { shaping } from './shaping';import { lineBreaking } from './linebreaking';import { lineAdjustment } from './line-adjustment';@@ -32,9 +34,21 @@ export function dealWidthParagraph(sectionBreakConfig: ISectionBreakConfig): IDocumentSkeletonPage[] {clearFontCreateConfigCache();+ const { content = '', children } = paragraphNode;+ let tableSkeleton = null;++ // Need to create table before shaping....+ if (children.length === 1 && children[0].nodeType === DataStreamTreeNodeType.TABLE) {+ tableSkeleton = createTableSkeleton(+ ctx,+ curPage,+ viewModel,+ children[0],+ sectionBreakConfig+ );+ }// Step 1: Text Shaping.- const { content = '' } = paragraphNode;const shapedTextList = shaping(ctx,content,@@ -50,7 +64,8 @@ export function dealWidthParagraph(shapedTextList,curPage,paragraphNode,- sectionBreakConfig+ sectionBreakConfig,+ tableSkeleton);// Step 3: Line Adjustment.@@ -65,26 +80,3 @@ export function dealWidthParagraph(return allPages;}-function _checkAndPush(pages: IDocumentSkeletonPage[], currentPages: IDocumentSkeletonPage[]) {- const curLast = pages.slice(-1)[0];- const newFirst = currentPages[0];- if (curLast === newFirst) {- if (currentPages.length === 1) {- return curLast;- }- currentPages.shift();- }-- pages.push(...currentPages);-- return pages.slice(-1)[0];-}--// function _getAllSkeDrawings(curPage: IDocumentSkeletonPage, pageWidth: number, skeletonResourceReference: ISkeletonResourceReference, paragraphAffectSkeDrawings: Map<string, IDocumentSkeletonDrawing>) {-// const { skeHeaders, skeFooters, skeListLevel } = skeletonResourceReference;-// const affectAllSkeDrawings = new Map([-// ...(skeHeaders?.get(curPage.headerId)?.get(pageWidth)?.skeDrawings || []),-// ...(skeFooters?.get(curPage.footerId)?.get(pageWidth)?.skeDrawings || []),-// ...paragraphAffectSkeDrawings,-// ]);-// }diff --git a/packages/engine-render/src/components/docs/layout/block/section.ts b/packages/engine-render/src/components/docs/layout/block/section.tsindex dbe06dbea3..c966f4c854 100644--- a/packages/engine-render/src/components/docs/layout/block/section.ts+++ b/packages/engine-render/src/components/docs/layout/block/section.ts@@ -23,7 +23,7 @@ import type { DocumentViewModel } from '../../view-model/document-view-model';import type { ILayoutContext } from '../tools';import { createSkeletonPage } from '../model/page';import { dealWithBlockError } from './block-error';-import { dealWidthParagraph } from './paragraph/layout';+import { dealWidthParagraph } from './paragraph/paragraph-layout';export function dealWithSection(ctx: ILayoutContext,diff --git a/packages/engine-render/src/components/docs/layout/block/table.ts b/packages/engine-render/src/components/docs/layout/block/table.tsnew file mode 100644index 0000000000..f3ad4b1770--- /dev/null+++ b/packages/engine-render/src/components/docs/layout/block/table.ts@@ -0,0 +1,159 @@+/**+ * 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 { INumberUnit, ITable } from '@univerjs/core';+import { TableAlignmentType } from '@univerjs/core';+import type { IDocumentSkeletonPage, IDocumentSkeletonRow, IDocumentSkeletonTable, ISectionBreakConfig } from '../../../../basics';+import type { DataStreamTreeNode } from '../../view-model/data-stream-tree-node';+import type { DocumentViewModel } from '../../view-model/document-view-model';+import { createSkeletonCellPage } from '../model/page';+import type { ILayoutContext } from '../tools';++export function createTableSkeleton(+ ctx: ILayoutContext,+ curPage: IDocumentSkeletonPage,+ viewModel: DocumentViewModel,+ tableNode: DataStreamTreeNode,+ sectionBreakConfig: ISectionBreakConfig+): IDocumentSkeletonTable {+ const { startIndex, endIndex, children: rowNodes } = tableNode;+ const table = viewModel.getTable(startIndex);+ if (table == null) {+ throw new Error('Table not found');+ }++ const tableSkeleton = getNullTableSkeleton(startIndex, endIndex, table);+ let rowTop = 0;+ let tableWidth = 0;++ for (const rowNode of rowNodes) {+ const { children: cellNodes, startIndex, endIndex } = rowNode;+ const row = rowNodes.indexOf(rowNode);+ const rowSkeleton = _getNullTableRowSkeleton(startIndex, endIndex, row, tableSkeleton);+ tableSkeleton.rows.push(rowSkeleton);+ let left = 0;+ let rowHeight = 0;++ for (const cellNode of cellNodes) {+ const col = cellNodes.indexOf(cellNode);+ const cellPageSkeleton = createSkeletonCellPage(+ ctx,+ viewModel,+ cellNode,+ sectionBreakConfig,+ table,+ row,+ col+ );++ const { marginTop = 0, marginBottom = 0 } = cellPageSkeleton;+ const pageHeight = cellPageSkeleton.height + marginTop + marginBottom;+ cellPageSkeleton.left = left;+ left += cellPageSkeleton.pageWidth;+ cellPageSkeleton.parent = rowSkeleton;+ rowSkeleton.cells.push(cellPageSkeleton);+ rowHeight = Math.max(rowHeight, pageHeight);+ }++ // Set row height to cell page height.+ for (const cellPageSkeleton of rowSkeleton.cells) {+ cellPageSkeleton.pageHeight = rowHeight;+ }++ rowSkeleton.height = rowHeight;+ rowSkeleton.top = rowTop;+ rowTop += rowHeight;++ tableWidth = Math.max(tableWidth, left);+ }++ tableSkeleton.width = tableWidth;+ tableSkeleton.height = rowTop;++ const { pageWidth, marginLeft = 0, marginRight = 0 } = curPage;++ tableSkeleton.left = _getTableLeft(pageWidth - marginLeft - marginRight, tableWidth, table.align, table.indent);++ return tableSkeleton;+}++function _getTableLeft(pageWidth: number, tableWidth: number, align: TableAlignmentType, indent: INumberUnit = { v: 0 }) {+ switch (align) {+ case TableAlignmentType.START: {+ return indent.v;+ }+ case TableAlignmentType.END: {+ return Math.max(0, pageWidth - tableWidth);+ }+ case TableAlignmentType.CENTER: {+ return Math.max(0, (pageWidth - tableWidth) / 2);+ }+ }+}++export function getNullTableSkeleton(+ st: number,+ ed: number,+ table: ITable+): IDocumentSkeletonTable {+ return {+ rows: [],+ width: 0,+ height: 0,+ top: 0,+ left: 0,+ st,+ ed,+ tableId: table.tableId,+ tableSource: table,+ };+}++function _getNullTableRowSkeleton(+ st: number,+ ed: number,+ index: number,+ parent: IDocumentSkeletonTable+): IDocumentSkeletonRow {+ return {+ cells: [],+ index,+ height: 0,+ top: 0,+ st,+ ed,+ parent,+ };+}++export function getTableSliceId(tableId: string, sliceIndex: number) {+ return `${tableId}#-#${sliceIndex}`;+}++export function getTableIdAndSliceIndex(tableSliceId: string) {+ if (!tableSliceId.includes('#-#')) {+ return {+ tableId: tableSliceId,+ sliceIndex: 0,+ };+ }++ const [tableId, sliceIndex] = tableSliceId.split('#-#');+ return {+ tableId,+ sliceIndex: Number(sliceIndex),+ };+}diff --git a/packages/engine-render/src/components/docs/layout/doc-skeleton.ts b/packages/engine-render/src/components/docs/layout/doc-skeleton.tsindex e6beb3ba9a..3b26e6745b 100644--- a/packages/engine-render/src/components/docs/layout/doc-skeleton.ts+++ b/packages/engine-render/src/components/docs/layout/doc-skeleton.ts@@ -29,6 +29,7 @@ import { Skeleton } from '../../skeleton';import { Liquid } from '../liquid';import type { DocumentViewModel } from '../view-model/document-view-model';import { DocumentEditArea } from '../view-model/document-view-model';+import { getPageFromPath } from '../text-selection/convert-text-range';import type { ILayoutContext } from './tools';import { getLastPage, getNullSkeleton, prepareSectionBreakConfig, resetContext, setPageParent, updateBlockIndex, updateInlineDrawingCoords } from './tools';import { createSkeletonSection } from './model/section';@@ -55,9 +56,15 @@ function removeDupPages(ctx: ILayoutContext) {});}+interface IDistance {+ coordInPage: boolean;+ distance: number;+ nestLevel: number;+}+interface INearestCache {nearestNodeList: INodeInfo[];- nearestNodeDistanceList: number[];+ nearestNodeDistanceList: IDistance[];nearestNodeDistanceY: number;}@@ -67,6 +74,43 @@ export interface IFindNodeRestrictions {segmentPage: number;}+function getPagePath(page: IDocumentSkeletonPage) {+ const path: (string | number)[] = [];++ // eslint-disable-next-line ts/no-explicit-any+ let skeNode: any = page;+ // eslint-disable-next-line ts/no-explicit-any+ let parent: any = skeNode.parent;+ while (parent) {+ if (parent.pages) {+ const index = parent.pages.indexOf(skeNode);++ if (index !== -1) {+ path.unshift('pages', index);+ }+ } else if (parent.cells) {+ const index = parent.cells.indexOf(skeNode);++ if (index !== -1) {+ path.unshift('cells', index);+ }+ } else if (parent.rows) {+ const index = parent.rows.indexOf(skeNode);++ if (index !== -1) {+ path.unshift('rows', index);+ }+ } else if (parent.skeTables && parent.skeTables.has(skeNode.tableId)) {+ path.unshift('skeTables', skeNode.tableId);+ }++ skeNode = parent;+ parent = parent?.parent;+ }++ return path;+}+export class DocumentSkeleton extends Skeleton {private _skeletonData: Nullable<IDocumentSkeletonCached>;@@ -184,9 +228,31 @@ export class DocumentSkeleton extends Skeleton {const sectionIndex = page.sections.indexOf(section);- const pageIndex = pageType !== DocumentSkeletonPageType.BODY- ? 0 // Because header or footer only has one page.- : skeletonData.pages.indexOf(page);+ let pageIndex = -1;++ const path = getPagePath(page);++ switch (pageType) {+ case DocumentSkeletonPageType.HEADER:+ case DocumentSkeletonPageType.FOOTER: {+ pageIndex = 0;+ break;+ }++ case DocumentSkeletonPageType.BODY: {+ pageIndex = skeletonData.pages.indexOf(page);+ break;+ }++ case DocumentSkeletonPageType.CELL: {+ pageIndex = path[1] as number;+ break;+ }++ default: {+ throw new Error('Invalid page type');+ }+ }return {glyph: glyphIndex,@@ -197,9 +263,33 @@ export class DocumentSkeleton extends Skeleton {page: pageIndex,segmentPage,pageType,+ path,};}+ findCharIndexByPosition(position: INodePosition): Nullable<number> {+ const glyph = this.findGlyphByPosition(position);+ const divide = glyph?.parent;++ if (divide == null) {+ return;+ }++ const { st, glyphGroup } = divide;++ let index = st;++ for (const g of glyphGroup) {+ if (g === glyph) {+ break;+ }++ index += g.count;+ }++ return index;+ }+findNodePositionByCharIndex(charIndex: number, isBack: boolean = true, segmentId = '', segmentPIndex = -1): Nullable<INodePosition> {const nodes = this._findNodeByIndex(charIndex, segmentId, segmentPIndex);@@ -217,16 +307,43 @@ export class DocumentSkeleton extends Skeleton {const { glyph, divide, line, column, section, page, segmentPageIndex, pageType } = nodes;+ const path = getPagePath(page);++ let pageIndex = -1;++ switch (pageType) {+ case DocumentSkeletonPageType.HEADER:+ case DocumentSkeletonPageType.FOOTER: {+ pageIndex = 0;+ break;+ }++ case DocumentSkeletonPageType.BODY: {+ pageIndex = pages.indexOf(page);+ break;+ }++ case DocumentSkeletonPageType.CELL: {+ pageIndex = path[1] as number;+ break;+ }++ default: {+ throw new Error('Invalid page type');+ }+ }+return {glyph: divide.glyphGroup.indexOf(glyph),divide: line.divides.indexOf(divide),line: column.lines.indexOf(line),column: section.columns.indexOf(column),section: page.sections.indexOf(section),- page: pageType === DocumentSkeletonPageType.BODY ? pages.indexOf(page) : 0,+ page: pageIndex,pageType,segmentPage: segmentPageIndex,isBack,+ path,};}@@ -249,19 +366,17 @@ export class DocumentSkeleton extends Skeleton {const { pages, skeFooters, skeHeaders } = skeletonData;- const { divide, line, column, section, page, isBack, segmentPage, pageType } = position;+ const { divide, line, column, section, isBack, segmentPage, pageType, path } = position;let { glyph } = position;- if (isBack === true) {- glyph -= 1;+ if (isBack === false) {+ glyph += 1;}- glyph = glyph < 0 ? 0 : glyph;-- let skePage = pages[page];+ let skePage: Nullable<IDocumentSkeletonPage> = null;- if (pageType !== DocumentSkeletonPageType.BODY) {+ if (pageType === DocumentSkeletonPageType.HEADER || pageType === DocumentSkeletonPageType.FOOTER) {skePage = pages[segmentPage];const { headerId, footerId, pageWidth } = skePage;@@ -280,13 +395,21 @@ export class DocumentSkeleton extends Skeleton {skePage = skeFooter;}}+ } else {+ skePage = getPageFromPath(skeletonData, path);+ }++ if (skePage == null) {+ return;}const glyphGroup =skePage.sections[section].columns[column].lines[line].divides[divide].glyphGroup;+ glyph = Math.min(glyph, glyphGroup.length - 1);+if (glyphGroup[glyph].glyphType === GlyphType.LIST) {- return glyphGroup[glyph + 1];+ glyph += 1;}return glyphGroup[glyph];@@ -564,11 +687,17 @@ export class DocumentSkeleton extends Skeleton {pi: number,cache: INearestCache,x: number,- y: number- ) {- const { sections } = segmentPage;-+ y: number,+ nestLevel: number = 0+ // eslint-disable-next-line ts/no-explicit-any+ ): any {+ const { sections, skeTables } = segmentPage;this._findLiquid.translateSave();+ const pointInPage = x >= this._findLiquid.x+ && x <= this._findLiquid.x + segmentPage.pageWidth+ && y >= this._findLiquid.y+ && y <= this._findLiquid.y + segmentPage.pageHeight;+switch (pageType) {case DocumentSkeletonPageType.HEADER: {this._findLiquid.translatePagePadding({@@ -590,142 +719,210 @@ export class DocumentSkeleton extends Skeleton {}}- for (const section of sections) {- const { columns } = section;-- this._findLiquid.translateSection(section);-- // const { y: startY } = this._findLiquid;-- // if (!(y >= startY && y <= startY + height)) {- // continue;- // }-- for (const column of columns) {- const { lines } = column;+ if (pointInPage) {+ for (const section of sections) {+ const { columns } = section;this._findLiquid.translateSave();- this._findLiquid.translateColumn(column);+ this._findLiquid.translateSection(section);- // const { x: startX } = this._findLiquid;-- // if (!(x >= startX && x <= startX + columnWidth)) {- // continue;- // }-- const linesCount = lines.length;-- for (let i = 0; i < linesCount; i++) {- const line = lines[i];- const { divides, type, lineHeight = 0 } = line;-- if (type === LineType.BLOCK) {- continue;- } else {- this._findLiquid.translateSave();- this._findLiquid.translateLine(line);-- const { y: startY } = this._findLiquid;-- const startY_fin = startY;-- const endY_fin = startY + lineHeight;-- const distanceY = Math.abs(y - endY_fin);+ for (const column of columns) {+ const { lines } = column;- // if (!(y >= startY_fin && y <= endY_fin)) {- // this._findLiquid.translateRestore();- // continue;- // }+ this._findLiquid.translateSave();+ this._findLiquid.translateColumn(column);- const divideLength = divides.length;- for (let i = 0; i < divideLength; i++) {- const divide = divides[i];- const { glyphGroup } = divide;+ for (let i = 0; i < lines.length; i++) {+ const line = lines[i];+ const { divides, type, lineHeight = 0 } = line;+ if (type === LineType.BLOCK) {+ continue;+ } else {this._findLiquid.translateSave();- this._findLiquid.translateDivide(divide);+ this._findLiquid.translateLine(line);- const { x: startX } = this._findLiquid;+ const { y: startY } = this._findLiquid;- // if (!(x >= startX && x <= startX + divideWidth)) {- // this._findLiquid.translateRestore();- // continue;- // }+ const startY_fin = startY;- for (const glyph of glyphGroup) {- if (!glyph.content || glyph.content.length === 0) {- continue;- }+ const endY_fin = startY + lineHeight;- const { width: glyphWidth, left: glyphLeft } = glyph;+ const distanceY = Math.abs(y - endY_fin);- const startX_fin = startX + glyphLeft;+ const divideLength = divides.length;+ for (let i = 0; i < divideLength; i++) {+ const divide = divides[i];+ const { glyphGroup } = divide;- const endX_fin = startX + glyphLeft + glyphWidth;+ this._findLiquid.translateSave();+ this._findLiquid.translateDivide(divide);- const distanceX = Math.abs(x - endX_fin);+ const { x: startX } = this._findLiquid;- if (y >= startY_fin && y <= endY_fin) {- if (x >= startX_fin && x <= endX_fin) {- return {+ for (const glyph of glyphGroup) {+ if (!glyph.content || glyph.content.length === 0) {+ continue;+ }++ const { width: glyphWidth, left: glyphLeft } = glyph;+ const startX_fin = startX + glyphLeft;+ const endX_fin = startX + glyphLeft + glyphWidth;+ const distanceX = Math.abs(x - endX_fin);++ // Handle pointer in the same line.+ if (y >= startY_fin && y <= endY_fin) {+ // Exact match glyph.+ if (x >= startX_fin && x <= endX_fin) {+ return {+ node: glyph,+ segmentPage: pageType === DocumentSkeletonPageType.BODY ? -1 : pi,+ segmentId,+ ratioX: x / (startX_fin + endX_fin),+ ratioY: y / (startY_fin + endY_fin),+ };+ }++ if (cache.nearestNodeDistanceY !== Number.NEGATIVE_INFINITY) {+ cache.nearestNodeList = [];+ cache.nearestNodeDistanceList = [];+ }+ cache.nearestNodeList.push({node: glyph,segmentPage: pageType === DocumentSkeletonPageType.BODY ? -1 : pi,segmentId,ratioX: x / (startX_fin + endX_fin),ratioY: y / (startY_fin + endY_fin),- };+ });++ cache.nearestNodeDistanceList.push({+ coordInPage: pointInPage,+ distance: distanceX,+ nestLevel,+ });++ cache.nearestNodeDistanceY = Number.NEGATIVE_INFINITY;+ continue;}- if (cache.nearestNodeDistanceY !== Number.NEGATIVE_INFINITY) {+ if (distanceY < cache.nearestNodeDistanceY) {+ cache.nearestNodeDistanceY = distanceY;cache.nearestNodeList = [];cache.nearestNodeDistanceList = [];}- cache.nearestNodeList.push({- node: glyph,- segmentPage: pageType === DocumentSkeletonPageType.BODY ? -1 : pi,- segmentId,- ratioX: x / (startX_fin + endX_fin),- ratioY: y / (startY_fin + endY_fin),- });-- cache.nearestNodeDistanceList.push(distanceX);-- cache.nearestNodeDistanceY = Number.NEGATIVE_INFINITY;- continue;- }- if (distanceY < cache.nearestNodeDistanceY) {- cache.nearestNodeDistanceY = distanceY;- cache.nearestNodeList = [];- cache.nearestNodeDistanceList = [];- }-- if (distanceY === cache.nearestNodeDistanceY) {- cache.nearestNodeList.push({- node: glyph,- segmentPage: pageType === DocumentSkeletonPageType.BODY ? -1 : pi,- segmentId,- ratioX: x / (startX_fin + endX_fin),- ratioY: y / (startY_fin + endY_fin),- });+ if (distanceY === cache.nearestNodeDistanceY) {+ cache.nearestNodeList.push({+ node: glyph,+ segmentPage: pageType === DocumentSkeletonPageType.BODY ? -1 : pi,+ segmentId,+ ratioX: x / (startX_fin + endX_fin),+ ratioY: y / (startY_fin + endY_fin),+ });- cache.nearestNodeDistanceList.push(distanceX);+ cache.nearestNodeDistanceList.push({+ coordInPage: pointInPage,+ distance: distanceX,+ nestLevel,+ });+ }}+ this._findLiquid.translateRestore();}this._findLiquid.translateRestore();}- this._findLiquid.translateRestore();}+ this._findLiquid.translateRestore();}+this._findLiquid.translateRestore();}}++ let exactMatch = null;+ if (skeTables.size > 0) {+ for (const table of skeTables.values()) {+ const { top: tableTop, left: tableLeft, rows } = table;++ this._findLiquid?.translateSave();+ this._findLiquid?.translate(tableLeft, tableTop);++ for (const row of rows) {+ const { top: rowTop, cells } = row;++ this._findLiquid?.translateSave();+ this._findLiquid?.translate(0, rowTop);++ for (const cell of cells) {+ const { left: cellLeft } = cell;++ this._findLiquid?.translateSave();+ this._findLiquid?.translate(cellLeft, 0);++ exactMatch = exactMatch ?? this._collectNearestNode(+ cell,+ DocumentSkeletonPageType.CELL,+ cell,+ segmentId,+ pi,+ cache,+ x,+ y,+ nestLevel + 1+ );++ this._findLiquid?.translateRestore();+ }++ this._findLiquid?.translateRestore();+ }++ this._findLiquid?.translateRestore();+ }+ }++ if (exactMatch) {+ this._findLiquid.translateRestore();+ return exactMatch;+ }+this._findLiquid.translateRestore();}- private _getNearestNode(nearestNodeList: INodeInfo[], nearestNodeDistanceList: number[]) {- const miniValue = Math.min(...nearestNodeDistanceList);+ private _getNearestNode(nearestNodeList: INodeInfo[], nearestNodeDistanceList: IDistance[]) {+ if (nearestNodeDistanceList.length === 0) {+ return;+ }++ if (nearestNodeDistanceList.length === 1) {+ return nearestNodeList[0];+ }++ let miniValue = nearestNodeDistanceList[0];++ for (let i = 1; i < nearestNodeDistanceList.length; i++) {+ const { distance, nestLevel, coordInPage } = nearestNodeDistanceList[i];++ if (nestLevel > miniValue.nestLevel) {+ miniValue = nearestNodeDistanceList[i];+ continue;+ }++ if (nestLevel === miniValue.nestLevel) {+ if (coordInPage === miniValue.coordInPage) {+ if (distance < miniValue.distance) {+ miniValue = nearestNodeDistanceList[i];+ continue;+ }+ } else {+ if (coordInPage) {+ miniValue = nearestNodeDistanceList[i];+ continue;+ }+ }+ }+ }+const miniValueIndex = nearestNodeDistanceList.indexOf(miniValue);return nearestNodeList[miniValueIndex];@@ -991,7 +1188,6 @@ export class DocumentSkeleton extends Skeleton {return;}- const editArea = this.getViewModel().getEditArea();const { pages, skeFooters, skeHeaders } = skeletonData;for (const page of pages) {@@ -1000,7 +1196,7 @@ export class DocumentSkeleton extends Skeleton {continue;}- const { pageWidth } = page;+ const { pageWidth, skeTables } = page;let segmentPage = page;if (segmentId) {@@ -1015,6 +1211,36 @@ export class DocumentSkeleton extends Skeleton {}}+ // Find node from tables.+ if (segmentId === '') {+ let foundCell = false;+ for (const table of skeTables.values()) {+ const { rows } = table;++ for (const row of rows) {+ const { cells } = row;++ for (const cell of cells) {+ const { st, ed } = cell;++ if (charIndex >= st && charIndex <= ed) {+ segmentPage = cell;+ foundCell = true;+ break;+ }+ }++ if (foundCell) {+ break;+ }+ }++ if (foundCell) {+ break;+ }+ }+ }+const { sections, st, ed } = segmentPage;if (charIndex < st || charIndex > ed) {diff --git a/packages/engine-render/src/components/docs/layout/model/line.ts b/packages/engine-render/src/components/docs/layout/model/line.tsindex 89833c3b8c..3d51336303 100644--- a/packages/engine-render/src/components/docs/layout/model/line.ts+++ b/packages/engine-render/src/components/docs/layout/model/line.ts@@ -23,11 +23,13 @@ import type {IDocumentSkeletonDrawingAnchor,IDocumentSkeletonLine,IDocumentSkeletonPage,+ IDocumentSkeletonTable,LineType,} from '../../../../basics/i-document-skeleton-cached';import { Path2 } from '../../../../basics/path2';import { Transform } from '../../../../basics/transform';import { Vector2 } from '../../../../basics/vector2';+import type { IParagraphConfig } from '../../../../basics';interface IDrawingsSplit {left: number;@@ -65,6 +67,7 @@ export function createSkeletonLine(columnWidth: number,lineIndex: number = 0,isParagraphStart: boolean = false,+ paragraphConfig: IParagraphConfig,page: IDocumentSkeletonPage,headerPage: Nullable<IDocumentSkeletonPage>,footerPage: Nullable<IDocumentSkeletonPage>@@ -80,6 +83,7 @@ export function createSkeletonLine(marginTop = 0,spaceBelowApply = 0,} = lineBoundingBox;+ const { skeTablesInParagraph } = paragraphConfig;const pageSkeDrawings = page.skeDrawings ?? new Map();const headersDrawings = headerPage?.skeDrawings;const footersDrawings = footerPage?.skeDrawings;@@ -96,6 +100,12 @@ export function createSkeletonLine(lineSke.marginTop = marginTop; // marginTop is initialized when it is created, and marginBottom is not calculated when it is created, it will be determined according to the situation of the next paragraphlineSke.spaceBelowApply = spaceBelowApply;+ if (isParagraphStart && Array.isArray(skeTablesInParagraph) && skeTablesInParagraph.length > 0) {+ const tableId = skeTablesInParagraph[skeTablesInParagraph.length - 1].tableId;+ lineSke.isBehindTable = true;+ lineSke.tableId = tableId;+ }+const affectSkeDrawings = new Map(Array.from(pageSkeDrawings).filter(([_, drawing]) => drawing.drawingOrigin.layoutType !== PositionedObjectLayoutType.INLINE));lineSke.divides = _calculateDividesByDrawings(@@ -128,6 +138,7 @@ export function calculateLineTopByDrawings() {let maxTop = lineTop;const pageSkeDrawings = page.skeDrawings;+ const skeTables = page.skeTables;const headersDrawings = headerPage?.skeDrawings;const footersDrawings = footerPage?.skeDrawings;@@ -158,9 +169,27 @@ export function calculateLineTopByDrawings(}});+ skeTables?.forEach((table) => {+ const top = _getLineTopWidthWrapNone(table, lineHeight, lineTop);+ if (top) {+ maxTop = Math.max(maxTop, top);+ }+ });+return maxTop;}+function _getLineTopWidthWrapNone(table: IDocumentSkeletonTable, lineHeight: number, lineTop: number) {+ const { top, height } = table;++ // No need to consider the dist.+ if (top + height < lineTop || top > lineHeight + lineTop) {+ return;+ }++ return top + height;+}+function _getLineTopWidthWrapTopBottom(drawing: IDocumentSkeletonDrawing, lineHeight: number, lineTop: number) {const { aTop, height, aLeft, width, angle = 0, drawingOrigin } = drawing;const { layoutType, distT = 0, distB = 0 } = drawingOrigin;@@ -567,6 +596,8 @@ function _getLineSke(lineType: LineType, paragraphIndex: number): IDocumentSkeledivideLen: 0, // divideLen 被对象分割为多少块st: -1, // startIndex 文本开始索引ed: -1, // endIndex 文本结束索引+ isBehindTable: false, // isBehindTable 是否在表格后面+ tableId: '', // tableId 表格idlineIndex: 0, // lineIndex 行号paragraphStart: false,};diff --git a/packages/engine-render/src/components/docs/layout/model/page.ts b/packages/engine-render/src/components/docs/layout/model/page.tsindex 085a124963..94eb8bbd44 100644--- a/packages/engine-render/src/components/docs/layout/model/page.ts+++ b/packages/engine-render/src/components/docs/layout/model/page.ts@@ -14,7 +14,7 @@* limitations under the License.*/-import type { Nullable } from '@univerjs/core';+import type { ITable, Nullable } from '@univerjs/core';import { BooleanNumber, PageOrientType } from '@univerjs/core';import type {IDocumentSkeletonHeaderFooter,@@ -27,6 +27,7 @@ import { dealWithSection } from '../block/section';import type { DocumentViewModel } from '../../view-model/document-view-model';import type { ILayoutContext } from '../tools';import { resetContext, updateBlockIndex } from '../tools';+import type { DataStreamTreeNode } from '../../view-model/data-stream-tree-node';import { createSkeletonSection } from './section';function getHeaderFooterMaxHeight(pageHeight: number) {@@ -179,6 +180,8 @@ function _getNullPage(angle: 0,width: 0,height: 0,+ // Only use in cell.+ left: 0,marginLeft: 0,marginRight: 0,originMarginTop: 0,@@ -189,6 +192,7 @@ function _getNullPage(st: 0,ed: 0,skeDrawings: new Map(),+ skeTables: new Map(),type,segmentId,};@@ -275,6 +279,62 @@ function _createSkeletonHeaderFooter(return page;}+export function createSkeletonCellPage(+ ctx: ILayoutContext,+ viewModel: DocumentViewModel,+ cellNode: DataStreamTreeNode,+ sectionBreakConfig: ISectionBreakConfig,+ tableConfig: ITable,+ row: number,+ col: number+) {+ const { lists, footerTreeMap, headerTreeMap, localeService, drawings } = sectionBreakConfig;+ const { skeletonResourceReference } = ctx;+ const { cellMargin, tableRows, tableColumns, tableId } = tableConfig;+ const cellConfig = tableRows[row].tableCells[col];+ // Table cell only has one section.+ const sectionNode = cellNode.children[0];+ const {+ start = { v: 10 },+ end = { v: 10 },+ top = { v: 5 },+ bottom = { v: 5 },+ } = cellConfig.margin ?? cellMargin ?? {};+ const pageWidth = tableColumns[col].size.width.v;+ const pageHeight = Number.POSITIVE_INFINITY;+ const cellSectionBreakConfig: ISectionBreakConfig = {+ lists,+ footerTreeMap,+ headerTreeMap,+ pageSize: {+ width: pageWidth,+ height: pageHeight,+ },+ marginTop: top.v,+ marginBottom: bottom.v,+ marginLeft: start.v,+ marginRight: end.v,+ localeService,+ drawings,+ };++ const areaPage = createSkeletonPage(ctx, cellSectionBreakConfig, skeletonResourceReference);+ areaPage.type = DocumentSkeletonPageType.CELL;+ areaPage.segmentId = tableId;++ const page = dealWithSection(+ ctx,+ viewModel,+ sectionNode,+ areaPage,+ cellSectionBreakConfig+ ).pages[0];++ updateBlockIndex([page], cellNode.startIndex);++ return page;+}+function _getVerticalMargin(marginTB: number,headerOrFooter: Nullable<IDocumentSkeletonHeaderFooter>,@@ -290,21 +350,3 @@ function _getVerticalMargin(return Math.min(maxMargin, Math.max(marginTB, HeaderFooterPageHeight));}--function __getHeaderMarginTop(marginTop: number, marginHeader: number, height: number) {- const maxMargin = Math.max(marginTop, marginHeader);- if (height > maxMargin) {- return 0;- }-- return maxMargin - height;-}--function __getHeaderMarginBottom(marginBottom: number, marginFooter: number, height: number) {- const maxMargin = Math.max(marginBottom, marginFooter);- if (height > maxMargin) {- return 0;- }-- return maxMargin - height;-}diff --git a/packages/engine-render/src/components/docs/layout/model/table.ts b/packages/engine-render/src/components/docs/layout/model/table.tsnew file mode 100644index 0000000000..cf732b1e13--- /dev/null+++ b/packages/engine-render/src/components/docs/layout/model/table.ts@@ -0,0 +1,16 @@+/**+ * 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.+ */+diff --git a/packages/engine-render/src/components/docs/layout/tools.ts b/packages/engine-render/src/components/docs/layout/tools.tsindex c90226a542..3104ca86bb 100644--- a/packages/engine-render/src/components/docs/layout/tools.ts+++ b/packages/engine-render/src/components/docs/layout/tools.ts@@ -321,7 +321,7 @@ export function updateBlockIndex(pages: IDocumentSkeletonPage[], start: number =let prePageStartIndex = start;for (const page of pages) {- const { sections } = page;+ const { sections, skeTables } = page;const pageStartIndex = prePageStartIndex;const pageEndIndex = pageStartIndex;let preSectionStartIndex = pageStartIndex;@@ -346,8 +346,14 @@ export function updateBlockIndex(pages: IDocumentSkeletonPage[], start: number =// const preLine: Nullable<IDocumentSkeletonLine> = null;for (const line of lines) {- const { divides, lineHeight, top } = line;- const lineStartIndex = preLineStartIndex;+ const { divides, lineHeight, top, isBehindTable, tableId } = line;+ let lineStartIndex = preLineStartIndex;+ if (isBehindTable && tableId) {+ const table = skeTables.get(tableId);+ if (table) {+ lineStartIndex = table.ed;+ }+ }const lineEndIndex = lineStartIndex;let preDivideStartIndex = lineStartIndex;let actualWidth = 0;@@ -417,8 +423,6 @@ export function updateBlockIndex(pages: IDocumentSkeletonPage[], start: number =maxColumnWidth = Math.max(maxColumnWidth, actualWidth);// Please do not use pre line's top and height to calculate the current's top,// because of float objects will between lines.- // line.top = (preLine?.top || 0) + (preLine?.lineHeight || 0);- // preLine = line;preLineStartIndex = line.ed;}column.st = columStartIndex + 1;@@ -504,15 +508,15 @@ export function glyphIterator(}export function lineIterator(- pages: IDocumentSkeletonPage[],+ pagesOrCells: (IDocumentSkeletonPage)[],cb: (line: IDocumentSkeletonLine,column: IDocumentSkeletonColumn,section: IDocumentSkeletonSection,page: IDocumentSkeletonPage) => void) {- for (const page of pages) {- const { sections } = page;+ for (const pageOrCell of pagesOrCells) {+ const { sections } = pageOrCell;for (const section of sections) {const { columns } = section;@@ -522,7 +526,7 @@ export function lineIterator(for (const line of lines) {if (cb && isFunction(cb)) {- cb(line, column, section, page);+ cb(line, column, section, pageOrCell);}}}diff --git a/packages/engine-render/src/components/docs/liquid.ts b/packages/engine-render/src/components/docs/liquid.tsindex 4724cf2ead..4dc28ef4c5 100644--- a/packages/engine-render/src/components/docs/liquid.ts+++ b/packages/engine-render/src/components/docs/liquid.ts@@ -69,34 +69,6 @@ export class Liquid {}}- // const {- // verticalAlign = VerticalAlign.TOP,- // horizontalAlign = HorizontalAlign.LEFT,- // centerAngle: centerAngleDeg = 0,- // vertexAngle: vertexAngleDeg = 0,- // wrapStrategy = WrapStrategy.UNSPECIFIED,- // isRotateNonEastAsian = BooleanNumber.FALSE,- // } = renderConfig;-- // let paddingTop = 0;-- // if (verticalAlign === VerticalAlign.MIDDLE && pageHeight !== Infinity) {- // paddingTop = (pageHeight - height) / 2;- // } else if (verticalAlign === VerticalAlign.BOTTOM && pageHeight !== Infinity) {- // paddingTop = pageHeight - height - pagePaddingBottom;- // } else {- // paddingTop = pagePaddingTop;- // }-- // let paddingLeft = 0;-- // if (horizontalAlign === HorizontalAlign.CENTER && pageWidth !== Infinity) {- // paddingLeft = (pageWidth - width) / 2;- // } else if (horizontalAlign === HorizontalAlign.RIGHT && pageWidth !== Infinity) {- // paddingLeft = pageWidth - width - pagePaddingRight;- // } else {- // paddingLeft = pagePaddingLeft;- // }translatePagePadding(page: IDocumentSkeletonPage) {const {marginTop: pagePaddingTop = 0,diff --git a/packages/engine-render/src/components/docs/text-selection/convert-rect-range.ts b/packages/engine-render/src/components/docs/text-selection/convert-rect-range.tsnew file mode 100644index 0000000000..c87bf6c65f--- /dev/null+++ b/packages/engine-render/src/components/docs/text-selection/convert-rect-range.ts@@ -0,0 +1,366 @@+/**+ * 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 Nullable, Tools } from '@univerjs/core';+import type { IDocumentSkeletonGlyph, IDocumentSkeletonPage, IDocumentSkeletonRow, IDocumentSkeletonTable, INodePosition, IPoint } from '../../../basics';+import { DocumentSkeletonPageType } from '../../../basics';+import type { IDocumentOffsetConfig } from '../document';+import type { DocumentSkeleton } from '../layout/doc-skeleton';+import { Liquid } from '../liquid';+import { getTableIdAndSliceIndex } from '../layout/block/table';+import { getPageFromPath, pushToPoints } from './convert-text-range';++// The anchor and focus need to be in the same table,+// and cannot be in the same cell, start node must be the first glyph in the cell,+// and end node must be the last glyph in the cell.+export function isValidRectRange(anchorNodePosition: INodePosition, focusNodePosition: INodePosition): boolean {+ const { path: anchorPath } = anchorNodePosition;+ const { path: focusPath } = focusNodePosition;++ if (anchorPath.length !== focusPath.length) {+ return false;+ }++ if (anchorPath.indexOf('cells') === -1) {+ return false;+ }++ const tableIdIndex = anchorPath.indexOf('skeTables') + 1;+ const rowIndex = anchorPath.indexOf('rows') + 1;+ const cellIndex = anchorPath.indexOf('cells') + 1;++ const anchorTableId = getTableIdAndSliceIndex(anchorPath[tableIdIndex] as string).tableId;+ const focusTableId = getTableIdAndSliceIndex(focusPath[tableIdIndex] as string).tableId;++ if (anchorTableId !== focusTableId) {+ return false;+ }++ const anchorRowIndex = anchorPath[rowIndex];+ const focusRowIndex = focusPath[rowIndex];+ const anchorCellIndex = anchorPath[cellIndex];+ const focusCellIndex = focusPath[cellIndex];++ if (anchorRowIndex === focusRowIndex && anchorCellIndex === focusCellIndex) {+ return false;+ }++ return true;+}++export function isInSameTableCell(anchorNodePosition: INodePosition, focusNodePosition: INodePosition): boolean {+ const { path: anchorPath } = anchorNodePosition;+ const { path: focusPath } = focusNodePosition;++ if (anchorPath.indexOf('cells') === -1 || focusPath.indexOf('cells') === -1) {+ return false;+ }++ return Tools.diffValue(anchorPath, focusPath);+}++// Return true if a is before b.+export function compareNodePositionInTable(a: INodePosition, b: INodePosition): boolean {+ const { path: aPath } = a;+ const { path: bPath } = b;++ const aRowCount = aPath[aPath.length - 3];+ const bRowCount = bPath[bPath.length - 3];+ const aCellCount = aPath[aPath.length - 1];+ const bCellCount = bPath[bPath.length - 1];++ if (aRowCount < bRowCount) {+ return true;+ }++ if (aRowCount > bRowCount) {+ return false;+ }++ return aCellCount < bCellCount;+}++function firstGlyphInCellPage(cellPage: IDocumentSkeletonPage): Nullable<IDocumentSkeletonGlyph> {+ return cellPage.sections[0].columns[0].lines[0].divides[0].glyphGroup[0];+}++function lastGlyphInCellPage(cellPage: IDocumentSkeletonPage): Nullable<IDocumentSkeletonGlyph> {+ const { sections } = cellPage;+ const lastSection = sections[sections.length - 1];+ const lastColumn = lastSection.columns[lastSection.columns.length - 1];+ const lastLine = lastColumn.lines[lastColumn.lines.length - 1];+ const lastDivide = lastLine.divides[lastLine.divides.length - 1];+ const lastGlyphGroup = lastDivide.glyphGroup;++ return lastGlyphGroup[lastGlyphGroup.length - 2];+}++interface IRectRangeNodePositions {+ anchor: INodePosition;+ focus: INodePosition;+}++export class NodePositionConvertToRectRange {+ private _liquid = new Liquid();++ constructor(+ private _documentOffsetConfig: IDocumentOffsetConfig,+ private _docSkeleton: DocumentSkeleton+ ) {+ // super+ }++ getRangePointData(startNodePosition: INodePosition, endNodePosition: INodePosition) {+ const pointGroup: IPoint[][] = [];+ const docSkeleton = this._docSkeleton;+ const skeletonData = docSkeleton.getSkeletonData();++ if (skeletonData == null) {+ return;+ }++ const { pages } = skeletonData;++ const { segmentPage: startSegmentPage, page: startPage, pageType } = startNodePosition;+ const { segmentPage: endSegmentPage, page: endPage } = endNodePosition;++ const rectInfo = this._getTableRectRangeInfo(startNodePosition, endNodePosition);++ if (rectInfo == null) {+ return;+ }++ const {+ tableId,+ startRowIndex: startRow,+ startColumnIndex: startColumn,+ endRowIndex: endRow,+ endColumnIndex: endColumn,+ } = rectInfo;++ this._liquid.reset();++ const { pageLayoutType, pageMarginLeft, pageMarginTop } = this._documentOffsetConfig;++ const skipPageIndex = pageType === DocumentSkeletonPageType.BODY || pageType === DocumentSkeletonPageType.CELL ? startPage : startSegmentPage;++ for (let p = 0; p < skipPageIndex; p++) {+ const page = pages[p];+ this._liquid.translatePage(page, pageLayoutType, pageMarginLeft, pageMarginTop);+ }++ const endIndex = pageType === DocumentSkeletonPageType.BODY || pageType === DocumentSkeletonPageType.CELL ? endPage : endSegmentPage;++ for (let p = skipPageIndex; p <= endIndex; p++) {+ const page = pages[p];+ this._liquid.translatePagePadding(page);+ const { skeTables } = page;++ let table = null;++ for (const [id, tableSke] of skeTables.entries()) {+ if (id.startsWith(tableId)) {+ table = tableSke;+ }+ }++ if (table == null) {+ this._liquid.restorePagePadding(page);+ this._liquid.translatePage(page, pageLayoutType, pageMarginLeft, pageMarginTop);+ continue;+ }++ this._liquid.translateSave();+ this._liquid.translate(0, table.top);++ const { x, y } = this._liquid;++ for (const row of table.rows) {+ if (row.index >= startRow && row.index <= endRow) {+ const rowStartCell = row.cells[startColumn];+ const rowEndCell = row.cells[endColumn];++ const position = {+ startX: x + rowStartCell.left,+ startY: y + row.top,+ endX: x + rowEndCell.left + rowEndCell.pageWidth,+ endY: y + row.top + row.height,+ };++ pointGroup.push(pushToPoints(position));+ }+ }++ this._liquid.translateRestore();+ this._liquid.restorePagePadding(page);+ this._liquid.translatePage(page, pageLayoutType, pageMarginLeft, pageMarginTop);+ }++ return {+ pointGroup,+ startRow,+ startColumn,+ endRow,+ endColumn,+ tableId,+ };+ }++ getNodePositionGroup(anchorNodePosition: INodePosition, focusNodePosition: INodePosition): Nullable<IRectRangeNodePositions[]> {+ const nodePositionGroup: IRectRangeNodePositions[] = [];+ const compare = compareNodePositionInTable(anchorNodePosition, focusNodePosition);+ const startNodePosition = compare ? anchorNodePosition : focusNodePosition;+ const endNodePosition = compare ? focusNodePosition : anchorNodePosition;++ // Start segmentPage will equal to end segmentPage.+ const { segmentPage } = startNodePosition;+ const rectInfo = this._getTableRectRangeInfo(startNodePosition, endNodePosition);++ if (rectInfo == null) {+ return;+ }++ const { tableId, pages, startRowIndex, startColumnIndex, endRowIndex, endColumnIndex } = rectInfo;++ const tables: IDocumentSkeletonTable[] = [];++ // TODO: @JOCS handle table in header and footer.+ for (const page of pages) {+ const { skeTables } = page;++ for (const [id, table] of skeTables.entries()) {+ if (id.startsWith(tableId)) {+ tables.push(table);+ }+ }+ }++ if (tables.length === 0) {+ return;+ }++ const totalColumns = tables[0].rows[0].cells.length;++ // Span entires row.+ if (startColumnIndex === 0 && endColumnIndex === totalColumns - 1) {+ nodePositionGroup.push({+ anchor: anchorNodePosition,+ focus: focusNodePosition,+ });++ return nodePositionGroup;+ }++ for (const table of tables) {+ this._collectPositionGroup(table, nodePositionGroup, startRowIndex, endRowIndex, startColumnIndex, endColumnIndex, segmentPage, compare);+ }++ return nodePositionGroup;+ }++ private _collectPositionGroup(+ table: IDocumentSkeletonTable,+ nodePositionGroup: IRectRangeNodePositions[],+ startRowIndex: number,+ endRowIndex: number,+ startColumnIndex: number,+ endColumnIndex: number,+ segmentPage: number,+ compare: boolean+ ) {+ // Not span entires row.+ for (let i = 0; i < table.rows.length; i++) {+ const row = table.rows[i];++ if (row.index < startRowIndex) {+ continue;+ }++ if (row.index > endRowIndex) {+ break;+ }++ const startCellInRow = row.cells[startColumnIndex];+ const endCellInRow = row.cells[endColumnIndex];++ const startCellGlyph = firstGlyphInCellPage(startCellInRow);+ const endCellGlyph = lastGlyphInCellPage(endCellInRow);++ if (startCellGlyph == null || endCellGlyph == null) {+ continue;+ }++ const startPosition = this._docSkeleton.findPositionByGlyph(startCellGlyph, segmentPage);+ const endPosition = this._docSkeleton.findPositionByGlyph(endCellGlyph, segmentPage);++ if (startPosition == null || endPosition == null) {+ continue;+ }++ const anchor = compare ? startPosition : endPosition;+ const focus = compare ? endPosition : startPosition;++ nodePositionGroup.push({+ anchor: {+ ...anchor,+ isBack: true, // true or false is the same.+ },+ focus: {+ ...focus,+ isBack: true,+ },+ });+ }+ }++ private _getTableRectRangeInfo(startNodePosition: INodePosition, endNodePosition: INodePosition) {+ const docSkeleton = this._docSkeleton;+ const skeletonData = docSkeleton.getSkeletonData();++ if (skeletonData == null) {+ return;+ }++ const { pages } = skeletonData;++ const { path: startPath } = startNodePosition;+ const { path: endPath } = endNodePosition;+ const startCell = getPageFromPath(skeletonData, startPath);+ const endCell = getPageFromPath(skeletonData, endPath);++ if (startCell == null || endCell == null) {+ return;+ }++ const tableId = startCell.segmentId;+ const startRow = (startCell.parent as IDocumentSkeletonRow).index;+ const startColumn = (startCell.parent as IDocumentSkeletonRow).cells.indexOf(startCell);++ const endRow = (endCell?.parent as IDocumentSkeletonRow).index;+ const endColumn = (endCell?.parent as IDocumentSkeletonRow).cells.indexOf(endCell);++ return {+ pages,+ tableId,+ startCell,+ endCell,+ startRowIndex: startRow,+ startColumnIndex: startColumn,+ endRowIndex: endRow,+ endColumnIndex: endColumn,+ };+ }+}diff --git a/packages/engine-render/src/components/docs/text-selection/convert-cursor.ts b/packages/engine-render/src/components/docs/text-selection/convert-text-range.tssimilarity index 87%rename from packages/engine-render/src/components/docs/text-selection/convert-cursor.tsrename to packages/engine-render/src/components/docs/text-selection/convert-text-range.tsindex 8a2eb818f5..2ca2256d86 100644--- a/packages/engine-render/src/components/docs/text-selection/convert-cursor.ts+++ b/packages/engine-render/src/components/docs/text-selection/convert-text-range.ts@@ -17,11 +17,13 @@import type { IPosition, ITextRange, Nullable } from '@univerjs/core';import type {+ IDocumentSkeletonCached,IDocumentSkeletonColumn,IDocumentSkeletonDivide,IDocumentSkeletonGlyph,IDocumentSkeletonLine,IDocumentSkeletonPage,+ IDocumentSkeletonRow,IDocumentSkeletonSection,} from '../../../basics/i-document-skeleton-cached';import { DocumentSkeletonPageType, GlyphType } from '../../../basics/i-document-skeleton-cached';@@ -179,6 +181,62 @@ function getOffsetInDivide(};}+export function pushToPoints(position: IPosition) {+ const { startX, startY, endX, endY } = position;+ const points: Array<{ x: number; y: number }> = [];++ points.push({+ x: startX,+ y: startY,+ });++ points.push({+ x: endX,+ y: startY,+ });++ points.push({+ x: endX,+ y: endY,+ });++ points.push({+ x: startX,+ y: endY,+ });++ points.push({+ x: startX,+ y: startY,+ });++ return points;+}++export function getPageFromPath(skeletonData: IDocumentSkeletonCached, path: (string | number)[]): Nullable<IDocumentSkeletonPage> {+ const pathCopy = [...path];+ let page: Nullable<IDocumentSkeletonPage> = null;++ while (pathCopy.length > 0) {+ const field = pathCopy.shift();++ if (field === 'pages') {+ const pageIndex = pathCopy.shift() as number;+ page = skeletonData.pages[pageIndex];+ } else if (field === 'skeTables') {+ const tableId = pathCopy.shift() as string;+ pathCopy.shift(); // rows+ const rowIndex = pathCopy.shift() as number;+ pathCopy.shift(); // cells+ const cellIndex = pathCopy.shift() as number;++ page = page!.skeTables?.get(tableId)?.rows[rowIndex]?.cells[cellIndex];+ }+ }++ return page;+}+export class NodePositionConvertToCursor {private _liquid = new Liquid();@@ -294,8 +352,8 @@ export class NodePositionConvertToCursor {};}- borderBoxPointGroup.push(this._pushToPoints(borderBoxPosition));- contentBoxPointGroup.push(this._pushToPoints(contentBoxPosition));+ borderBoxPointGroup.push(pushToPoints(borderBoxPosition));+ contentBoxPointGroup.push(pushToPoints(contentBoxPosition));cursorList.push({startOffset: isStartBack ? startOffset : startOffset + firstGlyph.count,@@ -433,38 +491,6 @@ export class NodePositionConvertToCursor {};}- private _pushToPoints(position: IPosition) {- const { startX, startY, endX, endY } = position;- const points: Array<{ x: number; y: number }> = [];-- points.push({- x: startX,- y: startY,- });-- points.push({- x: endX,- y: startY,- });-- points.push({- x: endX,- y: endY,- });-- points.push({- x: startX,- y: endY,- });-- points.push({- x: startX,- y: startY,- });-- return points;- }-private _selectionIterator(startPosition: INodePosition,endPosition: INodePosition,@@ -485,7 +511,7 @@ export class NodePositionConvertToCursor {return [];}- const { pageType } = startPosition; // startPosition and endPosition must has the same pageType and in the same segment page.+ const { pageType, path } = startPosition; // startPosition and endPosition must has the same pageType, path and in the same segment page.this._liquid.reset();@@ -508,14 +534,13 @@ export class NodePositionConvertToCursor {const { pageLayoutType, pageMarginLeft, pageMarginTop } = this._documentOffsetConfig;- const skipPageIndex = pageType === DocumentSkeletonPageType.BODY ? pageIndex : segmentPage;-+ const skipPageIndex = (pageType === DocumentSkeletonPageType.BODY || pageType === DocumentSkeletonPageType.CELL) ? pageIndex : segmentPage;for (let p = 0; p < skipPageIndex; p++) {const page = pages[p];this._liquid.translatePage(page, pageLayoutType, pageMarginLeft, pageMarginTop);}- const endIndex = pageType === DocumentSkeletonPageType.BODY ? endPageIndex : endSegmentPage;+ const endIndex = (pageType === DocumentSkeletonPageType.BODY || pageType === DocumentSkeletonPageType.CELL) ? endPageIndex : endSegmentPage;for (let p = skipPageIndex; p <= endIndex; p++) {const page = pages[p];@@ -526,6 +551,8 @@ export class NodePositionConvertToCursor {segmentPage = skeHeaders.get(headerId)?.get(pageWidth);} else if (pageType === DocumentSkeletonPageType.FOOTER) {segmentPage = skeFooters.get(footerId)?.get(pageWidth);+ } else if (pageType === DocumentSkeletonPageType.CELL) {+ segmentPage = getPageFromPath(skeletonData, path);}if (segmentPage == null) {@@ -540,7 +567,7 @@ export class NodePositionConvertToCursor {startPosition,endPosition,sections.length - 1,- pageType === DocumentSkeletonPageType.BODY ? p : 0+ pageType === DocumentSkeletonPageType.BODY || pageType === DocumentSkeletonPageType.CELL ? p : 0);this._liquid.translateSave();@@ -556,6 +583,18 @@ export class NodePositionConvertToCursor {this._liquid.translate(page.marginLeft, footerTop);break;}+ case DocumentSkeletonPageType.CELL: {+ this._liquid.translatePagePadding(page);+ const rowSke = segmentPage.parent as IDocumentSkeletonRow;+ const tableSke = rowSke.parent!;+ const { left: cellLeft } = segmentPage;+ const { top: tableTop, left: tableLeft } = tableSke;+ const { top: rowTop } = rowSke;++ this._liquid.translate(tableLeft + cellLeft, tableTop + rowTop);+ this._liquid.translatePagePadding(segmentPage);+ break;+ }default:this._liquid.translatePagePadding(page);break;diff --git a/packages/engine-render/src/components/docs/text-selection/range-interface.ts b/packages/engine-render/src/components/docs/text-selection/range-interface.tsnew file mode 100644index 0000000000..8462b62afd--- /dev/null+++ b/packages/engine-render/src/components/docs/text-selection/range-interface.ts@@ -0,0 +1,49 @@+/**+ * 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 { Nullable } from '@univerjs/core';+import type { INodePosition, ITextSelectionStyle, RANGE_DIRECTION } from '../../../basics';++export enum DOC_RANGE_TYPE {+ RECT = 'RECT',+ TEXT = 'TEXT',+}++export interface IDocRange {+ // RECT OR TEXT.+ rangeType: DOC_RANGE_TYPE;++ anchorNodePosition?: Nullable<INodePosition>;+ focusNodePosition?: Nullable<INodePosition>;+ // The style of selection and cursor.+ style: ITextSelectionStyle;++ // The start of selection in the dataStream.+ get startOffset(): Nullable<number>;+ // The end of selection in the dataStream.+ get endOffset(): Nullable<number>;+ // Whether the selection is collapsed. rect range will never collapsed.+ get collapsed(): boolean;+ get startNodePosition(): Nullable<INodePosition>;+ get endNodePosition(): Nullable<INodePosition>;+ get direction(): RANGE_DIRECTION;++ isActive(): boolean;++ dispose(): void;+ // Refresh the selection shape.+ refresh(): void;+}diff --git a/packages/engine-render/src/components/docs/text-selection/rect-range.ts b/packages/engine-render/src/components/docs/text-selection/rect-range.tsnew file mode 100644index 0000000000..d91297882a--- /dev/null+++ b/packages/engine-render/src/components/docs/text-selection/rect-range.ts@@ -0,0 +1,263 @@+/**+ * 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 { COLORS, type Nullable, Rectangle, Tools } from '@univerjs/core';+import type { INodePosition, IPoint, ITextSelectionStyle } from '../../../basics';+import { getColor, NORMAL_TEXT_SELECTION_PLUGIN_STYLE, RANGE_DIRECTION } from '../../../basics';+import type { ThinScene } from '../../../thin-scene';+import type { Documents } from '../document';+import type { DocumentSkeleton } from '../layout/doc-skeleton';+import { RegularPolygon } from '../../../shape';+import type { IDocRange } from './range-interface';+import { DOC_RANGE_TYPE } from './range-interface';+import { compareNodePositionInTable, NodePositionConvertToRectRange } from './convert-rect-range';+import { TEXT_RANGE_LAYER_INDEX } from './text-range';++const RECT_RANGE_KEY_PREFIX = '__DocTableRectRange__';+const ID_LENGTH = 6;++export function convertPositionsToRectRanges(+ scene: ThinScene,+ document: Documents,+ docSkeleton: DocumentSkeleton,+ anchorNodePosition: INodePosition,+ focusNodePosition: INodePosition,+ style: ITextSelectionStyle = NORMAL_TEXT_SELECTION_PLUGIN_STYLE,+ segmentId: string = ''+): RectRange[] {+ const documentOffsetConfig = document.getOffsetConfig();+ const convertor = new NodePositionConvertToRectRange(documentOffsetConfig, docSkeleton);+ const nodePositionGroup = convertor.getNodePositionGroup(anchorNodePosition, focusNodePosition);++ return (nodePositionGroup ?? []).map((position) => new RectRange(+ scene, document, docSkeleton, position.anchor, position.focus, style, segmentId+ ));+}++export class RectRange implements IDocRange {+ public rangeType: DOC_RANGE_TYPE = DOC_RANGE_TYPE.RECT;+ // The rendered rect range+ private _rangeShape: Nullable<RegularPolygon>;+ // Identifies whether the range is the current one, most of which is the last range.+ private _current = false;+ // Rect Range start row.+ private _startRow: number;+ // Rect Range start column.+ private _startCol: number;+ // Rect Range end row.+ private _endRow: number;+ // Rect Range end column.+ private _endCol: number;+ // table id in view model.+ private _tableId: string;++ constructor(+ private _scene: ThinScene,+ private _document: Documents,+ private _docSkeleton: DocumentSkeleton,+ public anchorNodePosition: INodePosition,+ public focusNodePosition: INodePosition,+ public style: ITextSelectionStyle = NORMAL_TEXT_SELECTION_PLUGIN_STYLE,+ private _segmentId: string = ''+ ) {+ this.refresh();+ }++ get startOffset(): Nullable<number> {+ const { startNodePosition } = this;++ return this._docSkeleton.findCharIndexByPosition(startNodePosition);+ }++ get endOffset(): Nullable<number> {+ const { endNodePosition } = this;++ return this._docSkeleton.findCharIndexByPosition(endNodePosition);+ }++ get collapsed(): boolean {+ return false;+ }++ get startRow() {+ return this._startRow;+ }++ get startColumn() {+ return this._startCol;+ }++ get endRow() {+ return this._endRow;+ }++ get endColumn() {+ return this._endCol;+ }++ get tableId() {+ return this._tableId;+ }++ get segmentId() {+ return this._segmentId;+ }++ get spanEntireRow(): boolean {+ const viewModel = this._docSkeleton.getViewModel();+ const table = viewModel.getSnapshot().tableSource?.[this._tableId];+ const { _startCol, _endCol } = this;+ if (table == null) {+ throw new Error('Table is not found.');+ }++ const { tableColumns } = table;++ return _startCol === 0 && _endCol === tableColumns.length - 1;+ }++ get spanEntireColumn(): boolean {+ const viewModel = this._docSkeleton.getViewModel();+ const table = viewModel.getSnapshot().tableSource?.[this._tableId];+ const { _startRow, _endRow } = this;+ if (table == null) {+ throw new Error('Table is not found.');+ }++ const { tableRows } = table;++ return _startRow === 0 && _endRow === tableRows.length - 1;+ }++ get spanEntireTable(): boolean {+ return this.spanEntireRow && this.spanEntireColumn;+ }++ get startNodePosition(): INodePosition {+ const { anchorNodePosition, focusNodePosition } = this;+ const compare = compareNodePositionInTable(anchorNodePosition, focusNodePosition);++ return compare ? anchorNodePosition : focusNodePosition;+ }++ get endNodePosition(): INodePosition {+ const { anchorNodePosition, focusNodePosition } = this;+ const compare = compareNodePositionInTable(anchorNodePosition, focusNodePosition);++ return compare ? focusNodePosition : anchorNodePosition;+ }++ get direction(): RANGE_DIRECTION {+ const { anchorNodePosition, focusNodePosition } = this;+ const compare = compareNodePositionInTable(anchorNodePosition, focusNodePosition);++ return compare ? RANGE_DIRECTION.FORWARD : RANGE_DIRECTION.BACKWARD;+ }++ isActive() {+ return this._current === true;+ }++ activate() {+ this._current = true;+ }++ deactivate() {+ this._current = false;+ }++ dispose(): void {+ this._rangeShape?.dispose();+ this._rangeShape = null;+ }++ isIntersection(compareRange: RectRange) {+ const { startRow, startColumn, endRow, endColumn } = this;+ const { startRow: cStartRow, startColumn: cStartColumn, endRow: cEndRow, endColumn: cEndColumn } = compareRange;+ const rect1 = {+ left: startColumn,+ top: startRow,+ right: endColumn,+ bottom: endRow,+ };+ const rect2 = {+ left: cStartColumn,+ top: cStartRow,+ right: cEndColumn,+ bottom: cEndRow,+ };++ return Rectangle.hasIntersectionBetweenTwoRect(rect1, rect2);+ }++ refresh(): void {+ this._rangeShape?.hide();++ const { startNodePosition, endNodePosition, _document, _docSkeleton } = this;++ const documentOffsetConfig = _document.getOffsetConfig();++ const { docsLeft, docsTop } = documentOffsetConfig;++ const convertor = new NodePositionConvertToRectRange(documentOffsetConfig, _docSkeleton);++ const rectInfo = convertor.getRangePointData(startNodePosition, endNodePosition);++ if (rectInfo == null) {+ return;+ }++ const { pointGroup = [], startRow, endRow, startColumn, endColumn, tableId } = rectInfo;++ if (pointGroup?.length > 0) {+ this._createOrUpdateRange(pointGroup, docsLeft, docsTop);+ }++ this._updateTableInfo(startRow, endRow, startColumn, endColumn, tableId);+ }++ private _updateTableInfo(startRow: number, endRow: number, startCol: number, endCol: number, tableId: string) {+ this._startRow = startRow;+ this._endRow = endRow;+ this._startCol = startCol;+ this._endCol = endCol;+ this._tableId = tableId;+ }++ private _createOrUpdateRange(pointsGroup: IPoint[][], left: number, top: number) {+ if (this._rangeShape) {+ this._rangeShape.translate(left, top);+ this._rangeShape.updatePointGroup(pointsGroup);+ this._rangeShape.show();++ return;+ }++ const OPACITY = 0.3;+ const polygon = new RegularPolygon(RECT_RANGE_KEY_PREFIX + Tools.generateRandomId(ID_LENGTH), {+ pointsGroup,+ fill: this.style?.fill || getColor(COLORS.black, OPACITY),+ left,+ top,+ evented: false,+ debounceParentDirty: false,+ });++ this._rangeShape = polygon;++ this._scene.addObject(polygon, TEXT_RANGE_LAYER_INDEX);+ }+}diff --git a/packages/engine-render/src/components/docs/text-selection/selection-utils.ts b/packages/engine-render/src/components/docs/text-selection/selection-utils.tsnew file mode 100644index 0000000000..4511300329--- /dev/null+++ b/packages/engine-render/src/components/docs/text-selection/selection-utils.ts@@ -0,0 +1,253 @@+/**+ * 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 { Nullable } from '@univerjs/core';+import type { IDocumentSkeletonGlyph, INodePosition, ITextSelectionStyle } from '../../../basics';+import { RANGE_DIRECTION } from '../../../basics';+import { getOffsetRectForDom } from '../../../basics/position';+import type { DocumentSkeleton } from '../layout/doc-skeleton';+import type { Engine } from '../../../engine';+import type { Documents } from '../document';+import type { Scene } from '../../../scene';+import { convertPositionsToRectRanges, type RectRange } from './rect-range';+import { TextRange } from './text-range';+import { isInSameTableCell, isValidRectRange } from './convert-rect-range';++interface IDocRangeList {+ textRanges: TextRange[];+ rectRanges: RectRange[];+}++export function getRangeListFromCharIndex(+ startOffset: number,+ endOffset: number,+ scene: Scene,+ document: Documents,+ skeleton: DocumentSkeleton,+ style: ITextSelectionStyle,+ segmentId: string,+ segmentPage: number+): Nullable<IDocRangeList> {+ const startNodePosition = skeleton.findNodePositionByCharIndex(startOffset, true, segmentId, segmentPage);+ const endNodePosition = skeleton.findNodePositionByCharIndex(endOffset, true, segmentId, segmentPage);++ if (startNodePosition == null || endNodePosition == null) {+ return;+ }++ return getRangeListFromSelection(+ startNodePosition,+ endNodePosition,+ scene,+ document,+ skeleton,+ style,+ segmentId,+ segmentPage+ );+}++export function getRangeListFromSelection(+ anchorPosition: INodePosition,+ focusPosition: INodePosition,+ scene: Scene,+ document: Documents,+ skeleton: DocumentSkeleton,+ style: ITextSelectionStyle,+ segmentId: string,+ segmentPage: number+): Nullable<IDocRangeList> {+ const textRanges: TextRange[] = [];+ const rectRanges: RectRange[] = [];+ const rangeParams: [+ Scene,+ Documents,+ DocumentSkeleton,+ INodePosition,+ INodePosition,+ ITextSelectionStyle,+ string+ ] = [scene, document, skeleton, anchorPosition, focusPosition, style, segmentId];++ // TODO: @JOCS handle NEST table.+ // Handle selection in same table cell.+ if (isInSameTableCell(anchorPosition, focusPosition)) {+ textRanges.push(new TextRange(...rangeParams));++ return {+ textRanges,+ rectRanges,+ };+ }++ // Handle selection in different table cell but in the same table.+ if (isValidRectRange(anchorPosition, focusPosition)) {+ const ranges = convertPositionsToRectRanges(+ ...rangeParams+ );++ rectRanges.push(...ranges);++ return {+ textRanges,+ rectRanges,+ };+ }++ const viewModel = skeleton.getViewModel().getSelfOrHeaderFooterViewModel(segmentId);+ const anchorOffset = skeleton.findCharIndexByPosition(anchorPosition);+ const focusOffset = skeleton.findCharIndexByPosition(focusPosition);++ if (anchorOffset == null || focusOffset == null) {+ return;+ }++ const direction = anchorOffset <= focusOffset ? RANGE_DIRECTION.FORWARD : RANGE_DIRECTION.BACKWARD;++ const startOffset = Math.min(anchorOffset, focusOffset);+ const endOffset = Math.max(anchorOffset, focusOffset);++ let start = startOffset;+ let end = endOffset;++ // TODO: @JOCS handle in header and footer.+ for (const section of viewModel.children) {+ for (const paragraph of section.children) {+ const { startIndex, endIndex, children } = paragraph;+ const table = children[0];++ let endInTable = false;++ if (table) {+ const { startIndex: tableStart, endIndex: tableEnd, children } = table;+ let tableStartPosition = null;+ let tableEndPosition = null;++ const startRow = children.find((row) => row.startIndex <= startOffset && row.endIndex >= startOffset)!;+ const endRow = children.find((row) => row.startIndex <= endOffset && row.endIndex >= endOffset)!;++ if (startOffset > tableStart && startOffset < tableEnd) {+ tableStartPosition = skeleton.findNodePositionByCharIndex(startRow.startIndex + 2, true, segmentId, segmentPage);+ tableEndPosition = skeleton.findNodePositionByCharIndex(tableEnd - 4, true, segmentId, segmentPage);+ start = tableEnd + 1;+ } else if (endOffset > tableStart && endOffset < tableEnd) {+ tableStartPosition = skeleton.findNodePositionByCharIndex(tableStart + 3, true, segmentId, segmentPage);+ tableEndPosition = skeleton.findNodePositionByCharIndex(endRow.endIndex - 3, true, segmentId, segmentPage);+ end = tableStart - 1;++ endInTable = true;+ } else if (tableStart > startOffset && tableEnd < endOffset) {+ tableStartPosition = skeleton.findNodePositionByCharIndex(tableStart + 3, true, segmentId, segmentPage);+ tableEndPosition = skeleton.findNodePositionByCharIndex(tableEnd - 4, true, segmentId, segmentPage);++ if (start < tableStart - 1) {+ const sp = skeleton.findNodePositionByCharIndex(start, true, segmentId, segmentPage);+ const ep = skeleton.findNodePositionByCharIndex(tableStart - 1, true, segmentId, segmentPage);+ const ap = direction ? sp : ep;+ const fp = direction ? ep : sp;++ textRanges.push(new TextRange(scene, document, skeleton, ap, fp, style, segmentId));+ }+ start = tableEnd + 1;+ }++ if (tableStartPosition && tableEndPosition) {+ const ap = direction ? tableStartPosition : tableEndPosition;+ const fp = direction ? tableEndPosition : tableStartPosition;++ rectRanges.push(...convertPositionsToRectRanges(+ scene,+ document,+ skeleton,+ ap,+ fp,+ style,+ segmentId+ ));+ }+ }++ if ((end >= startIndex && end <= endIndex) || endInTable) {+ const sp = skeleton.findNodePositionByCharIndex(start, true, segmentId, segmentPage);+ const ep = skeleton.findNodePositionByCharIndex(end, true, segmentId, segmentPage);+ const ap = direction ? sp : ep;+ const fp = direction ? ep : sp;++ textRanges.push(new TextRange(scene, document, skeleton, ap, fp, style, segmentId));+ }+ }+ }++ return {+ textRanges,+ rectRanges,+ };+}++export function getCanvasOffsetByEngine(engine: Nullable<Engine>) {+ const canvas = engine?.getCanvasElement();++ if (!canvas) {+ return {+ left: 0,+ top: 0,+ };+ }++ const { top, left } = getOffsetRectForDom(canvas);++ return {+ left,+ top,+ };+}++export function getParagraphInfoByGlyph(node: IDocumentSkeletonGlyph) {+ const line = node.parent?.parent;+ const column = line?.parent;++ if (line == null || column == null) {+ return;+ }++ const { paragraphIndex } = line;+ const lines = column.lines.filter((line) => line.paragraphIndex === paragraphIndex);+ let nodeIndex = -1;+ let content = '';+ let hasFound = false;++ for (const line of lines) {+ for (const divide of line.divides) {+ for (const glyph of divide.glyphGroup) {+ if (!hasFound) {+ nodeIndex += glyph.count;+ }+ if (glyph === node) {+ hasFound = true;+ }++ content += glyph.count > 0 ? glyph.content : '';+ }+ }+ }++ return {+ st: lines[0].st,+ ed: paragraphIndex,+ content,+ nodeIndex,+ };+}diff --git a/packages/engine-render/src/components/docs/text-selection/text-range.ts b/packages/engine-render/src/components/docs/text-selection/text-range.tsindex 8aaf14ffac..a7ae7e500a 100644--- a/packages/engine-render/src/components/docs/text-selection/text-range.ts+++ b/packages/engine-render/src/components/docs/text-selection/text-range.ts@@ -16,9 +16,8 @@import type { ITextRange, Nullable } from '@univerjs/core';import { BooleanNumber, COLORS, Tools } from '@univerjs/core';-import type { INodePosition } from '../../../basics/interfaces';-import type { ISuccinctTextRangeParam, ITextSelectionStyle } from '../../../basics/range';+import type { ISuccinctDocRangeParam, ITextSelectionStyle } from '../../../basics/range';import { NORMAL_TEXT_SELECTION_PLUGIN_STYLE, RANGE_DIRECTION } from '../../../basics/range';import { getColor } from '../../../basics/tools';import type { IPoint } from '../../../basics/vector2';@@ -35,7 +34,9 @@ import {getOneTextSelectionRange,NodePositionConvertToCursor,NodePositionMap,-} from './convert-cursor';+} from './convert-text-range';+import type { IDocRange } from './range-interface';+import { DOC_RANGE_TYPE } from './range-interface';const TEXT_RANGE_KEY_PREFIX = '__TestSelectionRange__';const TEXT_ANCHOR_KEY_PREFIX = '__TestSelectionAnchor__';@@ -48,17 +49,18 @@ export const TEXT_RANGE_LAYER_INDEX = 3;export function cursorConvertToTextRange(scene: Scene,- range: ISuccinctTextRangeParam,+ range: ISuccinctDocRangeParam,docSkeleton: DocumentSkeleton,document: Documents): Nullable<TextRange> {const { startOffset, endOffset, style = NORMAL_TEXT_SELECTION_PLUGIN_STYLE, segmentId = '', segmentPage } = range;const anchorNodePosition = docSkeleton.findNodePositionByCharIndex(startOffset, true, segmentId, segmentPage);- const focusNodePosition = startOffset !== endOffset ? docSkeleton.findNodePositionByCharIndex(endOffset, true, segmentId, segmentPage) : null;-- const textRange = new TextRange(scene, document, docSkeleton, anchorNodePosition, focusNodePosition, style);-- textRange.refresh();+ const focusNodePosition = startOffset !== endOffset+ ? docSkeleton.findNodePositionByCharIndex(endOffset, true, segmentId, segmentPage)+ : null;+ const textRange = new TextRange(+ scene, document, docSkeleton, anchorNodePosition, focusNodePosition, style, segmentId+ );return textRange;}@@ -69,7 +71,6 @@ export function getAnchorBounding(pointsGroup: IPoint[][]) {const endPoint = points[2];const { x: startX, y: startY } = startPoint;-const { x: endX, y: endY } = endPoint;return {@@ -102,7 +103,8 @@ export function getLineBounding(pointsGroup: IPoint[][]) {});}-export class TextRange {+export class TextRange implements IDocRange {+ public rangeType: DOC_RANGE_TYPE = DOC_RANGE_TYPE.TEXT;// Identifies whether the range is the current one, most of which is the last range.private _current = false;// The rendered range graphic when collapsed is false@@ -120,9 +122,12 @@ export class TextRange {private _docSkeleton: DocumentSkeleton,public anchorNodePosition?: Nullable<INodePosition>,public focusNodePosition?: Nullable<INodePosition>,- public style: ITextSelectionStyle = NORMAL_TEXT_SELECTION_PLUGIN_STYLE+ public style: ITextSelectionStyle = NORMAL_TEXT_SELECTION_PLUGIN_STYLE,+ private _segmentId: string = '') {this._anchorBlink();++ this.refresh();}private _anchorBlink() {@@ -150,7 +155,11 @@ export class TextRange {// The start position of the rangeget startOffset() {const { startOffset } = getOneTextSelectionRange(this._cursorList) ?? {};- const body = this._docSkeleton.getViewModel().getBody();+ const body = this._docSkeleton+ .getViewModel()+ .getDataModel()+ .getSelfOrHeaderFooterModel(this._segmentId)+ .getBody();if (startOffset == null || body == null) {return startOffset;@@ -164,7 +173,11 @@ export class TextRange {// The end position of the rangeget endOffset() {const { endOffset } = getOneTextSelectionRange(this._cursorList) ?? {};- const body = this._docSkeleton.getViewModel().getBody();+ const body = this._docSkeleton+ .getViewModel()+ .getDataModel()+ .getSelfOrHeaderFooterModel(this._segmentId)+ .getBody();if (endOffset == null || body == null) {return endOffset;@@ -221,6 +234,10 @@ export class TextRange {return compare ? RANGE_DIRECTION.FORWARD : RANGE_DIRECTION.BACKWARD;}+ get segmentId() {+ return this._segmentId;+ }+getAbsolutePosition() {const anchor = this.anchorNodePosition;const focus = this.focusNodePosition;@@ -319,6 +336,7 @@ export class TextRange {return activeStart <= compareEnd && activeEnd >= compareStart;}+ // render cursor and selection.refresh() {const { _document, _docSkeleton } = this;const anchor = this.anchorNodePosition;diff --git a/packages/engine-render/src/components/docs/text-selection/text-selection-render-manager.ts b/packages/engine-render/src/components/docs/text-selection/text-selection-render-manager.tsindex 08aca6073c..3f97f0656e 100644--- a/packages/engine-render/src/components/docs/text-selection/text-selection-render-manager.ts+++ b/packages/engine-render/src/components/docs/text-selection/text-selection-render-manager.ts@@ -20,13 +20,11 @@ import type { Observable, Subscription } from 'rxjs';import { BehaviorSubject, fromEvent, Subject } from 'rxjs';import { CURSOR_TYPE } from '../../../basics/const';-import type { IDocumentSkeletonGlyph } from '../../../basics/i-document-skeleton-cached';import { PageLayoutType } from '../../../basics/i-document-skeleton-cached';import type { IMouseEvent, IPointerEvent } from '../../../basics/i-events';import type { INodeInfo, INodePosition } from '../../../basics/interfaces';-import { getOffsetRectForDom } from '../../../basics/position';import type {- ISuccinctTextRangeParam,+ ISuccinctDocRangeParam,ITextRangeWithStyle,ITextSelectionStyle,RANGE_DIRECTION,@@ -40,65 +38,13 @@ import type { IScrollObserverParam, Viewport } from '../../../viewport';import type { DocumentSkeleton, IFindNodeRestrictions } from '../layout/doc-skeleton';import type { Documents } from '../document';import { getSystemHighlightColor } from '../../../basics/tools';-import { cursorConvertToTextRange, TextRange } from './text-range';--export function getCanvasOffsetByEngine(engine: Nullable<Engine>) {- const canvas = engine?.getCanvasElement();-- if (!canvas) {- return {- left: 0,- top: 0,- };- }-- const { top, left } = getOffsetRectForDom(canvas);-- return {- left,- top,- };-}--function getParagraphInfoByGlyph(node: IDocumentSkeletonGlyph) {- const line = node.parent?.parent;- const column = line?.parent;-- if (line == null || column == null) {- return;- }-- const { paragraphIndex } = line;- const lines = column.lines.filter((line) => line.paragraphIndex === paragraphIndex);- let nodeIndex = -1;- let content = '';- let hasFound = false;-- for (const line of lines) {- for (const divide of line.divides) {- for (const glyph of divide.glyphGroup) {- if (!hasFound) {- nodeIndex += glyph.count;- }- if (glyph === node) {- hasFound = true;- }-- content += glyph.count > 0 ? glyph.content : '';- }- }- }-- return {- st: lines[0].st,- ed: paragraphIndex,- content,- nodeIndex,- };-}+import { TextRange } from './text-range';+import type { RectRange } from './rect-range';+import { getCanvasOffsetByEngine, getParagraphInfoByGlyph, getRangeListFromCharIndex, getRangeListFromSelection } from './selection-utils';export interface ITextSelectionInnerParam {textRanges: TextRange[];+ rectRanges: RectRange[];segmentId: string;isEditing: boolean;style: ITextSelectionStyle;@@ -142,24 +88,25 @@ export interface ITextSelectionRenderManager {getSegmentPage(): number;setStyle(style: ITextSelectionStyle): void;resetStyle(): void;- removeAllTextRanges(): void;- addTextRanges(ranges: ISuccinctTextRangeParam[], isEditing?: boolean, options?: { [key: string]: boolean }): void;+ removeAllRanges(): void;+ addDocRanges(ranges: ISuccinctDocRangeParam[], isEditing?: boolean, options?: { [key: string]: boolean }): void;sync(): void;+activate(x: number, y: number): void;deactivate(): void;hasFocus(): boolean;focus(): void;blur(): void;-focusEditor(): void;blurEditor(): void;+changeRuntime(docSkeleton: DocumentSkeleton, scene: Scene, document: Documents): void;dispose(): void;handleDblClick(evt: IPointerEvent | IMouseEvent): void;handleTripleClick(evt: IPointerEvent | IMouseEvent): void;- eventTrigger(evt: IPointerEvent | IMouseEvent): void;+ onPointDown(evt: IPointerEvent | IMouseEvent): void;setCursorManually(evtOffsetX: number, evtOffsetY: number): void;}@@ -211,9 +158,16 @@ export class TextSelectionRenderManager extends RxDisposable implements ITextSelprivate _inputParent!: HTMLDivElement;private _input!: HTMLDivElement;private _scrollTimers: ScrollTimer[] = [];- private _viewportScrollX: number = 0;- private _viewportScrollY: number = 0;private _rangeList: TextRange[] = [];+ // Use to cache range list in moving.+ private _rangeListCache: TextRange[] = [];+ // Rect range list.+ private _rectRangeList: RectRange[] = [];+ // Use to cache rect range list in moving.+ private _rectRangeListCache: RectRange[] = [];+ private _anchorNodePosition: Nullable<INodePosition> = null;+ private _focusNodePosition: Nullable<INodePosition> = null;+private _currentSegmentId: string = '';private _currentSegmentPage: number = -1;private _selectionStyle: ITextSelectionStyle = NORMAL_TEXT_SELECTION_PLUGIN_STYLE;@@ -237,9 +191,7 @@ export class TextSelectionRenderManager extends RxDisposable implements ITextSelconstructor(@ILogService private readonly _logService: ILogService) {super();-this._initDOM();-this._setSystemHighlightColorToStyle();}@@ -283,7 +235,7 @@ export class TextSelectionRenderManager extends RxDisposable implements ITextSelthis._isSelectionEnabled = false;}- addTextRanges(ranges: ISuccinctTextRangeParam[], isEditing = true, options?: { [key: string]: boolean }) {+ addDocRanges(ranges: ISuccinctDocRangeParam[], isEditing = true, options?: { [key: string]: boolean }) {const {_scene: scene, _docSkeleton: docSkeleton, _document: document,_currentSegmentId: segmentId, _currentSegmentPage: segmentPage,@@ -291,18 +243,28 @@ export class TextSelectionRenderManager extends RxDisposable implements ITextSel} = this;for (const range of ranges) {- const textSelection = cursorConvertToTextRange(scene!, {- style: this._selectionStyle,- ...range,- segmentId,- segmentPage,- }, docSkeleton!, document!);+ const { startOffset, endOffset } = range;++ const rangeList = getRangeListFromCharIndex(+ startOffset, endOffset, scene!, document!, docSkeleton!, style, segmentId, segmentPage+ );++ if (rangeList == null) {+ continue;+ }- this._add(textSelection);+ const { textRanges, rectRanges } = rangeList;++ for (const textRange of textRanges) {+ this._addTextRange(textRange);+ }++ this._addRectRanges(rectRanges);}this._textSelectionInner$.next({textRanges: this._getAllTextRanges(),+ rectRanges: this._getAllRectRanges(),segmentId,segmentPage,style,@@ -323,7 +285,7 @@ export class TextSelectionRenderManager extends RxDisposable implements ITextSelconst position = this._getNodePosition(startNode);if (position == null) {- this._removeAllTextRanges();+ this._removeAllRanges();return;}@@ -339,6 +301,7 @@ export class TextSelectionRenderManager extends RxDisposable implements ITextSelthis._textSelectionInner$.next({textRanges: this._getAllTextRanges(),+ rectRanges: this._getAllRectRanges(),segmentId: this._currentSegmentId,segmentPage: this._currentSegmentPage,style: this._selectionStyle,@@ -393,7 +356,7 @@ export class TextSelectionRenderManager extends RxDisposable implements ITextSelchangeRuntime(docSkeleton: DocumentSkeleton, scene: Scene, document: Documents) {// Need to empty text ranges when change doc.if (docSkeleton !== this._docSkeleton) {- this.removeAllTextRanges();+ this.removeAllRanges();}this._docSkeleton = docSkeleton;@@ -457,7 +420,7 @@ export class TextSelectionRenderManager extends RxDisposable implements ITextSel}if (Number.isFinite(startOffset) && Number.isFinite(endOffset)) {- this.removeAllTextRanges();+ this.removeAllRanges();const textRanges = [{@@ -466,7 +429,7 @@ export class TextSelectionRenderManager extends RxDisposable implements ITextSel},];- this.addTextRanges(textRanges, false);+ this.addDocRanges(textRanges, false);}}@@ -491,7 +454,7 @@ export class TextSelectionRenderManager extends RxDisposable implements ITextSelreturn;}- this.removeAllTextRanges();+ this.removeAllRanges();const { st, ed } = paragraphInfo;@@ -503,11 +466,11 @@ export class TextSelectionRenderManager extends RxDisposable implements ITextSel},];- this.addTextRanges(textRanges, false);+ this.addDocRanges(textRanges, false);}// Handle pointer down.- eventTrigger(evt: IPointerEvent | IMouseEvent) {+ onPointDown(evt: IPointerEvent | IMouseEvent) {if (!this._scene || !this._isSelectionEnabled) {return;}@@ -523,19 +486,29 @@ export class TextSelectionRenderManager extends RxDisposable implements ITextSel});const position = this._getNodePosition(startNode);++ if (position == null || startNode == null) {+ this._removeAllRanges();++ return;+ }++ if (startNode?.node.streamType === DataStreamTreeTokenType.PARAGRAPH) {+ position.isBack = true;+ }+const textSelection = this._textSelectionInner$.value;if (startNode && evt.button === 2 && textSelection) {- const index = this._getNodeIndex(startNode);- if (textSelection.textRanges.some((textRange) => textRange.startOffset! <= index && textRange.endOffset! > index)) {+ const nodeCharIndex = this._docSkeleton?.findCharIndexByPosition(position);+ if (typeof nodeCharIndex === 'number' && textSelection.textRanges.some((textRange) => textRange.startOffset! <= nodeCharIndex && textRange.endOffset! > nodeCharIndex)) {return;}- }-- if (position == null || startNode == null) {- this._removeAllTextRanges();- return;+ if (typeof nodeCharIndex === 'number' && textSelection.rectRanges.some((rectRange) => rectRange.startOffset! <= nodeCharIndex && rectRange.endOffset! >= nodeCharIndex)) {+ return;+ }}+const { segmentId, segmentPage } = startNode;if (segmentId && this._currentSegmentId && segmentId !== this._currentSegmentId) {@@ -546,22 +519,14 @@ export class TextSelectionRenderManager extends RxDisposable implements ITextSelthis.setSegmentPage(segmentPage);}- if (startNode?.node.streamType === DataStreamTreeTokenType.PARAGRAPH) {- position.isBack = true;- }+ this._anchorNodePosition = position;if (evt.shiftKey && this._getActiveRangeInstance()) {- this._updateActiveRangeFocusPosition(position);- } else if (evt.ctrlKey || this._isEmpty()) {- const newTextSelection = new TextRange(scene, this._document!, this._docSkeleton!, position, undefined, this._selectionStyle);-- this._addTextRange(newTextSelection);- } else {- this._updateTextRangeAnchorPosition(position);+ this._updateActiveRangePosition(position);+ } else if (!evt.ctrlKey && !this._isEmpty()) {+ this._removeAllRanges();}- this._activeSelectionRefresh();-scene.disableEvent();const scrollTimer = ScrollTimer.create(scene);@@ -586,25 +551,38 @@ export class TextSelectionRenderManager extends RxDisposable implements ITextSelthis._moving(moveOffsetX, moveOffsetY);- // scrollTimer.scrolling(moveOffsetX, moveOffsetY, () => {- // this._moving(moveOffsetX, moveOffsetY);- // });-preMoveOffsetX = moveOffsetX;preMoveOffsetY = moveOffsetY;}));this._scenePointerUpSubs.push(scene.onPointerUp$.subscribeEvent(() => {- // scene.onPointerMoveObserver.remove(this._moveObserver);- // scene.onPointerUpObserver.remove(this._upObserver);[...this._scenePointerMoveSubs, ...this._scenePointerUpSubs].forEach((e) => {e.unsubscribe();});-scene.enableEvent();+ // Add cursor.+ if (this._anchorNodePosition && !this._focusNodePosition) {+ const textRange = new TextRange(this._scene!, this._document!, this._docSkeleton!, this._anchorNodePosition, undefined, this._selectionStyle, this._currentSegmentId);++ this._addTextRange(textRange);+ } else if (this._anchorNodePosition && this._focusNodePosition) {+ for (const textRange of this._rangeListCache) {+ this._addTextRange(textRange);+ }++ this._addRectRanges(this._rectRangeListCache);++ this._rangeListCache = [];+ this._rectRangeListCache = [];+ }++ this._anchorNodePosition = null;+ this._focusNodePosition = null;+const selectionInfo = {textRanges: this._getAllTextRanges(),+ rectRanges: this._getAllRectRanges(),segmentId: this._currentSegmentId,segmentPage: this._currentSegmentPage,style: this._selectionStyle,@@ -623,8 +601,8 @@ export class TextSelectionRenderManager extends RxDisposable implements ITextSel}));}- removeAllTextRanges() {- this._removeAllTextRanges();+ removeAllRanges() {+ this._removeAllRanges();this.deactivate();}@@ -646,6 +624,10 @@ export class TextSelectionRenderManager extends RxDisposable implements ITextSelreturn this._rangeList;}+ private _getAllRectRanges() {+ return this._rectRangeList;+ }+private _getActiveRange(): Nullable<IActiveTextRange> {const activeRange = this._rangeList.find((range) => range.isActive());@@ -672,17 +654,6 @@ export class TextSelectionRenderManager extends RxDisposable implements ITextSel};}- private _add(textRange: Nullable<TextRange>) {- if (textRange == null) {- return;- }-- this._addTextRange(textRange);-- // FIXME: @JOCS, why I need to refresh textRange? it already refreshed when create.- textRange.refresh();- }-private _getActiveRangeInstance() {return this._rangeList.find((range) => range.isActive());}@@ -691,7 +662,7 @@ export class TextSelectionRenderManager extends RxDisposable implements ITextSelsuper.dispose();this._detachEvent();- this._removeAllTextRanges();+ this._removeAllRanges();this._container.remove();}@@ -742,7 +713,7 @@ export class TextSelectionRenderManager extends RxDisposable implements ITextSel`;}- private _getNodePosition(node: Nullable<INodeInfo>) {+ private _getNodePosition(node: Nullable<INodeInfo>): Nullable<INodePosition> {if (node == null) {return;}@@ -764,30 +735,52 @@ export class TextSelectionRenderManager extends RxDisposable implements ITextSel};}- private _interactTextRange(textRange: TextRange) {- const newTextSelection: TextRange[] = [];- let hasIntersection = false;+ private _interactTextRanges(textRanges: TextRange[]) {+ const newTextRanges: TextRange[] = [];- this._rangeList.forEach((range) => {- if (range === textRange) {- return true;+ for (const range of this._rangeList) {+ if (textRanges.some((textRange) => textRange.isIntersection(range))) {+ range.dispose();+ continue;}- if (!textRange.isIntersection(range)) {- newTextSelection.push(range);- } else {- hasIntersection = true;+ newTextRanges.push(range);+ }++ this._rangeList = newTextRanges;+ }++ private _interactRectRanges(rectRanges: RectRange[]) {+ const newRanges: RectRange[] = [];++ for (const range of this._rectRangeList) {+ if (rectRanges.some((rectRange) => rectRange.isIntersection(range))) {range.dispose();+ continue;}- });- if (!hasIntersection) {- return;+ newRanges.push(range);}- newTextSelection.push(textRange);+ this._rectRangeList = newRanges;+ }- this._rangeList = newTextSelection;+ private _removeAllRanges() {+ this._removeAllTextRanges();+ this._removeAllRectRanges();+ }++ private _removeAllCacheRanges() {+ this._rangeListCache.forEach((range) => {+ range.dispose();+ });++ this._rectRangeListCache.forEach((range) => {+ range.dispose();+ });++ this._rangeListCache = [];+ this._rectRangeListCache = [];}private _removeAllTextRanges() {@@ -798,12 +791,30 @@ export class TextSelectionRenderManager extends RxDisposable implements ITextSelthis._rangeList = [];}+ private _removeAllRectRanges() {+ this._rectRangeList.forEach((range) => {+ range.dispose();+ });++ this._rectRangeList = [];+ }+private _deactivateAllTextRanges() {this._rangeList.forEach((range) => {range.deactivate();});}+ private _deactivateAllRectRanges() {+ this._rectRangeList.forEach((range) => {+ range.deactivate();+ });+ }++ private _addTextRangesToCache(textRanges: TextRange[]) {+ this._rangeListCache.push(...textRanges);+ }+private _addTextRange(textRange: TextRange) {this._deactivateAllTextRanges();textRange.activate();@@ -811,6 +822,21 @@ export class TextSelectionRenderManager extends RxDisposable implements ITextSelthis._rangeList.push(textRange);}+ private _addRectRangesToCache(rectRanges: RectRange[]) {+ this._rectRangeListCache.push(...rectRanges);+ }++ private _addRectRanges(rectRanges: RectRange[]) {+ if (rectRanges.length === 0) {+ return;+ }++ this._deactivateAllRectRanges();+ rectRanges[rectRanges.length - 1].activate();++ this._rectRangeList.push(...rectRanges);+ }+private _updateTextRangeAnchorPosition(position: INodePosition) {if (!this._scene) {return;@@ -819,7 +845,7 @@ export class TextSelectionRenderManager extends RxDisposable implements ITextSellet lastRange = this._rangeList.pop();if (!lastRange) {- lastRange = new TextRange(this._scene, this._document!, this._docSkeleton!, position, undefined, this._selectionStyle);+ lastRange = new TextRange(this._scene, this._document!, this._docSkeleton!, position, undefined, this._selectionStyle, this._currentSegmentId);}this._removeAllTextRanges();@@ -829,7 +855,7 @@ export class TextSelectionRenderManager extends RxDisposable implements ITextSelthis._rangeList = [lastRange];}- private _updateActiveRangeFocusPosition(position: INodePosition) {+ private _updateActiveRangePosition(position: INodePosition) {if (!this._scene) {this._logService.error('[TextSelectionRenderManager] _updateActiveRangeFocusPosition: scene is null');@@ -846,16 +872,42 @@ export class TextSelectionRenderManager extends RxDisposable implements ITextSelreturn;}- this._removeAllTextRanges();- activeTextRange.activate();- activeTextRange.focusNodePosition = position;+ this._removeAllRanges();++ this._anchorNodePosition = activeTextRange.anchorNodePosition;+ this._focusNodePosition = position;++ const { _anchorNodePosition, _focusNodePosition, _scene, _document, _docSkeleton, _selectionStyle, _currentSegmentId, _currentSegmentPage } = this;++ if (_anchorNodePosition == null || _focusNodePosition == null || _scene == null || _document == null || _docSkeleton == null) {+ return;+ }++ const ranges = getRangeListFromSelection(+ _anchorNodePosition,+ _focusNodePosition,+ _scene,+ _document,+ _docSkeleton,+ _selectionStyle,+ _currentSegmentId,+ _currentSegmentPage+ );++ if (ranges == null) {+ return;+ }++ const { textRanges, rectRanges } = ranges;++ this._addTextRangesToCache(textRanges);+ this._addRectRangesToCache(rectRanges);this.deactivate();- this._rangeList = [activeTextRange];}private _isEmpty() {- return this._rangeList.length === 0;+ return this._rangeList.length === 0 && this._rectRangeList.length === 0;}private _getCanvasOffset() {@@ -893,31 +945,68 @@ export class TextSelectionRenderManager extends RxDisposable implements ITextSelreturn;}- const endNode = this._findNodeByCoord(moveOffsetX, moveOffsetY, {+ const focusNode = this._findNodeByCoord(moveOffsetX, moveOffsetY, {strict: true,segmentId: this._currentSegmentId,segmentPage: this._currentSegmentPage,});- const focusNodePosition = this._getNodePosition(endNode);+ const focusNodePosition = this._getNodePosition(focusNode);- if (!focusNodePosition) {+ if (!focusNodePosition || focusNode == null) {return;}- const activeRangeInstance = this._getActiveRangeInstance();+ const divide = focusNode?.node.parent;+ const nextGlyph = divide?.glyphGroup[divide.glyphGroup.indexOf(focusNode.node) + 1];++ // Should not select the last paragraph break.+ if (+ focusNode?.node.streamType === DataStreamTreeTokenType.PARAGRAPH &&+ nextGlyph?.streamType === DataStreamTreeTokenType.SECTION_BREAK+ ) {+ focusNodePosition.isBack = true;+ }++ this._focusNodePosition = focusNodePosition;++ this._removeAllCacheRanges();- if (!activeRangeInstance) {+ const { _anchorNodePosition, _focusNodePosition, _scene, _document, _docSkeleton, _selectionStyle, _currentSegmentId, _currentSegmentPage } = this;++ if (_anchorNodePosition == null || _focusNodePosition == null || _scene == null || _document == null || _docSkeleton == null) {return;}- activeRangeInstance.focusNodePosition = focusNodePosition;+ const ranges = getRangeListFromSelection(+ _anchorNodePosition,+ _focusNodePosition,+ _scene,+ _document,+ _docSkeleton,+ _selectionStyle,+ _currentSegmentId,+ _currentSegmentPage+ );- activeRangeInstance.refresh();+ if (ranges == null) {+ return;+ }- this.deactivate();+ const { textRanges, rectRanges } = ranges;++ if (this._rangeList.length > 0 && textRanges.length > 0) {+ this._interactTextRanges(textRanges);+ }++ if (this._rectRangeList.length > 0 && rectRanges.length > 0) {+ this._interactRectRanges(rectRanges);+ }- this._interactTextRange(activeRangeInstance);+ this._addTextRangesToCache(textRanges);+ this._addRectRangesToCache(rectRanges);++ this.deactivate();this._scene?.getEngine()?.setRemainCapture();}@@ -994,6 +1083,12 @@ export class TextSelectionRenderManager extends RxDisposable implements ITextSelthis.disposeWithMe(fromEvent(this._input, 'input').subscribe((e) => {+ // Prevent input when there is any rect ranges.+ if (this._rectRangeList.length > 0) {+ e.stopPropagation();+ return e.preventDefault();+ }+if (this._isIMEInputApply) {return;}@@ -1007,6 +1102,12 @@ export class TextSelectionRenderManager extends RxDisposable implements ITextSelthis.disposeWithMe(fromEvent(this._input, 'compositionstart').subscribe((e) => {+ // Prevent input when there is any rect ranges.+ if (this._rectRangeList.length > 0) {+ e.stopPropagation();+ return e.preventDefault();+ }+this._isIMEInputApply = true;this._eventHandle(e, (config) => {diff --git a/packages/engine-render/src/components/docs/view-model/data-stream-tree-node.ts b/packages/engine-render/src/components/docs/view-model/data-stream-tree-node.tsindex e2df925f5a..90e201e878 100644--- a/packages/engine-render/src/components/docs/view-model/data-stream-tree-node.ts+++ b/packages/engine-render/src/components/docs/view-model/data-stream-tree-node.ts@@ -25,17 +25,11 @@ import {export class DataStreamTreeNode {children: DataStreamTreeNode[] = [];-parent: Nullable<DataStreamTreeNode>;-startIndex: number = -1;-endIndex: number = -1;-// isBullet: boolean = false;-// isIndent: boolean = false;-blocks: number[] = [];constructor(diff --git a/packages/engine-render/src/components/docs/view-model/document-view-model.ts b/packages/engine-render/src/components/docs/view-model/document-view-model.tsindex 420fcc9dbb..bb2b4a4e91 100644--- a/packages/engine-render/src/components/docs/view-model/document-view-model.ts+++ b/packages/engine-render/src/components/docs/view-model/document-view-model.ts@@ -16,10 +16,14 @@import type { ICustomDecorationForInterceptor, ICustomRangeForInterceptor, IDisposable, IDocumentBody, ITextRun, Nullable } from '@univerjs/core';import { DataStreamTreeNodeType, DataStreamTreeTokenType, DocumentDataModel, toDisposable } from '@univerjs/core';-import { BehaviorSubject } from 'rxjs';import { DataStreamTreeNode } from './data-stream-tree-node';+interface ITableCache {+ table: DataStreamTreeNode;+ isFinished: boolean;+}+export interface ICustomRangeInterceptor {getCustomRange: (index: number) => Nullable<ICustomRangeForInterceptor>;getCustomDecoration: (index: number) => Nullable<ICustomDecorationForInterceptor>;@@ -31,6 +35,128 @@ export enum DocumentEditArea {FOOTER = 'FOOTER',}+function batchParent(+ parent: DataStreamTreeNode,+ children: DataStreamTreeNode[],+ nodeType = DataStreamTreeNodeType.SECTION_BREAK+) {+ if (children.length === 0) {+ throw new Error('Missing `paragraphs` or `sectionBreaks` fields, or doesn\'t correspond to the location in `dataStream`.');+ }++ for (const child of children) {+ child.parent = parent;+ parent.children.push(child);+ }++ const startOffset = nodeType === DataStreamTreeNodeType.SECTION_BREAK ? 0 : 1;+ const allChildren = parent.children;++ parent.setIndexRange(allChildren[0].startIndex - startOffset, allChildren[allChildren.length - 1].endIndex + 1);+}++export function parseDataStreamToTree(dataStream: string) {+ let content = '';+ const dataStreamLen = dataStream.length;+ const sectionList: DataStreamTreeNode[] = [];+ // Only use to cache the outer paragraphs.+ const paragraphList: DataStreamTreeNode[] = [];+ // Use to cache paragraphs in cell.+ const cellParagraphList: DataStreamTreeNode[] = [];+ const tableList: ITableCache[] = [];+ const tableRowList: DataStreamTreeNode[] = [];+ const tableCellList: DataStreamTreeNode[] = [];+ const currentBlocks: number[] = [];++ for (let i = 0; i < dataStreamLen; i++) {+ const char = dataStream[i];++ if (char === DataStreamTreeTokenType.PARAGRAPH) {+ content += DataStreamTreeTokenType.PARAGRAPH;++ const paragraphNode = DataStreamTreeNode.create(DataStreamTreeNodeType.PARAGRAPH, content);++ const lastTableCache = tableList[tableList.length - 1];+ if (lastTableCache && lastTableCache.isFinished) {+ // Paragraph Node will only has one table node.+ batchParent(paragraphNode, [lastTableCache.table], DataStreamTreeNodeType.PARAGRAPH);++ tableList.pop();+ }++ // Paragraph start and end index is from the first char of the paragraph to the last char of the paragraph. not include the Table content.+ paragraphNode.setIndexRange(i - content.length + 1, i);+ paragraphNode.addBlocks(currentBlocks);+ currentBlocks.length = 0;+ content = '';++ if (tableCellList.length > 0) {+ cellParagraphList.push(paragraphNode);+ } else {+ paragraphList.push(paragraphNode);+ }+ } else if (char === DataStreamTreeTokenType.SECTION_BREAK) {+ const sectionNode = DataStreamTreeNode.create(DataStreamTreeNodeType.SECTION_BREAK);+ const tempParagraphList = tableCellList.length > 0 ? cellParagraphList : paragraphList;++ batchParent(sectionNode, tempParagraphList);++ const lastNode = tempParagraphList[tempParagraphList.length - 1];++ if (lastNode && lastNode.content) {+ lastNode.content += DataStreamTreeTokenType.SECTION_BREAK;+ }++ if (tableCellList.length > 0) {+ const lastCell = tableCellList[tableCellList.length - 1];++ batchParent(lastCell, [sectionNode], DataStreamTreeNodeType.TABLE_CELL);+ } else {+ sectionList.push(sectionNode);+ }++ tempParagraphList.length = 0;+ } else if (char === DataStreamTreeTokenType.TABLE_START) {+ const tableNode = DataStreamTreeNode.create(DataStreamTreeNodeType.TABLE);++ tableList.push({+ table: tableNode,+ isFinished: false,+ });+ } else if (char === DataStreamTreeTokenType.TABLE_ROW_START) {+ const rowNode = DataStreamTreeNode.create(DataStreamTreeNodeType.TABLE_ROW);++ tableRowList.push(rowNode);+ } else if (char === DataStreamTreeTokenType.TABLE_CELL_START) {+ const cellNode = DataStreamTreeNode.create(DataStreamTreeNodeType.TABLE_CELL);++ tableCellList.push(cellNode);+ } else if (char === DataStreamTreeTokenType.TABLE_END) {+ const lastTable = tableList[tableList.length - 1];+ lastTable.isFinished = true;+ content = '';+ } else if (char === DataStreamTreeTokenType.TABLE_ROW_END) {+ const rowNode = tableRowList.pop();+ const lastTableCache = tableList[tableList.length - 1];++ batchParent(lastTableCache.table, [rowNode!], DataStreamTreeNodeType.TABLE);+ } else if (char === DataStreamTreeTokenType.TABLE_CELL_END) {+ const cellNode = tableCellList.pop();++ const lastRow = tableRowList[tableRowList.length - 1];++ batchParent(lastRow, [cellNode!], DataStreamTreeNodeType.TABLE_ROW);+ } else if (char === DataStreamTreeTokenType.CUSTOM_BLOCK) {+ currentBlocks.push(i);+ content += char;+ } else {+ content += char;+ }+ }++ return sectionList;+}+export class DocumentViewModel implements IDisposable {private _interceptor: Nullable<ICustomRangeInterceptor> = null;@@ -54,7 +180,7 @@ export class DocumentViewModel implements IDisposable {return;}- this.children = this._transformToTree(_documentDataModel.getBody()!.dataStream);+ this.children = parseDataStreamToTree(_documentDataModel.getBody()!.dataStream);this._buildHeaderFooterViewModel();}@@ -70,7 +196,7 @@ export class DocumentViewModel implements IDisposable {});}- selfPlus(len: number, index: number) {+ selfPlus(_len: number, _index: number) {// empty}@@ -97,6 +223,10 @@ export class DocumentViewModel implements IDisposable {return this._documentDataModel.getBody();}+ getSnapshot() {+ return this._documentDataModel.getSnapshot();+ }+getDataModel() {return this._documentDataModel;}@@ -120,7 +250,7 @@ export class DocumentViewModel implements IDisposable {reset(documentDataModel: DocumentDataModel) {this._documentDataModel = documentDataModel;- this.children = this._transformToTree(documentDataModel.getBody()!.dataStream);+ this.children = parseDataStreamToTree(documentDataModel.getBody()!.dataStream);this._buildHeaderFooterViewModel();}@@ -279,16 +409,19 @@ export class DocumentViewModel implements IDisposable {}}- getParagraph(index: number) {+ getParagraph(index: number, fromStart = false) {const paragraphs = this.getBody()!.paragraphs;if (paragraphs == null) {return;}- for (let i = this._paragraphCurrentIndex; i < paragraphs.length; i++) {+ for (let i = fromStart ? 0 : this._paragraphCurrentIndex; i < paragraphs.length; i++) {const paragraph = paragraphs[i];if (paragraph.startIndex === index) {- this._paragraphCurrentIndex = i;+ if (!fromStart) {+ this._paragraphCurrentIndex = i;+ }+return paragraph;}}@@ -406,18 +539,26 @@ export class DocumentViewModel implements IDisposable {}getTable(index: number) {- const tables = this.getBody()!.tables;- if (tables == null) {+ const tables = this.getBody()?.tables;+ const tableSource = this.getSnapshot().tableSource;+ if (tables == null || tableSource == null) {return;}+ let tableId: Nullable<string> = null;+for (let i = this._tableBlockCurrentIndex; i < tables.length; i++) {const table = tables[i];if (table.startIndex === index) {this._tableBlockCurrentIndex = i;- return table;+ tableId = table.tableId;+ break;}}++ if (tableId != null && tableSource[tableId] != null) {+ return tableSource[tableId];+ }}getCustomRangeRaw(index: number) {@@ -464,131 +605,6 @@ export class DocumentViewModel implements IDisposable {return this.getCustomDecorationRaw(index);}- protected _transformToTree(dataStream: string) {- const dataStreamLen = dataStream.length;-- let content = '';- 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++;- node.setIndexRange(i - content.length + 1, i);- node.addBlocks(currentBlocks);- // node.isBullet = isBullet;- // node.isIndent = isIndent;- nodeList.push(node);- content = '';- 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) {- nodeList.push(DataStreamTreeNode.create(DataStreamTreeNodeType.TABLE));- } else if (char === DataStreamTreeTokenType.TABLE_ROW_START) {- nodeList.push(DataStreamTreeNode.create(DataStreamTreeNodeType.TABLE_ROW));- } else if (char === DataStreamTreeTokenType.TABLE_CELL_START) {- nodeList.push(DataStreamTreeNode.create(DataStreamTreeNodeType.TABLE_CELL));- } else if (char === DataStreamTreeTokenType.TABLE_END) {- this._processPreviousNodesUntil(nodeList, DataStreamTreeNodeType.TABLE);- } else if (char === DataStreamTreeTokenType.TABLE_ROW_END) {- this._processPreviousNodesUntil(nodeList, DataStreamTreeNodeType.TABLE_ROW);- } else if (char === DataStreamTreeTokenType.TABLE_CELL_END) {- this._processPreviousNodesUntil(nodeList, DataStreamTreeNodeType.TABLE_CELL);- } else if (char === DataStreamTreeTokenType.CUSTOM_BLOCK) {- currentBlocks.push(i);- content += char;- } else {- content += char;- }- }-- return sectionList;- }-- private _processPreviousNodesUntil(nodeList: DataStreamTreeNode[], untilNodeType: DataStreamTreeNodeType) {- const nodeCollection: DataStreamTreeNode[] = [];- let node = nodeList.pop();- while (node) {- if (node.nodeType === untilNodeType) {- break;- }-- nodeCollection.push(node);-- node = nodeList.pop();- }-- const recentTree = nodeList[nodeList.length - 1];- this._batchParent(recentTree, nodeCollection, DataStreamTreeNodeType.TABLE);-- if (untilNodeType === DataStreamTreeNodeType.TABLE_CELL) {- const firstNode = nodeCollection[0];- const lastNode = nodeCollection[nodeCollection.length];- firstNode.content = DataStreamTreeTokenType.TABLE_CELL_START + firstNode.content || '';- firstNode.startIndex -= 1;- lastNode.content += DataStreamTreeTokenType.TABLE_CELL_END;- lastNode.endIndex += 1;- } else if (untilNodeType === DataStreamTreeNodeType.TABLE_ROW) {- const firstNode = nodeCollection[0].children[0];- let lastNode = nodeCollection[nodeCollection.length];- lastNode = lastNode.children[lastNode.children.length - 1];- firstNode.content = DataStreamTreeTokenType.TABLE_ROW_START + firstNode.content || '';- firstNode.startIndex -= 1;- lastNode.content += DataStreamTreeTokenType.TABLE_ROW_END;- lastNode.endIndex += 1;- } else if (untilNodeType === DataStreamTreeNodeType.TABLE) {- const firstNode = nodeCollection[0].children[0].children[0];- let lastNode = nodeCollection[nodeCollection.length];- lastNode = lastNode.children[lastNode.children.length - 1];- lastNode = lastNode.children[lastNode.children.length - 1];- firstNode.content = DataStreamTreeTokenType.TABLE_START + firstNode.content || '';- firstNode.startIndex -= 1;- lastNode.content += DataStreamTreeTokenType.TABLE_END;- lastNode.endIndex += 1;- }- }-- private _batchParent(- parent: DataStreamTreeNode,- children: DataStreamTreeNode[],- nodeType = DataStreamTreeNodeType.SECTION_BREAK- ) {- if (children.length === 0) {- throw new Error('Missing `paragraphs` or `sectionBreaks` fields, or doesn\'t correspond to the location in `dataStream`.');- }-- for (const child of children) {- child.parent = parent;- parent.children.push(child);- }-- const startOffset = nodeType === DataStreamTreeNodeType.SECTION_BREAK ? 0 : 1;-- parent.setIndexRange(children[0].startIndex - startOffset, children[children.length - 1].endIndex + 1);- }-private _buildHeaderFooterViewModel() {const { headerModelMap, footerModelMap } = this._documentDataModel;@@ -777,10 +793,4 @@ export class DocumentViewModel implements IDisposable {}});}-- // private move() {}-- // private split() {}-- // private merge() {}}diff --git a/packages/engine-render/src/index.ts b/packages/engine-render/src/index.tsindex 97b2fad004..8cc155677f 100644--- a/packages/engine-render/src/index.ts+++ b/packages/engine-render/src/index.ts@@ -34,12 +34,13 @@ export * from './viewport';export { DocumentViewModel } from './components/docs/view-model/document-view-model';export { getAnchorBounding, TEXT_RANGE_LAYER_INDEX, TextRange, getLineBounding } from './components/docs/text-selection/text-range';-export { NodePositionConvertToCursor } from './components/docs/text-selection/convert-cursor';+export { RectRange, convertPositionsToRectRanges } from './components/docs/text-selection/rect-range';+export { NodePositionConvertToCursor } from './components/docs/text-selection/convert-text-range';export { Liquid } from './components/docs/liquid';+export { getCanvasOffsetByEngine } from './components/docs/text-selection/selection-utils';export {ITextSelectionRenderManager,TextSelectionRenderManager,- getCanvasOffsetByEngine,} from './components/docs/text-selection/text-selection-render-manager';export type { IActiveTextRange, IEditorInputConfig, ITextSelectionInnerParam } from './components/docs/text-selection/text-selection-render-manager';export { Documents } from './components/docs/document';@@ -52,4 +53,10 @@ export { type IChangeObserverConfig } from './scene.transformer';export { DEFAULT_PADDING_DATA } from './components/sheets/sheet-skeleton';export { DocumentEditArea } from './components/docs/view-model/document-view-model';export { lineIterator, glyphIterator } from './components/docs/layout/tools';-export { getOneTextSelectionRange } from './components/docs/text-selection/convert-cursor';+export { getOneTextSelectionRange } from './components/docs/text-selection/convert-text-range';+export { getLastLine } from './components/docs/layout/tools';+export { DataStreamTreeNode } from './components/docs/view-model/data-stream-tree-node';+export type { IDocRange } from './components/docs/text-selection/range-interface';+export { isInSameTableCell } from './components/docs/text-selection/convert-rect-range';+export { parseDataStreamToTree } from './components/docs/view-model/document-view-model';+export { DOC_RANGE_TYPE } from './components/docs/text-selection/range-interface';diff --git a/packages/sheets-formula/src/controllers/prompt.controller.ts b/packages/sheets-formula/src/controllers/prompt.controller.tsindex de37302711..259b72c1ac 100644--- a/packages/sheets-formula/src/controllers/prompt.controller.ts+++ b/packages/sheets-formula/src/controllers/prompt.controller.ts@@ -513,7 +513,7 @@ export class PromptController extends Disposable {private _initAcceptFormula() {this.disposeWithMe(this._formulaPromptService.acceptFormulaName$.subscribe((formulaString: string) => {- const activeRange = this._textSelectionManagerService.getActiveRange();+ const activeRange = this._textSelectionManagerService.getActiveTextRangeWithStyle();if (activeRange == null) {this._hideFunctionPanel();@@ -579,7 +579,7 @@ export class PromptController extends Disposable {}private _changeFunctionPanelState() {- const activeRange = this._textSelectionManagerService.getActiveRange();+ const activeRange = this._textSelectionManagerService.getActiveTextRangeWithStyle();if (activeRange == null) {this._hideFunctionPanel();@@ -678,7 +678,7 @@ export class PromptController extends Disposable {* @returns Return the character under the current cursor in the editor.*/private _getCurrentChar() {- const activeRange = this._textSelectionManagerService.getActiveRange();+ const activeRange = this._textSelectionManagerService.getActiveTextRangeWithStyle();if (activeRange == null) {return;@@ -807,7 +807,7 @@ export class PromptController extends Disposable {this._formulaPromptService.setSequenceNodes(lastSequenceNodes);- const activeRange = this._textSelectionManagerService.getActiveRange();+ const activeRange = this._textSelectionManagerService.getActiveTextRangeWithStyle();if (activeRange == null) {return;@@ -1197,7 +1197,7 @@ export class PromptController extends Disposable {this._isSelectionMovingRefSelections = refSelections;- const activeRange = this._textSelectionManagerService.getActiveRange();+ const activeRange = this._textSelectionManagerService.getActiveTextRangeWithStyle();if (activeRange == null) {return;@@ -1835,7 +1835,7 @@ export class PromptController extends Disposable {* Absolute range, triggered by F4*/private _changeRefString() {- const activeRange = this._textSelectionManagerService.getActiveRange();+ const activeRange = this._textSelectionManagerService.getActiveTextRangeWithStyle();if (activeRange == null) {return;diff --git a/packages/sheets-ui/package.json b/packages/sheets-ui/package.jsonindex de768e12b6..96e29b2ce3 100644--- a/packages/sheets-ui/package.json+++ b/packages/sheets-ui/package.json@@ -68,7 +68,6 @@"@univerjs/core": "workspace:*","@univerjs/design": "workspace:*","@univerjs/docs": "workspace:*",- "@univerjs/docs-ui": "workspace:*","@univerjs/engine-formula": "workspace:*","@univerjs/engine-numfmt": "workspace:*","@univerjs/engine-render": "workspace:*",diff --git a/packages/sheets-ui/src/controllers/menu/menu.ts b/packages/sheets-ui/src/controllers/menu/menu.tsindex d655783049..300cc00719 100644--- a/packages/sheets-ui/src/controllers/menu/menu.ts+++ b/packages/sheets-ui/src/controllers/menu/menu.ts@@ -1309,7 +1309,7 @@ function getFontStyleAtCursor(accessor: IAccessor) {const textSelectionService = accessor.get(TextSelectionManagerService);const editorDataModel = univerInstanceService.getUniverDocInstance(DOCS_NORMAL_EDITOR_UNIT_ID_KEY);- const activeTextRange = textSelectionService.getActiveRange();+ const activeTextRange = textSelectionService.getActiveTextRangeWithStyle();if (editorDataModel == null || activeTextRange == null) return null;diff --git a/packages/sheets-ui/src/services/clipboard/clipboard.service.ts b/packages/sheets-ui/src/services/clipboard/clipboard.service.tsindex 435f158280..0d80558cb9 100644--- a/packages/sheets-ui/src/services/clipboard/clipboard.service.ts+++ b/packages/sheets-ui/src/services/clipboard/clipboard.service.ts@@ -39,7 +39,6 @@ import {import { HTML_CLIPBOARD_MIME_TYPE, IClipboardInterfaceService, INotificationService, IPlatformService, PLAIN_TEXT_CLIPBOARD_MIME_TYPE } from '@univerjs/ui';import { BehaviorSubject } from 'rxjs';-import { PastePluginLark, PastePluginUniver, PastePluginWord } from '@univerjs/docs-ui';import { IRenderManagerService } from '@univerjs/engine-render';import { IMarkSelectionService } from '../mark-selection/mark-selection.service';import { SheetSkeletonManagerService } from '../sheet-skeleton-manager.service';@@ -60,6 +59,9 @@ import type {import { COPY_TYPE } from './type';import { USMToHtmlService } from './usm-to-html/convertor';import { clipboardItemIsFromExcel, convertTextToTable, discreteRangeContainsRange, mergeSetRangeValues, rangeIntersectWithDiscreteRange } from './utils';+import { WordPastePlugin } from './html-to-usm/paste-plugins/plugin-word';+import { LarkPastePlugin } from './html-to-usm/paste-plugins/plugin-lark';+import { UniverPastePlugin } from './html-to-usm/paste-plugins/plugin-univer';export const PREDEFINED_HOOK_NAME = {DEFAULT_COPY: 'default-copy',@@ -83,9 +85,9 @@ interface ICopyContent {* This service provide hooks for sheet features to supplement content or modify behavior of clipboard.*/-HtmlToUSMService.use(PastePluginWord);-HtmlToUSMService.use(PastePluginLark);-HtmlToUSMService.use(PastePluginUniver);+HtmlToUSMService.use(WordPastePlugin);+HtmlToUSMService.use(LarkPastePlugin);+HtmlToUSMService.use(UniverPastePlugin);export interface ISheetClipboardService {copy(): Promise<boolean>;diff --git a/packages/sheets-ui/src/services/clipboard/html-to-usm/converter.ts b/packages/sheets-ui/src/services/clipboard/html-to-usm/converter.tsindex 31bd996312..ffc11e7e3f 100644--- a/packages/sheets-ui/src/services/clipboard/html-to-usm/converter.ts+++ b/packages/sheets-ui/src/services/clipboard/html-to-usm/converter.ts@@ -18,7 +18,6 @@ import type { IDocumentBody, IDocumentData, ITextRun, ITextStyle, Nullable } froimport { ObjectMatrix, skipParseTagNames } from '@univerjs/core';import { handleStringToStyle, textTrim } from '@univerjs/ui';-import type { IPastePlugin } from '@univerjs/docs-ui';import type { SpreadsheetSkeleton } from '@univerjs/engine-render';import type { ISheetSkeletonManagerParam } from '../../sheet-skeleton-manager.service';import type {@@ -28,7 +27,7 @@ import type {IUniverSheetCopyDataModel,} from '../type';import { extractNodeStyle } from './parse-node-style';-import type { IAfterProcessRule } from './paste-plugins/type';+import type { IAfterProcessRule, IPastePlugin } from './paste-plugins/type';import parseToDom, { generateParagraphs } from './utils';export interface IStyleRule {@@ -82,14 +81,14 @@ interface IHtmlToUSMServiceProps {}export class HtmlToUSMService {- private static pluginList: IPastePlugin[] = [];+ private static _pluginList: IPastePlugin[] = [];static use(plugin: IPastePlugin) {- if (this.pluginList.includes(plugin)) {+ if (this._pluginList.includes(plugin)) {throw new Error(`Univer paste plugin ${plugin.name} already added`);}- this.pluginList.push(plugin);+ this._pluginList.push(plugin);}private _styleMap = new Map<string, CSSStyleDeclaration>();@@ -110,7 +109,7 @@ export class HtmlToUSMService {// eslint-disable-next-line max-lines-per-functionconvert(html: string): IUniverSheetCopyDataModel {- const pastePlugin = HtmlToUSMService.pluginList.find((plugin) => plugin.checkPasteType(html));+ const pastePlugin = HtmlToUSMService._pluginList.find((plugin) => plugin.checkPasteType(html));if (pastePlugin) {this._styleRules = [...pastePlugin.stylesRules];this._afterProcessRules = [...pastePlugin.afterProcessRules];diff --git a/packages/sheets-ui/src/services/clipboard/html-to-usm/paste-plugins/plugin-lark.ts b/packages/sheets-ui/src/services/clipboard/html-to-usm/paste-plugins/plugin-lark.tsindex 5c1acefd2f..96d60f1b69 100644--- a/packages/sheets-ui/src/services/clipboard/html-to-usm/paste-plugins/plugin-lark.ts+++ b/packages/sheets-ui/src/services/clipboard/html-to-usm/paste-plugins/plugin-lark.ts@@ -19,7 +19,7 @@ import { BooleanNumber } from '@univerjs/core';import { extractNodeStyle as getInlineStyle } from '../parse-node-style';import type { IPastePlugin } from './type';-const wordPastePlugin: IPastePlugin = {+export const LarkPastePlugin: IPastePlugin = {name: 'univer-doc-paste-plugin-lark',checkPasteType(html: string) {return /lark-record-clipboard/i.test(html);@@ -60,4 +60,3 @@ const wordPastePlugin: IPastePlugin = {],};-export default wordPastePlugin;diff --git a/packages/sheets-ui/src/services/clipboard/html-to-usm/paste-plugins/plugin-univer.ts b/packages/sheets-ui/src/services/clipboard/html-to-usm/paste-plugins/plugin-univer.tsnew file mode 100644index 0000000000..949e5f2c8f--- /dev/null+++ b/packages/sheets-ui/src/services/clipboard/html-to-usm/paste-plugins/plugin-univer.ts@@ -0,0 +1,55 @@+/**+ * 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 { getParagraphStyle } from '../utils';+import type { IPastePlugin } from './type';++export const UniverPastePlugin: IPastePlugin = {+ name: 'univer-doc-paste-plugin-univer',+ checkPasteType(html: string) {+ return /UniverNormal/i.test(html);+ },++ stylesRules: [],++ afterProcessRules: [+ {+ filter(el: HTMLElement) {+ return el.tagName === 'P' && /UniverNormal/i.test(el.className);+ },+ handler(doc, el) {+ if (doc.paragraphs == null) {+ doc.paragraphs = [];+ }++ const paragraph: IParagraph = {+ startIndex: doc.dataStream.length,+ };++ const paragraphStyle = getParagraphStyle(el);++ if (paragraphStyle) {+ paragraph.paragraphStyle = paragraphStyle;+ }++ doc.paragraphs.push(paragraph);+ doc.dataStream += '\r';+ },+ },+ ],+};+diff --git a/packages/sheets-ui/src/services/clipboard/html-to-usm/paste-plugins/plugin-word.ts b/packages/sheets-ui/src/services/clipboard/html-to-usm/paste-plugins/plugin-word.tsindex 4c36979903..543c79cade 100644--- a/packages/sheets-ui/src/services/clipboard/html-to-usm/paste-plugins/plugin-word.ts+++ b/packages/sheets-ui/src/services/clipboard/html-to-usm/paste-plugins/plugin-word.ts@@ -21,7 +21,7 @@ import { extractNodeStyle as getInlineStyle } from '../parse-node-style';import { getParagraphStyle } from '../utils';import type { IPastePlugin } from './type';-const wordPastePlugin: IPastePlugin = {+export const WordPastePlugin: IPastePlugin = {name: 'univer-doc-paste-plugin-word',checkPasteType(html: string) {return /word|mso/i.test(html);@@ -65,4 +65,3 @@ const wordPastePlugin: IPastePlugin = {],};-export default wordPastePlugin;diff --git a/packages/thread-comment-ui/src/views/thread-comment-editor/index.tsx b/packages/thread-comment-ui/src/views/thread-comment-editor/index.tsxindex 277fe6ef54..2336e97b6c 100644--- a/packages/thread-comment-ui/src/views/thread-comment-editor/index.tsx+++ b/packages/thread-comment-ui/src/views/thread-comment-editor/index.tsx@@ -91,9 +91,9 @@ export const ThreadCommentEditor = forwardRef<IThreadCommentEditorInstance, IThrsetLocalComment?.({ ...comment, text: transformTextNodes2Document(parseMentions(e.target.value)) });}}onFocus={() => {- const activeRange = textSelectionManagerService.getActiveRange();+ const activeRange = textSelectionManagerService.getActiveTextRangeWithStyle();if (activeRange && activeRange.collapsed) {- textSelectionRenderManager.removeAllTextRanges();+ textSelectionRenderManager.removeAllRanges();}textSelectionRenderManager.blur();setEditing(true);diff --git a/packages/ui/package.json b/packages/ui/package.jsonindex 2411f396bc..8de0996d0e 100644--- a/packages/ui/package.json+++ b/packages/ui/package.json@@ -82,7 +82,7 @@"rc-util": "^5.43.0"},"optionalDependencies": {- "vue": "^3.4.35"+ "vue": ">=3.0.0"},"devDependencies": {"@testing-library/react": "^16.0.0",diff --git a/packages/ui/src/common/component-manager.ts b/packages/ui/src/common/component-manager.tsindex c3e6ca4733..b8cc366142 100644--- a/packages/ui/src/common/component-manager.ts+++ b/packages/ui/src/common/component-manager.ts@@ -55,6 +55,7 @@ import {FreezeRowSingle,FreezeToSelectedSingle,FunctionSingle,+ GridSingle,Hide,HorizontalBorder,HorizontallySingle,@@ -224,6 +225,7 @@ export class ComponentManager {CancelFreezeSingle,FreezeColumnSingle,FreezeRowSingle,+ GridSingle,FreezeToSelectedSingle,CodeSingle,FontSizeIncreaseSingle,diff --git a/packages/ui/src/services/confirm/confirm.service.ts b/packages/ui/src/services/confirm/confirm.service.tsindex 80715f78a6..ce0173f535 100644--- a/packages/ui/src/services/confirm/confirm.service.ts+++ b/packages/ui/src/services/confirm/confirm.service.ts@@ -15,13 +15,14 @@*/import type { IDisposable } from '@univerjs/core';-import { createIdentifier } from '@univerjs/core';+import { createIdentifier, LifecycleStages, runOnLifecycle } from '@univerjs/core';import type { Subject } from 'rxjs';import type { IConfirmPartMethodOptions } from '../../views/components/confirm-part/interface';export const IConfirmService = createIdentifier<IConfirmService>('univer.confirm-service');+runOnLifecycle(LifecycleStages.Rendered, IConfirmService);export interface IConfirmService {readonly confirmOptions$: Subject<IConfirmPartMethodOptions[]>;diff --git a/packages/ui/src/services/editor/editor.service.ts b/packages/ui/src/services/editor/editor.service.tsindex 7364c10565..03a1209e3a 100644--- a/packages/ui/src/services/editor/editor.service.ts+++ b/packages/ui/src/services/editor/editor.service.ts@@ -18,7 +18,7 @@ import type { DocumentDataModel, IDisposable, IDocumentBody, IDocumentData, IDocimport { createIdentifier, DEFAULT_EMPTY_DOCUMENT_VALUE, DEFAULT_STYLES, Disposable, EDITOR_ACTIVATED, FOCUSING_EDITOR_INPUT_FORMULA, FOCUSING_EDITOR_STANDALONE, FOCUSING_UNIVER_EDITOR_STANDALONE_SINGLE_MODE, HorizontalAlign, IContextService, Inject, IUniverInstanceService, toDisposable, UniverInstanceType, VerticalAlign } from '@univerjs/core';import type { Observable } from 'rxjs';import { Subject } from 'rxjs';-import type { IRender, ISuccinctTextRangeParam, Scene } from '@univerjs/engine-render';+import type { IRender, ISuccinctDocRangeParam, Scene } from '@univerjs/engine-render';import { IRenderManagerService } from '@univerjs/engine-render';import { isReferenceStrings, LexerTreeBuilder, operatorToken } from '@univerjs/engine-formula';@@ -273,7 +273,7 @@ export interface IEditorService {blur$: Observable<unknown>;blur(): void;- focus$: Observable<ISuccinctTextRangeParam>;+ focus$: Observable<ISuccinctDocRangeParam>;focus(editorUnitId?: string): void;setValue$: Observable<IEditorSetValueParam>;@@ -337,7 +337,7 @@ export class EditorService extends Disposable implements IEditorService, IDisposprivate readonly _blur$ = new Subject();readonly blur$ = this._blur$.asObservable();- private readonly _focus$ = new Subject<ISuccinctTextRangeParam>();+ private readonly _focus$ = new Subject<ISuccinctDocRangeParam>();readonly focus$ = this._focus$.asObservable();private readonly _setValue$ = new Subject<IEditorSetValueParam>();@@ -649,8 +649,11 @@ export class EditorService extends Disposable implements IEditorService, IDispos*/const sheets = this._univerInstanceService.getAllUnitsForType<Workbook>(UniverInstanceType.UNIVER_SHEET);if (sheets.length > 0) {- const current = this._univerInstanceService.getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET)!;- this._univerInstanceService.focusUnit(current.getUnitId());+ const current = this._univerInstanceService.getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET);++ if (current) {+ this._univerInstanceService.focusUnit(current.getUnitId());+ }}}diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex a8072f5c4e..0c601873aa 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -516,6 +516,9 @@ importers:packages/core:dependencies:+ '@univerjs/core':+ specifier: workspace:*+ version: 'link:''@univerjs/protocol':specifier: 0.1.38version: 0.1.38(@grpc/[email protected])([email protected])@@ -592,7 +595,7 @@ importers:version: 18.3.1optionalDependencies:vue:- specifier: ^3.4.35+ specifier: '>=3.0.0'version: 3.4.35([email protected])devDependencies:'@univerjs/core':@@ -736,6 +739,10 @@ importers:version: 2.0.5(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])packages/docs:+ dependencies:+ '@univerjs/docs':+ specifier: workspace:*+ version: 'link:'devDependencies:'@univerjs/core':specifier: workspace:*@@ -2269,9 +2276,6 @@ importers:packages/sheets-ui:dependencies:- '@univerjs/docs-ui':- specifier: workspace:*- version: link:../docs-ui'@univerjs/icons':specifier: ^0.1.70@@ -2568,7 +2572,7 @@ importers:optionalDependencies:vue:- specifier: ^3.4.35+ specifier: '>=3.0.0'version: 3.4.35([email protected])devDependencies:'@testing-library/react':