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): image layout in doc (#1958)
Ran Luo00d0b7917d75
diff --git a/examples/src/data/docs/default-document-data-cn.ts b/examples/src/data/docs/default-document-data-cn.tsindex aa38dfc8cc..87be3a815a 100644--- a/examples/src/data/docs/default-document-data-cn.ts+++ b/examples/src/data/docs/default-document-data-cn.ts@@ -15,14 +15,135 @@*/import type { IDocumentData } from '@univerjs/core';-import { BooleanNumber, ColumnSeparatorType, SectionType } from '@univerjs/core';+import { BooleanNumber, ObjectRelativeFromH, ObjectRelativeFromV, PositionedObjectLayoutType, WrapTextType } from '@univerjs/core';import { ptToPixel } from '@univerjs/engine-render';export const DEFAULT_DOCUMENT_DATA_CN: IDocumentData = {- id: 'default-document-id',+ id: 'd',+ drawings: {+ shapeTest1: {+ objectId: 'shapeTest1',+ title: 'test shape',+ description: 'test shape',+ objectTransform: {+ 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: {+ objectId: 'shapeTest2',+ title: 'test shape',+ description: 'test shape',+ objectTransform: {+ 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: {+ objectId: 'shapeTest3',+ title: 'test shape',+ description: 'test shape',+ objectTransform: {+ 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: {+ objectId: 'shapeTest4',+ title: 'test shape',+ description: 'test shape',+ objectTransform: {+ 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: {+ objectId: 'shapeTest5',+ title: 'test shape',+ description: 'test shape',+ objectTransform: {+ 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,+ },+ },body: {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',+ '荷塘月色\r\r作者:朱自清\r\r这几天心里颇不宁静。今晚在院子里坐着乘凉,忽然想起日日走过的荷塘,在这满月的光里,总该另有一番样子吧。月亮渐渐地升高了,墙外马路上孩子们的欢笑,已经听不见了;妻在屋里拍着闰儿,迷迷糊糊地哼着眠歌。我悄悄地披了大衫,带上门出去。\r\r沿着荷塘,是一条曲折的小煤屑路。这是一条幽僻的路;白天也少人走,夜晚更加寂寞。荷塘四面,长着许多树,蓊蓊郁郁的。路图片一\b是些杨柳,和一些不知道名字的树。没有月光的晚上,这路上阴森森的,有些怕人。今晚却很好,虽然月光也还是淡淡的。\r\r路上只我一个人,背着手踱着。这一片天地好像是我的;我也像超出了平常的自己,到了另一个世界里。我爱热闹,也爱冷静;爱群居,也爱独处。像今晚上,一个人在这苍茫的月下,什么都可以想,什么都可以不想,便觉是个自由的人。白天里一定要做的事,一定要说的话\b现在都可不理。这是独处的妙处,我且受用这无边的荷香月色好了。\r\r曲曲折折的荷塘上面,弥望的是田田的叶子。叶子出水很高,像亭亭的舞女的裙。层层的叶子中间,零星地点缀着些白花,有袅娜地开着的,有羞涩地打着朵儿的;正如一粒粒的明珠,又如碧天里的星星\b又如刚出浴的美人。微风过处,送来缕缕清香,仿佛远处高楼上渺茫的歌声似的。这时候叶子与花也有一丝的颤动,像闪电般,霎时传过荷塘的那边去了。叶子本是肩并肩密密地挨着,这便宛然有了一道凝碧的波痕。叶子底下是脉脉的流水,遮住了,不能见一些颜色;而叶子却更见风致了。\r\r月光如流水一般,静静地泻在这一片叶子和花上。薄薄的青雾浮起在荷塘里。叶子和花仿佛在牛乳中洗过一样\b又像笼着轻纱的梦。虽然是满月,天上却有一层淡淡的云,所以不能朗照;但我以为这恰是到了好处——酣眠固不可少,小睡也别有风味的。月光是隔了树照过来的,高处丛生的灌木,落下参差的斑驳的黑影,峭楞楞如鬼一般;弯弯的杨柳的稀疏的倩影,却又像是画在荷叶上。塘中的月色并不均匀;但光与影有着和谐的旋律,如梵婀玲上奏着的名曲。\r\r荷塘的四面,远远近近,高高低低都是树,而杨柳最多。这些树将一片荷塘重重围住;只在小路一旁,漏着几段空隙,像是特为月光留下的。树色一例是阴阴的,乍看像一团烟雾;但杨柳的丰姿,便在烟雾里也辨得出。树梢上隐隐约约的是一带远山,只有些大意罢了。树缝里也漏着一两点路灯光,没精打采的\b是渴睡人的眼。这时候最热闹的,要数树上的蝉声与水里的蛙声;但热闹是它们的,我什么也没有。\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,@@ -582,18 +703,40 @@ export const DEFAULT_DOCUMENT_DATA_CN: IDocumentData = {sectionBreaks: [{startIndex: 3066,- columnProperties: [- {- width: ptToPixel(240),- paddingEnd: ptToPixel(15),- },- ],- columnSeparatorType: ColumnSeparatorType.NONE,- sectionType: SectionType.SECTION_TYPE_UNSPECIFIED,+ // columnProperties: [+ // {+ // width: ptToPixel(240),+ // paddingEnd: ptToPixel(15),+ // },+ // ],+ // columnSeparatorType: ColumnSeparatorType.NONE,+ // sectionType: SectionType.SECTION_TYPE_UNSPECIFIED,// textDirection: textDirectionDocument,// contentDirection: textDirection!,},],+ customBlocks: [+ {+ startIndex: 189,+ blockId: 'shapeTest1',+ },+ {+ startIndex: 367,+ blockId: 'shapeTest2',+ },+ {+ startIndex: 489,+ blockId: 'shapeTest3',+ },+ {+ startIndex: 668,+ blockId: 'shapeTest4',+ },+ {+ startIndex: 962,+ blockId: 'shapeTest5',+ },+ ],},documentStyle: {pageSize: {diff --git a/packages/core/src/docs/data-model/types.ts b/packages/core/src/docs/data-model/types.tsindex 35397be759..825e22ddfd 100644--- a/packages/core/src/docs/data-model/types.ts+++ b/packages/core/src/docs/data-model/types.ts@@ -24,7 +24,7 @@ export enum DataStreamTreeNodeType {TABLE,TABLE_ROW,TABLE_CELL,- // CUSTOM_BLOCK, // \b 图片 mention等不参与文档流的场景+ CUSTOM_BLOCK, // \b 图片 mention 等不参与文档流的场景// TABLE_START, // \x1A 表格开始// TABLE_ROW_START, // \x1B 表格开始// TABLE_CELL_START, // \x1C 表格开始diff --git a/packages/core/src/services/floating-object/floating-object-manager.service.ts b/packages/core/src/services/floating-object/floating-object-manager.service.tsindex 416c042c59..e0001927c4 100644--- a/packages/core/src/services/floating-object/floating-object-manager.service.ts+++ b/packages/core/src/services/floating-object/floating-object-manager.service.ts@@ -34,6 +34,8 @@ export interface IFloatingObjectManagerSearchItemParam extends IFloatingObjectMa}export interface IFloatingObjectManagerParam extends IFloatingObjectManagerSearchItemParam {+ // TODO: Maybe it shouldn't be here?+ behindText?: boolean; // If it's true, put the float object behind the text, otherwise, put it in front of the text.floatingObject: ITransformState;}@@ -61,9 +63,7 @@ export interface IFloatingObjectManagerService {remove(searchItem: IFloatingObjectManagerSearchItemParam): void;- BatchAddOrUpdate(insertParam: IFloatingObjectManagerParam[]): void;-- remove(searchItem: IFloatingObjectManagerSearchItemParam): void;+ batchAddOrUpdate(insertParam: IFloatingObjectManagerParam[]): void;pluginUpdateRefresh(searchObjects: IFloatingObjectManagerParam[]): void;}@@ -132,7 +132,7 @@ export class FloatingObjectManagerService implements IDisposable, IFloatingObjecthis._andOrUpdate$.next(searchObjects);}- BatchAddOrUpdate(insertParams: IFloatingObjectManagerParam[]): void {+ batchAddOrUpdate(insertParams: IFloatingObjectManagerParam[]): void {const searchObjects: IFloatingObjectManagerParam[] = [];insertParams.forEach((insertParam) => {searchObjects.push(...this._addByParam(insertParam));@@ -166,7 +166,7 @@ export class FloatingObjectManagerService implements IDisposable, IFloatingObjec}private _addByParam(insertParam: IFloatingObjectManagerParam): IFloatingObjectManagerParam[] {- const { unitId, subUnitId, floatingObject, floatingObjectId } = insertParam;+ const { unitId, subUnitId, floatingObject, floatingObjectId, behindText } = insertParam;if (!this._managerInfo.has(unitId)) {this._managerInfo.set(unitId, new Map());@@ -180,7 +180,7 @@ export class FloatingObjectManagerService implements IDisposable, IFloatingObjecsubComponentData.get(subUnitId)!.set(floatingObjectId, floatingObject);- return [{ unitId, subUnitId, floatingObjectId, floatingObject }];+ return [{ unitId, subUnitId, floatingObjectId, floatingObject, behindText }];}private _clearByParam(param: IFloatingObjectManagerSearchParam): IFloatingObjectManagerParam[] {diff --git a/packages/core/src/types/interfaces/i-document-data.ts b/packages/core/src/types/interfaces/i-document-data.tsindex 9b7941cddb..45eaf1b117 100644--- a/packages/core/src/types/interfaces/i-document-data.ts+++ b/packages/core/src/types/interfaces/i-document-data.ts@@ -26,10 +26,8 @@ import type { IColorStyle, IStyleBase } from './i-style-data';export interface IDocumentData extends IReferenceSource, IExtraModelData {/** unit ID */id: string;-/** Revision of this document. Would be used in collaborated editing. Starts with zero. */rev?: number;-locale?: LocaleType;title?: string;body?: IDocumentBody;@@ -118,11 +116,16 @@ export interface IDocumentBody {textRuns?: ITextRun[]; // textRun style,interactionparagraphs?: IParagraph[]; // paragraph+sectionBreaks?: ISectionBreak[]; // SectionBreak https://support.microsoft.com/en-us/office/insert-a-section-break-eef20fd8-e38c-4ba6-a027-e503bdf8375c+customBlocks?: ICustomBlock[]; // customBlock user-defined block through plug-in+tables?: ITable[]; // Table+// tableOfContents?: { [index: number]: ITableOfContent }; // tableOfContents// links?: { [index: number]: IHyperlink }; // links+customRanges?: ICustomRange[]; // plugin register,implement special logic for streams, hyperlink, field,structured document tags, bookmark,comment}@@ -282,6 +285,7 @@ export enum CustomRangeType {export interface ICustomBlock {startIndex: number;blockType?: BlockType;+ // A unique ID associated with a custom block.blockId: string;}@@ -501,7 +505,9 @@ export interface IDrawing {objectId: string;title: string;+description: string;+// embeddedObjectBorder?: IDocsBorder;objectTransform: IObjectTransform;@@ -546,8 +552,8 @@ export enum PositionedObjectLayoutType {*/export interface IObjectTransform {size: ISize;- positionH: ObjectPositionH;- positionV: ObjectPositionV;+ positionH: IObjectPositionH;+ positionV: IObjectPositionV;angle: number;// Union field properties can be only one of the following:// shapeProperties?: IShapeProperties;@@ -790,7 +796,7 @@ export interface INumberUnit {u: NumberUnitType; // unit}-export interface ObjectPositionH {+export interface IObjectPositionH {relativeFrom: ObjectRelativeFromH;// Union field properties can be only one of the following:align?: AlignTypeH;@@ -798,7 +804,7 @@ export interface ObjectPositionH {percent?: number;}-export interface ObjectPositionV {+export interface IObjectPositionV {relativeFrom: ObjectRelativeFromV;// Union field properties can be only one of the following:align?: AlignTypeV;@@ -808,26 +814,26 @@ export interface ObjectPositionV {// 20.4.3.4 ST_RelFromH (Horizontal Relative Positioning)export enum ObjectRelativeFromH {- CHARACTER,+ PAGE,COLUMN,- INSIDE_MARGIN,- LEFT_MARGIN,+ CHARACTER,MARGIN,+ INSIDE_MARGIN,OUTSIDE_MARGIN,- PAGE,+ LEFT_MARGIN,RIGHT_MARGIN,}// 20.4.3.4 ST_RelFromH (Horizontal Relative Positioning)export enum ObjectRelativeFromV {- BOTTOM_MARGIN,- INSIDE_MARGIN,- LINE,- MARGIN,- OUTSIDE_MARGIN,PAGE,PARAGRAPH,+ LINE,+ MARGIN,TOP_MARGIN,+ BOTTOM_MARGIN,+ INSIDE_MARGIN,+ OUTSIDE_MARGIN,}export enum NumberUnitType {POINT,diff --git a/packages/docs-ui/src/controllers/floating-object.controller.ts b/packages/docs-ui/src/controllers/doc-floating-object.controller.tssimilarity index 91%rename from packages/docs-ui/src/controllers/floating-object.controller.tsrename to packages/docs-ui/src/controllers/doc-floating-object.controller.tsindex 097bb82cde..ad57ec71dc 100644--- a/packages/docs-ui/src/controllers/floating-object.controller.ts+++ b/packages/docs-ui/src/controllers/doc-floating-object.controller.ts@@ -16,6 +16,7 @@import type { ICommandInfo, IFloatingObjectManagerParam } from '@univerjs/core';import {+ BooleanNumber,DEFAULT_DOCUMENT_SUB_COMPONENT_ID,Disposable,ICommandService,@@ -23,6 +24,7 @@ import {IUniverInstanceService,LifecycleStages,OnLifecycle,+ PositionedObjectLayoutType,} from '@univerjs/core';import type { IRichTextEditingMutationParams } from '@univerjs/docs';import { DocSkeletonManagerService, RichTextEditingMutation, SetDocZoomRatioOperation } from '@univerjs/docs';@@ -31,8 +33,8 @@ import { IRenderManagerService, Liquid } from '@univerjs/engine-render';import { IEditorService } from '@univerjs/ui';import { Inject } from '@wendellhu/redi';-@OnLifecycle(LifecycleStages.Steady, FloatingObjectController)-export class FloatingObjectController extends Disposable {+@OnLifecycle(LifecycleStages.Steady, DocFloatingObjectController)+export class DocFloatingObjectController extends Disposable {private _liquid = new Liquid();private _pageMarginCache = new Map<string, { marginLeft: number; marginTop: number }>();@@ -124,6 +126,7 @@ export class FloatingObjectController extends Disposable {const docsComponent = mainComponent as Documents;+ // TODO: Why NEED change skeleton here?docsComponent.changeSkeleton(documentSkeleton);this._refreshFloatingObject(unitId, documentSkeleton, currentRender);@@ -185,7 +188,7 @@ export class FloatingObjectController extends Disposable {const { pages } = skeletonData;- const Objects: IFloatingObjectManagerParam[] = [];+ const floatObjects: IFloatingObjectManagerParam[] = [];const { scaleX, scaleY } = scene.getAncestorScale();@@ -204,18 +207,19 @@ export class FloatingObjectController extends Disposable {for (let i = 0, len = pages.length; i < len; i++) {const page = pages[i];const { skeDrawings, marginLeft, marginTop } = page;-// cumPageLeft + = pageWidth + documents.pageMarginLeft;this._liquid.translatePagePadding(page);skeDrawings.forEach((drawing) => {- const { aLeft, aTop, height, width, objectId } = drawing;+ const { aLeft, aTop, height, width, objectId, drawingOrigin } = drawing;+ const behindText = drawingOrigin.layoutType === PositionedObjectLayoutType.WRAP_NONE && drawingOrigin.behindDoc === BooleanNumber.TRUE;- Objects.push({+ floatObjects.push({unitId,subUnitId: DEFAULT_DOCUMENT_SUB_COMPONENT_ID,floatingObjectId: objectId,+ behindText,floatingObject: {left: aLeft + docsLeft + this._liquid.x,top: aTop + docsTop + this._liquid.y,@@ -230,9 +234,11 @@ export class FloatingObjectController extends Disposable {});});+ this._liquid.restorePagePadding(page);+this._liquid.translatePage(page, pageLayoutType, pageMarginLeft, pageMarginTop);}- this._floatingObjectManagerService.BatchAddOrUpdate(Objects);+ this._floatingObjectManagerService.batchAddOrUpdate(floatObjects);}}diff --git a/packages/docs-ui/src/controllers/doc-render.controller.ts b/packages/docs-ui/src/controllers/doc-render.controller.tsindex 3c5c15ac43..ebb0bd9882 100644--- a/packages/docs-ui/src/controllers/doc-render.controller.ts+++ b/packages/docs-ui/src/controllers/doc-render.controller.ts@@ -20,14 +20,14 @@ import {LifecycleStages,OnLifecycle,RxDisposable } from '@univerjs/core';-import type { Documents, DocumentSkeleton, IRender } from '@univerjs/engine-render';+import type { DocBackground, Documents, DocumentSkeleton, IRender } from '@univerjs/engine-render';import { IRenderManagerService, PageLayoutType } from '@univerjs/engine-render';import { Inject } from '@wendellhu/redi';import { takeUntil } from 'rxjs';import { IEditorService } from '@univerjs/ui';import type { IDocSkeletonManagerParam, IRichTextEditingMutationParams } from '@univerjs/docs';-import { DocSkeletonManagerService, RichTextEditingMutation } from '@univerjs/docs';+import { DOCS_VIEW_KEY, DocSkeletonManagerService, RichTextEditingMutation } from '@univerjs/docs';@OnLifecycle(LifecycleStages.Rendered, DocRenderController)export class DocRenderController extends RxDisposable {@@ -66,20 +66,26 @@ export class DocRenderController extends RxDisposable {currentRender = this._renderManagerService.getRenderById(unitId)!;}- const { mainComponent } = currentRender;+ const { mainComponent, components } = currentRender;const docsComponent = mainComponent as Documents;+ const docBackground = components.get(DOCS_VIEW_KEY.BACKGROUND) as DocBackground;+docsComponent.changeSkeleton(documentSkeleton);+ docBackground.changeSkeleton(documentSkeleton);+this._recalculateSizeBySkeleton(currentRender, documentSkeleton);}private _recalculateSizeBySkeleton(currentRender: IRender, skeleton: DocumentSkeleton) {- const { mainComponent, scene, unitId } = currentRender;+ const { mainComponent, scene, unitId, components } = currentRender;const docsComponent = mainComponent as Documents;+ const docBackground = components.get(DOCS_VIEW_KEY.BACKGROUND) as DocBackground;+const pages = skeleton.getSkeletonData()?.pages;if (pages == null) {@@ -114,6 +120,7 @@ export class DocRenderController extends RxDisposable {}docsComponent.resize(width, height);+ docBackground.resize(width, height);if (!this._editorService.isEditor(unitId)) {scene.resize(width, height);diff --git a/packages/docs-ui/src/controllers/page-render.controller.ts b/packages/docs-ui/src/controllers/page-render.controller.tsdeleted file mode 100644index 701604cee5..0000000000--- a/packages/docs-ui/src/controllers/page-render.controller.ts+++ /dev/null@@ -1,102 +0,0 @@-/**- * Copyright 2023-present DreamNum Inc.- *- * Licensed under the Apache License, Version 2.0 (the "License");- * you may not use this file except in compliance with the License.- * You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */--import {- Disposable,- IUniverInstanceService,- LifecycleStages,- OnLifecycle,- toDisposable,-} from '@univerjs/core';-import type { Documents, IPageRenderConfig } from '@univerjs/engine-render';-import { IRenderManagerService, Rect } from '@univerjs/engine-render';-import { IEditorService } from '@univerjs/ui';--const PAGE_STROKE_COLOR = 'rgba(198, 198, 198, 1)';--const PAGE_FILL_COLOR = 'rgba(255, 255, 255, 1)';--@OnLifecycle(LifecycleStages.Rendered, PageRenderController)-export class PageRenderController extends Disposable {- constructor(- @IRenderManagerService private readonly _renderManagerService: IRenderManagerService,- @IEditorService private readonly _editorService: IEditorService,- @IUniverInstanceService private readonly _univerInstanceService: IUniverInstanceService- ) {- super();-- this._initialize();-- this._commandExecutedListener();- }-- private _initialize() {- this._initialRenderRefresh();- }-- private _initialRenderRefresh() {- this._renderManagerService.currentRender$.subscribe((unitId) => {- if (unitId == null) {- return;- }-- const currentRender = this._renderManagerService.getRenderById(unitId);- if (this._editorService.isEditor(unitId) || this._univerInstanceService.getUniverDocInstance(unitId) == null) {- return;- }-- if (currentRender == null) {- return;- }-- const { mainComponent } = currentRender;-- const docsComponent = mainComponent as Documents;-- const pageSize = docsComponent.getSkeleton()?.getPageSize();-- this.disposeWithMe(- toDisposable(- docsComponent.onPageRenderObservable.add((config: IPageRenderConfig) => {- if (this._editorService.isEditor(unitId)) {- return;- }-- // Draw page borders- const { page, pageLeft, pageTop, ctx } = config;- const { width, pageWidth, height, pageHeight } = page;-- ctx.save();-- ctx.translate(pageLeft - 0.5, pageTop - 0.5);- const options = {- width: pageSize?.width ?? pageWidth ?? width,- height: pageSize?.height ?? pageHeight ?? height,- strokeWidth: 1,- stroke: PAGE_STROKE_COLOR,- fill: PAGE_FILL_COLOR,- zIndex: 3,- };- Rect.drawWith(ctx, options);- ctx.restore();- })- )- );- });- }-- private _commandExecutedListener() { }-}diff --git a/packages/docs-ui/src/controllers/zoom.controller.ts b/packages/docs-ui/src/controllers/zoom.controller.tsindex dd1339db25..b966fb5c4a 100644--- a/packages/docs-ui/src/controllers/zoom.controller.ts+++ b/packages/docs-ui/src/controllers/zoom.controller.ts@@ -190,7 +190,7 @@ export class ZoomController extends Disposable {}private _calculatePagePosition(currentRender: IDocObjectParam, zoomRatio: number) {- const { document: docsComponent, scene } = currentRender;+ const { document: docsComponent, scene, docBackground } = currentRender;const parent = scene?.getParent();@@ -236,6 +236,7 @@ export class ZoomController extends Disposable {scene.resize(sceneWidth, sceneHeight + 200);docsComponent.translate(docsLeft, docsTop);+ docBackground.translate(docsLeft, docsTop);const viewport = scene.getViewport(VIEWPORT_KEY.VIEW_MAIN);if (scrollToX !== Number.POSITIVE_INFINITY && viewport != null) {diff --git a/packages/docs-ui/src/docs-ui-plugin.ts b/packages/docs-ui/src/docs-ui-plugin.tsindex c1e59a944d..e45af29050 100644--- a/packages/docs-ui/src/docs-ui-plugin.ts+++ b/packages/docs-ui/src/docs-ui-plugin.ts@@ -51,8 +51,7 @@ import { DocClipboardController } from './controllers/clipboard.controller';import { DocEditorBridgeController } from './controllers/doc-editor-bridge.controller';import { DocRenderController } from './controllers/doc-render.controller';import { DocCanvasView } from './views/doc-canvas-view';-import { FloatingObjectController } from './controllers/floating-object.controller';-import { PageRenderController } from './controllers/page-render.controller';+import { DocFloatingObjectController } from './controllers/doc-floating-object.controller';import { ZoomController } from './controllers/zoom.controller';import { TextSelectionController } from './controllers/text-selection.controller';import { BackScrollController } from './controllers/back-scroll.controller';@@ -109,8 +108,7 @@ export class UniverDocsUIPlugin extends Plugin {[DocClipboardController],[DocEditorBridgeController],[DocRenderController],- [FloatingObjectController],- [PageRenderController],+ [DocFloatingObjectController],[ZoomController],[TextSelectionController],[BackScrollController],diff --git a/packages/docs-ui/src/views/doc-canvas-view.ts b/packages/docs-ui/src/views/doc-canvas-view.tsindex 71e885c5ea..74606f53db 100644--- a/packages/docs-ui/src/views/doc-canvas-view.ts+++ b/packages/docs-ui/src/views/doc-canvas-view.ts@@ -22,9 +22,9 @@ import { IConfigService,RxDisposable,UniverInstanceType,} from '@univerjs/core';-import { DOCS_COMPONENT_DEFAULT_Z_INDEX, DOCS_COMPONENT_HEADER_LAYER_INDEX, DOCS_COMPONENT_MAIN_LAYER_INDEX, DOCS_VIEW_KEY, VIEWPORT_KEY } from '@univerjs/docs';+import { DOCS_COMPONENT_BACKGROUND_LAYER_INDEX, DOCS_COMPONENT_DEFAULT_Z_INDEX, DOCS_COMPONENT_HEADER_LAYER_INDEX, DOCS_COMPONENT_MAIN_LAYER_INDEX, DOCS_VIEW_KEY, VIEWPORT_KEY } from '@univerjs/docs';import type { IRender, IWheelEvent, Scene } from '@univerjs/engine-render';-import { Documents, EVENT_TYPE, IRenderManagerService, Layer, ScrollBar, Viewport } from '@univerjs/engine-render';+import { DocBackground, Documents, EVENT_TYPE, IRenderManagerService, Layer, ScrollBar, Viewport } from '@univerjs/engine-render';import { IEditorService } from '@univerjs/ui';import { BehaviorSubject, takeUntil } from 'rxjs';@@ -181,17 +181,24 @@ export class DocCanvasView extends RxDisposable {private _addComponent(currentRender: IRender) {const scene = this._scene;const documentModel = this._currentDocumentModel;- const documents = new Documents(DOCS_VIEW_KEY.MAIN, undefined, {+ const config = {pageMarginLeft: documentModel.documentStyle.marginLeft || 0,pageMarginTop: documentModel.documentStyle.marginTop || 0,- });+ };+ const documents = new Documents(DOCS_VIEW_KEY.MAIN, undefined, config);++ const docBackground = new DocBackground(DOCS_VIEW_KEY.BACKGROUND, undefined, config);documents.zIndex = DOCS_COMPONENT_DEFAULT_Z_INDEX;+ docBackground.zIndex = DOCS_COMPONENT_DEFAULT_Z_INDEX;+currentRender.mainComponent = documents;currentRender.components.set(DOCS_VIEW_KEY.MAIN, documents);+ currentRender.components.set(DOCS_VIEW_KEY.BACKGROUND, docBackground);scene.addObjects([documents], DOCS_COMPONENT_MAIN_LAYER_INDEX);+ scene.addObjects([docBackground], DOCS_COMPONENT_BACKGROUND_LAYER_INDEX);if (this._editorService.getEditor(documentModel.getUnitId()) == null) {scene.enableLayerCache(DOCS_COMPONENT_MAIN_LAYER_INDEX);diff --git a/packages/docs/src/basics/component-tools.ts b/packages/docs/src/basics/component-tools.tsindex f3723b90cc..9bba5df21f 100644--- a/packages/docs/src/basics/component-tools.ts+++ b/packages/docs/src/basics/component-tools.ts@@ -15,10 +15,12 @@*/import { type IUniverInstanceService, type Nullable, UniverInstanceType } from '@univerjs/core';-import type { Documents, Engine, IRenderManagerService, Scene } from '@univerjs/engine-render';+import type { DocBackground, Documents, Engine, IRenderManagerService, Scene } from '@univerjs/engine-render';+import { DOCS_VIEW_KEY } from './docs-view-key';export interface IDocObjectParam {document: Documents;+ docBackground: DocBackground;scene: Scene;engine: Engine;}@@ -38,11 +40,13 @@ export function getDocObject(return;}- const { mainComponent, scene, engine } = currentRender;+ const { mainComponent, scene, engine, components } = currentRender;const document = mainComponent as Documents;+ const docBackground = components.get(DOCS_VIEW_KEY.BACKGROUND) as DocBackground;return {document,+ docBackground,scene,engine,};@@ -57,11 +61,13 @@ export function getDocObjectById(return;}- const { mainComponent, scene, engine } = currentRender;+ const { mainComponent, scene, engine, components } = currentRender;const document = mainComponent as Documents;+ const docBackground = components.get(DOCS_VIEW_KEY.BACKGROUND) as DocBackground;return {document,+ docBackground,scene,engine,};diff --git a/packages/docs/src/basics/docs-view-key.ts b/packages/docs/src/basics/docs-view-key.tsindex 0fe7852571..b51a3a6ca8 100644--- a/packages/docs/src/basics/docs-view-key.ts+++ b/packages/docs/src/basics/docs-view-key.ts@@ -16,6 +16,7 @@export enum DOCS_VIEW_KEY {MAIN = '__Document_Render_Main__',+ BACKGROUND = '__Document_Render_Background__',}export enum VIEWPORT_KEY {@@ -25,9 +26,11 @@ export enum VIEWPORT_KEY {VIEW_LEFT_TOP = 'viewLeftTop',}-export const DOCS_COMPONENT_MAIN_LAYER_INDEX = 0;+export const DOCS_COMPONENT_BACKGROUND_LAYER_INDEX = 0;-export const DOCS_COMPONENT_HEADER_LAYER_INDEX = 2;+export const DOCS_COMPONENT_MAIN_LAYER_INDEX = 2;++export const DOCS_COMPONENT_HEADER_LAYER_INDEX = 4;export const DOCS_COMPONENT_DEFAULT_Z_INDEX = 10;diff --git a/packages/docs/src/commands/commands/set-floating-object-transform.command.ts b/packages/docs/src/commands/commands/set-floating-object-transform.command.tsindex fb791b7a97..bf1936e127 100644--- a/packages/docs/src/commands/commands/set-floating-object-transform.command.ts+++ b/packages/docs/src/commands/commands/set-floating-object-transform.command.ts@@ -14,7 +14,7 @@* limitations under the License.*/-import type { ICommand, ISize, ObjectPositionH, ObjectPositionV } from '@univerjs/core';+import type { ICommand, IObjectPositionH, IObjectPositionV, ISize } from '@univerjs/core';import { CommandType, ICommandService, IUndoRedoService, IUniverInstanceService } from '@univerjs/core';import type { IAccessor } from '@wendellhu/redi';@@ -78,8 +78,8 @@ export const SetDrawingSizeCommand: ICommand = {export interface ISetDrawingPositionCommandParams {documentId: string;objectId: string;- positionH: ObjectPositionH;- positionV: ObjectPositionV;+ positionH: IObjectPositionH;+ positionV: IObjectPositionV;}export const SetDrawingPositionCommand: ICommand = {diff --git a/packages/docs/src/commands/mutations/core-editing.mutation.ts b/packages/docs/src/commands/mutations/core-editing.mutation.tsindex c3d0f64aa1..3120ee8dca 100644--- a/packages/docs/src/commands/mutations/core-editing.mutation.ts+++ b/packages/docs/src/commands/mutations/core-editing.mutation.ts@@ -45,6 +45,7 @@ export const RichTextEditingMutation: IMutation<IRichTextEditingMutationParams,type: CommandType.MUTATION,+ // eslint-disable-next-line max-lines-per-functionhandler: (accessor, params) => {const {unitId,diff --git a/packages/docs/src/commands/mutations/set-floating-object.mutation.ts b/packages/docs/src/commands/mutations/set-floating-object.mutation.tsindex 34ba5f8aa5..3394142e6e 100644--- a/packages/docs/src/commands/mutations/set-floating-object.mutation.ts+++ b/packages/docs/src/commands/mutations/set-floating-object.mutation.ts@@ -17,9 +17,9 @@import type {BooleanNumber,IMutation,+ IObjectPositionH,+ IObjectPositionV,ISize,- ObjectPositionH,- ObjectPositionV,PositionedObjectLayoutType,WrapTextType,} from '@univerjs/core';@@ -33,8 +33,8 @@ export interface ISeachDrawingMutation {export interface IDrawingTransformMutation extends ISeachDrawingMutation {size?: ISize;- positionH?: ObjectPositionH;- positionV?: ObjectPositionV;+ positionH?: IObjectPositionH;+ positionV?: IObjectPositionV;angle?: number;}diff --git a/packages/engine-render/src/basics/i-document-skeleton-cached.ts b/packages/engine-render/src/basics/i-document-skeleton-cached.tsindex 6d5d800a49..ef3fe50a5d 100644--- a/packages/engine-render/src/basics/i-document-skeleton-cached.ts+++ b/packages/engine-render/src/basics/i-document-skeleton-cached.ts@@ -185,6 +185,7 @@ export interface IDocumentSkeletonGlyph {parent?: IDocumentSkeletonDivide;url?: string; // image urlfeatureId?: string; // support interaction for feature ,eg. hyperLine person+ objectId?: string; // drawing.objectId}export interface IDocumentSkeletonBullet extends IIndentStart {diff --git a/packages/engine-render/src/basics/interfaces.ts b/packages/engine-render/src/basics/interfaces.tsindex 70e609004e..ba43c1327c 100644--- a/packages/engine-render/src/basics/interfaces.ts+++ b/packages/engine-render/src/basics/interfaces.ts@@ -117,6 +117,7 @@ export interface ISectionBreakConfig extends IDocStyleBase, ISectionBreakBase, Iexport interface IParagraphConfig {paragraphIndex: number;paragraphAffectSkeDrawings?: Map<string, IDocumentSkeletonDrawing>;+ paragraphInlineSkeDrawings?: Map<string, IDocumentSkeletonDrawing>;// headerAndFooterAffectSkeDrawings?: Map<string, IDocumentSkeletonDrawing>;bulletSkeleton?: IDocumentSkeletonBullet;// pageContentWidth: number;diff --git a/packages/engine-render/src/components/docs/doc-background.ts b/packages/engine-render/src/components/docs/doc-background.tsnew file mode 100644index 0000000000..b1edc05902--- /dev/null+++ b/packages/engine-render/src/components/docs/doc-background.ts@@ -0,0 +1,109 @@+/**+ * 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 { IViewportBound } from '../../basics/vector2';+import type { UniverRenderingContext } from '../../context';+import { Rect } from '../../shape';+import { Liquid } from './liquid';+import type { IDocumentsConfig } from './doc-component';+import { DocComponent } from './doc-component';+import type { DocumentSkeleton } from './layout/doc-skeleton';++const PAGE_STROKE_COLOR = 'rgba(198, 198, 198, 1)';+const PAGE_FILL_COLOR = 'rgba(255, 255, 255, 1)';++export class DocBackground extends DocComponent {+ private _drawLiquid: Liquid;++ constructor(oKey: string, documentSkeleton?: DocumentSkeleton, config?: IDocumentsConfig) {+ super(oKey, documentSkeleton, config);++ this._drawLiquid = new Liquid();++ this.makeDirty(true);+ }++ static create(oKey: string, documentSkeleton?: DocumentSkeleton, config?: IDocumentsConfig) {+ return new DocBackground(oKey, documentSkeleton, config);+ }++ override draw(ctx: UniverRenderingContext, bounds?: IViewportBound) {+ const skeletonData = this.getSkeleton()?.getSkeletonData();++ if (skeletonData == null) {+ return;+ }++ this._drawLiquid.reset();++ const { pages } = skeletonData;++ // broadcasting the pageTop and pageLeft for each page in the document with multiple pages.+ let pageTop = 0;+ let pageLeft = 0;++ for (let i = 0, len = pages.length; i < len; i++) {+ const page = pages[i];++ if (this.isSkipByDiffBounds(page, pageTop, pageLeft, bounds)) {+ const { x, y } = this._drawLiquid.translatePage(+ page,+ this.pageLayoutType,+ this.pageMarginLeft,+ this.pageMarginTop+ );+ pageLeft += x;+ pageTop += y;+ continue;+ }++ // Draw background.+ const { width, pageWidth, height, pageHeight } = page;++ ctx.save();+ ctx.translate(pageLeft - 0.5, pageTop - 0.5);+ const options = {+ width: pageWidth ?? width,+ height: pageHeight ?? height,+ strokeWidth: 1,+ stroke: PAGE_STROKE_COLOR,+ fill: PAGE_FILL_COLOR,+ zIndex: 3,+ };+ Rect.drawWith(ctx, options);+ ctx.restore();++ const { x, y } = this._drawLiquid.translatePage(+ page,+ this.pageLayoutType,+ this.pageMarginLeft,+ this.pageMarginTop+ );+ pageLeft += x;+ pageTop += y;+ }+ }++ changeSkeleton(newSkeleton: DocumentSkeleton) {+ this.setSkeleton(newSkeleton);++ return this;+ }++ protected override _draw(ctx: UniverRenderingContext, bounds?: IViewportBound) {+ this.draw(ctx, bounds);+ }+}diff --git a/packages/engine-render/src/components/docs/doc-component.ts b/packages/engine-render/src/components/docs/doc-component.tsindex 06c162c5f3..e01373e188 100644--- a/packages/engine-render/src/components/docs/doc-component.ts+++ b/packages/engine-render/src/components/docs/doc-component.ts@@ -17,7 +17,7 @@import type { Nullable } from '@univerjs/core';import { RENDER_CLASS_TYPE } from '../../basics/const';-import type { IDocumentSkeletonGlyph, IDocumentSkeletonLine } from '../../basics/i-document-skeleton-cached';+import type { IDocumentSkeletonGlyph, IDocumentSkeletonLine, IDocumentSkeletonPage } from '../../basics/i-document-skeleton-cached';import { PageLayoutType } from '../../basics/i-document-skeleton-cached';import type { INodeInfo } from '../../basics/interfaces';import type { IBoundRectNoAngle, IViewportBound } from '../../basics/vector2';@@ -26,6 +26,16 @@ import { RenderComponent } from '../component';import type { DOCS_EXTENSION_TYPE } from './doc-extension';import type { DocumentSkeleton } from './layout/doc-skeleton';+export interface IPageMarginLayout {+ pageMarginLeft: number;+ pageMarginTop: number;+ pageLayoutType?: PageLayoutType;+}++export interface IDocumentsConfig extends IPageMarginLayout {+ hasEditor?: boolean;+}+export class DocComponent extends RenderComponent<IDocumentSkeletonGlyph | IDocumentSkeletonLine,DOCS_EXTENSION_TYPE,@@ -39,9 +49,12 @@ export class DocComponent extends RenderComponent<constructor(oKey: string,- private _skeleton?: DocumentSkeleton+ private _skeleton?: DocumentSkeleton,+ config?: IDocumentsConfig) {super(oKey);++ this._setConfig(config);}getSkeleton() {@@ -52,6 +65,26 @@ export class DocComponent extends RenderComponent<this._skeleton = skeleton;}+ private _setConfig(config?: IDocumentsConfig) {+ if (config?.pageMarginLeft != null) {+ this.pageMarginLeft = config?.pageMarginLeft;+ } else {+ this.pageMarginLeft = 17;+ }++ if (config?.pageMarginTop != null) {+ this.pageMarginTop = config?.pageMarginTop;+ } else {+ this.pageMarginTop = 14;+ }++ if (config?.pageLayoutType != null) {+ this.pageLayoutType = config?.pageLayoutType;+ } else {+ this.pageLayoutType = PageLayoutType.VERTICAL;+ }+ }+override render(mainCtx: UniverRenderingContext, bounds?: IViewportBound) {if (!this.visible) {this.makeDirty(false);@@ -88,6 +121,34 @@ export class DocComponent extends RenderComponent<};}+ isSkipByDiffBounds(page: IDocumentSkeletonPage, pageTop: number, pageLeft: number, bounds?: IViewportBound) {+ if (bounds === null || bounds === undefined) {+ return false;+ }++ const { pageWidth, pageHeight, marginBottom, marginTop, marginLeft, marginRight } = page;++ const pageRight = pageLeft + pageWidth + marginLeft + marginRight;++ const pageBottom = pageTop + pageHeight + marginBottom + marginTop;++ const { left, top, right, bottom } = bounds.viewBound;++ if (pageRight < left || pageBottom < top) {+ return true;+ }++ if (pageLeft > right && pageWidth !== Number.POSITIVE_INFINITY) {+ return true;+ }++ if (pageTop > bottom && pageHeight !== Number.POSITIVE_INFINITY) {+ return true;+ }++ return false;+ }+scrollBySelection() {}syncSelection() {}diff --git a/packages/engine-render/src/components/docs/document.ts b/packages/engine-render/src/components/docs/document.tsindex 4bc14209ff..9ac3892537 100644--- a/packages/engine-render/src/components/docs/document.ts+++ b/packages/engine-render/src/components/docs/document.ts@@ -22,7 +22,7 @@ import { CellValueType, HorizontalAlign, Observable, VerticalAlign, WrapStrategyimport { calculateRectRotate, getRotateOffsetAndFarthestHypotenuse } from '../../basics/draw';import type { IDocumentSkeletonCached, IDocumentSkeletonPage } from '../../basics/i-document-skeleton-cached';-import { LineType, PageLayoutType } 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';import type { IViewportBound } from '../../basics/vector2';@@ -33,20 +33,11 @@ import type { IExtensionConfig } from '../extension';import { DocumentsSpanAndLineExtensionRegistry } from '../extension';import { VERTICAL_ROTATE_ANGLE } from '../../basics/text-rotation';import { Liquid } from './liquid';+import type { IDocumentsConfig, IPageMarginLayout } from './doc-component';import { DocComponent } from './doc-component';import { DOCS_EXTENSION_TYPE } from './doc-extension';import type { DocumentSkeleton } from './layout/doc-skeleton';-interface IPageMarginLayout {- pageMarginLeft: number;- pageMarginTop: number;- pageLayoutType?: PageLayoutType;-}--export interface IDocumentsConfig extends IPageMarginLayout {- hasEditor?: boolean;-}-export interface IPageRenderConfig {page: IDocumentSkeletonPage;pageLeft: number;@@ -80,9 +71,7 @@ export class Documents extends DocComponent {// private _textAngleRotateOffset: number = 0;constructor(oKey: string, documentSkeleton?: DocumentSkeleton, config?: IDocumentsConfig) {- super(oKey, documentSkeleton);-- this.setConfig(config);+ super(oKey, documentSkeleton, config);this._drawLiquid = new Liquid();@@ -95,10 +84,6 @@ export class Documents extends DocComponent {this.makeDirty(true);}- // get hasEditor() {- // return this._hasEditor;- // }-static create(oKey: string, documentSkeleton?: DocumentSkeleton, config?: IDocumentsConfig) {return new Documents(oKey, documentSkeleton, config);}@@ -113,26 +98,6 @@ export class Documents extends DocComponent {this._findLiquid = null as unknown as Liquid;}- setConfig(config?: IDocumentsConfig) {- if (config?.pageMarginLeft != null) {- this.pageMarginLeft = config?.pageMarginLeft;- } else {- this.pageMarginLeft = 17;- }-- if (config?.pageMarginTop != null) {- this.pageMarginTop = config?.pageMarginTop;- } else {- this.pageMarginTop = 14;- }-- if (config?.pageLayoutType != null) {- this.pageLayoutType = config?.pageLayoutType;- } else {- this.pageLayoutType = PageLayoutType.VERTICAL;- }- }-getOffsetConfig(): IDocumentOffsetConfig {const {transform: documentTransform,@@ -202,18 +167,6 @@ export class Documents extends DocComponent {override draw(ctx: UniverRenderingContext, bounds?: IViewportBound) {- const documentSkeleton = this.getSkeleton();-- if (!documentSkeleton) {- return;- }-- // if (this.isCalculateSkeleton) {- // documentSkeleton.calculate(bounds);- // }-- this._drawLiquid.reset();-const skeletonData = this.getSkeleton()?.getSkeletonData();if (skeletonData == null) {@@ -285,7 +238,7 @@ export class Documents extends DocComponent {const finalAngle = vertexAngle - centerAngle;- if (this._isSkipByDiffBounds(page, pageTop, pageLeft, bounds)) {+ if (this.isSkipByDiffBounds(page, pageTop, pageLeft, bounds)) {const { x, y } = this._drawLiquid.translatePage(page,this.pageLayoutType,@@ -602,34 +555,6 @@ export class Documents extends DocComponent {});}- private _isSkipByDiffBounds(page: IDocumentSkeletonPage, pageTop: number, pageLeft: number, bounds?: IViewportBound) {- if (bounds === null || bounds === undefined) {- return false;- }-- const { pageWidth, pageHeight, marginBottom, marginTop, marginLeft, marginRight } = page;-- const pageRight = pageLeft + pageWidth + marginLeft + marginRight;-- const pageBottom = pageTop + pageHeight + marginBottom + marginTop;-- const { left, top, right, bottom } = bounds.viewBound;-- if (pageRight < left || pageBottom < top) {- return true;- }-- if (pageLeft > right && pageWidth !== Number.POSITIVE_INFINITY) {- return true;- }-- if (pageTop > bottom && pageHeight !== Number.POSITIVE_INFINITY) {- return true;- }-- return false;- }-// private _addSkeletonChangeObserver(skeleton?: DocumentSkeleton) {// if (!skeleton) {// return;diff --git a/packages/engine-render/src/components/docs/layout/block/paragraph/inline-drawing.ts b/packages/engine-render/src/components/docs/layout/block/paragraph/inline-drawing.tsdeleted file mode 100644index 6d350fe652..0000000000--- a/packages/engine-render/src/components/docs/layout/block/paragraph/inline-drawing.ts+++ /dev/null@@ -1,30 +0,0 @@-/**- * Copyright 2023-present DreamNum Inc.- *- * Licensed under the Apache License, Version 2.0 (the "License");- * you may not use this file except in compliance with the License.- * You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */--import type { IDrawing, LocaleService } from '@univerjs/core';--import type { IDocumentSkeletonPage } from '../../../../../basics/i-document-skeleton-cached';-import type { IParagraphConfig, ISectionBreakConfig } from '../../../../../basics/interfaces';--export function dealWidthInlineDrawing(- drawing: IDrawing,- sectionBreakConfig: ISectionBreakConfig,- allPages?: IDocumentSkeletonPage[],- paragraphConfig?: IParagraphConfig,- localeService?: LocaleService-) {- return [];-}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 3cf1885141..6b8f1746b1 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,8 +15,7 @@*/import type { INumberUnit } from '@univerjs/core';-import { BooleanNumber, DataStreamTreeTokenType, GridType, SpacingRule } from '@univerjs/core';-+import { BooleanNumber, DataStreamTreeTokenType, GridType, ObjectRelativeFromV, PositionedObjectLayoutType, SpacingRule } from '@univerjs/core';import type {IDocumentSkeletonColumn,IDocumentSkeletonDrawing,@@ -28,14 +27,17 @@ import { GlyphType, LineType } from '../../../../../basics/i-document-skeleton-cimport type { IParagraphConfig, ISectionBreakConfig } from '../../../../../basics/interfaces';import {calculateLineTopByDrawings,+ collisionDetection,createAndUpdateBlockAnchor,createSkeletonLine,setDivideFullState,} from '../../model/line';-import { createSkeletonPage } from '../../model/page';import { setColumnFullState } from '../../model/section';import { addGlyphToDivide, createSkeletonBulletGlyph } from '../../model/glyph';+import type {+ ILayoutContext,+} from '../../tools';import {getCharSpaceApply,getCharSpaceConfig,@@ -49,9 +51,11 @@ import {getPositionHorizon,getPositionVertical,isColumnFull,+ lineIterator,} from '../../tools';export function layoutParagraph(+ ctx: ILayoutContext,glyphGroup: IDocumentSkeletonGlyph[],pages: IDocumentSkeletonPage[],sectionBreakConfig: ISectionBreakConfig,@@ -70,12 +74,12 @@ export function layoutParagraph(const charSpaceApply = getCharSpaceApply(charSpace, defaultTabStop, gridType, snapToGrid);const bulletGlyph = createSkeletonBulletGlyph(glyphGroup[0], bulletSkeleton, charSpaceApply);- _lineOperator([bulletGlyph, ...glyphGroup], pages, sectionBreakConfig, paragraphConfig, paragraphStart);+ _lineOperator(ctx, [bulletGlyph, ...glyphGroup], pages, sectionBreakConfig, paragraphConfig, paragraphStart);} else {- _lineOperator(glyphGroup, pages, sectionBreakConfig, paragraphConfig, paragraphStart);+ _lineOperator(ctx, glyphGroup, pages, sectionBreakConfig, paragraphConfig, paragraphStart);}} else {- _divideOperator(glyphGroup, pages, sectionBreakConfig, paragraphConfig, paragraphStart);+ _divideOperator(ctx, glyphGroup, pages, sectionBreakConfig, paragraphConfig, paragraphStart);}return [...pages];@@ -131,6 +135,7 @@ function isGlyphGroupBeyondContentBox(glyphGroup: IDocumentSkeletonGlyph[], left}function _divideOperator(+ ctx: ILayoutContext,glyphGroup: IDocumentSkeletonGlyph[],pages: IDocumentSkeletonPage[],sectionBreakConfig: ISectionBreakConfig,@@ -191,7 +196,8 @@ function _divideOperator(addGlyphToDivide(divide, sliceGlyphGroup, preOffsetLeft);if (glyphGroup.length) {- _lineOperator(+ _divideOperator(+ ctx,glyphGroup,pages,sectionBreakConfig,@@ -201,7 +207,8 @@ function _divideOperator();}} else {- _lineOperator(+ _divideOperator(+ ctx,glyphGroup,pages,sectionBreakConfig,@@ -252,6 +259,7 @@ function _divideOperator(const { paragraphStart: lineIsStart } = column?.lines.pop()!; // Delete the previous line and recalculate according to the maximum content height_lineOperator(+ ctx,newSpanGroup,pages,sectionBreakConfig,@@ -261,7 +269,9 @@ function _divideOperator();for (let i = startIndex; i < spanGroupCached.length; i++) {+ // TODO: @jocs Here you may see non-breakpoints appearing at the end of the line._divideOperator(+ ctx,[spanGroupCached[i]],pages,sectionBreakConfig,@@ -270,7 +280,7 @@ function _divideOperator();}- _divideOperator(glyphGroup, pages, sectionBreakConfig, paragraphConfig, paragraphStart);+ _divideOperator(ctx, glyphGroup, pages, sectionBreakConfig, paragraphConfig, paragraphStart);return;}@@ -279,11 +289,12 @@ function _divideOperator(addGlyphToDivide(divide, glyphGroup, preOffsetLeft);}} else {- _lineOperator(glyphGroup, pages, sectionBreakConfig, paragraphConfig, paragraphStart, defaultSpanLineHeight);+ _lineOperator(ctx, glyphGroup, pages, sectionBreakConfig, paragraphConfig, paragraphStart, defaultSpanLineHeight);}}function _lineOperator(+ ctx: ILayoutContext,glyphGroup: IDocumentSkeletonGlyph[],pages: IDocumentSkeletonPage[],sectionBreakConfig: ISectionBreakConfig,@@ -295,7 +306,7 @@ function _lineOperator(let columnInfo = getLastNotFullColumnInfo(lastPage);if (!columnInfo || !columnInfo.column) {// 如果列不存在,则做一个兜底策略,新增一页。- _pageOperator(glyphGroup, pages, sectionBreakConfig, paragraphConfig);+ _pageOperator(ctx, glyphGroup, pages, sectionBreakConfig, paragraphConfig);lastPage = getLastPage(pages);columnInfo = getLastNotFullColumnInfo(lastPage);}@@ -320,6 +331,7 @@ function _lineOperator(const {paragraphStyle = {},paragraphAffectSkeDrawings,+ paragraphInlineSkeDrawings,skeHeaders,skeFooters,drawingAnchor,@@ -390,13 +402,29 @@ function _lineOperator(const headersDrawings = skeHeaders?.get(headerId)?.get(pageWidth)?.skeDrawings;const footersDrawings = skeFooters?.get(footerId)?.get(pageWidth)?.skeDrawings;- __updateDrawingPosition(- lineTop,- lineHeight,- column,- drawingAnchor?.get(paragraphIndex)?.top,- paragraphAffectSkeDrawings- ); // 初始化paragraphAffectSkeDrawings的位置,drawing的布局参照Paragraph开始位置,如果段落中有换页的情况,换页之后的drawing参照位置是0, 0+ // Handle float object relative to line.+ if (line) {+ const drawingsInLine = _getCustomBlockIdsInLine(line);+ if (drawingsInLine.length > 0) {+ const affectDrawings = ctx.paragraphConfigCache.get(line.paragraphIndex)?.paragraphAffectSkeDrawings;+ const relativeLineDrawings = ([...(affectDrawings?.values() ?? [])])+ .filter((drawing) => drawing.drawingOrigin.objectTransform.positionV.relativeFrom === ObjectRelativeFromV.LINE);++ __updateAndPositionDrawings(ctx, line.top, line.lineHeight, column, relativeLineDrawings, line.paragraphIndex);+ }++ const affectInlineDrawings = ctx.paragraphConfigCache.get(line.paragraphIndex)?.paragraphInlineSkeDrawings;+ // Update inline drawings after the line is layout.+ if (affectInlineDrawings && affectInlineDrawings.size > 0) {+ __updatePreLineDrawingPosition(line, affectInlineDrawings);+ }+ }++ if (paragraphAffectSkeDrawings != null && paragraphAffectSkeDrawings.size > 0) {+ const targetDrawings = [...paragraphAffectSkeDrawings.values()]+ .filter((drawing) => drawing.drawingOrigin.objectTransform.positionV.relativeFrom !== ObjectRelativeFromV.LINE);+ __updateAndPositionDrawings(ctx, lineTop, lineHeight, column, targetDrawings, paragraphConfig.paragraphIndex, drawingAnchor?.get(paragraphIndex)?.top);+ }const newLineTop = calculateLineTopByDrawings(lineHeight,@@ -410,7 +438,7 @@ function _lineOperator(// 行高超过Col高度,且列中已存在一行以上,且section大于一个;// console.log('_lineOperator', { glyphGroup, pages, lineHeight, newLineTop, sectionHeight: section.height, lastPage });setColumnFullState(column, true);- _columnOperator(glyphGroup, pages, sectionBreakConfig, paragraphConfig, paragraphStart, defaultSpanLineHeight);+ _columnOperator(ctx, glyphGroup, pages, sectionBreakConfig, paragraphConfig, paragraphStart, defaultSpanLineHeight);return;}@@ -452,10 +480,179 @@ function _lineOperator(column.lines.push(newLine);newLine.parent = column;createAndUpdateBlockAnchor(paragraphIndex, newLine, lineTop, drawingAnchor);- _divideOperator(glyphGroup, pages, sectionBreakConfig, paragraphConfig, paragraphStart, defaultSpanLineHeight);+ _divideOperator(ctx, glyphGroup, pages, sectionBreakConfig, paragraphConfig, paragraphStart, defaultSpanLineHeight);+}++function __updateAndPositionDrawings(+ ctx: ILayoutContext,+ lineTop: number,+ lineHeight: number,+ column: IDocumentSkeletonColumn,+ targetDrawings: IDocumentSkeletonDrawing[],+ paragraphIndex: number,+ drawingAnchorTop?: number+) {+ if (targetDrawings.length === 0) {+ return;+ }++ const drawings = __getDrawingPosition(+ lineTop,+ lineHeight,+ column,+ drawingAnchorTop,+ targetDrawings+ );++ if (drawings == null || drawings.size === 0) {+ return;+ }++ _reLayoutCheck(ctx, drawings, column, paragraphIndex);++ __updateDrawingPosition(+ column,+ drawings+ );+}++function _getCustomBlockIdsInLine(line: IDocumentSkeletonLine) {+ const customBlockIds: string[] = [];++ for (const divide of line.divides) {+ for (const glyph of divide.glyphGroup) {+ if (glyph.streamType === DataStreamTreeTokenType.CUSTOM_BLOCK) {+ customBlockIds.push(glyph.objectId!);+ }+ }+ }++ return customBlockIds;+}++function _reLayoutCheck(+ ctx: ILayoutContext,+ drawings: Map<string, IDocumentSkeletonDrawing>,+ column: IDocumentSkeletonColumn,+ paragraphIndex: number+) {+ const page = column.parent?.parent;+ const needUpdatedDrawings = new Map([...drawings]);++ if (drawings.size === 0 || page == null) {+ return drawings;+ }++ let needBreakLineIterator = false;++ // Handle situations where an image anchor paragraph is squeezed to the next page.+ for (const drawing of drawings.values()) {+ const drawingCache = ctx.drawingsCache.get(drawing.objectId);+ if (drawingCache == null) {+ continue;+ }+ // TODO: 如何判断 drawing 是否在同一页???+ const cachePageStartParagraphIndex = drawingCache.page.sections[0]?.columns[0]?.lines[0]?.paragraphIndex;+ const startIndex = page.sections[0]?.columns[0]?.lines[0]?.paragraphIndex;+ if (drawingCache.page && cachePageStartParagraphIndex && startIndex && cachePageStartParagraphIndex !== startIndex) {+ drawingCache.page.skeDrawings.delete(drawing.objectId);++ lineIterator([drawingCache.page], (line) => {+ const { lineHeight, top } = line;+ const width = line.parent?.width ?? 0;++ if (needBreakLineIterator) {+ return;+ }++ const collision = collisionDetection(drawingCache.drawing, lineHeight, top, width);+ if (collision) {+ // No need to loop next line.+ needBreakLineIterator = true;+ ctx.isDirty = true;+ ctx.layoutStartPointer.paragraphIndex = Math.min(line.paragraphIndex, ctx.layoutStartPointer.paragraphIndex ?? Number.POSITIVE_INFINITY);+ ctx.paragraphsOpenNewPage.add(paragraphIndex);+ }+ });+ }+ }++ needBreakLineIterator = false;++ lineIterator([page], (line) => {+ const { lineHeight, top } = line;+ const width = column.width;++ if (needBreakLineIterator) {+ return;+ }++ for (const drawing of drawings.values()) {+ let targetDrawing = drawing;++ if (ctx.drawingsCache.has(drawing.objectId)) {+ const needRePosition = checkRelativeDrawingNeedRePosition(ctx, drawing);++ if (needRePosition) {+ targetDrawing = ctx.drawingsCache.get(drawing.objectId)?.drawing ?? drawing;+ } else {+ continue;+ }+ }++ const collision = collisionDetection(targetDrawing, lineHeight, top, width);+ // console.log(line.top + line.lineHeight, line.divides[0].glyphGroup[0].content);+ if (collision) {+ // No need to loop next line.+ needBreakLineIterator = true;++ ctx.isDirty = true;+ ctx.layoutStartPointer.paragraphIndex = Math.min(line.paragraphIndex, ctx.layoutStartPointer.paragraphIndex ?? Number.POSITIVE_INFINITY);++ let drawingCache = ctx.drawingsCache.get(drawing.objectId);+ if (drawingCache == null) {+ drawingCache = {+ count: 0,+ drawing,+ page,+ };++ ctx.drawingsCache.set(drawing.objectId, drawingCache);+ }++ drawingCache.count++;+ drawingCache.drawing = drawing;+ drawingCache.page = page;+ }+ }+ });++ return needUpdatedDrawings;+}++// Detect the relative positioning of the image, whether the position needs to be repositioned.+function checkRelativeDrawingNeedRePosition(ctx: ILayoutContext, drawing: IDocumentSkeletonDrawing) {+ const { relativeFrom } = drawing.drawingOrigin.objectTransform.positionV;+ const drawingCache = ctx.drawingsCache.get(drawing.objectId);++ if (drawingCache == null) {+ return false;+ }++ if (relativeFrom === ObjectRelativeFromV.PARAGRAPH || relativeFrom === ObjectRelativeFromV.LINE) {+ const { count, drawing: prevDrawing } = drawingCache;+ // Floating elements can be positioned no more than 5 times,+ // and when the error is within 5 pixels, there is no need to re-layout+ if (count < 5 && Math.abs(drawing.aTop - prevDrawing.aTop) > 5) {+ return true;+ }+ }++ return false;}function _columnOperator(+ ctx: ILayoutContext,glyphGroup: IDocumentSkeletonGlyph[],pages: IDocumentSkeletonPage[],sectionBreakConfig: ISectionBreakConfig,@@ -467,13 +664,14 @@ function _columnOperator(const columnIsFull = isColumnFull(lastPage);if (columnIsFull === true) {- _pageOperator(glyphGroup, pages, sectionBreakConfig, paragraphConfig, paragraphStart, defaultSpanLineHeight);+ _pageOperator(ctx, glyphGroup, pages, sectionBreakConfig, paragraphConfig, paragraphStart, defaultSpanLineHeight);} else {- _lineOperator(glyphGroup, pages, sectionBreakConfig, paragraphConfig, paragraphStart, defaultSpanLineHeight);+ _lineOperator(ctx, glyphGroup, pages, sectionBreakConfig, paragraphConfig, paragraphStart, defaultSpanLineHeight);}}function _pageOperator(+ ctx: ILayoutContext,glyphGroup: IDocumentSkeletonGlyph[],pages: IDocumentSkeletonPage[],sectionBreakConfig: ISectionBreakConfig,@@ -484,8 +682,8 @@ function _pageOperator(const curSkeletonPage: IDocumentSkeletonPage = getLastPage(pages);const { skeHeaders, skeFooters } = paragraphConfig;- pages.push(createSkeletonPage(sectionBreakConfig, { skeHeaders, skeFooters }, curSkeletonPage?.pageNumber));- _columnOperator(glyphGroup, pages, sectionBreakConfig, paragraphConfig, paragraphStart, defaultSpanLineHeight);+ pages.push(createSkeletonPage(ctx, sectionBreakConfig, { skeHeaders, skeFooters }, curSkeletonPage?.pageNumber));+ _columnOperator(ctx, glyphGroup, pages, sectionBreakConfig, paragraphConfig, paragraphStart, defaultSpanLineHeight);}/**@@ -621,57 +819,128 @@ function __getLineHeight(};}-// 更新paragraphAffectSkeDrawings的绝对位置,相对于段落的第一行布局-function __updateDrawingPosition(+function __updatePreLineDrawingPosition(+ line: IDocumentSkeletonLine,+ paragraphInlineSkeDrawings?: Map<string, IDocumentSkeletonDrawing>+) {+ const page = line?.parent?.parent?.parent;++ if (page == null) {+ return;+ }++ const drawings: Map<string, IDocumentSkeletonDrawing> = new Map();+ const { top } = line;++ for (const divide of line.divides) {+ for (const glyph of divide.glyphGroup) {+ if (glyph.streamType === DataStreamTreeTokenType.CUSTOM_BLOCK && glyph.width !== 0) {+ const { objectId } = glyph;++ if (objectId == null) {+ continue;+ }++ const drawing = paragraphInlineSkeDrawings?.get(objectId);++ const drawingOrigin = drawing?.drawingOrigin;++ if (drawingOrigin == null || drawing == null) {+ continue;+ }++ const { objectTransform } = drawingOrigin;++ const { size, angle } = objectTransform;+ const { width = 0, height = 0 } = size;++ drawing.aLeft = glyph.left || 0;+ drawing.aTop = top || 0;+ drawing.width = width;+ drawing.height = height;+ drawing.angle = angle;++ drawings.set(drawing.objectId, drawing);+ }+ }+ }++ page.skeDrawings = new Map([...page.skeDrawings, ...drawings]);+}++function __getDrawingPosition(lineTop: number,lineHeight: number,column: IDocumentSkeletonColumn,blockAnchorTop?: number,- paragraphAffectSkeDrawings?: Map<string, IDocumentSkeletonDrawing>+ needPositionDrawings: IDocumentSkeletonDrawing[] = []) {- if (!paragraphAffectSkeDrawings) {- return;- }-const page = column.parent?.parent;-- if (!page) {+ if (+ page == null ||+ needPositionDrawings.length === 0+ ) {return;}const drawings: Map<string, IDocumentSkeletonDrawing> = new Map();const isPageBreak = __checkPageBreak(column);- // console.log('__updateDrawingPosition', lineTop, lineHeight, column, blockAnchorTop, paragraphAffectSkeDrawings);-- paragraphAffectSkeDrawings.forEach((drawing) => {- if (!drawing) {- return;- }-+ for (const drawing of needPositionDrawings) {const { initialState, drawingOrigin } = drawing;- if (initialState || !drawingOrigin) {- return;+ if (!drawingOrigin) {+ continue;}const { objectTransform } = drawingOrigin;-const { positionH, positionV, size, angle } = objectTransform;const { width = 0, height = 0 } = size;- drawing.aLeft = getPositionHorizon(positionH, column, page, width, isPageBreak) || 0;- drawing.aTop =- getPositionVertical(positionV, page, lineTop, lineHeight, height, blockAnchorTop, isPageBreak) || 0;+ drawing.aLeft = getPositionHorizon(positionH, column, page, width, isPageBreak) ?? 0;+ drawing.aTop = getPositionVertical(+ positionV, page, lineTop, lineHeight, height, blockAnchorTop, isPageBreak+ ) ?? 0;drawing.width = width;drawing.height = height;drawing.angle = angle;drawing.initialState = true;drawings.set(drawing.objectId, drawing);- });+ }- page.skeDrawings = new Map([...page.skeDrawings, ...drawings]);+ // if (drawings.size) {+ // console.log(`lineTop: ${lineTop}, blockAnchorTop: ${blockAnchorTop}`, drawings);+ // }++ return drawings;+}+++// 更新 paragraphAffectSkeDrawings 的绝对位置,相对于段落的第一行布局+function __updateDrawingPosition(+ column: IDocumentSkeletonColumn,+ drawings?: Map<string, IDocumentSkeletonDrawing>+) {+ const page = column.parent?.parent;+ if (drawings != null && drawings.size !== 0 && page != null) {+ for (const drawing of drawings.values()) {+ const originDrawing = page.skeDrawings.get(drawing.objectId);++ if (originDrawing) {+ // If it's a layout that splits the text up and down,+ // choose an image that is closer to the bottom for the layout+ if (originDrawing.drawingOrigin.layoutType === PositionedObjectLayoutType.WRAP_TOP_AND_BOTTOM) {+ const lowerDrawing = originDrawing.aTop > drawing.aTop ? originDrawing : drawing;+ page.skeDrawings.set(drawing.objectId, lowerDrawing);+ } else {+ page.skeDrawings.set(drawing.objectId, drawing);+ }+ } else {+ page.skeDrawings.set(drawing.objectId, drawing);+ }+ }+ }}// 检查是否跨页的场景,如果向上搜索不到paragraphStart === true 的行,则代表一个段落跨页了diff --git a/packages/engine-render/src/components/docs/layout/block/paragraph/layout.ts b/packages/engine-render/src/components/docs/layout/block/paragraph/layout.tsindex 6bc313a57c..f77085cca2 100644--- a/packages/engine-render/src/components/docs/layout/block/paragraph/layout.ts+++ b/packages/engine-render/src/components/docs/layout/block/paragraph/layout.ts@@ -14,8 +14,9 @@* limitations under the License.*/-import type { IDocumentSkeletonPage, ISkeletonResourceReference } from '../../../../../basics/i-document-skeleton-cached';+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';@@ -24,24 +25,24 @@ import { lineBreaking } from './linebreaking';import { lineAdjustment } from './line-adjustment';export function dealWidthParagraph(- bodyModel: DocumentViewModel,+ ctx: ILayoutContext,+ viewModel: DocumentViewModel,paragraphNode: DataStreamTreeNode,curPage: IDocumentSkeletonPage,- sectionBreakConfig: ISectionBreakConfig,- skeletonResourceReference: ISkeletonResourceReference+ sectionBreakConfig: ISectionBreakConfig): IDocumentSkeletonPage[] {clearFontCreateConfigCache();// Step 1: Text Shaping.const { endIndex, content = '' } = paragraphNode;- const paragraph = bodyModel.getParagraph(endIndex) || { startIndex: 0 };+ const paragraph = viewModel.getParagraph(endIndex) || { startIndex: 0 };const { paragraphStyle = {} } = paragraph;const shapedTextList = shaping(content,- bodyModel,+ viewModel,paragraphNode,sectionBreakConfig,paragraphStyle@@ -49,12 +50,11 @@ export function dealWidthParagraph(// Step 2: Line Breaking.const allPages = lineBreaking(+ ctx,shapedTextList,curPage,- bodyModel,paragraphNode,- sectionBreakConfig,- skeletonResourceReference+ sectionBreakConfig);// Step 3: Line Adjustment.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 8cfb41f8d4..cb6970760a 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@@ -14,19 +14,18 @@* limitations under the License.*/-import type { IBullet, ICustomBlock, IDrawing, IDrawings, Nullable } from '@univerjs/core';+import type { IBullet, IDrawing, IDrawings, Nullable } from '@univerjs/core';import { DataStreamTreeTokenType, PositionedObjectLayoutType } from '@univerjs/core';import { BreakType } from '../../../../../basics/i-document-skeleton-cached';-import type { IDocumentSkeletonBullet, IDocumentSkeletonDrawing, IDocumentSkeletonPage, ISkeletonResourceReference } from '../../../../../basics/i-document-skeleton-cached';+import type { IDocumentSkeletonBullet, IDocumentSkeletonDrawing, IDocumentSkeletonPage } from '../../../../../basics/i-document-skeleton-cached';import { createSkeletonPage } from '../../model/page';import { setColumnFullState } from '../../model/section';+import type { ILayoutContext } from '../../tools';import { getLastNotFullColumnInfo } from '../../tools';import type { DataStreamTreeNode } from '../../../view-model/data-stream-tree-node';-import type { DocumentViewModel } from '../../../view-model/document-view-model';import type { IParagraphConfig, ISectionBreakConfig } from '../../../../../basics/interfaces';import type { IShapedText } from './shaping';import { layoutParagraph } from './layout-ruler';-import { dealWidthInlineDrawing } from './inline-drawing';import { dealWithBullet } from './bullet';function _getListLevelAncestors(@@ -93,6 +92,7 @@ function _changeDrawingToSkeletonFormat(function _getDrawingSkeletonFormat(drawingOrigin: IDrawing) {const objectId = drawingOrigin.objectId;+return {objectId,aLeft: 0,@@ -110,38 +110,42 @@ function _getNextPageNumber(lastPage: IDocumentSkeletonPage) {}export function lineBreaking(+ ctx: ILayoutContext,shapedTextList: IShapedText[],curPage: IDocumentSkeletonPage,- bodyModel: DocumentViewModel,paragraphNode: DataStreamTreeNode,- sectionBreakConfig: ISectionBreakConfig,- skeletonResourceReference: ISkeletonResourceReference+ sectionBreakConfig: ISectionBreakConfig): IDocumentSkeletonPage[] {+ const { viewModel, skeletonResourceReference } = ctx;const {lists,drawings = {},localeService,} = sectionBreakConfig;- const { endIndex, startIndex, blocks = [] } = paragraphNode;+ const { endIndex, blocks = [] } = paragraphNode;- const paragraph = bodyModel.getParagraph(endIndex) || { startIndex: 0 };+ const paragraph = viewModel.getParagraph(endIndex) || { startIndex: 0 };const { paragraphStyle = {}, bullet } = paragraph;const { skeHeaders, skeFooters, skeListLevel, drawingAnchor } = skeletonResourceReference;const paragraphAffectSkeDrawings: Map<string, IDocumentSkeletonDrawing> = new Map();+ const paragraphInlineSkeDrawings: Map<string, IDocumentSkeletonDrawing> = new Map();const paragraphConfig: IParagraphConfig = {paragraphIndex: endIndex,paragraphStyle,paragraphAffectSkeDrawings,+ paragraphInlineSkeDrawings,skeHeaders,skeFooters,drawingAnchor,};+ ctx.paragraphConfigCache.set(endIndex, paragraphConfig);+const listLevelAncestors = _getListLevelAncestors(bullet, skeListLevel); // 取得列表所有 level 的缓存const bulletSkeleton = dealWithBullet(bullet, lists, listLevelAncestors, localeService); // 生成 bullet@@ -149,35 +153,34 @@ export function lineBreaking(paragraphConfig.bulletSkeleton = bulletSkeleton;- const customBlockCache = new Map<number, Nullable<ICustomBlock>>();-for (let i = 0, len = blocks.length; i < len; i++) {const charIndex = blocks[i];- const customBlock = bodyModel.getCustomBlock(charIndex);+ const customBlock = viewModel.getCustomBlock(charIndex);+if (customBlock == null) {continue;}- customBlockCache.set(charIndex, customBlock);- const blockId = customBlock.blockId;+ const { blockId } = customBlock;const drawingOrigin = drawings[blockId];if (drawingOrigin.layoutType !== PositionedObjectLayoutType.INLINE) {paragraphAffectSkeDrawings.set(blockId, _getDrawingSkeletonFormat(drawingOrigin));+ } else {+ paragraphInlineSkeDrawings.set(blockId, _getDrawingSkeletonFormat(drawingOrigin));}}let allPages = [curPage];let paragraphStart = true;- let charIndex = startIndex;for (const { text, glyphs } of shapedTextList) {- charIndex += text.length;const pushPending = () => {if (glyphs.length === 0) {return;}allPages = layoutParagraph(+ ctx,glyphs,allPages,sectionBreakConfig,@@ -188,30 +191,11 @@ export function lineBreaking(paragraphStart = false;};- if (text.endsWith(DataStreamTreeTokenType.CUSTOM_BLOCK)) {- let customBlock = customBlockCache.get(charIndex);- if (customBlock == null) {- customBlock = bodyModel.getCustomBlock(charIndex);- }- if (customBlock != null) {- const blockId = customBlock.blockId;- const drawingOrigin = drawings[blockId];- if (drawingOrigin.layoutType === PositionedObjectLayoutType.INLINE) {- allPages = dealWidthInlineDrawing(- drawingOrigin,- sectionBreakConfig,- allPages,- paragraphConfig,- localeService- );- }- }- pushPending();- continue;- } else if (text.endsWith(DataStreamTreeTokenType.PAGE_BREAK)) {+ if (text.endsWith(DataStreamTreeTokenType.PAGE_BREAK)) {pushPending();allPages.push(createSkeletonPage(+ ctx,sectionBreakConfig,skeletonResourceReference,_getNextPageNumber(allPages[allPages.length - 1]),@@ -219,6 +203,7 @@ export function lineBreaking());paragraphAffectSkeDrawings.clear();+ paragraphInlineSkeDrawings.clear();continue;} else if (text.endsWith(DataStreamTreeTokenType.COLUMN_BREAK)) {pushPending();@@ -231,6 +216,7 @@ export function lineBreaking(} else {allPages.push(createSkeletonPage(+ ctx,sectionBreakConfig,skeletonResourceReference,_getNextPageNumber(lastPage),diff --git a/packages/engine-render/src/components/docs/layout/block/paragraph/shaping.ts b/packages/engine-render/src/components/docs/layout/block/paragraph/shaping.tsindex dd0f955f8b..e9e6b4d5cc 100644--- a/packages/engine-render/src/components/docs/layout/block/paragraph/shaping.ts+++ b/packages/engine-render/src/components/docs/layout/block/paragraph/shaping.ts@@ -14,12 +14,12 @@* limitations under the License.*/-import type { IParagraphStyle } from '@univerjs/core';-import { BooleanNumber, DataStreamTreeTokenType, GridType } from '@univerjs/core';+import type { IParagraphStyle, Nullable } from '@univerjs/core';+import { BooleanNumber, DataStreamTreeTokenType, GridType, PositionedObjectLayoutType } from '@univerjs/core';import type { IDocumentSkeletonGlyph } from '../../../../../basics/i-document-skeleton-cached';import { LineBreaker } from '../../linebreak';import { tabLineBreakExtension } from '../../linebreak/extensions/tab-linebreak-extension';-import { createSkeletonLetterGlyph, createSkeletonTabGlyph, glyphShrinkLeft, glyphShrinkRight } from '../../model/glyph';+import { createSkeletonCustomBlockGlyph, createSkeletonLetterGlyph, createSkeletonTabGlyph, glyphShrinkLeft, glyphShrinkRight } from '../../model/glyph';import { getCharSpaceApply, getFontCreateConfig } from '../../tools';import type { DataStreamTreeNode } from '../../../view-model/data-stream-tree-node';import type { DocumentViewModel } from '../../../view-model/document-view-model';@@ -91,7 +91,7 @@ export interface IShapedText {glyphs: IDocumentSkeletonGlyph[];}-// eslint-disable-next-line max-lines-per-function+export function shaping(content: string,bodyModel: DocumentViewModel,@@ -104,6 +104,7 @@ export function shaping(gridType = GridType.LINES,charSpace = 0,defaultTabStop = 10.5,+ drawings = {},} = sectionBreakConfig;const { snapToGrid = BooleanNumber.TRUE } = paragraphStyle;const shapedTextList: IShapedText[] = [];@@ -174,9 +175,33 @@ export function shaping(break;}- if (/\s/.test(char) || hasCJK(char)) {+ if (char === DataStreamTreeTokenType.CUSTOM_BLOCK) {+ const config = getFontCreateConfig(i, bodyModel, paragraphNode, sectionBreakConfig, paragraphStyle);+ let newSpan: Nullable<IDocumentSkeletonGlyph> = null;+ const customBlock = bodyModel.getCustomBlock(paragraphNode.startIndex + i);++ if (customBlock != null) {+ const { blockId } = customBlock;+ const drawingOrigin = drawings[blockId];+ if (drawingOrigin.layoutType === PositionedObjectLayoutType.INLINE) {+ const { width, height } = drawingOrigin.objectTransform.size;+ const { objectId } = drawingOrigin;+ newSpan = createSkeletonCustomBlockGlyph(config, width, height, objectId);+ } else {+ newSpan = createSkeletonCustomBlockGlyph(config, 0, 0, drawingOrigin.objectId);+ }+ }++ if (newSpan == null) {+ newSpan = createSkeletonLetterGlyph(char, config);+ }++ shapedGlyphs.push(newSpan);+ i += char.length;+ src = src.substring(char.length);+ } else if (/\s/.test(char) || hasCJK(char)) {const config = getFontCreateConfig(i, bodyModel, paragraphNode, sectionBreakConfig, paragraphStyle);- let newSpan: IDocumentSkeletonGlyph;+ let newSpan: Nullable<IDocumentSkeletonGlyph> = null;if (char === DataStreamTreeTokenType.TAB) {const charSpaceApply = getCharSpaceApply(charSpace, defaultTabStop, gridType, snapToGrid);@@ -248,16 +273,34 @@ export function shaping(// Continuous punctuation space adjustment.punctuationSpaceAdjustment(shapedGlyphs);- shapedTextList.push({- text: word,- glyphs: shapedGlyphs,- });+ const shapedGlyphsList: IDocumentSkeletonGlyph[][] = [[]];++ for (let i = 0; i < shapedGlyphs.length; i++) {+ const lastList = shapedGlyphsList[shapedGlyphsList.length - 1];+ const glyph = shapedGlyphs[i];++ // Inline Custom Block can open a new line.+ if (glyph.streamType === DataStreamTreeTokenType.CUSTOM_BLOCK && glyph.width !== 0) {+ shapedGlyphsList.push([glyph]);+ } else {+ lastList.push(glyph);+ }+ }++ for (const shapedGlyphs of shapedGlyphsList) {+ const word = shapedGlyphs.map((g) => g.content).join();++ shapedTextList.push({+ text: word,+ glyphs: shapedGlyphs,+ });+ }+last = bk.position;}// Add some spacing between Han characters and western characters.addCJKLatinSpacing(shapedTextList);- // console.log(shapedTextList);return shapedTextList;}diff --git a/packages/engine-render/src/components/docs/layout/block/section.ts b/packages/engine-render/src/components/docs/layout/block/section.tsindex e29d484494..5c7cc58cb5 100644--- a/packages/engine-render/src/components/docs/layout/block/section.ts+++ b/packages/engine-render/src/components/docs/layout/block/section.ts@@ -14,27 +14,45 @@* limitations under the License.*/+import type { Nullable } from '@univerjs/core';import { DataStreamTreeNodeType } from '@univerjs/core';--import type { IDocumentSkeletonPage, ISkeletonResourceReference } from '../../../../basics/i-document-skeleton-cached';+import type { IDocumentSkeletonPage } from '../../../../basics/i-document-skeleton-cached';import type { ISectionBreakConfig } from '../../../../basics/interfaces';import type { DataStreamTreeNode } from '../../view-model/data-stream-tree-node';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';-export function dealWithSections(- bodyModel: DocumentViewModel,+export function dealWithSection(+ ctx: ILayoutContext,+ viewModel: DocumentViewModel,sectionNode: DataStreamTreeNode,curPage: IDocumentSkeletonPage,sectionBreakConfig: ISectionBreakConfig,- skeletonResourceReference: ISkeletonResourceReference,- _preRenderedBlockIdMap?: Map<string, boolean>+ layoutAnchor: Nullable<number>) {const allCurrentSkeletonPages: IDocumentSkeletonPage[] = [];const renderedBlockIdMap = new Map<string, boolean>();- for (const node of sectionNode.children) {+ let paragraphStartIndex = 0;++ if (layoutAnchor != null) {+ const { startIndex, endIndex } = sectionNode;+ if (layoutAnchor >= startIndex && layoutAnchor <= endIndex) {+ for (let pi = 0; pi < sectionNode.children.length; pi++) {+ const paragraph = sectionNode.children[pi];+ if (paragraph.endIndex === layoutAnchor) {+ paragraphStartIndex = pi;+ break;+ }+ }+ }+ }++ for (let i = paragraphStartIndex; i < sectionNode.children.length; i++) {+ const paragraphNode = sectionNode.children[i];// const { paragraph, table, tableOfContents, blockType, customBlock, blockId } = block;// if (preRenderedBlockIdMap?.get(blockId)) {// continue;@@ -44,16 +62,25 @@ export function dealWithSections(if (allCurrentSkeletonPages.length > 0) {currentPageCache = allCurrentSkeletonPages[allCurrentSkeletonPages.length - 1];}- if (node.nodeType === DataStreamTreeNodeType.PARAGRAPH) {++ if (paragraphNode.nodeType === DataStreamTreeNodeType.PARAGRAPH) {// Paragraph 段落+ if (ctx.paragraphsOpenNewPage.has(paragraphNode.endIndex)) {+ currentPageCache = createSkeletonPage(+ ctx,+ sectionBreakConfig,+ ctx.skeletonResourceReference,+ currentPageCache.pageNumber + 1+ );+ }skeletonPages = dealWidthParagraph(- bodyModel,- node,+ ctx,+ viewModel,+ paragraphNode,currentPageCache,- sectionBreakConfig,- skeletonResourceReference+ sectionBreakConfig);- } else if (node.nodeType === DataStreamTreeNodeType.TABLE) {+ } else if (paragraphNode.nodeType === DataStreamTreeNodeType.TABLE) {// Table 表格}@@ -64,6 +91,14 @@ export function dealWithSections(_pushPage(allCurrentSkeletonPages, skeletonPages);// renderedBlockIdMap.set(blockId, true);+ if (ctx.isDirty) {+ break;+ }+ }++ if (ctx.isDirty && ctx.layoutStartPointer.paragraphIndex != null) {+ // Rollback the skeleton to the layout start point.+ _rollbackPages(ctx.layoutStartPointer.paragraphIndex, allCurrentSkeletonPages);}return {@@ -72,6 +107,54 @@ export function dealWithSections(};}+// Roll back pages to the state it was in before the dirty paragraph.+function _rollbackPages(paragraphIndex: number, allCurrentSkeletonPages: IDocumentSkeletonPage[]) {+ let findFirstDirtyLine = false;+ for (let pageIndex = 0; pageIndex < allCurrentSkeletonPages.length; pageIndex++) {+ const page = allCurrentSkeletonPages[pageIndex];++ for (let sectionIndex = 0; sectionIndex < page.sections.length; sectionIndex++) {+ const section = page.sections[sectionIndex];++ for (let columnIndex = 0; columnIndex < section.columns.length; columnIndex++) {+ const column = section.columns[columnIndex];++ for (let lineIndex = 0; lineIndex < column.lines.length; lineIndex++) {+ const line = column.lines[lineIndex];++ if (line.paragraphIndex === paragraphIndex) {+ findFirstDirtyLine = true;+ column.lines.splice(lineIndex);+ break;+ }+ }++ if (findFirstDirtyLine) {+ const columnSplitIndex = column.lines.length ? columnIndex + 1 : columnIndex;+ const preColumnIndex = columnSplitIndex - 1;+ if (preColumnIndex >= 0) {+ section.columns[preColumnIndex].isFull = false;+ }+ section.columns.splice(columnSplitIndex);+ break;+ }+ }++ if (findFirstDirtyLine) {+ const sectionSplitIndex = section.columns.length ? sectionIndex + 1 : sectionIndex;+ page.sections.splice(sectionSplitIndex);+ break;+ }+ }++ if (findFirstDirtyLine) {+ const pageSplitIndex = page.sections.length ? pageIndex + 1 : pageIndex;+ allCurrentSkeletonPages.splice(pageSplitIndex);+ break;+ }+ }+}+function _pushPage(allCurrentSkeletonPages: IDocumentSkeletonPage[], blockSkeletonPages: IDocumentSkeletonPage[]) {const lastIndex = allCurrentSkeletonPages.length - 1;const lastOldPage = allCurrentSkeletonPages[lastIndex];diff --git a/packages/engine-render/src/components/docs/layout/doc-skeleton.ts b/packages/engine-render/src/components/docs/layout/doc-skeleton.tsindex 0a4619fe42..c31ec6957e 100644--- a/packages/engine-render/src/components/docs/layout/doc-skeleton.ts+++ b/packages/engine-render/src/components/docs/layout/doc-skeleton.ts@@ -14,18 +14,8 @@* limitations under the License.*/-import type { ISectionBreak, ISectionColumnProperties, LocaleService, Nullable } from '@univerjs/core';-import {- ColumnSeparatorType,- GridType,- HorizontalAlign,- PageOrientType,- PRESET_LIST_TYPE,- SectionType,- VerticalAlign,- WrapStrategy,-} from '@univerjs/core';-+import type { ColumnSeparatorType, ISectionColumnProperties, LocaleService, Nullable } from '@univerjs/core';+import { GridType, PRESET_LIST_TYPE, SectionType } from '@univerjs/core';import type {IDocumentSkeletonCached,IDocumentSkeletonGlyph,@@ -33,23 +23,17 @@ import type {ISkeletonResourceReference,} from '../../../basics/i-document-skeleton-cached';import { GlyphType, LineType, PageLayoutType } from '../../../basics/i-document-skeleton-cached';-import type { IDocsConfig, INodeInfo, INodePosition, INodeSearch, ISectionBreakConfig } from '../../../basics/interfaces';+import type { IDocsConfig, INodeInfo, INodePosition, INodeSearch } from '../../../basics/interfaces';import type { IViewportBound, Vector2 } from '../../../basics/vector2';import { Skeleton } from '../../skeleton';import { Liquid } from '../liquid';import type { DocumentViewModel } from '../view-model/document-view-model';-import { getLastPage, updateBlockIndex } from './tools';+import type { ILayoutContext } from './tools';+import { getLastPage, getNullSkeleton, prepareSectionBreakConfig, setPageParent, updateBlockIndex } from './tools';import { createSkeletonSection } from './model/section';-import { dealWithSections } from './block/section';+import { dealWithSection } from './block/section';import { createSkeletonPage } from './model/page';-const DEFAULT_SECTION_BREAK: ISectionBreak = {- columnProperties: [],- columnSeparatorType: ColumnSeparatorType.NONE,- sectionType: SectionType.SECTION_TYPE_UNSPECIFIED,- startIndex: 0,-};-export enum DocumentSkeletonState {PENDING = 'pending',CALCULATING = 'calculating',@@ -57,13 +41,29 @@ export enum DocumentSkeletonState {INVALID = 'invalid',}+function resetContext(ctx: ILayoutContext) {+ ctx.isDirty = false;+ ctx.skeleton.drawingAnchor?.clear();+}++function removeDupPages(ctx: ILayoutContext) {+ const hash = new Set();++ ctx.skeleton.pages = ctx.skeleton.pages.filter((page) => {+ const hasPage = hash.has(page);+ hash.add(page);++ return !hasPage;+ });+}+export class DocumentSkeleton extends Skeleton {private _skeletonData: Nullable<IDocumentSkeletonCached>;- private _renderedBlockIdMap = new Map<string, boolean>();-private _findLiquid: Liquid = new Liquid();+ private _iteratorCount = 0;+constructor(private _docViewModel: DocumentViewModel,localeService: LocaleService@@ -78,7 +78,6 @@ export class DocumentSkeleton extends Skeleton {override dispose(): void {super.dispose();this._skeletonData = null;- this._renderedBlockIdMap.clear();this._findLiquid = null as unknown as Liquid;this._docViewModel.dispose();}@@ -93,9 +92,12 @@ export class DocumentSkeleton extends Skeleton {return;}+ const ctx = this._prepareLayoutContext();+// const start = +new Date();- this._skeletonData = this._createSkeleton(bounds);+ this._skeletonData = this._createSkeleton(ctx, bounds);// console.log('skeleton calculate cost', +new Date() - start);+ // console.log(this._skeletonData);}getSkeletonData() {@@ -454,77 +456,22 @@ export class DocumentSkeleton extends Skeleton {this._findLiquid.translatePage(page, pageLayoutType, pageMarginLeft, pageMarginTop);}- /**- * \v COLUMN_BREAK- * \f PAGE_BREAK- * \0 DOCS_END- * \t TAB- *- * Needs to be changed:- * \r PARAGRAPH- * \n SECTION_BREAK- *- * \b customBlock: Scenarios where customBlock, images, mentions, etc. do not participate in the document flow.- *- * Table- * \x1A table start- * \x1B table row start- * \x1C table cell start- * \x1D table cell end- * \x1E table row end- * \x1F table end- *- * Special ranges within the document flow::hyperlinks,field,structured document tags, bookmark,comment- * \x1F customRange start- * \x1E customRange end- *- * Split the document according to SectionBreak and perform layout calculations.- * @returns view model: skeleton- */-- private _createSkeleton(_bounds?: IViewportBound) {- // 每一个布局- const DEFAULT_PAGE_SIZE = { width: Number.POSITIVE_INFINITY, height: Number.POSITIVE_INFINITY };+ private _prepareLayoutContext(): ILayoutContext {const viewModel = this.getViewModel();+ const dataModel = viewModel.getDataModel();const { headerTreeMap, footerTreeMap } = viewModel;- const { documentStyle, drawings, lists: customLists = {} } = viewModel.getDataModel();+ const { documentStyle, drawings, lists: customLists = {} } = dataModel;const lists = {...PRESET_LIST_TYPE,...customLists,};const {- pageNumberStart: global_pageNumberStart = 1, // pageNumberStart- pageSize: global_pageSize = DEFAULT_PAGE_SIZE,- pageOrient: global_pageOrient = PageOrientType.PORTRAIT,- defaultHeaderId: global_defaultHeaderId,- defaultFooterId: global_defaultFooterId,- evenPageHeaderId: global_evenPageHeaderId,- evenPageFooterId: global_evenPageFooterId,- firstPageHeaderId: global_firstPageHeaderId,- firstPageFooterId: global_firstPageFooterId,- useFirstPageHeaderFooter: global_useFirstPageHeaderFooter,- useEvenPageHeaderFooter: global_useEvenPageHeaderFooter,-- marginTop: global_marginTop = 0,- marginBottom: global_marginBottom = 0,- marginRight: global_marginRight = 0,- marginLeft: global_marginLeft = 0,- marginHeader: global_marginHeader = 0,- marginFooter: global_marginFooter = 0,-charSpace = 0, // charSpacelinePitch = 15.6, // linePitch ptgridType = GridType.LINES, // gridTypeparagraphLineGapDefault = 0,defaultTabStop = 10.5,textStyle = {},- renderConfig: global_renderConfig = {- horizontalAlign: HorizontalAlign.LEFT,- verticalAlign: VerticalAlign.TOP,- centerAngle: 0,- vertexAngle: 0,- wrapStrategy: WrapStrategy.UNSPECIFIED,- },} = documentStyle;const docsConfig: IDocsConfig = {@@ -542,7 +489,7 @@ export class DocumentSkeleton extends Skeleton {documentTextStyle: textStyle,};- const skeleton = this._getNullSke();+ const skeleton = getNullSkeleton();const { skeHeaders, skeFooters, skeListLevel, drawingAnchor } = skeleton;@@ -553,96 +500,95 @@ export class DocumentSkeleton extends Skeleton {drawingAnchor,};- const allSkeletonPages: IDocumentSkeletonPage[] = [];-- skeleton.pages = allSkeletonPages;-- const bodyModel = this.getViewModel();-- bodyModel.resetCache();-- for (let i = 0, len = bodyModel.children.length; i < len; i++) {- const sectionNode = bodyModel.children[i];- const sectionBreak = bodyModel.getSectionBreak(sectionNode.endIndex) || DEFAULT_SECTION_BREAK;- const {- pageNumberStart = global_pageNumberStart,- pageSize = global_pageSize,- pageOrient = global_pageOrient,- marginTop = global_marginTop,- marginBottom = global_marginBottom,- marginRight = global_marginRight,- marginLeft = global_marginLeft,- marginHeader = global_marginHeader,- marginFooter = global_marginFooter,-- defaultHeaderId = global_defaultHeaderId,- defaultFooterId = global_defaultFooterId,- evenPageHeaderId = global_evenPageHeaderId,- evenPageFooterId = global_evenPageFooterId,- firstPageHeaderId = global_firstPageHeaderId,- firstPageFooterId = global_firstPageFooterId,- useFirstPageHeaderFooter = global_useFirstPageHeaderFooter,- useEvenPageHeaderFooter = global_useEvenPageHeaderFooter,-- columnProperties = [],- columnSeparatorType = ColumnSeparatorType.NONE,- contentDirection,- sectionType,- textDirection,- renderConfig = global_renderConfig,- } = sectionBreak;-- const sectionNodeNext = bodyModel.children[i + 1];- const sectionTypeNext = bodyModel.getSectionBreak(sectionNodeNext?.endIndex)?.sectionType;-- const headerIds = { defaultHeaderId, evenPageHeaderId, firstPageHeaderId };- const footerIds = { defaultFooterId, evenPageFooterId, firstPageFooterId };-- if (pageSize.width === null) {- pageSize.width = Number.POSITIVE_INFINITY;- }+ return {+ viewModel,+ dataModel,+ skeleton,+ skeletonResourceReference,+ docsConfig,+ layoutStartPointer: {+ paragraphIndex: null,+ },+ isDirty: false,+ drawingsCache: new Map(),+ paragraphConfigCache: new Map(),+ sectionBreakConfigCache: new Map(),+ paragraphsOpenNewPage: new Set(),+ };+ }- if (pageSize.height === null) {- pageSize.height = Number.POSITIVE_INFINITY;+ /**+ * \v COLUMN_BREAK+ * \f PAGE_BREAK+ * \0 DOCS_END+ * \t TAB+ *+ * Needs to be changed:+ * \r PARAGRAPH+ * \n SECTION_BREAK+ *+ * \b customBlock: Scenarios where customBlock, images, mentions, etc. do not participate in the document flow.+ *+ * Table+ * \x1A table start+ * \x1B table row start+ * \x1C table cell start+ * \x1D table cell end+ * \x1E table row end+ * \x1F table end+ *+ * Special ranges within the document flow::hyperlinks,field,structured document tags, bookmark,comment+ * \x1F customRange start+ * \x1E customRange end+ *+ * Split the document according to SectionBreak and perform layout calculations.+ * @returns view model: skeleton+ */++ private _createSkeleton(ctx: ILayoutContext, _bounds?: IViewportBound): IDocumentSkeletonCached {+ // console.log('createSkeleton: iterate ', this._iteratorCount, 'times');+ const { viewModel, skeleton, skeletonResourceReference } = ctx;++ const allSkeletonPages = skeleton.pages;++ viewModel.resetCache();++ let startSectionIndex = 0;++ const layoutAnchor = ctx.layoutStartPointer.paragraphIndex;++ // Reset layoutStartPointer.+ ctx.layoutStartPointer.paragraphIndex = null;++ if (layoutAnchor != null) {+ for (let sectionIndex = 0; sectionIndex < viewModel.children.length; sectionIndex++) {+ const sectionNode = viewModel.children[sectionIndex];+ const { endIndex, startIndex } = sectionNode;+ if (layoutAnchor >= startIndex && layoutAnchor <= endIndex) {+ startSectionIndex = sectionIndex;+ break;+ }}+ }- const sectionBreakConfig: ISectionBreakConfig = {- pageNumberStart,- pageSize,- pageOrient,- marginTop,- marginBottom,- marginRight,- marginLeft,- marginHeader,- marginFooter,-- headerIds,- footerIds,-- useFirstPageHeaderFooter,- useEvenPageHeaderFooter,-- columnProperties,- columnSeparatorType,- contentDirection,- sectionType,- sectionTypeNext,- textDirection,- renderConfig,-- ...docsConfig,- };-- let curSkeletonPage: IDocumentSkeletonPage = getLastPage(allSkeletonPages);+ // Loop the sections with the start section index.+ for (let i = startSectionIndex, len = viewModel.children.length; i < len; i++) {+ const sectionNode = viewModel.children[i];+ const sectionBreakConfig = prepareSectionBreakConfig(ctx, i);+ const { sectionType, columnProperties, columnSeparatorType, sectionTypeNext } = sectionBreakConfig;++ let curSkeletonPage = getLastPage(allSkeletonPages);let isContinuous = false;+ ctx.sectionBreakConfigCache.set(sectionNode.endIndex, sectionBreakConfig);+if (sectionType === SectionType.CONTINUOUS) {updateBlockIndex(allSkeletonPages);- this._addNewSectionByContinuous(curSkeletonPage, columnProperties, columnSeparatorType);+ this._addNewSectionByContinuous(curSkeletonPage, columnProperties!, columnSeparatorType!);isContinuous = true;- } else {+ } else if (layoutAnchor == null || curSkeletonPage == null) {curSkeletonPage = createSkeletonPage(+ ctx,sectionBreakConfig,skeletonResourceReference,curSkeletonPage?.pageNumber@@ -650,44 +596,47 @@ export class DocumentSkeleton extends Skeleton {}// 计算页内布局,block 结构- const blockInfo = dealWithSections(- bodyModel,+ const { pages } = dealWithSection(+ ctx,+ viewModel,sectionNode,curSkeletonPage,sectionBreakConfig,- skeletonResourceReference,- this._renderedBlockIdMap+ layoutAnchor);// todo: 当本节有多个列,且下一节为连续节类型的时候,需要按照列数分割,重新计算 lines- if (sectionTypeNext === SectionType.CONTINUOUS && columnProperties.length > 0) {+ if (sectionTypeNext === SectionType.CONTINUOUS && columnProperties!.length > 0) {// TODO}- const { pages } = blockInfo;-- // renderedBlockIdMap.forEach((value, blockId) => {- // this._renderedBlockIdMap.set(blockId, value);- // });-if (isContinuous) {pages.splice(0, 1);}allSkeletonPages.push(...pages);- }-- // 计算页和节的位置信息- updateBlockIndex(allSkeletonPages);- this._setPageParent(allSkeletonPages, skeleton);-- return skeleton;- }+ // The page needs to be reflowed due to floating objects.+ if (ctx.isDirty) {+ break;+ }+ }- private _setPageParent(pages: IDocumentSkeletonPage[], parent: IDocumentSkeletonCached) {- for (const page of pages) {- page.parent = parent;+ // TODO: 10 is too small?+ if (ctx.isDirty && this._iteratorCount < 10) {+ this._iteratorCount++;++ resetContext(ctx);+ return this._createSkeleton(ctx, _bounds);+ } else {+ // 计算页和节的位置信息+ this._iteratorCount = 0;+ removeDupPages(ctx);+ updateBlockIndex(skeleton.pages);++ setPageParent(skeleton.pages, skeleton);+ // console.log(skeleton);+ return skeleton;}}@@ -722,19 +671,6 @@ export class DocumentSkeleton extends Skeleton {sections.push(newSection);}- private _getNullSke(): IDocumentSkeletonCached {- return {- pages: [],- left: 0,- top: 0,- st: 0,- skeHeaders: new Map(),- skeFooters: new Map(),- skeListLevel: new Map(),- drawingAnchor: new Map(),- };- }-private _findNodeIterator(charIndex: number) {const skeletonData = this.getSkeletonData();diff --git a/packages/engine-render/src/components/docs/layout/model/glyph.ts b/packages/engine-render/src/components/docs/layout/model/glyph.tsindex ce6e719380..d06bf4ca41 100644--- a/packages/engine-render/src/components/docs/layout/model/glyph.ts+++ b/packages/engine-render/src/components/docs/layout/model/glyph.ts@@ -97,6 +97,39 @@ export function createSkeletonTabGlyph(config: IFontCreateConfig, glyphWidth?: nreturn _createSkeletonWordOrLetter(GlyphType.TAB, DT.TAB, config, glyphWidth);}+// It is used to create inline custom blocks, such as inline images, to occupy placeholders in the layout.+export function createSkeletonCustomBlockGlyph(config: IFontCreateConfig, glyphWidth = 0, glyphHeight = 0, objectId = ''): IDocumentSkeletonGlyph {+ const { fontStyle, textStyle } = config;+ const content = DT.CUSTOM_BLOCK;++ return {+ content: '',+ ts: textStyle,+ fontStyle,+ width: glyphWidth,+ bBox: {+ width: 0,+ ba: glyphHeight, // Or 1/2 glyphHeight each for ba and bd.+ bd: 0,+ aba: 0,+ abd: 0,+ sp: 0,+ sbr: 0,+ sbo: 0,+ spr: 0,+ spo: 0,+ },+ xOffset: 0,+ left: 0,+ isJustifiable: false,+ adjustability: baseAdjustability(content, 0),+ glyphType: GlyphType.PLACEHOLDER,+ streamType: content as DT,+ count: 1,+ objectId,+ };+}+export function _createSkeletonWordOrLetter(glyphType: GlyphType,content: string,diff --git a/packages/engine-render/src/components/docs/layout/model/line.ts b/packages/engine-render/src/components/docs/layout/model/line.tsindex 6904d0cc17..c21e28d027 100644--- a/packages/engine-render/src/components/docs/layout/model/line.ts+++ b/packages/engine-render/src/components/docs/layout/model/line.ts@@ -64,7 +64,7 @@ export function createSkeletonLine(columnWidth: number,lineIndex: number = 0,isParagraphStart: boolean = false,- affectSkeDrawings?: Map<string, IDocumentSkeletonDrawing>,+ pageSkeDrawings: Map<string, IDocumentSkeletonDrawing> = new Map(),headersDrawings?: Map<string, IDocumentSkeletonDrawing>,footersDrawings?: Map<string, IDocumentSkeletonDrawing>): IDocumentSkeletonLine {@@ -92,6 +92,8 @@ 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;+ const affectSkeDrawings = new Map(Array.from(pageSkeDrawings).filter(([_, drawing]) => drawing.drawingOrigin.layoutType !== PositionedObjectLayoutType.INLINE));+lineSke.divides = _calculateDividesByDrawings(lineHeight,lineTop,@@ -163,6 +165,7 @@ function _getLineTopWidthWrapTopBottom(drawing: IDocumentSkeletonDrawing, lineHeif (newAtop + newHeight < lineTop || newAtop > lineHeight + lineTop) {return;}+return newAtop + height;}// 旋转的情况,要考虑行首位与drawing旋转后得到的最大区域@@ -233,6 +236,17 @@ export function setLineMarginBottom(line: IDocumentSkeletonLine, marginBottom: n// 获得文字内容后的行信息计算export function updateDivideInLine(line: IDocumentSkeletonLine) {}+export function collisionDetection(+ drawing: IDocumentSkeletonDrawing,+ lineHeight: number,+ lineTop: number,+ columnWidth: number+) {+ const { aTop, height, aLeft, width, angle = 0, drawingOrigin } = drawing;+ // TODO: handle angle is not 0.+ return !!__getSplitWidthNoAngle(aTop, height, aLeft, width, lineTop, lineHeight, columnWidth, drawingOrigin);+}+function _calculateSplit(drawing: IDocumentSkeletonDrawing,lineHeight: number,@@ -309,6 +323,7 @@ function __getBoundingBox(angle: number, left: number, width: number, top: numbeconst rt = new Vector2(left + width, top);const rb = new Vector2(left + width, top + height);const boundingBox = transform.makeBoundingBoxFromPoints([lt, lb, rt, rb]); // 返回旋转后的点集合以及矩形选区+return boundingBox;}@@ -490,6 +505,7 @@ export function createAndUpdateBlockAnchor(if (!drawingAnchor) {return;}+if (drawingAnchor.has(paragraphIndex)) {const anchor = drawingAnchor.get(paragraphIndex);anchor?.elements.push(line);diff --git a/packages/engine-render/src/components/docs/layout/model/page.ts b/packages/engine-render/src/components/docs/layout/model/page.tsindex f8738538c8..16f627bf41 100644--- a/packages/engine-render/src/components/docs/layout/model/page.ts+++ b/packages/engine-render/src/components/docs/layout/model/page.ts@@ -16,7 +16,6 @@import type { Nullable } from '@univerjs/core';import { PageOrientType } from '@univerjs/core';-import type {IDocumentSkeletonFooter,IDocumentSkeletonHeader,@@ -25,9 +24,9 @@ import type {} from '../../../../basics/i-document-skeleton-cached';import { BreakType } from '../../../../basics/i-document-skeleton-cached';import type { ISectionBreakConfig } from '../../../../basics/interfaces';--import { dealWithSections } from '../block/section';+import { dealWithSection } from '../block/section';import type { DocumentViewModel } from '../../view-model/document-view-model';+import type { ILayoutContext } from '../tools';import { updateBlockIndex } from '../tools';import { createSkeletonSection } from './section';@@ -35,6 +34,7 @@ import { createSkeletonSection } from './section';// 判断奇数和偶数页码export function createSkeletonPage(+ ctx: ILayoutContext,sectionBreakConfig: ISectionBreakConfig,skeletonResourceReference: ISkeletonResourceReference,pageNumber = 1,@@ -100,6 +100,7 @@ export function createSkeletonPage(header = skeHeaders.get(headerId)?.get(pageWidth);} else if (headerTreeMap && headerTreeMap.has(headerId)) {header = _createSkeletonHeader(+ ctx,headerTreeMap.get(headerId)!,sectionBreakConfig,skeletonResourceReference@@ -114,6 +115,7 @@ export function createSkeletonPage(footer = skeFooters.get(footerId)?.get(pageWidth);} else if (footerTreeMap && footerTreeMap.has(footerId)) {footer = _createSkeletonHeader(+ ctx,footerTreeMap.get(footerId)!,sectionBreakConfig,skeletonResourceReference@@ -151,7 +153,7 @@ export function createSkeletonPage(}// 检测是否溢出了一页-function checkPageOverflow(page: IDocumentSkeletonPage) {}+function checkPageOverflow(page: IDocumentSkeletonPage) { }function _getNullPage() {return {@@ -180,6 +182,7 @@ function _getNullPage() {}function _createSkeletonHeader(+ ctx: ILayoutContext,headerOrFooter: DocumentViewModel,sectionBreakConfig: ISectionBreakConfig,skeletonResourceReference: ISkeletonResourceReference,@@ -212,13 +215,13 @@ function _createSkeletonHeader(drawings,};- const areaPage = createSkeletonPage(headerConfig, skeletonResourceReference);- const page = dealWithSections(+ const areaPage = createSkeletonPage(ctx, headerConfig, skeletonResourceReference);+ const page = dealWithSection(+ ctx,headerOrFooter,headerOrFooter.children[0],areaPage,- headerConfig,- skeletonResourceReference+ headerConfig).pages[0];updateBlockIndex([page]);diff --git a/packages/engine-render/src/components/docs/layout/tools.ts b/packages/engine-render/src/components/docs/layout/tools.tsindex 71b163aadb..7d9cbe7b75 100644--- a/packages/engine-render/src/components/docs/layout/tools.ts+++ b/packages/engine-render/src/components/docs/layout/tools.ts@@ -15,36 +15,47 @@*/import type {+ DocumentDataModel,INumberUnit,+ IObjectPositionH,+ IObjectPositionV,IParagraphStyle,+ ISectionBreak,ITextStyle,Nullable,- ObjectPositionH,- ObjectPositionV,} from '@univerjs/core';import {AlignTypeH,AlignTypeV,BooleanNumber,+ ColumnSeparatorType,GridType,+ HorizontalAlign,NumberUnitType,ObjectMatrix,ObjectRelativeFromH,ObjectRelativeFromV,+ PageOrientType,+ SectionType,SpacingRule,+ VerticalAlign,+ WrapStrategy,} from '@univerjs/core';import { DEFAULT_DOCUMENT_FONTSIZE } from '../../../basics/const';import type {+ IDocumentSkeletonCached,IDocumentSkeletonColumn,IDocumentSkeletonDivide,+ IDocumentSkeletonDrawing,IDocumentSkeletonFontStyle,IDocumentSkeletonGlyph,IDocumentSkeletonLine,IDocumentSkeletonPage,+ ISkeletonResourceReference,} from '../../../basics/i-document-skeleton-cached';import { GlyphType } from '../../../basics/i-document-skeleton-cached';-import type { IParagraphConfig, ISectionBreakConfig } from '../../../basics/interfaces';+import type { IDocsConfig, IParagraphConfig, ISectionBreakConfig } from '../../../basics/interfaces';import { getFontStyleString, isFunction } from '../../../basics/tools';import type { DataStreamTreeNode } from '../view-model/data-stream-tree-node';import type { DocumentViewModel } from '../view-model/document-view-model';@@ -315,7 +326,7 @@ export function updateBlockIndex(pages: IDocumentSkeletonPage[], start: number =let preLineStartIndex = columStartIndex;let columnHeight = 0;let maxColumnWidth = Number.NEGATIVE_INFINITY;- let preLine: Nullable<IDocumentSkeletonLine> = null;+ // const preLine: Nullable<IDocumentSkeletonLine> = null;for (const line of lines) {const { divides, lineHeight } = line;@@ -381,8 +392,10 @@ export function updateBlockIndex(pages: IDocumentSkeletonPage[], start: number =line.width = actualWidth;line.asc = maxLineAsc;maxColumnWidth = Math.max(maxColumnWidth, actualWidth);- line.top = (preLine?.top || 0) + (preLine?.lineHeight || 0);- preLine = line;+ // 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;@@ -486,7 +499,7 @@ export function columnIterator(export function getPositionHorizon(- positionH: ObjectPositionH,+ positionH: IObjectPositionH,column: IDocumentSkeletonColumn,page: IDocumentSkeletonPage,objectWidth: number,@@ -581,7 +594,7 @@ export function getPositionHorizon(export function getPositionVertical(- positionV: ObjectPositionV,+ positionV: IObjectPositionV,page: IDocumentSkeletonPage,lineTop: number,lineHeight: number,@@ -602,8 +615,7 @@ export function getPositionVertical(absoluteTop = lineTop + lineHeight / 2 - objectHeight / 2;}return absoluteTop;- }- if (relativeFrom === ObjectRelativeFromV.TOP_MARGIN) {+ } else if (relativeFrom === ObjectRelativeFromV.TOP_MARGIN) {// TODO} else if (relativeFrom === ObjectRelativeFromV.MARGIN) {// TODO@@ -623,14 +635,16 @@ export function getPositionVertical(}return absoluteTop;}- } else if (posOffset) {+ } else if (posOffset != null) {let absoluteTop = 0;+ const { marginTop } = page;+if (relativeFrom === ObjectRelativeFromV.LINE) {- absoluteTop = lineTop || 0 + posOffset;+ absoluteTop = (lineTop || 0) + posOffset;} else if (relativeFrom === ObjectRelativeFromV.TOP_MARGIN) {// TODO} else if (relativeFrom === ObjectRelativeFromV.MARGIN) {- // TODO+ absoluteTop = posOffset;} else if (relativeFrom === ObjectRelativeFromV.BOTTOM_MARGIN) {// TODO} else if (relativeFrom === ObjectRelativeFromV.INSIDE_MARGIN) {@@ -638,12 +652,12 @@ export function getPositionVertical(} else if (relativeFrom === ObjectRelativeFromV.OUTSIDE_MARGIN) {// TODO} else if (relativeFrom === ObjectRelativeFromV.PAGE) {- absoluteTop = posOffset;+ absoluteTop = posOffset - marginTop;} else if (relativeFrom === ObjectRelativeFromV.PARAGRAPH) {absoluteTop = (isPageBreak ? 0 : blockAnchorTop == null ? lineTop : blockAnchorTop) + posOffset;}return absoluteTop;- } else if (percent) {+ } else if (percent != null) {const { pageHeight, marginBottom, marginTop } = page;if (relativeFrom === ObjectRelativeFromV.TOP_MARGIN) {// TODO@@ -742,3 +756,173 @@ export function getFontCreateConfig(return result;}++// Generate an empty doc skeleton with the initial states.+export function getNullSkeleton(): IDocumentSkeletonCached {+ return {+ pages: [],+ left: 0,+ top: 0,+ st: 0,+ skeHeaders: new Map(),+ skeFooters: new Map(),+ skeListLevel: new Map(), // TODO: 移到 context 中管理?+ drawingAnchor: new Map(), // TODO: 移到 context 中管理+ };+}++export function setPageParent(pages: IDocumentSkeletonPage[], parent: IDocumentSkeletonCached) {+ for (const page of pages) {+ page.parent = parent;+ }+}++// The context state of the layout process, which is used to store some cache and intermediate states in the typesetting process,+// as well as identifying information such as the pointer of the layout.+export interface ILayoutContext {+ // The view model of current layout document.+ viewModel: DocumentViewModel;+ // The data model of current layout document.+ dataModel: DocumentDataModel;+ // The document style: pageSize, renderConfig, etc.+ // documentStyle: IDocumentStyle;+ // Configuration for document layout.+ docsConfig: IDocsConfig;+ // The initial layout skeleton, it will be the empty skeleton if it's the first layout.+ skeleton: IDocumentSkeletonCached;+ // The position coordinates of the layout,+ // which are used to indicate which section and paragraph are currently layout,+ // and used to support the starting point of the reflow when re-layout.+ layoutStartPointer: {+ paragraphIndex: Nullable<number>; // Layout from the beginning if the paragraphIndex is null.+ };+ // It is used to identify whether it is a re-layout,+ // and if it is a re-layout, the skeleton needs to be backtracked to the layoutStartPointer states.+ isDirty: boolean;+ // Used to store the resource of document and resource cache.+ skeletonResourceReference: ISkeletonResourceReference;+ // Positioned float objects cache.+ drawingsCache: Map<string, {+ count: number;+ page: IDocumentSkeletonPage;+ drawing: IDocumentSkeletonDrawing;+ }>;+ paragraphConfigCache: Map<number, IParagraphConfig>;+ sectionBreakConfigCache: Map<number, ISectionBreakConfig>;+ paragraphsOpenNewPage: Set<number>;+}++const DEFAULT_SECTION_BREAK: ISectionBreak = {+ columnProperties: [],+ columnSeparatorType: ColumnSeparatorType.NONE,+ sectionType: SectionType.SECTION_TYPE_UNSPECIFIED,+ startIndex: 0,+};++export const DEFAULT_PAGE_SIZE = { width: Number.POSITIVE_INFINITY, height: Number.POSITIVE_INFINITY };++export function prepareSectionBreakConfig(ctx: ILayoutContext, nodeIndex: number) {+ const { viewModel, dataModel, docsConfig } = ctx;+ const sectionNode = viewModel.children[nodeIndex];+ const sectionBreak = viewModel.getSectionBreak(sectionNode.endIndex) || DEFAULT_SECTION_BREAK;+ const { documentStyle } = dataModel;+ const {+ pageNumberStart: global_pageNumberStart = 1, // pageNumberStart+ pageSize: global_pageSize = DEFAULT_PAGE_SIZE,+ pageOrient: global_pageOrient = PageOrientType.PORTRAIT,+ defaultHeaderId: global_defaultHeaderId,+ defaultFooterId: global_defaultFooterId,+ evenPageHeaderId: global_evenPageHeaderId,+ evenPageFooterId: global_evenPageFooterId,+ firstPageHeaderId: global_firstPageHeaderId,+ firstPageFooterId: global_firstPageFooterId,+ useFirstPageHeaderFooter: global_useFirstPageHeaderFooter,+ useEvenPageHeaderFooter: global_useEvenPageHeaderFooter,++ marginTop: global_marginTop = 0,+ marginBottom: global_marginBottom = 0,+ marginRight: global_marginRight = 0,+ marginLeft: global_marginLeft = 0,+ marginHeader: global_marginHeader = 0,+ marginFooter: global_marginFooter = 0,++ renderConfig: global_renderConfig = {+ horizontalAlign: HorizontalAlign.LEFT,+ verticalAlign: VerticalAlign.TOP,+ centerAngle: 0,+ vertexAngle: 0,+ wrapStrategy: WrapStrategy.UNSPECIFIED,+ },+ } = documentStyle;+ const {+ pageNumberStart = global_pageNumberStart,+ pageSize = global_pageSize,+ pageOrient = global_pageOrient,+ marginTop = global_marginTop,+ marginBottom = global_marginBottom,+ marginRight = global_marginRight,+ marginLeft = global_marginLeft,+ marginHeader = global_marginHeader,+ marginFooter = global_marginFooter,++ defaultHeaderId = global_defaultHeaderId,+ defaultFooterId = global_defaultFooterId,+ evenPageHeaderId = global_evenPageHeaderId,+ evenPageFooterId = global_evenPageFooterId,+ firstPageHeaderId = global_firstPageHeaderId,+ firstPageFooterId = global_firstPageFooterId,+ useFirstPageHeaderFooter = global_useFirstPageHeaderFooter,+ useEvenPageHeaderFooter = global_useEvenPageHeaderFooter,++ columnProperties = [],+ columnSeparatorType = ColumnSeparatorType.NONE,+ contentDirection,+ sectionType,+ textDirection,+ renderConfig = global_renderConfig,+ } = sectionBreak;++ const sectionNodeNext = viewModel.children[nodeIndex + 1];+ const sectionTypeNext = viewModel.getSectionBreak(sectionNodeNext?.endIndex)?.sectionType;++ const headerIds = { defaultHeaderId, evenPageHeaderId, firstPageHeaderId };+ const footerIds = { defaultFooterId, evenPageFooterId, firstPageFooterId };++ if (pageSize.width === null) {+ pageSize.width = Number.POSITIVE_INFINITY;+ }++ if (pageSize.height === null) {+ pageSize.height = Number.POSITIVE_INFINITY;+ }++ const sectionBreakConfig: ISectionBreakConfig = {+ pageNumberStart,+ pageSize,+ pageOrient,+ marginTop,+ marginBottom,+ marginRight,+ marginLeft,+ marginHeader,+ marginFooter,++ headerIds,+ footerIds,++ useFirstPageHeaderFooter,+ useEvenPageHeaderFooter,++ columnProperties,+ columnSeparatorType,+ contentDirection,+ sectionType,+ sectionTypeNext,+ textDirection,+ renderConfig,++ ...docsConfig,+ };++ return sectionBreakConfig;+}diff --git a/packages/engine-render/src/index.ts b/packages/engine-render/src/index.tsindex 27df8f420d..19b1a4a6bc 100644--- a/packages/engine-render/src/index.ts+++ b/packages/engine-render/src/index.ts@@ -44,6 +44,7 @@ export {} 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';+export { DocBackground } from './components/docs/doc-background';export type { IPageRenderConfig } from './components/docs/document';export { DocumentSkeleton } from './components/docs/layout/doc-skeleton';export { ThinEngine } from './thin-engine';diff --git a/packages/image/src/controllers/image.load.controller.ts b/packages/image/src/controllers/image.load.controller.tsindex 69085da05c..5d5e946811 100644--- a/packages/image/src/controllers/image.load.controller.ts+++ b/packages/image/src/controllers/image.load.controller.ts@@ -30,6 +30,9 @@ import { IRenderManagerService, Picture } from '@univerjs/engine-render';import { IImageManagerService } from '../services/image-manager.service';import { IImageRenderService } from '../services/image-render.service';+const IMAGE_DEFAULT_LAYER_INDEX = 11;+const IMAGE_BEHIND_TEXT_LAYER_INDEX = 1;+@OnLifecycle(LifecycleStages.Rendered, ImageLoadController)export class ImageLoadController extends Disposable {constructor(@@ -67,13 +70,14 @@ export class ImageLoadController extends Disposable {);}+private _floatingObjectListener() {this.disposeWithMe(toDisposable(this._floatingObjectManagerService.andOrUpdate$.subscribe((params) => {const sceneList: Scene[] = [];params.forEach((param) => {- const { unitId, subUnitId, floatingObjectId, floatingObject } = param;+ const { unitId, subUnitId, floatingObjectId, floatingObject, behindText } = param;const renderObject = this._renderManagerService.getRenderById(unitId);@@ -132,7 +136,7 @@ export class ImageLoadController extends Disposable {scene.openTransformer();}- scene.addObject(image);+ scene.addObject(image, behindText ? IMAGE_BEHIND_TEXT_LAYER_INDEX : IMAGE_DEFAULT_LAYER_INDEX);if (!sceneList.includes(scene)) {sceneList.push(scene);diff --git a/packages/image/src/plugin.ts b/packages/image/src/plugin.tsindex fe8c57dcf2..b42bf9e679 100644--- a/packages/image/src/plugin.ts+++ b/packages/image/src/plugin.ts@@ -37,16 +37,20 @@ export class UniverImagePlugin extends Plugin {override onStarting(_injector: Injector): void {this._initDependencies(_injector);this._injector = _injector;++ this._mockAddImage();}- override onReady(): void {+ override onReady(): void {}++ private _mockAddImage(): void {/*** TODO: @DR-Univer Before the loading process is completed, mock some data for testing.*/const imageManagerService = this._injector.get(IImageManagerService);const model = new ImageModel({imageId: 'shapeTest1',- contentUrl: 'https://minio.cnbabylon.com/univer/slide/gartner-tech-2022.png',+ contentUrl: 'https://static01.nyt.com/images/2019/09/04/business/04chinaclone-01/merlin_160087014_de761d9a-4360-402d-a15b-ddeff775760d-master1050.jpg',});imageManagerService.add({unitId: 'd',@@ -55,6 +59,50 @@ export class UniverImagePlugin extends Plugin {imageModel: model,});+ const model2 = new ImageModel({+ imageId: 'shapeTest2',+ contentUrl: 'https://minio.cnbabylon.com/univer/slide/gartner-tech-2022.png',+ });+ imageManagerService.add({+ unitId: 'd',+ subUnitId: DEFAULT_DOCUMENT_SUB_COMPONENT_ID,+ imageId: 'shapeTest2',+ imageModel: model2,+ });++ const model3 = new ImageModel({+ imageId: 'shapeTest3',+ contentUrl: 'https://p.potaufeu.asahi.com/e511-p/picture/28108272/c96ce4be5caeb371b0d3acace6a846c4.jpg',+ });+ imageManagerService.add({+ unitId: 'd',+ subUnitId: DEFAULT_DOCUMENT_SUB_COMPONENT_ID,+ imageId: 'shapeTest3',+ imageModel: model3,+ });++ const model4 = new ImageModel({+ imageId: 'shapeTest4',+ contentUrl: 'https://i.epochtimes.com/assets/uploads/2017/12/dddcat-2838801-600x400.jpg',+ });+ imageManagerService.add({+ unitId: 'd',+ subUnitId: DEFAULT_DOCUMENT_SUB_COMPONENT_ID,+ imageId: 'shapeTest4',+ imageModel: model4,+ });++ const model5 = new ImageModel({+ imageId: 'shapeTest5',+ contentUrl: 'https://pic2.zhimg.com/80/b0fb7ff44b35986d9f8569e34d30692d_1440w.webp',+ });+ imageManagerService.add({+ unitId: 'd',+ subUnitId: DEFAULT_DOCUMENT_SUB_COMPONENT_ID,+ imageId: 'shapeTest5',+ imageModel: model5,+ });+// imageProperties: {// contentUrl: 'https://minio.cnbabylon.com/univer/slide/gartner-tech-2022.png',// },diff --git a/packages/sheets-ui/src/basics/editor/get-editor-object.ts b/packages/sheets-ui/src/basics/editor/get-editor-object.tsindex 272b8aaa01..ad016925d7 100644--- a/packages/sheets-ui/src/basics/editor/get-editor-object.ts+++ b/packages/sheets-ui/src/basics/editor/get-editor-object.ts@@ -15,10 +15,12 @@*/import type { Nullable } from '@univerjs/core';-import type { Documents, Engine, IRenderManagerService, Scene } from '@univerjs/engine-render';+import { DOCS_VIEW_KEY } from '@univerjs/docs';+import type { DocBackground, Documents, Engine, IRenderManagerService, Scene } from '@univerjs/engine-render';export interface IDocObjectParam {document: Documents;+ docBackground: DocBackground;scene: Scene;engine: Engine;}@@ -37,12 +39,14 @@ export function getEditorObject(return;}- const { mainComponent, scene, engine } = currentRender;+ const { mainComponent, scene, engine, components } = currentRender;const document = mainComponent as Documents;+ const docBackground = components.get(DOCS_VIEW_KEY.BACKGROUND) as DocBackground;return {document,+ docBackground,scene,engine,};diff --git a/packages/slides/src/views/render/adaptors/docs-adaptor.ts b/packages/slides/src/views/render/adaptors/docs-adaptor.tsindex f90a894dd9..a8b06cd4c5 100644--- a/packages/slides/src/views/render/adaptors/docs-adaptor.ts+++ b/packages/slides/src/views/render/adaptors/docs-adaptor.ts@@ -61,6 +61,7 @@ export class DocsAdaptor extends ObjectAdaptor {return this;}+ // eslint-disable-next-line max-lines-per-functionoverride convert(pageElement: IPageElement, mainScene: Scene) {const {id,