Skip to content

Build your own AI office with Univer Office SDK. Bring editing, calculation, collaboration, and file processing into your product for people and AI agents. Built on an extensible open-source core.

feat(drawing): sheets and docs drawing (#2324)

Univer4853425aef1e
diff --git a/.vscode/settings.json b/.vscode/settings.json
index 634b22352b..ffbfb135bc 100644
--- a/.vscode/settings.json
+++ b/.vscode/settings.json
@@ -83,6 +83,7 @@
"pnmp",
"Polyton",
"ponyfill",
+ "prst",
"PWDEBUG",
"Quan",
"redi",
@@ -95,6 +96,7 @@
"TBRL",
"undoredo",
"undos",
+ "Ungroup",
"unhine",
"Uniscript",
"univer",
@@ -127,6 +129,7 @@
// Disable the default formatter, use eslint instead
"prettier.enable": false,
"editor.formatOnSave": false,
+ "search.followSymlinks": false,
// Auto fix
"editor.codeActionsOnSave": {
diff --git a/common/storybook/.storybook/preview.tsx b/common/storybook/.storybook/preview.tsx
index 6da395063b..951b40f7c2 100644
--- a/common/storybook/.storybook/preview.tsx
+++ b/common/storybook/.storybook/preview.tsx
@@ -23,11 +23,9 @@ import {
ContextService,
DesktopLogService,
ErrorService,
- FloatingObjectManagerService,
ICommandService,
IConfigService,
IContextService,
- IFloatingObjectManagerService,
ILocalStorageService,
ILogService,
IPermissionService,
@@ -100,7 +98,6 @@ const preview: Preview = {
[IUndoRedoService, { useClass: LocalUndoRedoService, lazy: true }],
[IConfigService, { useClass: ConfigService }],
[IContextService, { useClass: ContextService }],
- [IFloatingObjectManagerService, { useClass: FloatingObjectManagerService, lazy: true }],
[IResourceManagerService, { useClass: ResourceManagerService, lazy: true }],
[IPermissionService, { useClass: PermissionService }],
diff --git a/examples/package.json b/examples/package.json
index 9214655830..0bb03cdc03 100644
--- a/examples/package.json
+++ b/examples/package.json
@@ -17,18 +17,21 @@
"@univerjs/debugger": "workspace:*",
"@univerjs/design": "workspace:*",
"@univerjs/docs": "workspace:*",
+ "@univerjs/docs-drawing-ui": "workspace:*",
"@univerjs/docs-ui": "workspace:*",
+ "@univerjs/drawing": "workspace:*",
+ "@univerjs/drawing-ui": "workspace:*",
"@univerjs/engine-formula": "workspace:*",
"@univerjs/engine-render": "workspace:*",
"@univerjs/facade": "workspace:*",
"@univerjs/find-replace": "workspace:*",
"@univerjs/icons": "^0.1.52",
- "@univerjs/image": "workspace:*",
"@univerjs/rpc": "workspace:*",
"@univerjs/sheets": "workspace:*",
"@univerjs/sheets-conditional-formatting": "workspace:*",
"@univerjs/sheets-conditional-formatting-ui": "workspace:*",
"@univerjs/sheets-data-validation": "workspace:*",
+ "@univerjs/sheets-drawing-ui": "workspace:*",
"@univerjs/sheets-filter": "workspace:*",
"@univerjs/sheets-filter-ui": "workspace:*",
"@univerjs/sheets-find-replace": "workspace:*",
diff --git a/examples/src/data/docs/default-document-data-cn.ts b/examples/src/data/docs/default-document-data-cn.ts
index c94436ec88..715d216f04 100644
--- a/examples/src/data/docs/default-document-data-cn.ts
+++ b/examples/src/data/docs/default-document-data-cn.ts
@@ -15,17 +15,20 @@
*/
import type { IDocumentData } from '@univerjs/core';
-import { BooleanNumber, ObjectRelativeFromH, ObjectRelativeFromV, PositionedObjectLayoutType, WrapTextType } from '@univerjs/core';
+import { BooleanNumber, DrawingTypeEnum, ObjectRelativeFromH, ObjectRelativeFromV, PositionedObjectLayoutType, WrapTextType } from '@univerjs/core';
import { ptToPixel } from '@univerjs/engine-render';
export const DEFAULT_DOCUMENT_DATA_CN: IDocumentData = {
id: 'd',
drawings: {
shapeTest1: {
- objectId: 'shapeTest1',
+ unitId: 'd',
+ subUnitId: 'd',
+ drawingType: DrawingTypeEnum.DRAWING_SHAPE,
+ drawingId: 'shapeTest1',
title: 'test shape',
description: 'test shape',
- objectTransform: {
+ docTransform: {
size: {
width: 1484 * 0.12,
height: 864 * 0.15,
@@ -49,10 +52,13 @@ export const DEFAULT_DOCUMENT_DATA_CN: IDocumentData = {
distR: 0,
},
shapeTest2: {
- objectId: 'shapeTest2',
+ unitId: 'd',
+ subUnitId: 'd',
+ drawingType: DrawingTypeEnum.DRAWING_SHAPE,
+ drawingId: 'shapeTest2',
title: 'test shape',
description: 'test shape',
- objectTransform: {
+ docTransform: {
size: {
width: 1484 * 0.3,
height: 864 * 0.3,
@@ -72,10 +78,13 @@ export const DEFAULT_DOCUMENT_DATA_CN: IDocumentData = {
wrapText: WrapTextType.BOTH_SIDES,
},
shapeTest3: {
- objectId: 'shapeTest3',
+ unitId: 'd',
+ subUnitId: 'd',
+ drawingType: DrawingTypeEnum.DRAWING_SHAPE,
+ drawingId: 'shapeTest3',
title: 'test shape',
description: 'test shape',
- objectTransform: {
+ docTransform: {
size: {
width: 1484 * 0.3,
height: 864 * 0.3,
@@ -95,10 +104,13 @@ export const DEFAULT_DOCUMENT_DATA_CN: IDocumentData = {
wrapText: WrapTextType.BOTH_SIDES,
},
shapeTest4: {
- objectId: 'shapeTest4',
+ unitId: 'd',
+ subUnitId: 'd',
+ drawingType: DrawingTypeEnum.DRAWING_SHAPE,
+ drawingId: 'shapeTest4',
title: 'test shape',
description: 'test shape',
- objectTransform: {
+ docTransform: {
size: {
width: 1484 * 0.3,
height: 864 * 0.3,
@@ -118,10 +130,13 @@ export const DEFAULT_DOCUMENT_DATA_CN: IDocumentData = {
wrapText: WrapTextType.BOTH_SIDES,
},
shapeTest5: {
- objectId: 'shapeTest5',
+ unitId: 'd',
+ subUnitId: 'd',
+ drawingType: DrawingTypeEnum.DRAWING_SHAPE,
+ drawingId: 'shapeTest5',
title: 'test shape',
description: 'test shape',
- objectTransform: {
+ docTransform: {
size: {
width: 1484 * 0.3,
height: 864 * 0.3,
@@ -141,6 +156,13 @@ export const DEFAULT_DOCUMENT_DATA_CN: IDocumentData = {
wrapText: WrapTextType.BOTH_SIDES,
},
},
+ drawingsOrder: [
+ 'shapeTest1',
+ 'shapeTest2',
+ 'shapeTest3',
+ 'shapeTest4',
+ 'shapeTest5',
+ ],
body: {
dataStream:
'荷塘月色\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',
diff --git a/examples/src/data/docs/default-document-data-dreamer.ts b/examples/src/data/docs/default-document-data-dreamer.ts
index dfd86ed969..aa36784a3a 100644
--- a/examples/src/data/docs/default-document-data-dreamer.ts
+++ b/examples/src/data/docs/default-document-data-dreamer.ts
@@ -18,6 +18,7 @@ import type { IDocumentData } from '@univerjs/core';
import {
BooleanNumber,
ColumnSeparatorType,
+ DrawingTypeEnum,
ObjectRelativeFromH,
ObjectRelativeFromV,
PositionedObjectLayoutType,
@@ -30,10 +31,13 @@ export const DEFAULT_DOCUMENT_DATA_DREAMER: IDocumentData = {
id: 'd',
drawings: {
shapeTest1: {
- objectId: 'shapeTest1',
+ unitId: 'd',
+ subUnitId: 'd',
+ drawingType: DrawingTypeEnum.DRAWING_SHAPE,
+ drawingId: 'shapeTest1',
title: 'test shape',
description: 'test shape',
- objectTransform: {
+ docTransform: {
size: {
width: 1484 * 0.15,
height: 864 * 0.15,
@@ -53,10 +57,13 @@ export const DEFAULT_DOCUMENT_DATA_DREAMER: IDocumentData = {
wrapText: WrapTextType.BOTH_SIDES,
},
shapeTest2: {
- objectId: 'shapeTest2',
+ unitId: 'd',
+ subUnitId: 'd',
+ drawingType: DrawingTypeEnum.DRAWING_SHAPE,
+ drawingId: 'shapeTest2',
title: 'test shape',
description: 'test shape',
- objectTransform: {
+ docTransform: {
size: {
width: 2548 * 0.1,
height: 2343 * 0.1,
diff --git a/examples/src/data/docs/default-document-data-en.ts b/examples/src/data/docs/default-document-data-en.ts
index 1190a7e93f..be17c86649 100644
--- a/examples/src/data/docs/default-document-data-en.ts
+++ b/examples/src/data/docs/default-document-data-en.ts
@@ -18,6 +18,7 @@ import type { IDocumentData } from '@univerjs/core';
import {
BooleanNumber,
ColumnSeparatorType,
+ DrawingTypeEnum,
ObjectRelativeFromH,
ObjectRelativeFromV,
PositionedObjectLayoutType,
@@ -31,10 +32,13 @@ export const DEFAULT_DOCUMENT_DATA_EN: IDocumentData = {
id: 'd',
drawings: {
shapeTest1: {
- objectId: 'shapeTest1',
+ unitId: 'd',
+ subUnitId: 'd',
+ drawingType: DrawingTypeEnum.DRAWING_SHAPE,
+ drawingId: 'shapeTest1',
title: 'test shape',
description: 'test shape',
- objectTransform: {
+ docTransform: {
size: {
width: 1484 * 0.15,
height: 864 * 0.15,
@@ -58,10 +62,13 @@ export const DEFAULT_DOCUMENT_DATA_EN: IDocumentData = {
wrapText: WrapTextType.BOTH_SIDES,
},
shapeTest2: {
- objectId: 'shapeTest2',
+ unitId: 'd',
+ subUnitId: 'd',
+ drawingType: DrawingTypeEnum.DRAWING_SHAPE,
+ drawingId: 'shapeTest2',
title: 'test shape',
description: 'test shape',
- objectTransform: {
+ docTransform: {
size: {
width: 2548 * 0.1,
height: 2343 * 0.1,
diff --git a/examples/src/data/docs/default-document-data.ts b/examples/src/data/docs/default-document-data.ts
index 845f71b038..e71dba1039 100644
--- a/examples/src/data/docs/default-document-data.ts
+++ b/examples/src/data/docs/default-document-data.ts
@@ -19,6 +19,7 @@ import {
BaselineOffset,
BooleanNumber,
ColumnSeparatorType,
+ DrawingTypeEnum,
ObjectRelativeFromH,
ObjectRelativeFromV,
PositionedObjectLayoutType,
@@ -31,10 +32,13 @@ export const DEFAULT_DOCUMENT_DATA: IDocumentData = {
id: 'd',
drawings: {
shapeTest1: {
- objectId: 'shapeTest1',
+ unitId: 'd',
+ subUnitId: 'd',
+ drawingType: DrawingTypeEnum.DRAWING_SHAPE,
+ drawingId: 'shapeTest1',
title: 'test shape',
description: 'test shape',
- objectTransform: {
+ docTransform: {
size: {
width: 100,
height: 400,
diff --git a/examples/src/data/sheets/default-workbook-data.ts b/examples/src/data/sheets/default-workbook-data.ts
index 19b9daec53..7ade0db68a 100644
--- a/examples/src/data/sheets/default-workbook-data.ts
+++ b/examples/src/data/sheets/default-workbook-data.ts
@@ -20,6 +20,7 @@ import {
BooleanNumber,
BorderStyleTypes,
ColumnSeparatorType,
+ DrawingTypeEnum,
HorizontalAlign,
LocaleType,
ObjectRelativeFromH,
@@ -37,10 +38,13 @@ const richTextTestFloat: IDocumentData = {
id: 'd',
drawings: {
shapeTest1: {
- objectId: 'shapeTest1',
+ unitId: 'd',
+ subUnitId: 'd',
+ drawingType: DrawingTypeEnum.DRAWING_SHAPE,
+ drawingId: 'shapeTest1',
title: 'test shape',
description: 'test shape',
- objectTransform: {
+ docTransform: {
size: {
width: 100,
height: 400,
diff --git a/examples/src/data/slides/default-pages/page1.ts b/examples/src/data/slides/default-pages/page1.ts
index d69cc555d7..35fcb01026 100644
--- a/examples/src/data/slides/default-pages/page1.ts
+++ b/examples/src/data/slides/default-pages/page1.ts
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-import { PageElementType, PageType, ShapeType } from '@univerjs/core';
+import { BasicShapes, PageElementType, PageType } from '@univerjs/core';
export const DEFAULT_FIRST_PAGE = {
id: 'cover_1',
@@ -53,7 +53,7 @@ export const DEFAULT_FIRST_PAGE = {
description: '',
type: PageElementType.SHAPE,
shape: {
- shapeType: ShapeType.RECTANGLE,
+ shapeType: BasicShapes.Rect,
text: '',
shapeProperties: {
shapeBackgroundFill: {
@@ -92,7 +92,7 @@ export const DEFAULT_FIRST_PAGE = {
description: '',
type: PageElementType.SHAPE,
shape: {
- shapeType: ShapeType.RECTANGLE,
+ shapeType: BasicShapes.Rect,
text: '',
shapeProperties: {
shapeBackgroundFill: {
diff --git a/examples/src/data/slides/default-pages/page2.ts b/examples/src/data/slides/default-pages/page2.ts
index 30388301da..c1e677bf26 100644
--- a/examples/src/data/slides/default-pages/page2.ts
+++ b/examples/src/data/slides/default-pages/page2.ts
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-import { PageElementType, PageType, ShapeType } from '@univerjs/core';
+import { BasicShapes, PageElementType, PageType } from '@univerjs/core';
export const DEFAULT_SECOND_PAGE = {
id: 'catalog_1',
@@ -53,7 +53,7 @@ export const DEFAULT_SECOND_PAGE = {
description: '',
type: PageElementType.SHAPE,
shape: {
- shapeType: ShapeType.RECTANGLE,
+ shapeType: BasicShapes.Rect,
text: '',
shapeProperties: {
shapeBackgroundFill: {
@@ -91,7 +91,7 @@ export const DEFAULT_SECOND_PAGE = {
description: '',
type: PageElementType.SHAPE,
shape: {
- shapeType: ShapeType.RECTANGLE,
+ shapeType: BasicShapes.Rect,
text: '',
shapeProperties: {
shapeBackgroundFill: {
@@ -111,7 +111,7 @@ export const DEFAULT_SECOND_PAGE = {
description: '',
type: PageElementType.SHAPE,
shape: {
- shapeType: ShapeType.RECTANGLE,
+ shapeType: BasicShapes.Rect,
text: '',
shapeProperties: {
shapeBackgroundFill: {
@@ -131,7 +131,7 @@ export const DEFAULT_SECOND_PAGE = {
description: '',
type: PageElementType.SHAPE,
shape: {
- shapeType: ShapeType.RECTANGLE,
+ shapeType: BasicShapes.Rect,
text: '',
shapeProperties: {
shapeBackgroundFill: {
@@ -151,7 +151,7 @@ export const DEFAULT_SECOND_PAGE = {
description: '',
type: PageElementType.SHAPE,
shape: {
- shapeType: ShapeType.RECTANGLE,
+ shapeType: BasicShapes.Rect,
text: '',
shapeProperties: {
shapeBackgroundFill: {
@@ -171,7 +171,7 @@ export const DEFAULT_SECOND_PAGE = {
description: '',
type: PageElementType.SHAPE,
shape: {
- shapeType: ShapeType.RECTANGLE,
+ shapeType: BasicShapes.Rect,
text: '',
shapeProperties: {
shapeBackgroundFill: {
diff --git a/examples/src/data/slides/default-pages/page3.ts b/examples/src/data/slides/default-pages/page3.ts
index c338b07d99..eafb5a2ff3 100644
--- a/examples/src/data/slides/default-pages/page3.ts
+++ b/examples/src/data/slides/default-pages/page3.ts
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-import { PageElementType, PageType, ShapeType } from '@univerjs/core';
+import { BasicShapes, PageElementType, PageType } from '@univerjs/core';
import { PAGE3_RICHTEXT_1 } from '../rich-text/page3-richtext1';
import { PAGE3_RICHTEXT_2 } from '../rich-text/page3-richtext2';
@@ -41,7 +41,7 @@ export const DEFAULT_THIRD_PAGE = {
description: '',
type: PageElementType.SHAPE,
shape: {
- shapeType: ShapeType.RECTANGLE,
+ shapeType: BasicShapes.Rect,
text: '',
shapeProperties: {
shapeBackgroundFill: {
@@ -119,7 +119,7 @@ export const DEFAULT_THIRD_PAGE = {
description: '',
type: PageElementType.SHAPE,
shape: {
- shapeType: ShapeType.RECTANGLE,
+ shapeType: BasicShapes.Rect,
text: '',
shapeProperties: {
shapeBackgroundFill: {
@@ -175,7 +175,7 @@ export const DEFAULT_THIRD_PAGE = {
description: '',
type: PageElementType.SHAPE,
shape: {
- shapeType: ShapeType.RECTANGLE,
+ shapeType: BasicShapes.Rect,
text: '',
shapeProperties: {
shapeBackgroundFill: {
@@ -231,7 +231,7 @@ export const DEFAULT_THIRD_PAGE = {
description: '',
type: PageElementType.SHAPE,
shape: {
- shapeType: ShapeType.RECTANGLE,
+ shapeType: BasicShapes.Rect,
text: '',
shapeProperties: {
shapeBackgroundFill: {
diff --git a/examples/src/data/slides/default-pages/page4.ts b/examples/src/data/slides/default-pages/page4.ts
index b0cabf7ae8..dd45e2c64e 100644
--- a/examples/src/data/slides/default-pages/page4.ts
+++ b/examples/src/data/slides/default-pages/page4.ts
@@ -15,7 +15,7 @@
*/
import type { IWorksheetData } from '@univerjs/core';
-import { PageElementType, PageType, ShapeType } from '@univerjs/core';
+import { BasicShapes, PageElementType, PageType } from '@univerjs/core';
import { SLIDE_WORKBOOK_DATA } from '../../sheets/slide-workbook-data';
@@ -43,7 +43,7 @@ export const DEFAULT_FORTH_PAGE = {
description: '',
type: PageElementType.SHAPE,
shape: {
- shapeType: ShapeType.RECTANGLE,
+ shapeType: BasicShapes.Rect,
text: '',
shapeProperties: {
shapeBackgroundFill: {
diff --git a/examples/src/data/slides/default-pages/page5.ts b/examples/src/data/slides/default-pages/page5.ts
index a3fb34f101..e20d5bed26 100644
--- a/examples/src/data/slides/default-pages/page5.ts
+++ b/examples/src/data/slides/default-pages/page5.ts
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-import { PageElementType, PageType, ShapeType } from '@univerjs/core';
+import { BasicShapes, PageElementType, PageType } from '@univerjs/core';
export const DEFAULT_FIFTH_PAGE = {
id: 'technology_1',
@@ -37,7 +37,7 @@ export const DEFAULT_FIFTH_PAGE = {
description: '',
type: PageElementType.SHAPE,
shape: {
- shapeType: ShapeType.RECTANGLE,
+ shapeType: BasicShapes.Rect,
text: '',
shapeProperties: {
shapeBackgroundFill: {
diff --git a/examples/src/data/slides/default-pages/page6.ts b/examples/src/data/slides/default-pages/page6.ts
index db0caabba2..628f987a82 100644
--- a/examples/src/data/slides/default-pages/page6.ts
+++ b/examples/src/data/slides/default-pages/page6.ts
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-import { PageElementType, PageType, ShapeType } from '@univerjs/core';
+import { BasicShapes, PageElementType, PageType } from '@univerjs/core';
import { DEFAULT_DOCUMENT_DATA_EN } from '../../docs/default-document-data-en';
@@ -39,7 +39,7 @@ export const DEFAULT_SIXTH_PAGE = {
description: '',
type: PageElementType.SHAPE,
shape: {
- shapeType: ShapeType.RECTANGLE,
+ shapeType: BasicShapes.Rect,
text: '',
shapeProperties: {
shapeBackgroundFill: {
diff --git a/examples/src/data/slides/default-pages/page7.ts b/examples/src/data/slides/default-pages/page7.ts
index 85b3d0b366..33de81214a 100644
--- a/examples/src/data/slides/default-pages/page7.ts
+++ b/examples/src/data/slides/default-pages/page7.ts
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-import { PageElementType, PageType, ShapeType } from '@univerjs/core';
+import { BasicShapes, PageElementType, PageType } from '@univerjs/core';
import { generateUnlimitedSlideData } from '../unlimited-slide-data';
@@ -55,7 +55,7 @@ export const DEFAULT_SEVEN_PAGE = {
description: '',
type: PageElementType.SHAPE,
shape: {
- shapeType: ShapeType.RECTANGLE,
+ shapeType: BasicShapes.Rect,
text: '',
shapeProperties: {
shapeBackgroundFill: {
@@ -94,7 +94,7 @@ export const DEFAULT_SEVEN_PAGE = {
description: '',
type: PageElementType.SHAPE,
shape: {
- shapeType: ShapeType.RECTANGLE,
+ shapeType: BasicShapes.Rect,
text: '',
shapeProperties: {
shapeBackgroundFill: {
diff --git a/examples/src/data/slides/unlimited-slide-data.ts b/examples/src/data/slides/unlimited-slide-data.ts
index 3f4f098a40..3b97337847 100644
--- a/examples/src/data/slides/unlimited-slide-data.ts
+++ b/examples/src/data/slides/unlimited-slide-data.ts
@@ -15,7 +15,7 @@
*/
import type { ISlideData } from '@univerjs/core';
-import { PageElementType, PageType, ShapeType } from '@univerjs/core';
+import { BasicShapes, PageElementType, PageType } from '@univerjs/core';
import { DEFAULT_SECOND_PAGE } from './default-pages/page2';
import { DEFAULT_THIRD_PAGE } from './default-pages/page3';
@@ -70,7 +70,7 @@ export function generateUnlimitedSlideData(ratio: number = 1, slideData?: ISlide
description: '',
type: PageElementType.SHAPE,
shape: {
- shapeType: ShapeType.RECTANGLE,
+ shapeType: BasicShapes.Rect,
text: '',
shapeProperties: {
shapeBackgroundFill: {
@@ -109,7 +109,7 @@ export function generateUnlimitedSlideData(ratio: number = 1, slideData?: ISlide
description: '',
type: PageElementType.SHAPE,
shape: {
- shapeType: ShapeType.RECTANGLE,
+ shapeType: BasicShapes.Rect,
text: '',
shapeProperties: {
shapeBackgroundFill: {
diff --git a/examples/src/docs/main.ts b/examples/src/docs/main.ts
index 34ecdaaefa..0f1d3345c3 100644
--- a/examples/src/docs/main.ts
+++ b/examples/src/docs/main.ts
@@ -21,10 +21,11 @@ import { UniverDocsPlugin } from '@univerjs/docs';
import { UniverDocsUIPlugin } from '@univerjs/docs-ui';
import { UniverRenderEnginePlugin } from '@univerjs/engine-render';
import { UniverUIPlugin } from '@univerjs/ui';
-import { UniverImagePlugin } from '@univerjs/image';
+import { UniverDrawingPlugin } from '@univerjs/drawing';
import { UniverFormulaEnginePlugin } from '@univerjs/engine-formula';
import { UniverDebuggerPlugin } from '@univerjs/debugger';
-
+import { UniverDrawingUIPlugin } from '@univerjs/drawing-ui';
+import { UniverDocsDrawingUIPlugin } from '@univerjs/docs-drawing-ui';
import { DEFAULT_DOCUMENT_DATA_CN } from '../data';
import { enUS, ruRU, zhCN } from '../locales';
@@ -56,6 +57,7 @@ univer.registerPlugin(UniverUIPlugin, {
container: 'app',
footer: false,
});
+univer.registerPlugin(UniverDrawingPlugin);
univer.registerPlugin(UniverDocsPlugin);
univer.registerPlugin(UniverDocsUIPlugin, {
container: 'univerdoc',
@@ -66,7 +68,8 @@ univer.registerPlugin(UniverDocsUIPlugin, {
},
});
-univer.registerPlugin(UniverImagePlugin);
+univer.registerPlugin(UniverDrawingUIPlugin);
+univer.registerPlugin(UniverDocsDrawingUIPlugin);
univer.createUnit(UniverInstanceType.UNIVER_DOC, DEFAULT_DOCUMENT_DATA_CN);
diff --git a/examples/src/sheets/main.ts b/examples/src/sheets/main.ts
index 3020875157..e88bdf9afa 100644
--- a/examples/src/sheets/main.ts
+++ b/examples/src/sheets/main.ts
@@ -40,6 +40,9 @@ import { UniverDebuggerPlugin } from '@univerjs/debugger';
import { FUniver } from '@univerjs/facade';
import { IThreadCommentMentionDataService } from '@univerjs/thread-comment-ui';
+import { UniverDrawingPlugin } from '@univerjs/drawing';
+import { UniverDrawingUIPlugin } from '@univerjs/drawing-ui';
+import { UniverSheetsDrawingUIPlugin } from '@univerjs/sheets-drawing-ui';
import { DEFAULT_WORKBOOK_DATA_DEMO } from '../data/sheets/demo/default-workbook-data-demo';
import { enUS, ruRU, zhCN } from '../locales';
@@ -69,9 +72,13 @@ univer.registerPlugin(UniverUIPlugin, {
container: 'app',
});
+univer.registerPlugin(UniverDrawingPlugin);
+
univer.registerPlugin(UniverDocsUIPlugin);
-univer.registerPlugin(UniverSheetsPlugin);
+univer.registerPlugin(UniverSheetsPlugin, {
+ notExecuteFormula: true,
+});
univer.registerPlugin(UniverSheetsUIPlugin);
// sheet feature plugins
@@ -102,6 +109,9 @@ univer.registerPlugin(UniverSheetsConditionalFormattingUIPlugin);
// sheet permission
univer.registerPlugin(UniverSheetsPermissionUIPlugin);
+// drawing
+univer.registerPlugin(UniverDrawingUIPlugin);
+univer.registerPlugin(UniverSheetsDrawingUIPlugin);
// create univer sheet instance
if (!IS_E2E) {
diff --git a/examples/src/sheets/worker.ts b/examples/src/sheets/worker.ts
index c4f1b80c06..98f821ce65 100644
--- a/examples/src/sheets/worker.ts
+++ b/examples/src/sheets/worker.ts
@@ -25,7 +25,7 @@ const univer = new Univer({
locale: LocaleType.ZH_CN,
});
-univer.registerPlugin(UniverSheetsPlugin);
+univer.registerPlugin(UniverSheetsPlugin, { onlyRegisterFormulaRelatedMutations: true });
univer.registerPlugin(UniverFormulaEnginePlugin);
univer.registerPlugin(UniverRPCWorkerThreadPlugin);
univer.registerPlugin(UniverSheetsFilterPlugin);
diff --git a/packages/core/src/docs/data-model/document-data-model.ts b/packages/core/src/docs/data-model/document-data-model.ts
index a9d7daa995..6e127e6930 100644
--- a/packages/core/src/docs/data-model/document-data-model.ts
+++ b/packages/core/src/docs/data-model/document-data-model.ts
@@ -21,6 +21,7 @@ import type {
IDocumentData,
IDocumentRenderConfig,
IDocumentStyle,
+ IDrawings,
} from '../../types/interfaces/i-document-data';
import type { IPaddingData } from '../../types/interfaces/i-style-data';
import { UnitModel, UniverInstanceType } from '../../common/unit';
@@ -72,6 +73,11 @@ class DocumentDataModelSimple extends UnitModel<IDocumentData, UniverInstanceTyp
return this.snapshot.settings?.zoomRatio || 1;
}
+ resetDrawing(drawings: IDrawings, drawingsOrder: string[]) {
+ this.snapshot.drawings = drawings;
+ this.snapshot.drawingsOrder = drawingsOrder;
+ }
+
getBody() {
return this.snapshot.body;
}
@@ -172,7 +178,7 @@ class DocumentDataModelSimple extends UnitModel<IDocumentData, UniverInstanceTyp
return;
}
- const objectTransform = drawing.objectTransform;
+ const objectTransform = drawing.docTransform;
objectTransform.size.width = width;
objectTransform.size.height = height;
@@ -219,6 +225,14 @@ export class DocumentDataModel extends DocumentDataModelSimple {
});
}
+ getDrawings() {
+ return this.snapshot.drawings;
+ }
+
+ getDrawingsOrder() {
+ return this.snapshot.drawingsOrder;
+ }
+
getRev(): number {
return this.snapshot.rev ?? 1;
}
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index 79c8992678..b9a0db69f0 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -77,14 +77,26 @@ export { IConfigService } from './services/config/config.service';
export * from './services/context/context';
export { ContextService, IContextService } from './services/context/context.service';
export { ErrorService, type IError } from './services/error/error.service';
-export type { IOffset, IScale, ISize, ITransformState } from './services/floating-object/floating-object-interfaces';
+export type { IOffset, IScale, ISize, ITransformState, IRotationSkewFlipTransform, IAbsoluteTransform, ISrcRect } from './services/drawing/drawing-interfaces';
export {
DEFAULT_DOCUMENT_SUB_COMPONENT_ID,
- FloatingObjectManagerService,
- type IFloatingObjectManagerParam,
- type IFloatingObjectManagerSearchItemParam,
- IFloatingObjectManagerService,
-} from './services/floating-object/floating-object-manager.service';
+ type DrawingType,
+ DrawingTypeEnum,
+ type IDrawingSearch,
+ type IDrawingSpace,
+ type IDrawingParam,
+ IDrawingManagerService,
+ type IDrawingOrderUpdateParam,
+ type IUnitDrawingService,
+ type IDrawingMap,
+ type IDrawingSubunitMap,
+ type IDrawingOrderMapParam,
+ type IDrawingGroupUpdateParam,
+ type IDrawingVisibleParam,
+ type IDrawingMapItemData,
+ type IDrawingMapItem,
+ ArrangeTypeEnum,
+} from './services/drawing/drawing-manager.service';
export { IUniverInstanceService } from './services/instance/instance.service';
export { LifecycleStages, OnLifecycle, runOnLifecycle } from './services/lifecycle/lifecycle';
export { LifecycleService } from './services/lifecycle/lifecycle.service';
@@ -192,3 +204,4 @@ export { IAuthzIoService } from './services/authz-io/type';
export { createDefaultUser } from './services/user-manager/const';
installShims();
+
diff --git a/packages/core/src/observer/observable.ts b/packages/core/src/observer/observable.ts
index 472ddde744..fdbd21dcd6 100644
--- a/packages/core/src/observer/observable.ts
+++ b/packages/core/src/observer/observable.ts
@@ -305,6 +305,9 @@ export class Observable<T> {
* Clear the list of observers
*/
clear(): void {
+ this._observers.forEach((observer) => {
+ observer.dispose();
+ });
this._observers = new Array<Observer<T>>();
this._onObserverAdded = null;
}
diff --git a/packages/core/src/services/context/context.ts b/packages/core/src/services/context/context.ts
index 8a1014c2b0..39b2cc41e2 100644
--- a/packages/core/src/services/context/context.ts
+++ b/packages/core/src/services/context/context.ts
@@ -31,3 +31,8 @@ export const FOCUSING_UNIVER_EDITOR = 'FOCUSING_UNIVER_EDITOR';
export const FOCUSING_EDITOR_STANDALONE = 'FOCUSING_EDITOR_INPUT_FORMULA';
export const FOCUSING_UNIVER_EDITOR_STANDALONE_SINGLE_MODE = 'FOCUSING_UNIVER_EDITOR_STANDALONE_SINGLE_MODE';
+
+/**
+ * The focusing state of the common drawings.
+ */
+export const FOCUSING_COMMON_DRAWINGS = 'FOCUSING_COMMON_DRAWINGS';
diff --git a/packages/core/src/services/floating-object/floating-object-interfaces.ts b/packages/core/src/services/drawing/drawing-interfaces.ts
similarity index 75%
rename from packages/core/src/services/floating-object/floating-object-interfaces.ts
rename to packages/core/src/services/drawing/drawing-interfaces.ts
index 58cbaa7673..89309ed282 100644
--- a/packages/core/src/services/floating-object/floating-object-interfaces.ts
+++ b/packages/core/src/services/drawing/drawing-interfaces.ts
@@ -29,10 +29,23 @@ export interface IOffset {
top?: number;
}
-export interface ITransformState extends IOffset, ISize, IScale {
+export interface IRotationSkewFlipTransform {
angle?: number;
skewX?: number;
skewY?: number;
flipX?: boolean;
flipY?: boolean;
}
+
+export interface ISrcRect extends IOffset {
+ right?: number;
+ bottom?: number;
+}
+
+export interface IAbsoluteTransform extends ISize, IOffset, IScale {
+
+}
+
+export interface ITransformState extends IAbsoluteTransform, IRotationSkewFlipTransform {
+
+}
diff --git a/packages/core/src/services/drawing/drawing-manager.service.ts b/packages/core/src/services/drawing/drawing-manager.service.ts
new file mode 100644
index 0000000000..0d1c947a96
--- /dev/null
+++ b/packages/core/src/services/drawing/drawing-manager.service.ts
@@ -0,0 +1,199 @@
+/**
+ * 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 { IDisposable } from '@wendellhu/redi';
+import { createIdentifier } from '@wendellhu/redi';
+import type { Observable } from 'rxjs';
+import type { Nullable } from '../../common/type-util';
+import type { ITransformState } from './drawing-interfaces';
+
+export const DEFAULT_DOCUMENT_SUB_COMPONENT_ID = '__default_document_sub_component_id20231101__';
+
+export enum ArrangeTypeEnum {
+ forward,
+ backward,
+ front,
+ back,
+}
+
+export enum DrawingTypeEnum {
+ UNRECOGNIZED = -1,
+ DRAWING_IMAGE = 0,
+ DRAWING_SHAPE = 1,
+ DRAWING_CHART = 2,
+ DRAWING_TABLE = 3,
+ DRAWING_SMART_ART = 4,
+ DRAWING_VIDEO = 5,
+ DRAWING_GROUP = 6,
+ DRAWING_UNIT = 7,
+}
+
+export type DrawingType = DrawingTypeEnum | number;
+
+export interface IDrawingSpace {
+ unitId: string;
+ subUnitId: string; //sheetId, pageId and so on, it has a default name in doc business
+}
+
+export interface IDrawingSearch extends IDrawingSpace {
+ drawingId: string;
+}
+
+export interface IDrawingParam extends IDrawingSearch {
+ drawingType: DrawingType;
+ transform?: Nullable<ITransformState>;
+ groupId?: string;
+}
+
+export interface IDrawingMap<T extends IDrawingParam> {
+ [unitId: string]: IDrawingSubunitMap<T>;
+}
+
+export interface IDrawingSubunitMap<T extends IDrawingParam> {
+ [subUnitId: string]: IDrawingMapItem<T>;
+}
+
+export interface IDrawingMapItemData<T> {
+ [drawingId: string]: T;
+}
+export interface IDrawingMapItem<T extends IDrawingParam> {
+ data: IDrawingMapItemData<T>;
+ order: string[];
+}
+
+export interface IDrawingOrderMapParam {
+ unitId: string;
+ subUnitId: string;
+ drawingIds: string[];
+}
+
+export interface IDrawingOrderUpdateParam extends IDrawingOrderMapParam {
+ arrangeType: ArrangeTypeEnum;
+}
+
+export interface IDrawingGroupUpdateParam {
+ parent: IDrawingParam;
+ children: IDrawingParam[];
+}
+
+export interface IDrawingVisibleParam extends IDrawingSearch {
+ visible: boolean;
+}
+
+/**
+ * Responsible for operations related to drawing additions, deletions, and modifications,
+ * including observers, events, broadcasting, and generating operations.
+ */
+export interface IUnitNormalDrawingService<T extends IDrawingParam> {
+ readonly remove$: Observable<IDrawingSearch[]>;
+ readonly add$: Observable<IDrawingSearch[]>;
+ readonly update$: Observable<IDrawingSearch[]>;
+
+ readonly refreshTransform$: Observable<T[]>;
+ readonly visible$: Observable<IDrawingVisibleParam[]>;
+
+ readonly featurePluginUpdate$: Observable<T[]>;
+
+ refreshTransform(updateParams: T[]): void;
+
+ removeNotification(removeParams: IDrawingSearch[]): void;
+ addNotification(insertParams: IDrawingSearch[]): void;
+ updateNotification(updateParams: IDrawingSearch[]): void;
+
+ refreshTransformNotification(refreshParams: T[]): void;
+ visibleNotification(visibleParams: IDrawingVisibleParam[]): void;
+
+ getBatchAddOp(insertParams: T[]): unknown;
+ getBatchRemoveOp(removeParams: IDrawingSearch[]): unknown;
+ getBatchUpdateOp(updateParams: T[]): unknown;
+
+ featurePluginUpdateNotification(updateParams: T[]): void;
+}
+
+/**
+ * Responsible for operations related to drawing focus, including observers,broadcasting
+ */
+export interface IUnitFocusDrawingService {
+ readonly focus$: Observable<IDrawingParam[]>;
+
+ focusDrawing(params: Nullable<IDrawingSearch[]>): void;
+ getFocusDrawings(): IDrawingParam[];
+}
+
+/**
+ * Responsible for operations related to drawing grouping, including observers,broadcasting, and generating operations.
+ */
+export interface IUnitGroupDrawingService {
+ readonly group$: Observable<IDrawingGroupUpdateParam[]>;
+ readonly ungroup$: Observable<IDrawingGroupUpdateParam[]>;
+
+ readonly featurePluginGroupUpdate$: Observable<IDrawingGroupUpdateParam[]>;
+ readonly featurePluginUngroupUpdate$: Observable<IDrawingGroupUpdateParam[]>;
+
+ getGroupDrawingOp(groupParams: IDrawingGroupUpdateParam[]): unknown;
+ getUngroupDrawingOp(groupParams: IDrawingGroupUpdateParam[]): unknown;
+ groupUpdateNotification(groupParams: IDrawingGroupUpdateParam[]): void;
+ ungroupUpdateNotification(groupParams: IDrawingGroupUpdateParam[]): void;
+ getDrawingsByGroup(groupParam: IDrawingSearch): IDrawingParam[];
+
+ featurePluginGroupUpdateNotification(groupParams: IDrawingGroupUpdateParam[]): void;
+ featurePluginUngroupUpdateNotification(groupParams: IDrawingGroupUpdateParam[]): void;
+}
+
+/**
+ * Responsible for operations related to drawing order, including observers,broadcasting, and generating operations.
+ */
+export interface IUnitOrderDrawingService {
+
+ readonly order$: Observable<IDrawingOrderMapParam>;
+
+ readonly featurePluginOrderUpdate$: Observable<IDrawingOrderUpdateParam>;
+
+ orderNotification(orderParams: IDrawingOrderMapParam): void;
+
+ getForwardDrawingsOp(orderParams: IDrawingOrderMapParam): unknown;
+ getBackwardDrawingOp(orderParams: IDrawingOrderMapParam): unknown;
+ getFrontDrawingsOp(orderParams: IDrawingOrderMapParam): unknown;
+ getBackDrawingsOp(orderParams: IDrawingOrderMapParam): unknown;
+ // replaceDrawingOrder(unitId: string, subUnitId: string, drawingIds: string[]): void;
+ getDrawingOrder(unitId: string, subUnitId: string): string[];
+ orderUpdateNotification(orderParams: IDrawingOrderMapParam): void;
+
+ featurePluginOrderUpdateNotification(drawingOrderUpdateParam: IDrawingOrderUpdateParam): void;
+}
+
+export interface IUnitDrawingService<T extends IDrawingParam> extends IUnitNormalDrawingService<T>, IUnitFocusDrawingService, IUnitGroupDrawingService, IUnitOrderDrawingService, IDisposable {
+ drawingManagerData: IDrawingMap<T>;
+
+ dispose(): void;
+
+ getDrawingDataForUnit(unitId: string): IDrawingSubunitMap<T>;
+ removeDrawingDataForUnit(unitId: string): void;
+ registerDrawingData(unitId: string, data: IDrawingSubunitMap<T>): void;
+
+ getDrawingData(unitId: string, subUnitId: string): IDrawingMapItemData<T>;
+
+ getDrawingByParam(param: Nullable<IDrawingSearch>): Nullable<T>;
+ getOldDrawingByParam(param: Nullable<IDrawingSearch>): Nullable<T>;
+
+ getDrawingOKey(oKey: string): Nullable<T>;
+
+ applyJson1(unitId: string, subUnitId: string, jsonOp: unknown): void;
+}
+
+export interface IDrawingManagerService extends IUnitDrawingService<IDrawingParam> {}
+
+export const IDrawingManagerService = createIdentifier<IUnitDrawingService<IDrawingParam>>('univer.drawing-manager.service');
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.ts
deleted file mode 100644
index e0001927c4..0000000000
--- a/packages/core/src/services/floating-object/floating-object-manager.service.ts
+++ /dev/null
@@ -1,223 +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 { IDisposable } from '@wendellhu/redi';
-import { createIdentifier } from '@wendellhu/redi';
-import type { Observable } from 'rxjs';
-import { Subject } from 'rxjs';
-
-import type { Nullable } from '../../common/type-util';
-import type { ITransformState } from './floating-object-interfaces';
-
-export const DEFAULT_DOCUMENT_SUB_COMPONENT_ID = '__default_document_sub_component_id20231101__';
-
-export interface IFloatingObjectManagerSearchParam {
- unitId: string;
- subUnitId: string; //sheetId, pageId and so on, it has a default name in doc business
-}
-
-export interface IFloatingObjectManagerSearchItemParam extends IFloatingObjectManagerSearchParam {
- floatingObjectId: string;
-}
-
-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;
-}
-
-export type FloatingObjects = Map<string, ITransformState>;
-
-//{ [unitId: string]: { [sheetId: string]: ISelectionWithCoord[] } }
-export type IFloatingObjectManagerInfo = Map<string, Map<string, FloatingObjects>>;
-
-export interface IFloatingObjectManagerService {
- readonly remove$: Observable<IFloatingObjectManagerParam[]>;
-
- readonly andOrUpdate$: Observable<IFloatingObjectManagerParam[]>;
-
- readonly pluginUpdate$: Observable<IFloatingObjectManagerParam[]>;
-
- getFloatObject(searchItem: IFloatingObjectManagerSearchItemParam): Nullable<ITransformState>;
-
- getFloatObjects(search: IFloatingObjectManagerSearchParam): Nullable<FloatingObjects>;
-
- dispose(): void;
-
- clear(search: IFloatingObjectManagerSearchParam): void;
-
- addOrUpdate(insertParam: IFloatingObjectManagerParam): void;
-
- remove(searchItem: IFloatingObjectManagerSearchItemParam): void;
-
- batchAddOrUpdate(insertParam: IFloatingObjectManagerParam[]): void;
-
- pluginUpdateRefresh(searchObjects: IFloatingObjectManagerParam[]): void;
-}
-
-/**
- * This service is primarily used for the management of 'univer' floating objects,
- * decoupling common configurations such as position, volume,
- * and rotation of the floating objects from the core business.
- * This allows plugins to be reused across multiple core businesses.
- *
- * Floating elements in spreadsheets need to stay synchronized with the grid layout,
- * and inserting rows and columns will change their position;
- * Floating elements in documents need to stay synchronized with the text layout and can affect the text layout;
- * Floating elements in slides are more flexible but support settings such as animations.
- *
- * Please open the architecture diagram with TLDraw.
- * https://github.com/dream-num/univer/blob/db227563b4df65572dd4fceebecdbd9f27fa7a39/docs/selection%20architecture%20design.tldr
- */
-export class FloatingObjectManagerService implements IDisposable, IFloatingObjectManagerService {
- private readonly _managerInfo: IFloatingObjectManagerInfo = new Map();
-
- /**
- * The deletion action is triggered and broadcasted within the core business plugin.
- * Upon receiving the deletion broadcast, the plugin executes the plugin command logic.
- */
- private readonly _remove$ = new Subject<IFloatingObjectManagerParam[]>();
- readonly remove$ = this._remove$.asObservable();
-
- /**
- * Addition and updates are also triggered and broadcasted within the core business plugin.
- * Upon receiving the update broadcast, the plugin updates the location of its business components.
- */
- private readonly _andOrUpdate$ = new Subject<IFloatingObjectManagerParam[]>();
- readonly andOrUpdate$ = this._andOrUpdate$.asObservable();
-
- /**
- * The position, width, and height of the plugin's business components can be changed by the user through interface operations.
- * Here, it is necessary to notify the core business plugin to update the relevant location model.
- * The logic converges in the core business plugin.
- */
- private readonly _pluginUpdate$ = new Subject<IFloatingObjectManagerParam[]>();
- readonly pluginUpdate$ = this._pluginUpdate$.asObservable();
-
- getFloatObject(searchItem: IFloatingObjectManagerSearchItemParam): Nullable<ITransformState> {
- return this._getFloatingObject(searchItem);
- }
-
- getFloatObjects(search: IFloatingObjectManagerSearchParam): Nullable<FloatingObjects> {
- return this._getFloatingObjects(search);
- }
-
- dispose(): void {
- this._remove$.complete();
- this._andOrUpdate$.complete();
- this._pluginUpdate$.complete();
- this._managerInfo.clear();
- }
-
- clear(search: IFloatingObjectManagerSearchParam): void {
- const searchObjects = this._clearByParam(search);
- this._remove$.next(searchObjects);
- }
-
- addOrUpdate(insertParam: IFloatingObjectManagerParam): void {
- const searchObjects = this._addByParam(insertParam);
- this._andOrUpdate$.next(searchObjects);
- }
-
- batchAddOrUpdate(insertParams: IFloatingObjectManagerParam[]): void {
- const searchObjects: IFloatingObjectManagerParam[] = [];
- insertParams.forEach((insertParam) => {
- searchObjects.push(...this._addByParam(insertParam));
- });
- this._andOrUpdate$.next(searchObjects);
- }
-
- remove(searchItem: IFloatingObjectManagerSearchItemParam): void {
- const searchObjects = this._removeByParam(searchItem);
- this._remove$.next(searchObjects);
- }
-
- pluginUpdateRefresh(updateObjects: IFloatingObjectManagerParam[]) {
- this._pluginUpdate$.next(updateObjects);
- }
-
- private _getFloatingObjects(param: Nullable<IFloatingObjectManagerSearchParam>) {
- if (param == null) {
- return;
- }
- const { unitId, subUnitId } = param;
- return this._managerInfo.get(unitId)?.get(subUnitId);
- }
-
- private _getFloatingObject(param: Nullable<IFloatingObjectManagerSearchItemParam>) {
- if (param == null) {
- return;
- }
- const { unitId, subUnitId, floatingObjectId } = param;
- return this._managerInfo.get(unitId)?.get(subUnitId)?.get(floatingObjectId);
- }
-
- private _addByParam(insertParam: IFloatingObjectManagerParam): IFloatingObjectManagerParam[] {
- const { unitId, subUnitId, floatingObject, floatingObjectId, behindText } = insertParam;
-
- if (!this._managerInfo.has(unitId)) {
- this._managerInfo.set(unitId, new Map());
- }
-
- const subComponentData = this._managerInfo.get(unitId)!;
-
- if (!subComponentData.has(subUnitId)) {
- subComponentData.set(subUnitId, new Map());
- }
-
- subComponentData.get(subUnitId)!.set(floatingObjectId, floatingObject);
-
- return [{ unitId, subUnitId, floatingObjectId, floatingObject, behindText }];
- }
-
- private _clearByParam(param: IFloatingObjectManagerSearchParam): IFloatingObjectManagerParam[] {
- const floatingObjects = this._getFloatingObjects(param);
-
- const { unitId, subUnitId } = param;
-
- const refreshObjects: IFloatingObjectManagerParam[] = [];
-
- floatingObjects?.forEach((value, key) => {
- refreshObjects.push({
- unitId,
- subUnitId,
- floatingObjectId: key,
- floatingObject: value,
- });
- });
-
- floatingObjects?.clear();
-
- return refreshObjects;
- }
-
- private _removeByParam(param: IFloatingObjectManagerSearchItemParam): IFloatingObjectManagerParam[] {
- const floatingObjects = this._getFloatingObjects(param);
- const item = floatingObjects?.get(param.floatingObjectId);
-
- if (item == null) {
- return [];
- }
-
- floatingObjects?.delete(param.floatingObjectId);
-
- return [{ ...param, floatingObject: item }];
- }
-}
-
-export const IFloatingObjectManagerService = createIdentifier<IFloatingObjectManagerService>(
- 'univer.floating-object.service'
-);
diff --git a/packages/core/src/shared/check-if-move.ts b/packages/core/src/shared/check-if-move.ts
new file mode 100644
index 0000000000..f7bfc47f37
--- /dev/null
+++ b/packages/core/src/shared/check-if-move.ts
@@ -0,0 +1,39 @@
+/**
+ * Copyright 2023-present DreamNum Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { Nullable } from '../common/type-util';
+import type { ITransformState } from '../services/drawing/drawing-interfaces';
+
+export const MOVE_BUFFER_VALUE = 2;
+
+export const ROTATE_BUFFER_VALUE = 1;
+
+export function checkIfMove(transform: Nullable<ITransformState>, previousTransform: Nullable<ITransformState>): boolean {
+ if (previousTransform == null || transform == null) {
+ return true;
+ }
+
+ const { left: leftPrev = 0, top: topPrev = 0, height: heightPrev = 0, width: widthPrev = 0, angle: anglePrev = 0 } = previousTransform;
+ const { left = 0, top = 0, height = 0, width = 0, angle = 0 } = transform;
+
+ const allWidth = width;
+ const allHeight = height;
+
+ const allWidthPrev = widthPrev;
+ const allHeightPrev = heightPrev;
+
+ return Math.abs(left - leftPrev) > MOVE_BUFFER_VALUE || Math.abs(top - topPrev) > MOVE_BUFFER_VALUE || Math.abs(allWidth - allWidthPrev) > MOVE_BUFFER_VALUE || Math.abs(allHeight - allHeightPrev) > MOVE_BUFFER_VALUE || Math.abs(angle - anglePrev) > ROTATE_BUFFER_VALUE;
+}
diff --git a/packages/core/src/shared/index.ts b/packages/core/src/shared/index.ts
index aa386bc861..8e9e4f261e 100644
--- a/packages/core/src/shared/index.ts
+++ b/packages/core/src/shared/index.ts
@@ -14,6 +14,7 @@
* limitations under the License.
*/
+export { checkIfMove, MOVE_BUFFER_VALUE, ROTATE_BUFFER_VALUE } from './check-if-move';
export * from './array-search';
export * from './blob';
export * from './color/color';
diff --git a/packages/core/src/sheets/range.ts b/packages/core/src/sheets/range.ts
index 667e15b16f..889423f045 100644
--- a/packages/core/src/sheets/range.ts
+++ b/packages/core/src/sheets/range.ts
@@ -427,7 +427,7 @@ export class Range {
* Returns the font size in point size of the cell in the top-left corner of the range.
*/
getFontSize(): number {
- const { p } = this.getValue() ?? {};
+ const p = (this.getValue()?.p || {}) as IDocumentData;
if (p && Array.isArray(p.body?.textRuns) && p.body.textRuns.length > 0) {
if (p.body.textRuns.some((textRun) => textRun?.ts?.fs != null)) {
diff --git a/packages/core/src/types/enum/index.ts b/packages/core/src/types/enum/index.ts
index eebd4f3dc2..2278b84624 100644
--- a/packages/core/src/types/enum/index.ts
+++ b/packages/core/src/types/enum/index.ts
@@ -27,7 +27,7 @@ export * from './interpolation-point-type';
export * from './locale-type';
export * from './protection-type';
export * from './relative-date';
-export * from './shape-type';
export * from './sheet-types';
export * from './text-style';
export * from './theme-color-type';
+export * from './prst-geom-type';
diff --git a/packages/core/src/types/enum/prst-geom-type.ts b/packages/core/src/types/enum/prst-geom-type.ts
new file mode 100644
index 0000000000..0b706f0f4b
--- /dev/null
+++ b/packages/core/src/types/enum/prst-geom-type.ts
@@ -0,0 +1,124 @@
+/**
+ * Copyright 2023-present DreamNum Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+export enum BasicShapes {
+ Line = 'line',
+ LineInv = 'lineInv',
+ Triangle = 'triangle',
+ RtTriangle = 'rtTriangle',
+ Rect = 'rect',
+ Diamond = 'diamond',
+ Parallelogram = 'parallelogram',
+ Trapezoid = 'trapezoid',
+ NonIsocelesTrapezoid = 'nonIsocelesTrapezoid',
+ Pentagon = 'pentagon',
+ Hexagon = 'hexagon',
+ Heptagon = 'heptagon',
+ Octagon = 'octagon',
+ Decagon = 'decagon',
+ Dodecagon = 'dodecagon',
+ Star4 = 'star4',
+ Star5 = 'star5',
+ Star6 = 'star6',
+ Star7 = 'star7',
+ Star8 = 'star8',
+ Star10 = 'star10',
+ Star12 = 'star12',
+ Star16 = 'star16',
+ Star24 = 'star24',
+ Star32 = 'star32',
+ RoundRect = 'roundRect',
+ Round1Rect = 'round1Rect',
+ Round2SameRect = 'round2SameRect',
+ Round2DiagRect = 'round2DiagRect',
+ Ellipse = 'ellipse',
+}
+
+export enum ArrowsAndMarkersShapes {
+ RightArrow = 'rightArrow',
+ LeftArrow = 'leftArrow',
+ UpArrow = 'upArrow',
+ DownArrow = 'downArrow',
+ LeftRightArrow = 'leftRightArrow',
+ UpDownArrow = 'upDownArrow',
+ QuadArrow = 'quadArrow',
+ LeftRightUpArrow = 'leftRightUpArrow',
+ BentArrow = 'bentArrow',
+ UturnArrow = 'uturnArrow',
+ CircularArrow = 'circularArrow',
+ NotchedRightArrow = 'notchedRightArrow',
+ HomePlate = 'homePlate',
+ Chevron = 'chevron',
+ LeftCircularArrow = 'leftCircularArrow',
+ LeftRightCircularArrow = 'leftRightCircularArrow',
+}
+
+export enum OtherShapes {
+ Plaque = 'plaque',
+ Can = 'can',
+ Cube = 'cube',
+ Bevel = 'bevel',
+ Donut = 'donut',
+ NoSmoking = 'noSmoking',
+ BlockArc = 'blockArc',
+ FoldedCorner = 'foldedCorner',
+}
+
+export enum SpecialShapes {
+ SmileyFace = 'smileyFace',
+ Heart = 'heart',
+ LightningBolt = 'lightningBolt',
+ Sun = 'sun',
+ Moon = 'moon',
+ Cloud = 'cloud',
+ Arc = 'arc',
+ Backpack = 'backpack',
+ Frame = 'frame',
+ HalfFrame = 'halfFrame',
+ Corner = 'corner',
+ Chord = 'chord',
+ Pie = 'pie',
+ Teardrop = 'teardrop',
+ WedgeRectCallout = 'wedgeRectCallout',
+ WedgeRRectCallout = 'wedgeRRectCallout',
+ WedgeEllipseCallout = 'wedgeEllipseCallout',
+ CloudCallout = 'cloudCallout',
+ BorderCallout1 = 'borderCallout1',
+ BorderCallout2 = 'borderCallout2',
+ BorderCallout3 = 'borderCallout3',
+ AccentCallout1 = 'accentCallout1',
+ AccentCallout2 = 'accentCallout2',
+ AccentCallout3 = 'accentCallout3',
+ Callout1 = 'callout1',
+ Callout2 = 'callout2',
+ Callout3 = 'callout3',
+ ActionButtonBackPrevious = 'actionButtonBackPrevious',
+ ActionButtonEnd = 'actionButtonEnd',
+ ActionButtonForwardNext = 'actionButtonForwardNext',
+ ActionButtonHelp = 'actionButtonHelp',
+ ActionButtonHome = 'actionButtonHome',
+ ActionButtonInformation = 'actionButtonInformation',
+ ActionButtonMovie = 'actionButtonMovie',
+ ActionButtonReturn = 'actionButtonReturn',
+ ActionButtonSound = 'actionButtonSound',
+}
+
+/**
+ * 20.1.9.18 prstGeom (Preset geometry)
+ */
+export type ShapeType = BasicShapes | ArrowsAndMarkersShapes | OtherShapes | SpecialShapes;
+export type PresetGeometryType = ShapeType | 'custom';
+
diff --git a/packages/core/src/types/enum/shape-type.ts b/packages/core/src/types/enum/shape-type.ts
deleted file mode 100644
index 6b1e69ff90..0000000000
--- a/packages/core/src/types/enum/shape-type.ts
+++ /dev/null
@@ -1,161 +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.
- */
-
-export enum ShapeType {
- TYPE_UNSPECIFIED, //The shape type that is not predefined.
- TEXT_BOX, //Text box shape.
- RECTANGLE, //Rectangle shape. Corresponds to ECMA-376 ST_ShapeType 'rect'.
- ROUND_RECTANGLE, //Round corner rectangle shape. Corresponds to ECMA-376 ST_ShapeType 'roundRect'
- ELLIPSE, //Ellipse shape. Corresponds to ECMA-376 ST_ShapeType 'ellipse'
- ARC, //Curved arc shape. Corresponds to ECMA-376 ST_ShapeType 'arc'
- BENT_ARROW, //Bent arrow shape. Corresponds to ECMA-376 ST_ShapeType 'bentArrow'
- BENT_UP_ARROW, //Bent up arrow shape. Corresponds to ECMA-376 ST_ShapeType 'bentUpArrow'
- BEVEL, //Bevel shape. Corresponds to ECMA-376 ST_ShapeType 'bevel'
- BLOCK_ARC, //Block arc shape. Corresponds to ECMA-376 ST_ShapeType 'blockArc'
- BRACE_PAIR, //Brace pair shape. Corresponds to ECMA-376 ST_ShapeType 'bracePair'
- BRACKET_PAIR, //Bracket pair shape. Corresponds to ECMA-376 ST_ShapeType 'bracketPair'
- CAN, //Can shape. Corresponds to ECMA-376 ST_ShapeType 'can'
- CHEVRON, //Chevron shape. Corresponds to ECMA-376 ST_ShapeType 'chevron'
- CHORD, //Chord shape. Corresponds to ECMA-376 ST_ShapeType 'chord'
- CLOUD, //Cloud shape. Corresponds to ECMA-376 ST_ShapeType 'cloud'
- CORNER, //Corner shape. Corresponds to ECMA-376 ST_ShapeType 'corner'
- CUBE, //Cube shape. Corresponds to ECMA-376 ST_ShapeType 'cube'
- CURVED_DOWN_ARROW, //Curved down arrow shape. Corresponds to ECMA-376 ST_ShapeType 'curvedDownArrow'
- CURVED_LEFT_ARROW, //Curved left arrow shape. Corresponds to ECMA-376 ST_ShapeType 'curvedLeftArrow'
- CURVED_RIGHT_ARROW, //Curved right arrow shape. Corresponds to ECMA-376 ST_ShapeType 'curvedRightArrow'
- CURVED_UP_ARROW, //Curved up arrow shape. Corresponds to ECMA-376 ST_ShapeType 'curvedUpArrow'
- DECAGON, //Decagon shape. Corresponds to ECMA-376 ST_ShapeType 'decagon'
- DIAGONAL_STRIPE, //Diagonal stripe shape. Corresponds to ECMA-376 ST_ShapeType 'diagStripe'
- DIAMOND, //Diamond shape. Corresponds to ECMA-376 ST_ShapeType 'diamond'
- DODECAGON, //Dodecagon shape. Corresponds to ECMA-376 ST_ShapeType 'dodecagon'
- DONUT, //Donut shape. Corresponds to ECMA-376 ST_ShapeType 'donut'
- DOUBLE_WAVE, //Double wave shape. Corresponds to ECMA-376 ST_ShapeType 'doubleWave'
- DOWN_ARROW, //Down arrow shape. Corresponds to ECMA-376 ST_ShapeType 'downArrow'
- DOWN_ARROW_CALLOUT, //Callout down arrow shape. Corresponds to ECMA-376 ST_ShapeType 'downArrowCallout'
- FOLDED_CORNER, //Folded corner shape. Corresponds to ECMA-376 ST_ShapeType 'foldedCorner'
- FRAME, //Frame shape. Corresponds to ECMA-376 ST_ShapeType 'frame'
- HALF_FRAME, //Half frame shape. Corresponds to ECMA-376 ST_ShapeType 'halfFrame'
- HEART, //Heart shape. Corresponds to ECMA-376 ST_ShapeType 'heart'
- HEPTAGON, //Heptagon shape. Corresponds to ECMA-376 ST_ShapeType 'heptagon'
- HEXAGON, //Hexagon shape. Corresponds to ECMA-376 ST_ShapeType 'hexagon'
- HOME_PLATE, //Home plate shape. Corresponds to ECMA-376 ST_ShapeType 'homePlate'
- HORIZONTAL_SCROLL, //Horizontal scroll shape. Corresponds to ECMA-376 ST_ShapeType 'horizontalScroll'
- IRREGULAR_SEAL_1, //Irregular seal 1 shape. Corresponds to ECMA-376 ST_ShapeType 'irregularSeal1'
- IRREGULAR_SEAL_2, //Irregular seal 2 shape. Corresponds to ECMA-376 ST_ShapeType 'irregularSeal2'
- LEFT_ARROW, //Left arrow shape. Corresponds to ECMA-376 ST_ShapeType 'leftArrow'
- LEFT_ARROW_CALLOUT, //Callout left arrow shape. Corresponds to ECMA-376 ST_ShapeType 'leftArrowCallout'
- LEFT_BRACE, //Left brace shape. Corresponds to ECMA-376 ST_ShapeType 'leftBrace'
- LEFT_BRACKET, //Left bracket shape. Corresponds to ECMA-376 ST_ShapeType 'leftBracket'
- LEFT_RIGHT_ARROW, //Left right arrow shape. Corresponds to ECMA-376 ST_ShapeType 'leftRightArrow'
- LEFT_RIGHT_ARROW_CALLOUT, //Callout left right arrow shape. Corresponds to ECMA-376 ST_ShapeType 'leftRightArrowCallout'
- LEFT_RIGHT_UP_ARROW, //Left right up arrow shape. Corresponds to ECMA-376 ST_ShapeType 'leftRightUpArrow'
- LEFT_UP_ARROW, //Left up arrow shape. Corresponds to ECMA-376 ST_ShapeType 'leftUpArrow'
- LIGHTNING_BOLT, //Lightning bolt shape. Corresponds to ECMA-376 ST_ShapeType 'lightningBolt'
- MATH_DIVIDE, //Divide math shape. Corresponds to ECMA-376 ST_ShapeType 'mathDivide'
- MATH_EQUAL, //Equal math shape. Corresponds to ECMA-376 ST_ShapeType 'mathEqual'
- MATH_MINUS, //Minus math shape. Corresponds to ECMA-376 ST_ShapeType 'mathMinus'
- MATH_MULTIPLY, //Multiply math shape. Corresponds to ECMA-376 ST_ShapeType 'mathMultiply'
- MATH_NOT_EQUAL, //Not equal math shape. Corresponds to ECMA-376 ST_ShapeType 'mathNotEqual'
- MATH_PLUS, //Plus math shape. Corresponds to ECMA-376 ST_ShapeType 'mathPlus'
- MOON, //Moon shape. Corresponds to ECMA-376 ST_ShapeType 'moon'
- NO_SMOKING, //No smoking shape. Corresponds to ECMA-376 ST_ShapeType 'noSmoking'
- NOTCHED_RIGHT_ARROW, //Notched right arrow shape. Corresponds to ECMA-376 ST_ShapeType 'notchedRightArrow'
- OCTAGON, //Octagon shape. Corresponds to ECMA-376 ST_ShapeType 'octagon'
- PARALLELOGRAM, //Parallelogram shape. Corresponds to ECMA-376 ST_ShapeType 'parallelogram'
- PENTAGON, //Pentagon shape. Corresponds to ECMA-376 ST_ShapeType 'pentagon'
- PIE, //Pie shape. Corresponds to ECMA-376 ST_ShapeType 'pie'
- PLAQUE, //Plaque shape. Corresponds to ECMA-376 ST_ShapeType 'plaque'
- PLUS, //Plus shape. Corresponds to ECMA-376 ST_ShapeType 'plus'
- QUAD_ARROW, //Quad-arrow shape. Corresponds to ECMA-376 ST_ShapeType 'quadArrow'
- QUAD_ARROW_CALLOUT, //Callout quad-arrow shape. Corresponds to ECMA-376 ST_ShapeType 'quadArrowCallout'
- RIBBON, //Ribbon shape. Corresponds to ECMA-376 ST_ShapeType 'ribbon'
- RIBBON_2, //Ribbon 2 shape. Corresponds to ECMA-376 ST_ShapeType 'ribbon2'
- RIGHT_ARROW, //Right arrow shape. Corresponds to ECMA-376 ST_ShapeType 'rightArrow'
- RIGHT_ARROW_CALLOUT, //Callout right arrow shape. Corresponds to ECMA-376 ST_ShapeType 'rightArrowCallout'
- RIGHT_BRACE, //Right brace shape. Corresponds to ECMA-376 ST_ShapeType 'rightBrace'
- RIGHT_BRACKET, //Right bracket shape. Corresponds to ECMA-376 ST_ShapeType 'rightBracket'
- ROUND_1_RECTANGLE, //One round corner rectangle shape. Corresponds to ECMA-376 ST_ShapeType 'round1Rect'
- ROUND_2_DIAGONAL_RECTANGLE, //Two diagonal round corner rectangle shape. Corresponds to ECMA-376 ST_ShapeType 'round2DiagRect'
- ROUND_2_SAME_RECTANGLE, //Two same-side round corner rectangle shape. Corresponds to ECMA-376 ST_ShapeType 'round2SameRect'
- RIGHT_TRIANGLE, //Right triangle shape. Corresponds to ECMA-376 ST_ShapeType 'rtTriangle'
- SMILEY_FACE, //Smiley face shape. Corresponds to ECMA-376 ST_ShapeType 'smileyFace'
- SNIP_1_RECTANGLE, //One snip corner rectangle shape. Corresponds to ECMA-376 ST_ShapeType 'snip1Rect'
- SNIP_2_DIAGONAL_RECTANGLE, //Two diagonal snip corner rectangle shape. Corresponds to ECMA-376 ST_ShapeType 'snip2DiagRect'
- SNIP_2_SAME_RECTANGLE, //Two same-side snip corner rectangle shape. Corresponds to ECMA-376 ST_ShapeType 'snip2SameRect'
- SNIP_ROUND_RECTANGLE, //One snip one round corner rectangle shape. Corresponds to ECMA-376 ST_ShapeType 'snipRoundRect'
- STAR_10, //Ten pointed star shape. Corresponds to ECMA-376 ST_ShapeType 'star10'
- STAR_12, //Twelve pointed star shape. Corresponds to ECMA-376 ST_ShapeType 'star12'
- STAR_16, //Sixteen pointed star shape. Corresponds to ECMA-376 ST_ShapeType 'star16'
- STAR_24, //Twenty four pointed star shape. Corresponds to ECMA-376 ST_ShapeType 'star24'
- STAR_32, //Thirty two pointed star shape. Corresponds to ECMA-376 ST_ShapeType 'star32'
- STAR_4, //Four pointed star shape. Corresponds to ECMA-376 ST_ShapeType 'star4'
- STAR_5, //Five pointed star shape. Corresponds to ECMA-376 ST_ShapeType 'star5'
- STAR_6, //Six pointed star shape. Corresponds to ECMA-376 ST_ShapeType 'star6'
- STAR_7, //Seven pointed star shape. Corresponds to ECMA-376 ST_ShapeType 'star7'
- STAR_8, //Eight pointed star shape. Corresponds to ECMA-376 ST_ShapeType 'star8'
- STRIPED_RIGHT_ARROW, //Striped right arrow shape. Corresponds to ECMA-376 ST_ShapeType 'stripedRightArrow'
- SUN, //Sun shape. Corresponds to ECMA-376 ST_ShapeType 'sun'
- TRAPEZOID, //Trapezoid shape. Corresponds to ECMA-376 ST_ShapeType 'trapezoid'
- TRIANGLE, //Triangle shape. Corresponds to ECMA-376 ST_ShapeType 'triangle'
- UP_ARROW, //Up arrow shape. Corresponds to ECMA-376 ST_ShapeType 'upArrow'
- UP_ARROW_CALLOUT, //Callout up arrow shape. Corresponds to ECMA-376 ST_ShapeType 'upArrowCallout'
- UP_DOWN_ARROW, //Up down arrow shape. Corresponds to ECMA-376 ST_ShapeType 'upDownArrow'
- UTURN_ARROW, //U-turn arrow shape. Corresponds to ECMA-376 ST_ShapeType 'uturnArrow'
- VERTICAL_SCROLL, //Vertical scroll shape. Corresponds to ECMA-376 ST_ShapeType 'verticalScroll'
- WAVE, //Wave shape. Corresponds to ECMA-376 ST_ShapeType 'wave'
- WEDGE_ELLIPSE_CALLOUT, //Callout wedge ellipse shape. Corresponds to ECMA-376 ST_ShapeType 'wedgeEllipseCallout'
- WEDGE_RECTANGLE_CALLOUT, //Callout wedge rectangle shape. Corresponds to ECMA-376 ST_ShapeType 'wedgeRectCallout'
- WEDGE_ROUND_RECTANGLE_CALLOUT, //Callout wedge round rectangle shape. Corresponds to ECMA-376 ST_ShapeType 'wedgeRoundRectCallout'
- FLOW_CHART_ALTERNATE_PROCESS, //Alternate process flow shape. Corresponds to ECMA-376 ST_ShapeType 'flowChartAlternateProcess'
- FLOW_CHART_COLLATE, //Collate flow shape. Corresponds to ECMA-376 ST_ShapeType 'flowChartCollate'
- FLOW_CHART_CONNECTOR, //Connector flow shape. Corresponds to ECMA-376 ST_ShapeType 'flowChartConnector'
- FLOW_CHART_DECISION, //Decision flow shape. Corresponds to ECMA-376 ST_ShapeType 'flowChartDecision'
- FLOW_CHART_DELAY, //Delay flow shape. Corresponds to ECMA-376 ST_ShapeType 'flowChartDelay'
- FLOW_CHART_DISPLAY, //Display flow shape. Corresponds to ECMA-376 ST_ShapeType 'flowChartDisplay'
- FLOW_CHART_DOCUMENT, //Document flow shape. Corresponds to ECMA-376 ST_ShapeType 'flowChartDocument'
- FLOW_CHART_EXTRACT, //Extract flow shape. Corresponds to ECMA-376 ST_ShapeType 'flowChartExtract'
- FLOW_CHART_INPUT_OUTPUT, //Input output flow shape. Corresponds to ECMA-376 ST_ShapeType 'flowChartInputOutput'
- FLOW_CHART_INTERNAL_STORAGE, //Internal storage flow shape. Corresponds to ECMA-376 ST_ShapeType 'flowChartInternalStorage'
- FLOW_CHART_MAGNETIC_DISK, //Magnetic disk flow shape. Corresponds to ECMA-376 ST_ShapeType 'flowChartMagneticDisk'
- FLOW_CHART_MAGNETIC_DRUM, //Magnetic drum flow shape. Corresponds to ECMA-376 ST_ShapeType 'flowChartMagneticDrum'
- FLOW_CHART_MAGNETIC_TAPE, //Magnetic tape flow shape. Corresponds to ECMA-376 ST_ShapeType 'flowChartMagneticTape'
- FLOW_CHART_MANUAL_INPUT, //Manual input flow shape. Corresponds to ECMA-376 ST_ShapeType 'flowChartManualInput'
- FLOW_CHART_MANUAL_OPERATION, //Manual operation flow shape. Corresponds to ECMA-376 ST_ShapeType 'flowChartManualOperation'
- FLOW_CHART_MERGE, //Merge flow shape. Corresponds to ECMA-376 ST_ShapeType 'flowChartMerge'
- FLOW_CHART_MULTIDOCUMENT, //Multi-document flow shape. Corresponds to ECMA-376 ST_ShapeType 'flowChartMultidocument'
- FLOW_CHART_OFFLINE_STORAGE, //Offline storage flow shape. Corresponds to ECMA-376 ST_ShapeType 'flowChartOfflineStorage'
- FLOW_CHART_OFFPAGE_CONNECTOR, //Off-page connector flow shape. Corresponds to ECMA-376 ST_ShapeType 'flowChartOffpageConnector'
- FLOW_CHART_ONLINE_STORAGE, //Online storage flow shape. Corresponds to ECMA-376 ST_ShapeType 'flowChartOnlineStorage'
- FLOW_CHART_OR, //Or flow shape. Corresponds to ECMA-376 ST_ShapeType 'flowChartOr'
- FLOW_CHART_PREDEFINED_PROCESS, //Predefined process flow shape. Corresponds to ECMA-376 ST_ShapeType 'flowChartPredefinedProcess'
- FLOW_CHART_PREPARATION, //Preparation flow shape. Corresponds to ECMA-376 ST_ShapeType 'flowChartPreparation'
- FLOW_CHART_PROCESS, //Process flow shape. Corresponds to ECMA-376 ST_ShapeType 'flowChartProcess'
- FLOW_CHART_PUNCHED_CARD, //Punched card flow shape. Corresponds to ECMA-376 ST_ShapeType 'flowChartPunchedCard'
- FLOW_CHART_PUNCHED_TAPE, //Punched tape flow shape. Corresponds to ECMA-376 ST_ShapeType 'flowChartPunchedTape'
- FLOW_CHART_SORT, //Sort flow shape. Corresponds to ECMA-376 ST_ShapeType 'flowChartSort'
- FLOW_CHART_SUMMING_JUNCTION, //Summing junction flow shape. Corresponds to ECMA-376 ST_ShapeType 'flowChartSummingJunction'
- FLOW_CHART_TERMINATOR, //Terminator flow shape. Corresponds to ECMA-376 ST_ShapeType 'flowChartTerminator'
- ARROW_EAST, //East arrow shape.
- ARROW_NORTH_EAST, //Northeast arrow shape.
- ARROW_NORTH, //North arrow shape.
- SPEECH, //Speech shape.
- STARBURST, //Star burst shape.
- TEARDROP, //Teardrop shape. Corresponds to ECMA-376 ST_ShapeType 'teardrop'
- ELLIPSE_RIBBON, //Ellipse ribbon shape. Corresponds to ECMA-376 ST_ShapeType 'ellipseRibbon'
- ELLIPSE_RIBBON_2, //Ellipse ribbon 2 shape. Corresponds to ECMA-376 ST_ShapeType 'ellipseRibbon2'
- CLOUD_CALLOUT, //Callout cloud shape. Corresponds to ECMA-376 ST_ShapeType 'cloudCallout'
- CUSTOM, //Custom shape.
-}
diff --git a/packages/core/src/types/interfaces/i-document-data.ts b/packages/core/src/types/interfaces/i-document-data.ts
index 7819be05bd..938a52f309 100644
--- a/packages/core/src/types/interfaces/i-document-data.ts
+++ b/packages/core/src/types/interfaces/i-document-data.ts
@@ -14,7 +14,8 @@
* limitations under the License.
*/
-import type { ISize } from '../../services/floating-object/floating-object-interfaces';
+import type { ISize } from '../../services/drawing/drawing-interfaces';
+import type { IDrawingParam } from '../../services/drawing/drawing-manager.service';
import type { BooleanNumber, CellValueType, HorizontalAlign, LocaleType, TextDirection, VerticalAlign, WrapStrategy } from '../enum';
import type { IExtraModelData } from './i-extra-model-data';
import type { IColorStyle, IStyleBase } from './i-style-data';
@@ -43,6 +44,7 @@ export interface IReferenceSource {
headers?: IHeaders;
lists?: ILists;
drawings?: IDrawings;
+ drawingsOrder?: string[];
}
export interface IDocumentSettings {
@@ -74,7 +76,7 @@ export interface ILists {
* Set of Drawings
*/
export interface IDrawings {
- [objectId: string]: IDrawing;
+ [drawingId: string]: IDocDrawingBase;
}
/**
@@ -436,7 +438,7 @@ export interface IParagraph {
startIndex: number;
paragraphStyle?: IParagraphStyle; // paragraphStyle
bullet?: IBullet; // bullet
- // dIds?: string[]; // drawingIds objectId
+ // dIds?: string[]; // drawingIds drawingId
}
// export interface IElementsOrder {
@@ -507,8 +509,8 @@ export interface IBullet {
* 20.4.2.19 wrapTight (Tight Wrapping)
* 20.4.2.20 wrapTopAndBottom (Top and Bottom Wrapping)
*/
-export interface IDrawing {
- objectId: string;
+export interface IDocDrawingBase extends IDrawingParam {
+ drawingId: string;
title: string;
@@ -516,7 +518,7 @@ export interface IDrawing {
// embeddedObjectBorder?: IDocsBorder;
- objectTransform: IObjectTransform;
+ docTransform: IDocDrawingPosition;
layoutType: PositionedObjectLayoutType;
@@ -556,7 +558,7 @@ export enum PositionedObjectLayoutType {
/**
* Properties of a draw object
*/
-export interface IObjectTransform {
+export interface IDocDrawingPosition {
size: ISize;
positionH: IObjectPositionH;
positionV: IObjectPositionV;
diff --git a/packages/core/src/types/interfaces/i-image-io-service.ts b/packages/core/src/types/interfaces/i-image-io-service.ts
new file mode 100644
index 0000000000..507f2378fc
--- /dev/null
+++ b/packages/core/src/types/interfaces/i-image-io-service.ts
@@ -0,0 +1,55 @@
+/**
+ * Copyright 2023-present DreamNum Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { createIdentifier } from '@wendellhu/redi';
+import type { Observable } from 'rxjs';
+import type { Nullable } from '../../shared';
+
+export enum ImageSourceType {
+ URL = 'URL',
+ UUID = 'UUID',
+ BASE64 = 'BASE64',
+}
+
+export enum ImageUploadStatusType {
+ SUCCUSS = '0',
+ ERROR_EXCEED_SIZE = '1',
+ ERROR_IMAGE_TYPE = '2',
+ ERROR_UPLOAD_COUNT_LIMIT = '3',
+ ERROR_IMAGE = '4',
+}
+
+export interface IImageIoServiceParam {
+ imageId: string;
+ imageSourceType: ImageSourceType;
+ source: string;
+ base64Cache: string;
+ status: ImageUploadStatusType;
+}
+
+export interface IImageIoService {
+ change$: Observable<number>;
+ setWaitCount(count: number): void;
+
+ getImage(imageId: string): Promise<string>;
+
+ saveImage(imageFile: File): Promise<Nullable<IImageIoServiceParam>>;
+
+ getImageSourceCache(source: string, imageSourceType: ImageSourceType): Nullable<HTMLImageElement>;
+ addImageSourceCache(source: string, imageSourceType: ImageSourceType, imageSource: Nullable<HTMLImageElement>): void;
+}
+
+export const IImageIoService = createIdentifier<IImageIoService>('core.image-io.service');
diff --git a/packages/core/src/types/interfaces/i-slide-data.ts b/packages/core/src/types/interfaces/i-slide-data.ts
index 64b9d02f2a..9b5009a495 100644
--- a/packages/core/src/types/interfaces/i-slide-data.ts
+++ b/packages/core/src/types/interfaces/i-slide-data.ts
@@ -14,10 +14,10 @@
* limitations under the License.
*/
-import type { ISize, ITransformState } from '../../services/floating-object/floating-object-interfaces';
+import type { ISize, ITransformState } from '../../services/drawing/drawing-interfaces';
import type { IKeyType, Nullable } from '../../shared/types';
import type { LocaleType, ThemeColorType } from '../enum';
-import type { ShapeType } from '../enum/shape-type';
+import type { ShapeType } from '../enum/prst-geom-type';
import type { ICustomBlock, IDocumentData, ILists } from './i-document-data';
import type { IExtraModelData } from './i-extra-model-data';
import type { IImageProperties } from './i-image-properties';
diff --git a/packages/core/src/types/interfaces/index.ts b/packages/core/src/types/interfaces/index.ts
index 95ced0c1c7..655ab8b08a 100644
--- a/packages/core/src/types/interfaces/index.ts
+++ b/packages/core/src/types/interfaces/index.ts
@@ -31,3 +31,4 @@ export * from './i-univer-data';
export * from './i-workbook-data';
export * from './i-worksheet-data';
export * from './i-worksheet-order-data';
+export * from './i-image-io-service';
diff --git a/packages/core/src/univer.ts b/packages/core/src/univer.ts
index 210ab46dbe..d677f63fac 100644
--- a/packages/core/src/univer.ts
+++ b/packages/core/src/univer.ts
@@ -22,10 +22,6 @@ import { CommandService, ICommandService } from './services/command/command.serv
import { ConfigService, IConfigService } from './services/config/config.service';
import { ContextService, IContextService } from './services/context/context.service';
import { ErrorService } from './services/error/error.service';
-import {
- FloatingObjectManagerService,
- IFloatingObjectManagerService,
-} from './services/floating-object/floating-object-manager.service';
import { IUniverInstanceService, UniverInstanceService } from './services/instance/instance.service';
import { LifecycleStages } from './services/lifecycle/lifecycle';
import { LifecycleInitializerService, LifecycleService } from './services/lifecycle/lifecycle.service';
@@ -182,7 +178,6 @@ function createUniverInjector(parentInjector?: Injector, override?: DependencyOv
[IUndoRedoService, { useClass: LocalUndoRedoService, lazy: true }],
[IConfigService, { useClass: ConfigService }],
[IContextService, { useClass: ContextService }],
- [IFloatingObjectManagerService, { useClass: FloatingObjectManagerService, lazy: true }],
[IResourceManagerService, { useClass: ResourceManagerService, lazy: true }],
[IResourceLoaderService, { useClass: ResourceLoaderService, lazy: true }],
[IAuthzIoService, { useClass: AuthzIoLocalService, lazy: true }],
diff --git a/packages/docs-drawing-ui/README.md b/packages/docs-drawing-ui/README.md
new file mode 100644
index 0000000000..46711e8350
--- /dev/null
+++ b/packages/docs-drawing-ui/README.md
@@ -0,0 +1,16 @@
+# @univerjs/docs-drawing-ui
+
+[![npm version](https://img.shields.io/npm/v/@univerjs/docs-drawing-ui)](https://npmjs.org/packages/@univerjs/docs-drawing-ui)
+[![license](https://img.shields.io/npm/l/@univerjs/docs-drawing-ui)](https://img.shields.io/npm/l/@univerjs/docs-drawing-ui)
+
+## Introduction
+
+> TODO: Introduction
+
+## Usage
+
+### Installation
+
+```shell
+npm i @univerjs/docs-drawing-ui
+```
diff --git a/packages/docs-drawing-ui/package.json b/packages/docs-drawing-ui/package.json
new file mode 100644
index 0000000000..590c7f085e
--- /dev/null
+++ b/packages/docs-drawing-ui/package.json
@@ -0,0 +1,99 @@
+{
+ "name": "@univerjs/docs-drawing-ui",
+ "version": "0.0.1",
+ "private": true,
+ "description": "",
+ "author": "DreamNum <[email protected]>",
+ "license": "Apache-2.0",
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/univer"
+ },
+ "homepage": "https://univer.ai",
+ "repository": {
+ "type": "git",
+ "url": "https://github.com/dream-num/univer"
+ },
+ "bugs": {
+ "url": "https://github.com/dream-num/univer/issues"
+ },
+ "keywords": [],
+ "sideEffects": [
+ "**/*.css"
+ ],
+ "exports": {
+ ".": "./src/index.ts",
+ "./*": "./src/*",
+ "./locale/*": "./src/locale/*.ts"
+ },
+ "main": "./lib/cjs/index.js",
+ "module": "./lib/es/index.js",
+ "types": "./lib/types/index.d.ts",
+ "publishConfig": {
+ "access": "public",
+ "main": "./lib/cjs/index.js",
+ "module": "./lib/es/index.js",
+ "exports": {
+ ".": {
+ "import": "./lib/es/index.js",
+ "require": "./lib/cjs/index.js",
+ "types": "./lib/types/index.d.ts"
+ },
+ "./*": {
+ "import": "./lib/es/*",
+ "require": "./lib/cjs/*",
+ "types": "./lib/types/index.d.ts"
+ },
+ "./locale/*": "./lib/locale/*.json",
+ "./lib/*": "./lib/*"
+ }
+ },
+ "directories": {
+ "lib": "lib"
+ },
+ "files": [
+ "lib"
+ ],
+ "engines": {
+ "node": ">=16.0.0",
+ "npm": ">=8.0.0"
+ },
+ "scripts": {
+ "test": "vitest run",
+ "test:watch": "vitest",
+ "coverage": "vitest run --coverage",
+ "lint:types": "tsc --noEmit",
+ "build": "tsc && vite build"
+ },
+ "peerDependencies": {
+ "@univerjs/core": "workspace:*",
+ "@univerjs/design": "workspace:*",
+ "@univerjs/ui": "workspace:*",
+ "@wendellhu/redi": ">=0.12.13",
+ "clsx": ">=2.0.0",
+ "react": ">=16.9.0",
+ "rxjs": ">=7.0.0"
+ },
+ "dependencies": {
+ "@univerjs/icons": "^0.1.46"
+ },
+ "devDependencies": {
+ "@univerjs/core": "workspace:*",
+ "@univerjs/design": "workspace:*",
+ "@univerjs/docs": "workspace:*",
+ "@univerjs/docs-ui": "workspace:*",
+ "@univerjs/drawing": "workspace:*",
+ "@univerjs/drawing-ui": "workspace:*",
+ "@univerjs/engine-render": "workspace:*",
+ "@univerjs/shared": "workspace:*",
+ "@univerjs/ui": "workspace:*",
+ "@wendellhu/redi": "0.15.2",
+ "clsx": "^2.1.0",
+ "less": "^4.2.0",
+ "react": "^18.2.0",
+ "rxjs": "^7.8.1",
+ "typescript": "^5.3.3",
+ "vite": "^5.1.4",
+ "vitest": "^1.3.1"
+ }
+}
diff --git a/packages/docs-drawing-ui/src/commands/commands/delete-drawings.command.ts b/packages/docs-drawing-ui/src/commands/commands/delete-drawings.command.ts
new file mode 100644
index 0000000000..15ebd56eef
--- /dev/null
+++ b/packages/docs-drawing-ui/src/commands/commands/delete-drawings.command.ts
@@ -0,0 +1,54 @@
+/**
+ * Copyright 2023-present DreamNum Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { CommandType, type ICommand, ICommandService } from '@univerjs/core';
+import type { IAccessor } from '@wendellhu/redi';
+import type { IDocDrawing } from '@univerjs/docs';
+import { IDocDrawingService } from '@univerjs/docs';
+import { RemoveDocDrawingCommand } from './remove-doc-drawing.command';
+import type { IDeleteDrawingCommandParams } from './interfaces';
+
+export const DeleteDocDrawingsCommand: ICommand = {
+ id: 'doc.command.delete-drawing',
+ type: CommandType.COMMAND,
+ handler: (accessor: IAccessor) => {
+ const commandService = accessor.get(ICommandService);
+ const docDrawingService = accessor.get(IDocDrawingService);
+
+ const drawings = docDrawingService.getFocusDrawings();
+
+ if (drawings.length === 0) {
+ return false;
+ }
+
+ const unitId = drawings[0].unitId;
+
+ const newDrawings = drawings.map((drawing) => {
+ const { unitId, subUnitId, drawingId, drawingType } = drawing as IDocDrawing;
+
+ return {
+ unitId,
+ subUnitId,
+ drawingId,
+ drawingType,
+ };
+ });
+ return commandService.executeCommand<IDeleteDrawingCommandParams>(RemoveDocDrawingCommand.id, {
+ unitId,
+ drawings: newDrawings,
+ });
+ },
+};
diff --git a/packages/docs-drawing-ui/src/commands/commands/group-doc-drawing.command.ts b/packages/docs-drawing-ui/src/commands/commands/group-doc-drawing.command.ts
new file mode 100644
index 0000000000..89d2c2bd8d
--- /dev/null
+++ b/packages/docs-drawing-ui/src/commands/commands/group-doc-drawing.command.ts
@@ -0,0 +1,76 @@
+/**
+ * Copyright 2023-present DreamNum Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { ICommand, IDrawingGroupUpdateParam } from '@univerjs/core';
+import {
+ CommandType,
+ ICommandService,
+ IUndoRedoService,
+} from '@univerjs/core';
+
+import type { IAccessor } from '@wendellhu/redi';
+import type { IDrawingJsonUndo1 } from '@univerjs/drawing';
+import { DocDrawingApplyType, IDocDrawingService, SetDocDrawingApplyMutation } from '@univerjs/docs';
+import { ClearDocDrawingTransformerOperation } from '../operations/clear-drawing-transformer.operation';
+import { groupToUngroup } from './utils';
+
+/**
+ * The command to insert new defined name
+ */
+export const GroupDocDrawingCommand: ICommand = {
+ id: 'doc.command.group-doc-image',
+ type: CommandType.COMMAND,
+ handler: (accessor: IAccessor, params?: IDrawingGroupUpdateParam[]) => {
+ const commandService = accessor.get(ICommandService);
+ const undoRedoService = accessor.get(IUndoRedoService);
+ const docDrawingService = accessor.get(IDocDrawingService);
+
+ if (!params) return false;
+
+ const unitIds: string[] = [];
+ params.forEach(({ parent, children }) => {
+ unitIds.push(parent.unitId);
+ children.forEach((child) => {
+ unitIds.push(child.unitId);
+ });
+ });
+
+ // execute do mutations and add undo mutations to undo stack if completed
+ const jsonOp = docDrawingService.getGroupDrawingOp(params) as IDrawingJsonUndo1;
+
+ const { unitId, subUnitId, undo, redo, objects } = jsonOp;
+
+ const result = commandService.syncExecuteCommand(SetDocDrawingApplyMutation.id, { op: redo, unitId, subUnitId, objects, type: DocDrawingApplyType.GROUP });
+
+ if (result) {
+ undoRedoService.pushUndoRedo({
+ unitID: unitId,
+ undoMutations: [
+ { id: SetDocDrawingApplyMutation.id, params: { op: undo, unitId, subUnitId, objects: groupToUngroup(objects as IDrawingGroupUpdateParam[]), type: DocDrawingApplyType.UNGROUP } },
+ { id: ClearDocDrawingTransformerOperation.id, params: unitIds },
+ ],
+ redoMutations: [
+ { id: SetDocDrawingApplyMutation.id, params: { op: redo, unitId, subUnitId, objects, type: DocDrawingApplyType.GROUP } },
+ { id: ClearDocDrawingTransformerOperation.id, params: unitIds },
+ ],
+ });
+
+ return true;
+ }
+
+ return false;
+ },
+};
diff --git a/packages/docs-drawing-ui/src/commands/commands/insert-doc-drawing.command.ts b/packages/docs-drawing-ui/src/commands/commands/insert-doc-drawing.command.ts
new file mode 100644
index 0000000000..e7872cf508
--- /dev/null
+++ b/packages/docs-drawing-ui/src/commands/commands/insert-doc-drawing.command.ts
@@ -0,0 +1,75 @@
+/**
+ * Copyright 2023-present DreamNum Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { ICommand } from '@univerjs/core';
+import {
+ CommandType,
+ ICommandService,
+ IUndoRedoService,
+} from '@univerjs/core';
+
+import { DocDrawingApplyType, IDocDrawingService, SetDocDrawingApplyMutation } from '@univerjs/docs';
+import type { IAccessor } from '@wendellhu/redi';
+import type { IDrawingJsonUndo1 } from '@univerjs/drawing';
+import { ClearDocDrawingTransformerOperation } from '../operations/clear-drawing-transformer.operation';
+import type { IInsertDrawingCommandParams } from './interfaces';
+
+/**
+ * The command to insert new defined name
+ */
+export const InsertDocDrawingCommand: ICommand = {
+ id: 'doc.command.insert-doc-image',
+ type: CommandType.COMMAND,
+ handler: (accessor: IAccessor, params?: IInsertDrawingCommandParams) => {
+ const commandService = accessor.get(ICommandService);
+ const undoRedoService = accessor.get(IUndoRedoService);
+ const docDrawingService = accessor.get(IDocDrawingService);
+
+ if (!params) return false;
+
+ // const { drawingParam, imageParam } = params;
+
+ const drawings = params.drawings;
+
+ // const sheetDrawingParams = drawings.map((param) => param.sheetDrawingParam);
+ const unitIds: string[] = drawings.map((param) => param.unitId);
+
+ // execute do mutations and add undo mutations to undo stack if completed
+ const jsonOp = docDrawingService.getBatchAddOp(drawings) as IDrawingJsonUndo1;
+
+ const { unitId, subUnitId, undo, redo, objects } = jsonOp;
+
+ const result = commandService.syncExecuteCommand(SetDocDrawingApplyMutation.id, { op: redo, unitId, subUnitId, objects, type: DocDrawingApplyType.INSERT });
+
+ if (result) {
+ undoRedoService.pushUndoRedo({
+ unitID: unitId,
+ undoMutations: [
+ { id: SetDocDrawingApplyMutation.id, params: { op: undo, unitId, subUnitId, objects, type: DocDrawingApplyType.REMOVE } },
+ { id: ClearDocDrawingTransformerOperation.id, params: unitIds },
+ ],
+ redoMutations: [
+ { id: SetDocDrawingApplyMutation.id, params: { op: redo, unitId, subUnitId, objects, type: DocDrawingApplyType.INSERT } },
+ { id: ClearDocDrawingTransformerOperation.id, params: unitIds },
+ ],
+ });
+
+ return true;
+ }
+
+ return false;
+ },
+};
diff --git a/packages/docs-drawing-ui/src/commands/commands/interfaces.ts b/packages/docs-drawing-ui/src/commands/commands/interfaces.ts
new file mode 100644
index 0000000000..14601ace2a
--- /dev/null
+++ b/packages/docs-drawing-ui/src/commands/commands/interfaces.ts
@@ -0,0 +1,40 @@
+/**
+ * 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 { DrawingTypeEnum } from '@univerjs/core';
+import type { IDocDrawing } from '@univerjs/docs';
+
+export interface IInsertDrawingCommandParams {
+ unitId: string;
+ drawings: IDocDrawing[];
+}
+
+export interface IDeleteDrawingCommandParam {
+ unitId: string;
+ subUnitId: string;
+ drawingId: string;
+ drawingType: DrawingTypeEnum;
+}
+
+export interface IDeleteDrawingCommandParams {
+ unitId: string;
+ drawings: IDeleteDrawingCommandParam[];
+}
+
+export interface ISetDrawingCommandParams {
+ unitId: string;
+ drawings: Partial<IDocDrawing>[];
+}
diff --git a/packages/docs-drawing-ui/src/commands/commands/move-drawings.command.ts b/packages/docs-drawing-ui/src/commands/commands/move-drawings.command.ts
new file mode 100644
index 0000000000..b9896caba2
--- /dev/null
+++ b/packages/docs-drawing-ui/src/commands/commands/move-drawings.command.ts
@@ -0,0 +1,89 @@
+/**
+ * Copyright 2023-present DreamNum Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { ICommand } from '@univerjs/core';
+import { CommandType, Direction, ICommandService } from '@univerjs/core';
+import type { IAccessor } from '@wendellhu/redi';
+
+import type { IDocDrawing } from '@univerjs/docs';
+import { IDocDrawingService } from '@univerjs/docs';
+import { ITextSelectionRenderManager } from '@univerjs/engine-render';
+import { transformToDocDrawingPosition } from '@univerjs/docs-ui';
+import { ClearDocDrawingTransformerOperation } from '../operations/clear-drawing-transformer.operation';
+import type { ISetDrawingCommandParams } from './interfaces';
+import { SetDocDrawingCommand } from './set-doc-drawing.command';
+
+export interface IMoveDrawingsCommandParams {
+ direction: Direction ;
+}
+
+export const MoveDocDrawingsCommand: ICommand = {
+ id: 'doc.command.move-drawing',
+ type: CommandType.COMMAND,
+ handler: (accessor: IAccessor, params: IMoveDrawingsCommandParams) => {
+ const commandService = accessor.get(ICommandService);
+ const docDrawingService = accessor.get(IDocDrawingService);
+ const textSelectionRenderService = accessor.get(ITextSelectionRenderManager);
+
+ const { direction } = params;
+
+ const drawings = docDrawingService.getFocusDrawings();
+
+ if (drawings.length === 0) {
+ return false;
+ }
+
+ const unitId = drawings[0].unitId;
+
+ const newDrawings = drawings.map((drawing) => {
+ const { transform } = drawing as IDocDrawing;
+ if (transform == null) {
+ return null;
+ }
+ const newTransform = { ...transform };
+
+ const { left = 0, top = 0 } = transform;
+
+ if (direction === Direction.UP) {
+ newTransform.top = top - 1;
+ } else if (direction === Direction.DOWN) {
+ newTransform.top = top + 1;
+ } else if (direction === Direction.LEFT) {
+ newTransform.left = left - 1;
+ } else if (direction === Direction.RIGHT) {
+ newTransform.left = left + 1;
+ }
+
+ return {
+ ...drawing,
+ transform: newTransform,
+ docTransform: transformToDocDrawingPosition(newTransform),
+ } as IDocDrawing;
+ }).filter((drawing) => drawing != null) as IDocDrawing[];
+
+ const result = commandService.syncExecuteCommand<ISetDrawingCommandParams>(SetDocDrawingCommand.id, {
+ unitId,
+ drawings: newDrawings,
+ });
+
+ if (result) {
+ commandService.syncExecuteCommand(ClearDocDrawingTransformerOperation.id, [unitId]);
+ return true;
+ }
+
+ return false;
+ },
+};
diff --git a/packages/docs-drawing-ui/src/commands/commands/remove-doc-drawing.command.ts b/packages/docs-drawing-ui/src/commands/commands/remove-doc-drawing.command.ts
new file mode 100644
index 0000000000..c3136cf448
--- /dev/null
+++ b/packages/docs-drawing-ui/src/commands/commands/remove-doc-drawing.command.ts
@@ -0,0 +1,77 @@
+/**
+ * Copyright 2023-present DreamNum Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { ICommand } from '@univerjs/core';
+import {
+ CommandType,
+ ICommandService,
+ IUndoRedoService,
+} from '@univerjs/core';
+import { DocDrawingApplyType, IDocDrawingService, SetDocDrawingApplyMutation } from '@univerjs/docs';
+import type { IAccessor } from '@wendellhu/redi';
+import type { IDrawingJsonUndo1 } from '@univerjs/drawing';
+import { ClearDocDrawingTransformerOperation } from '../operations/clear-drawing-transformer.operation';
+import type { IDeleteDrawingCommandParams } from './interfaces';
+
+/**
+ * The command to remove new sheet image
+ */
+export const RemoveDocDrawingCommand: ICommand = {
+ id: 'doc.command.remove-doc-image',
+ type: CommandType.COMMAND,
+ handler: (accessor: IAccessor, params?: IDeleteDrawingCommandParams) => {
+ const commandService = accessor.get(ICommandService);
+ const undoRedoService = accessor.get(IUndoRedoService);
+
+ const docDrawingService = accessor.get(IDocDrawingService);
+
+ if (!params) return false;
+
+ const { drawings } = params;
+
+ const unitIds: string[] = [];
+
+ drawings.forEach((param) => {
+ const { unitId } = param;
+ unitIds.push(unitId);
+ });
+
+ const jsonOp = docDrawingService.getBatchRemoveOp(drawings) as IDrawingJsonUndo1;
+
+ const { unitId, subUnitId, undo, redo, objects } = jsonOp;
+
+ // execute do mutations and add undo mutations to undo stack if completed
+ const result = commandService.syncExecuteCommand(SetDocDrawingApplyMutation.id, { unitId, subUnitId, op: redo, objects, type: DocDrawingApplyType.REMOVE });
+
+ if (result) {
+ undoRedoService.pushUndoRedo({
+ unitID: unitId,
+ undoMutations: [
+ { id: SetDocDrawingApplyMutation.id, params: { unitId, subUnitId, op: undo, objects, type: DocDrawingApplyType.INSERT } },
+ { id: ClearDocDrawingTransformerOperation.id, params: unitIds },
+ ],
+ redoMutations: [
+ { id: SetDocDrawingApplyMutation.id, params: { unitId, subUnitId, op: redo, objects, type: DocDrawingApplyType.REMOVE } },
+ { id: ClearDocDrawingTransformerOperation.id, params: unitIds },
+ ],
+ });
+
+ return true;
+ }
+
+ return false;
+ },
+};
diff --git a/packages/docs-drawing-ui/src/commands/commands/set-doc-drawing.command.ts b/packages/docs-drawing-ui/src/commands/commands/set-doc-drawing.command.ts
new file mode 100644
index 0000000000..d356b1d51e
--- /dev/null
+++ b/packages/docs-drawing-ui/src/commands/commands/set-doc-drawing.command.ts
@@ -0,0 +1,74 @@
+/**
+ * Copyright 2023-present DreamNum Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { ICommand } from '@univerjs/core';
+import {
+ CommandType,
+ ICommandService,
+ IUndoRedoService,
+} from '@univerjs/core';
+
+import type { IAccessor } from '@wendellhu/redi';
+import type { IDrawingJsonUndo1 } from '@univerjs/drawing';
+import type { IDocDrawing } from '@univerjs/docs';
+import { DocDrawingApplyType, IDocDrawingService, SetDocDrawingApplyMutation } from '@univerjs/docs';
+import { ClearDocDrawingTransformerOperation } from '../operations/clear-drawing-transformer.operation';
+import type { ISetDrawingCommandParams } from './interfaces';
+
+/**
+ * The command to update defined name
+ */
+export const SetDocDrawingCommand: ICommand = {
+ id: 'doc.command.set-doc-image',
+ type: CommandType.COMMAND,
+ handler: (accessor: IAccessor, params?: ISetDrawingCommandParams) => {
+ const commandService = accessor.get(ICommandService);
+ const undoRedoService = accessor.get(IUndoRedoService);
+ const docDrawingService = accessor.get(IDocDrawingService);
+
+ if (!params) return false;
+
+ const { drawings } = params;
+
+ // const newSheetDrawingParams = drawings.map((param) => param.newDrawing);
+ // const oldSheetDrawingParams = drawings.map((param) => param.oldDrawing);
+
+ const jsonOp = docDrawingService.getBatchUpdateOp(drawings as IDocDrawing[]) as IDrawingJsonUndo1;
+
+ const { unitId, subUnitId, undo, redo, objects } = jsonOp;
+
+ // execute do mutations and add undo mutations to undo stack if completed
+ const result = commandService.syncExecuteCommand(SetDocDrawingApplyMutation.id, { unitId, subUnitId, op: redo, objects, type: DocDrawingApplyType.UPDATE });
+
+ if (result) {
+ undoRedoService.pushUndoRedo({
+ unitID: unitId,
+ undoMutations: [
+ { id: SetDocDrawingApplyMutation.id, params: { unitId, subUnitId, op: undo, objects, type: DocDrawingApplyType.UPDATE } },
+ { id: ClearDocDrawingTransformerOperation.id, params: [unitId] },
+ ],
+ redoMutations: [
+ { id: SetDocDrawingApplyMutation.id, params: { unitId, subUnitId, op: redo, objects, type: DocDrawingApplyType.UPDATE } },
+ { id: ClearDocDrawingTransformerOperation.id, params: [unitId] },
+ ],
+ });
+
+ return true;
+ }
+
+ return false;
+ },
+};
diff --git a/packages/docs-drawing-ui/src/commands/commands/set-drawing-arrange.command.ts b/packages/docs-drawing-ui/src/commands/commands/set-drawing-arrange.command.ts
new file mode 100644
index 0000000000..bc154ccc66
--- /dev/null
+++ b/packages/docs-drawing-ui/src/commands/commands/set-drawing-arrange.command.ts
@@ -0,0 +1,84 @@
+/**
+ * Copyright 2023-present DreamNum Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { ICommand, IDrawingOrderMapParam, Nullable } from '@univerjs/core';
+import { ArrangeTypeEnum,
+ CommandType,
+ ICommandService,
+ IUndoRedoService,
+} from '@univerjs/core';
+import { DocDrawingApplyType, IDocDrawingService, SetDocDrawingApplyMutation } from '@univerjs/docs';
+import type { IDrawingJsonUndo1 } from '@univerjs/drawing';
+import type { IAccessor } from '@wendellhu/redi';
+
+export interface ISetDrawingArrangeCommandParams extends IDrawingOrderMapParam {
+ arrangeType: ArrangeTypeEnum;
+}
+
+/**
+ * The command to insert new defined name
+ */
+export const SetDocDrawingArrangeCommand: ICommand = {
+ id: 'doc.command.set-drawing-arrange',
+ type: CommandType.COMMAND,
+ handler: (accessor: IAccessor, params?: ISetDrawingArrangeCommandParams) => {
+ const commandService = accessor.get(ICommandService);
+ const undoRedoService = accessor.get(IUndoRedoService);
+
+ if (!params) return false;
+
+ const docDrawingService = accessor.get(IDocDrawingService);
+
+ const { unitId, subUnitId, drawingIds, arrangeType } = params;
+
+ const drawingOrderMapParam = { unitId, subUnitId, drawingIds } as IDrawingOrderMapParam;
+
+ let jsonOp: Nullable<IDrawingJsonUndo1>;
+ if (arrangeType === ArrangeTypeEnum.forward) {
+ jsonOp = docDrawingService.getForwardDrawingsOp(drawingOrderMapParam) as IDrawingJsonUndo1;
+ } else if (arrangeType === ArrangeTypeEnum.backward) {
+ jsonOp = docDrawingService.getBackwardDrawingOp(drawingOrderMapParam) as IDrawingJsonUndo1;
+ } else if (arrangeType === ArrangeTypeEnum.front) {
+ jsonOp = docDrawingService.getFrontDrawingsOp(drawingOrderMapParam) as IDrawingJsonUndo1;
+ } else if (arrangeType === ArrangeTypeEnum.back) {
+ jsonOp = docDrawingService.getBackDrawingsOp(drawingOrderMapParam) as IDrawingJsonUndo1;
+ }
+
+ if (jsonOp == null) {
+ return false;
+ }
+
+ const { objects, redo, undo } = jsonOp;
+
+ const result = commandService.syncExecuteCommand(SetDocDrawingApplyMutation.id, { op: redo, unitId, subUnitId, objects, type: DocDrawingApplyType.ARRANGE });
+
+ if (result) {
+ undoRedoService.pushUndoRedo({
+ unitID: unitId,
+ undoMutations: [
+ { id: SetDocDrawingApplyMutation.id, params: { op: undo, unitId, subUnitId, objects, type: DocDrawingApplyType.ARRANGE } },
+ ],
+ redoMutations: [
+ { id: SetDocDrawingApplyMutation.id, params: { op: redo, unitId, subUnitId, objects, type: DocDrawingApplyType.ARRANGE } },
+ ],
+ });
+
+ return true;
+ }
+
+ return false;
+ },
+};
diff --git a/packages/docs-drawing-ui/src/commands/commands/ungroup-doc-drawing.command.ts b/packages/docs-drawing-ui/src/commands/commands/ungroup-doc-drawing.command.ts
new file mode 100644
index 0000000000..27345963c0
--- /dev/null
+++ b/packages/docs-drawing-ui/src/commands/commands/ungroup-doc-drawing.command.ts
@@ -0,0 +1,76 @@
+/**
+ * Copyright 2023-present DreamNum Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { ICommand, IDrawingGroupUpdateParam } from '@univerjs/core';
+import {
+ CommandType,
+ ICommandService,
+ IUndoRedoService,
+} from '@univerjs/core';
+
+import type { IAccessor } from '@wendellhu/redi';
+import type { IDrawingJsonUndo1 } from '@univerjs/drawing';
+import { DocDrawingApplyType, IDocDrawingService, SetDocDrawingApplyMutation } from '@univerjs/docs';
+import { ClearDocDrawingTransformerOperation } from '../operations/clear-drawing-transformer.operation';
+import { ungroupToGroup } from './utils';
+
+/**
+ * The command to insert new defined name
+ */
+export const UngroupDocDrawingCommand: ICommand = {
+ id: 'doc.command.ungroup-doc-image',
+ type: CommandType.COMMAND,
+ handler: (accessor: IAccessor, params?: IDrawingGroupUpdateParam[]) => {
+ const commandService = accessor.get(ICommandService);
+ const undoRedoService = accessor.get(IUndoRedoService);
+ const docDrawingService = accessor.get(IDocDrawingService);
+
+ if (!params) return false;
+
+ const unitIds: string[] = [];
+ params.forEach(({ parent, children }) => {
+ unitIds.push(parent.unitId);
+ children.forEach((child) => {
+ unitIds.push(child.unitId);
+ });
+ });
+
+ // execute do mutations and add undo mutations to undo stack if completed
+ const jsonOp = docDrawingService.getUngroupDrawingOp(params) as IDrawingJsonUndo1;
+
+ const { unitId, subUnitId, undo, redo, objects } = jsonOp;
+
+ const result = commandService.syncExecuteCommand(SetDocDrawingApplyMutation.id, { op: redo, unitId, subUnitId, objects, type: DocDrawingApplyType.UNGROUP });
+
+ if (result) {
+ undoRedoService.pushUndoRedo({
+ unitID: unitId,
+ undoMutations: [
+ { id: SetDocDrawingApplyMutation.id, params: { op: undo, unitId, subUnitId, objects: ungroupToGroup(objects as IDrawingGroupUpdateParam[]), type: DocDrawingApplyType.GROUP } },
+ { id: ClearDocDrawingTransformerOperation.id, params: unitIds },
+ ],
+ redoMutations: [
+ { id: SetDocDrawingApplyMutation.id, params: { op: redo, unitId, subUnitId, objects, type: DocDrawingApplyType.UNGROUP } },
+ { id: ClearDocDrawingTransformerOperation.id, params: unitIds },
+ ],
+ });
+
+ return true;
+ }
+
+ return false;
+ },
+};
diff --git a/packages/docs-drawing-ui/src/commands/commands/utils.ts b/packages/docs-drawing-ui/src/commands/commands/utils.ts
new file mode 100644
index 0000000000..f7860ab2fe
--- /dev/null
+++ b/packages/docs-drawing-ui/src/commands/commands/utils.ts
@@ -0,0 +1,97 @@
+/**
+ * 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 { DrawingTypeEnum, type IDrawingGroupUpdateParam, type IDrawingParam } from '@univerjs/core';
+import { getGroupState, transformObjectOutOfGroup } from '@univerjs/engine-render';
+
+export function ungroupToGroup(ungroupParams: IDrawingGroupUpdateParam[]) {
+ const newGroupParams: IDrawingGroupUpdateParam[] = [];
+
+ ungroupParams.forEach((ungroupParam) => {
+ const { parent, children } = ungroupParam;
+ const { unitId, subUnitId, drawingId: groupId } = parent;
+ const groupTransform = getGroupState(0, 0, children.map((o) => o.transform || {}));
+
+ const newChildren = children.map((drawing) => {
+ const transform = drawing.transform || { left: 0, top: 0 };
+ const { unitId, subUnitId, drawingId } = drawing;
+ return {
+ unitId, subUnitId, drawingId,
+ transform: {
+ ...transform,
+ left: transform.left! - groupTransform.left,
+ top: transform.top! - groupTransform.top,
+ },
+ groupId,
+ };
+ }) as IDrawingParam[];
+
+ const groupParam = {
+ unitId,
+ subUnitId,
+ drawingId: groupId,
+ drawingType: DrawingTypeEnum.DRAWING_GROUP,
+ transform: groupTransform,
+ } as IDrawingParam;
+
+ newGroupParams.push({
+ parent: groupParam,
+ children: newChildren,
+ });
+ });
+
+ return newGroupParams;
+}
+
+export function groupToUngroup(groupParams: IDrawingGroupUpdateParam[]) {
+ const newGroupParams: IDrawingGroupUpdateParam[] = [];
+
+ groupParams.forEach((groupParam) => {
+ const { parent, children } = groupParam;
+ const { unitId, subUnitId, drawingId: groupId, transform: groupTransform = { width: 0, height: 0 } } = parent;
+ if (groupTransform == null) {
+ return;
+ }
+ const newChildren = children.map((object) => {
+ const { transform } = object;
+ const { unitId, subUnitId, drawingId } = object;
+ const newTransform = transformObjectOutOfGroup(transform || {}, groupTransform, groupTransform.width || 0, groupTransform.height || 0);
+ return {
+ unitId, subUnitId, drawingId,
+ transform: newTransform,
+ groupId: undefined,
+ };
+ }) as IDrawingParam[];
+
+ const ungroupParam = {
+ unitId,
+ subUnitId,
+ drawingId: groupId,
+ drawingType: DrawingTypeEnum.DRAWING_GROUP,
+ transform: {
+ left: 0,
+ top: 0,
+ },
+ } as IDrawingParam;
+
+ newGroupParams.push({
+ parent: ungroupParam,
+ children: newChildren,
+ });
+ });
+
+ return newGroupParams;
+}
diff --git a/packages/docs/src/commands/mutations/remove-floating-object.mutation.ts b/packages/docs-drawing-ui/src/commands/operations/clear-drawing-transformer.operation.ts
similarity index 53%
rename from packages/docs/src/commands/mutations/remove-floating-object.mutation.ts
rename to packages/docs-drawing-ui/src/commands/operations/clear-drawing-transformer.operation.ts
index 82a3b0a77e..f37af42b59 100644
--- a/packages/docs/src/commands/mutations/remove-floating-object.mutation.ts
+++ b/packages/docs-drawing-ui/src/commands/operations/clear-drawing-transformer.operation.ts
@@ -15,28 +15,18 @@
*/
import type { IMutation } from '@univerjs/core';
-import { CommandType, IUniverInstanceService } from '@univerjs/core';
+import { CommandType } from '@univerjs/core';
+import { IRenderManagerService } from '@univerjs/engine-render';
-import type { ISeachDrawingMutation } from './set-floating-object.mutation';
-
-export const RemoveDrawingMutation: IMutation<ISeachDrawingMutation> = {
- id: 'doc.mutation.remove-drawing',
+export const ClearDocDrawingTransformerOperation: IMutation<string[]> = {
+ id: 'sheet.operation.clear-drawing-transformer',
type: CommandType.MUTATION,
handler: (accessor, params) => {
- const univerdoc = accessor.get(IUniverInstanceService).getUniverDocInstance(params.documentId);
-
- if (univerdoc == null) {
- return false;
- }
-
- let drawings = univerdoc.getSnapshot().drawings;
-
- if (drawings == null) {
- drawings = {};
- univerdoc.getSnapshot().drawings = drawings;
- }
+ const renderManagerService = accessor.get(IRenderManagerService);
- delete drawings[params.objectId];
+ params.forEach((unitId) => {
+ renderManagerService.getRenderById(unitId)?.scene.getTransformer()?.debounceRefreshControls();
+ });
return true;
},
diff --git a/packages/docs-drawing-ui/src/commands/operations/edit-doc-drawing.operation.ts b/packages/docs-drawing-ui/src/commands/operations/edit-doc-drawing.operation.ts
new file mode 100644
index 0000000000..e102320fb5
--- /dev/null
+++ b/packages/docs-drawing-ui/src/commands/operations/edit-doc-drawing.operation.ts
@@ -0,0 +1,41 @@
+/**
+ * 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 { IDrawingSearch, IOperation } from '@univerjs/core';
+import {
+ CommandType,
+ ICommandService,
+ IDrawingManagerService,
+
+} from '@univerjs/core';
+import type { IAccessor } from '@wendellhu/redi';
+import { SidebarDocDrawingOperation } from './open-drawing-panel.operation';
+
+export const EditDocDrawingOperation: IOperation<IDrawingSearch> = {
+ id: 'sheet.operation.edit-sheet-image',
+ type: CommandType.OPERATION,
+ handler: (accessor: IAccessor, params?: IDrawingSearch) => {
+ const drawingManagerService = accessor.get(IDrawingManagerService);
+ const commandService = accessor.get(ICommandService);
+
+ if (params == null) {
+ return false;
+ }
+ drawingManagerService.focusDrawing([params]);
+ commandService.executeCommand(SidebarDocDrawingOperation.id, { value: 'open' });
+ return true;
+ },
+};
diff --git a/packages/docs-drawing-ui/src/commands/operations/insert-image.operation.ts b/packages/docs-drawing-ui/src/commands/operations/insert-image.operation.ts
new file mode 100644
index 0000000000..b6e01bc977
--- /dev/null
+++ b/packages/docs-drawing-ui/src/commands/operations/insert-image.operation.ts
@@ -0,0 +1,30 @@
+/**
+ * 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 { IOperation, Nullable } from '@univerjs/core';
+import { CommandType } from '@univerjs/core';
+
+export interface IInsertImageOperationParams {
+ files: Nullable<File[]>;
+};
+
+export const InsertDocImageOperation: IOperation<IInsertImageOperationParams> = {
+ id: 'doc.operation.insert-float-image',
+ type: CommandType.OPERATION,
+ handler: (accessor, params) => {
+ return true;
+ },
+};
diff --git a/packages/docs-drawing-ui/src/commands/operations/open-drawing-panel.operation.ts b/packages/docs-drawing-ui/src/commands/operations/open-drawing-panel.operation.ts
new file mode 100644
index 0000000000..1c002f4cff
--- /dev/null
+++ b/packages/docs-drawing-ui/src/commands/operations/open-drawing-panel.operation.ts
@@ -0,0 +1,54 @@
+/**
+ * Copyright 2023-present DreamNum Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { ICommand } from '@univerjs/core';
+import { CommandType, IDrawingManagerService, LocaleService } from '@univerjs/core';
+import { ISidebarService } from '@univerjs/ui';
+import type { IAccessor } from '@wendellhu/redi';
+import { COMPONENT_DOC_DRAWING_PANEL } from '../../views/doc-image-panel/component-name';
+
+export interface IUIComponentCommandParams {
+ value: string;
+}
+
+export const SidebarDocDrawingOperation: ICommand = {
+ id: 'sidebar.operation.doc-image',
+ type: CommandType.COMMAND,
+ handler: async (accessor: IAccessor, params: IUIComponentCommandParams) => {
+ const sidebarService = accessor.get(ISidebarService);
+ const localeService = accessor.get(LocaleService);
+ const drawingManagerService = accessor.get(IDrawingManagerService);
+
+ switch (params.value) {
+ case 'open':
+ sidebarService.open({
+ header: { title: localeService.t('docImage.panel.title') },
+ children: { label: COMPONENT_DOC_DRAWING_PANEL },
+ onClose: () => {
+ drawingManagerService.focusDrawing(null);
+ },
+ width: 360,
+ });
+ break;
+ case 'close':
+ default:
+ sidebarService.close();
+ break;
+ }
+ return true;
+ },
+};
+
diff --git a/packages/docs-drawing-ui/src/controllers/doc-drawing-update.controller.ts b/packages/docs-drawing-ui/src/controllers/doc-drawing-update.controller.ts
new file mode 100644
index 0000000000..6eb23105de
--- /dev/null
+++ b/packages/docs-drawing-ui/src/controllers/doc-drawing-update.controller.ts
@@ -0,0 +1,396 @@
+/**
+ * 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 { DocumentDataModel, ICommandInfo, IDocDrawingPosition, IImageIoServiceParam, Nullable } from '@univerjs/core';
+import { Disposable, DrawingTypeEnum, FOCUSING_COMMON_DRAWINGS, ICommandService, IContextService, IDrawingManagerService, IImageIoService, ImageUploadStatusType, IUniverInstanceService, LifecycleStages, LocaleService, ObjectRelativeFromH, ObjectRelativeFromV, OnLifecycle, PositionedObjectLayoutType, UniverInstanceType } from '@univerjs/core';
+import { Inject } from '@wendellhu/redi';
+import { DRAWING_IMAGE_ALLOW_SIZE, DRAWING_IMAGE_COUNT_LIMIT, DRAWING_IMAGE_HEIGHT_LIMIT, DRAWING_IMAGE_WIDTH_LIMIT, getImageSize } from '@univerjs/drawing';
+import { IMessageService } from '@univerjs/ui';
+import { MessageType } from '@univerjs/design';
+import type { IDocDrawing } from '@univerjs/docs';
+import { DocSkeletonManagerService, IDocDrawingService, TextSelectionManagerService } from '@univerjs/docs';
+import { docDrawingPositionToTransform, transformToDocDrawingPosition } from '@univerjs/docs-ui';
+import type { Documents } from '@univerjs/engine-render';
+import { IRenderManagerService, ITextSelectionRenderManager, Liquid } from '@univerjs/engine-render';
+import type { IInsertImageOperationParams } from '../commands/operations/insert-image.operation';
+import { InsertDocImageOperation } from '../commands/operations/insert-image.operation';
+import type { IInsertDrawingCommandParams, ISetDrawingCommandParams } from '../commands/commands/interfaces';
+import { type ISetDrawingArrangeCommandParams, SetDocDrawingArrangeCommand } from '../commands/commands/set-drawing-arrange.command';
+import { InsertDocDrawingCommand } from '../commands/commands/insert-doc-drawing.command';
+import { GroupDocDrawingCommand } from '../commands/commands/group-doc-drawing.command';
+import { UngroupDocDrawingCommand } from '../commands/commands/ungroup-doc-drawing.command';
+import { SetDocDrawingCommand } from '../commands/commands/set-doc-drawing.command';
+
+@OnLifecycle(LifecycleStages.Rendered, DocDrawingUpdateController)
+export class DocDrawingUpdateController extends Disposable {
+ constructor(
+ @ICommandService private readonly _commandService: ICommandService,
+ @IUniverInstanceService private readonly _univerInstanceService: IUniverInstanceService,
+ @Inject(TextSelectionManagerService) private readonly _textSelectionManagerService: TextSelectionManagerService,
+ @ITextSelectionRenderManager private readonly _textSelectionRenderManager: ITextSelectionRenderManager,
+ @IImageIoService private readonly _imageIoService: IImageIoService,
+ @IDocDrawingService private readonly _sheetDrawingService: IDocDrawingService,
+ @IDrawingManagerService private readonly _drawingManagerService: IDrawingManagerService,
+ @IContextService private readonly _contextService: IContextService,
+ @IMessageService private readonly _messageService: IMessageService,
+ @Inject(LocaleService) private readonly _localeService: LocaleService,
+ @Inject(DocSkeletonManagerService) private readonly _docSkeletonManagerService: DocSkeletonManagerService,
+ @IRenderManagerService private readonly _renderManagerService: IRenderManagerService
+ ) {
+ super();
+
+ this._init();
+ }
+
+ private _init(): void {
+ this._initCommandListeners();
+
+ this._updateDrawingListener();
+
+ this._updateOrderListener();
+
+ this._groupDrawingListener();
+
+ this._focusDrawingListener();
+ }
+
+ /**
+ * Upload image to cell or float image
+ */
+ private _initCommandListeners() {
+ this.disposeWithMe(
+ this._commandService.onCommandExecuted(async (command: ICommandInfo) => {
+ if (command.id === InsertDocImageOperation.id) {
+ const params = command.params as IInsertImageOperationParams;
+ if (params.files == null) {
+ return;
+ }
+
+ const fileLength = params.files.length;
+
+ if (fileLength > DRAWING_IMAGE_COUNT_LIMIT) {
+ this._messageService.show({
+ type: MessageType.Error,
+ content: this._localeService.t('update-status.exceedMaxCount', String(DRAWING_IMAGE_COUNT_LIMIT)),
+ });
+ return;
+ }
+
+ this._imageIoService.setWaitCount(fileLength);
+
+ params.files.forEach(async (file) => {
+ await this._insertFloatImage(file);
+ });
+ }
+ })
+ );
+ }
+
+ private async _insertFloatImage(file: File) {
+ let imageParam: Nullable<IImageIoServiceParam>;
+
+ try {
+ imageParam = await this._imageIoService.saveImage(file);
+ } catch (error) {
+ const type = (error as Error).message;
+ if (type === ImageUploadStatusType.ERROR_EXCEED_SIZE) {
+ this._messageService.show({
+ type: MessageType.Error,
+ content: this._localeService.t('update-status.exceedMaxSize', String(DRAWING_IMAGE_ALLOW_SIZE / 1024 * 1024)),
+ });
+ } else if (type === ImageUploadStatusType.ERROR_IMAGE_TYPE) {
+ this._messageService.show({
+ type: MessageType.Error,
+ content: this._localeService.t('update-status.invalidImageType'),
+ });
+ } else if (type === ImageUploadStatusType.ERROR_IMAGE) {
+ this._messageService.show({
+ type: MessageType.Error,
+ content: this._localeService.t('update-status.invalidImage'),
+ });
+ }
+ }
+
+ if (imageParam == null) {
+ return;
+ }
+
+ const info = this._getUnitInfo();
+ if (info == null) {
+ return;
+ }
+ const { unitId, subUnitId } = info;
+ const { imageId, imageSourceType, source, base64Cache } = imageParam;
+ const { width, height, image } = await getImageSize(base64Cache || '');
+
+ this._imageIoService.addImageSourceCache(imageId, imageSourceType, image);
+
+ let scale = 1;
+ if (width > DRAWING_IMAGE_WIDTH_LIMIT || height > DRAWING_IMAGE_HEIGHT_LIMIT) {
+ const scaleWidth = DRAWING_IMAGE_WIDTH_LIMIT / width;
+ const scaleHeight = DRAWING_IMAGE_HEIGHT_LIMIT / height;
+ scale = Math.max(scaleWidth, scaleHeight);
+ }
+
+ const docTransform = this._getImagePosition(width, height, scale);
+
+ if (docTransform == null) {
+ return;
+ }
+
+ const docDrawingParam: IDocDrawing = {
+ unitId,
+ subUnitId,
+ drawingId: imageId,
+ drawingType: DrawingTypeEnum.DRAWING_IMAGE,
+ imageSourceType,
+ source,
+ transform: docDrawingPositionToTransform(docTransform, this._textSelectionRenderManager),
+ docTransform,
+ title: '', description: '', layoutType: PositionedObjectLayoutType.WRAP_SQUARE,
+ };
+
+ this._commandService.executeCommand(InsertDocDrawingCommand.id, {
+ unitId,
+ drawings: [docDrawingParam],
+ } as IInsertDrawingCommandParams);
+
+ this._docSkeletonManagerService.getCurrent()?.skeleton.calculate();
+ }
+
+ private _getUnitInfo() {
+ const documentDataModel = this._univerInstanceService.getCurrentUnitForType<DocumentDataModel>(UniverInstanceType.UNIVER_DOC);
+ if (documentDataModel == null) {
+ return;
+ }
+
+ const unitId = documentDataModel.getUnitId();
+ const subUnitId = unitId;
+
+ return {
+ unitId,
+ subUnitId,
+ };
+ }
+
+ private _getImagePosition(imageWidth: number, imageHeight: number, scale: number): Nullable<IDocDrawingPosition> {
+ const activeTextRange = this._textSelectionManagerService.getActiveTextRange();
+ const position = activeTextRange?.getAbsolutePosition() || {
+ left: 0,
+ top: 0,
+ };
+
+ // TODO:@Jocs calculate the position of the image in doc
+ return {
+ size: {
+ width: imageWidth * scale,
+ height: imageHeight * scale,
+ },
+ positionH: {
+ relativeFrom: ObjectRelativeFromH.MARGIN,
+ posOffset: position.left,
+ },
+ positionV: {
+ relativeFrom: ObjectRelativeFromV.PAGE,
+ posOffset: position.top,
+ },
+ angle: 0,
+ };
+ }
+
+ private _updateOrderListener() {
+ this._drawingManagerService.featurePluginOrderUpdate$.subscribe((params) => {
+ const { unitId, subUnitId, drawingIds, arrangeType } = params;
+
+ this._commandService.executeCommand(SetDocDrawingArrangeCommand.id, {
+ unitId,
+ subUnitId,
+ drawingIds,
+ arrangeType,
+ } as ISetDrawingArrangeCommandParams);
+ });
+ }
+
+ private _updateDrawingListener() {
+ this._drawingManagerService.featurePluginUpdate$.subscribe((params) => {
+ const drawings: Partial<IDocDrawing>[] = [];
+
+ if (params.length === 0) {
+ return;
+ }
+
+ // const offsetInfo = this._getDocsOffsetInfo();
+
+ // const { pageMarginCache, docsLeft, docsTop } = offsetInfo;
+
+ (params as IDocDrawing[]).forEach((param) => {
+ const { unitId, subUnitId, drawingId, drawingType, transform } = param;
+ if (transform == null) {
+ return;
+ }
+
+ const sheetDrawing = this._sheetDrawingService.getDrawingByParam({ unitId, subUnitId, drawingId });
+
+ if (sheetDrawing == null) {
+ return;
+ }
+
+ // const { marginLeft, marginTop } = pageMarginCache.get(drawingId) || { marginLeft: 0, marginTop: 0 };
+
+ const docTransform = transformToDocDrawingPosition({ ...sheetDrawing.transform, ...transform });
+
+ if (docTransform == null) {
+ return;
+ }
+
+ const newDrawing: Partial<IDocDrawing> = {
+ ...param,
+ transform: { ...transform, ...docDrawingPositionToTransform(docTransform, this._textSelectionRenderManager) },
+ docTransform: { ...docTransform },
+ };
+
+ drawings.push(newDrawing);
+ });
+
+ if (drawings.length > 0) {
+ this._commandService.syncExecuteCommand(SetDocDrawingCommand.id, {
+ unitId: params[0].unitId,
+ drawings,
+ } as ISetDrawingCommandParams);
+
+ this._refreshDocSkeleton();
+ }
+ });
+ }
+
+ private _getDocsOffsetInfo() {
+ const docsSkeletonObject = this._docSkeletonManagerService.getCurrent();
+ if (docsSkeletonObject == null) {
+ return {
+ pageMarginCache: new Map<string, { marginLeft: number; marginTop: number }>(),
+ docsLeft: 0,
+ docsTop: 0,
+ };
+ }
+
+ const { unitId, skeleton } = docsSkeletonObject;
+
+ const currentRender = this._renderManagerService.getRenderById(unitId);
+
+ const skeletonData = skeleton?.getSkeletonData();
+
+ if (currentRender == null || !skeletonData) {
+ return {
+ pageMarginCache: new Map<string, { marginLeft: number; marginTop: number }>(),
+ docsLeft: 0,
+ docsTop: 0,
+ };
+ }
+
+ const { mainComponent } = currentRender;
+
+ const documentComponent = mainComponent as Documents;
+
+ const { left: docsLeft, top: docsTop, pageLayoutType, pageMarginLeft, pageMarginTop } = documentComponent;
+
+ const { pages } = skeletonData;
+
+ const liquid = new Liquid();
+
+ const pageMarginCache = new Map<string, { marginLeft: number; marginTop: number }>();
+
+ for (let i = 0, len = pages.length; i < len; i++) {
+ const page = pages[i];
+ const { skeDrawings, marginLeft, marginTop } = page;
+ // cumPageLeft + = pageWidth + documents.pageMarginLeft;
+
+ liquid.translatePagePadding(page);
+
+ skeDrawings.forEach((drawing) => {
+ const { aLeft, aTop, height, width, drawingId, drawingOrigin } = drawing;
+ // const behindText = drawingOrigin.layoutType === PositionedObjectLayoutType.WRAP_NONE && drawingOrigin.behindDoc === BooleanNumber.TRUE;
+ // floatObjects.push({
+ // unitId,
+ // subUnitId: DEFAULT_DOCUMENT_SUB_COMPONENT_ID,
+ // floatingObjectId: drawingId,
+ // behindText,
+ // floatingObject: {
+ // left: aLeft + docsLeft + liquid.x,
+ // top: aTop + docsTop + liquid.y,
+ // width,
+ // height,
+ // },
+ // });
+
+ pageMarginCache.set(drawingId, {
+ marginLeft: liquid.x,
+ marginTop: liquid.y,
+ });
+ });
+
+ liquid.restorePagePadding(page);
+
+ liquid.translatePage(page, pageLayoutType, pageMarginLeft, pageMarginTop);
+ }
+
+ return { pageMarginCache, docsLeft, docsTop };
+ }
+
+ private _refreshDocSkeleton() {
+ const docsSkeletonObject = this._docSkeletonManagerService.getCurrent();
+ if (docsSkeletonObject == null) {
+ return;
+ }
+
+ const { unitId, skeleton } = docsSkeletonObject;
+
+ const currentRender = this._renderManagerService.getRenderById(unitId);
+
+ if (currentRender == null) {
+ return;
+ }
+
+ const { mainComponent } = currentRender;
+
+ skeleton?.calculate();
+
+ mainComponent?.makeDirty();
+ }
+
+ private _groupDrawingListener() {
+ this._drawingManagerService.featurePluginGroupUpdate$.subscribe((params) => {
+ this._commandService.executeCommand(GroupDocDrawingCommand.id, params);
+ });
+
+ this._drawingManagerService.featurePluginUngroupUpdate$.subscribe((params) => {
+ this._commandService.executeCommand(UngroupDocDrawingCommand.id, params);
+ });
+ }
+
+ private _focusDrawingListener() {
+ this.disposeWithMe(
+ this._drawingManagerService.focus$.subscribe((params) => {
+ if (params == null || params.length === 0) {
+ this._contextService.setContextValue(FOCUSING_COMMON_DRAWINGS, false);
+ this._sheetDrawingService.focusDrawing([]);
+ } else {
+ this._contextService.setContextValue(FOCUSING_COMMON_DRAWINGS, true);
+ this._sheetDrawingService.focusDrawing(params);
+ }
+ })
+ );
+ }
+}
diff --git a/packages/docs-drawing-ui/src/controllers/doc-drawing.controller.ts b/packages/docs-drawing-ui/src/controllers/doc-drawing.controller.ts
new file mode 100644
index 0000000000..aba66d9717
--- /dev/null
+++ b/packages/docs-drawing-ui/src/controllers/doc-drawing.controller.ts
@@ -0,0 +1,112 @@
+/**
+ * Copyright 2023-present DreamNum Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { Disposable, ICommandService, LifecycleStages, OnLifecycle } from '@univerjs/core';
+import type { IMenuItemFactory } from '@univerjs/ui';
+import { ComponentManager, IMenuService, IShortcutService } from '@univerjs/ui';
+import { Inject, Injector } from '@wendellhu/redi';
+
+import { AddImageSingle } from '@univerjs/icons';
+import { UploadFileMenu } from '../views/upload-component/UploadFile';
+import { COMPONENT_DOC_UPLOAD_FILE_MENU } from '../views/upload-component/component-name';
+import { ImageMenuFactory, ImageUploadIcon, UploadFloatImageMenuFactory } from '../views/menu/image.menu';
+import { InsertDocImageOperation } from '../commands/operations/insert-image.operation';
+import { COMPONENT_DOC_DRAWING_PANEL } from '../views/doc-image-panel/component-name';
+import { DocDrawingPanel } from '../views/doc-image-panel/DocDrawingPanel';
+
+import { ClearDocDrawingTransformerOperation } from '../commands/operations/clear-drawing-transformer.operation';
+import { EditDocDrawingOperation } from '../commands/operations/edit-doc-drawing.operation';
+import { SidebarDocDrawingOperation } from '../commands/operations/open-drawing-panel.operation';
+import { MoveDocDrawingsCommand } from '../commands/commands/move-drawings.command';
+import { DeleteDocDrawingsCommand } from '../commands/commands/delete-drawings.command';
+import { SetDocDrawingArrangeCommand } from '../commands/commands/set-drawing-arrange.command';
+import { SetDocDrawingCommand } from '../commands/commands/set-doc-drawing.command';
+import { RemoveDocDrawingCommand } from '../commands/commands/remove-doc-drawing.command';
+import { UngroupDocDrawingCommand } from '../commands/commands/ungroup-doc-drawing.command';
+import { GroupDocDrawingCommand } from '../commands/commands/group-doc-drawing.command';
+import { InsertDocDrawingCommand } from '../commands/commands/insert-doc-drawing.command';
+import { DeleteDrawingsShortcutItem, MoveDrawingDownShortcutItem, MoveDrawingLeftShortcutItem, MoveDrawingRightShortcutItem, MoveDrawingUpShortcutItem } from './shortcuts/drawing.shortcut';
+
+@OnLifecycle(LifecycleStages.Ready, DocDrawingUIController)
+export class DocDrawingUIController extends Disposable {
+ constructor(
+ @Inject(Injector) private readonly _injector: Injector,
+ @Inject(ComponentManager) private readonly _componentManager: ComponentManager,
+ @IMenuService private readonly _menuService: IMenuService,
+ @ICommandService private readonly _commandService: ICommandService,
+ @IShortcutService private readonly _shortcutService: IShortcutService
+ ) {
+ super();
+
+ this._init();
+ }
+
+ private _initCustomComponents(): void {
+ const componentManager = this._componentManager;
+ this.disposeWithMe(componentManager.register(ImageUploadIcon, AddImageSingle));
+ this.disposeWithMe(componentManager.register(COMPONENT_DOC_UPLOAD_FILE_MENU, UploadFileMenu));
+ this.disposeWithMe(componentManager.register(COMPONENT_DOC_DRAWING_PANEL, DocDrawingPanel));
+ }
+
+ private _initMenus(): void {
+ // init menus
+ (
+ [
+ ImageMenuFactory,
+ UploadFloatImageMenuFactory,
+ ] as IMenuItemFactory[]
+ ).forEach((factory) => {
+ this.disposeWithMe(this._menuService.addMenuItem(this._injector.invoke(factory), {}));
+ });
+ }
+
+ private _initCommands() {
+ [
+ InsertDocImageOperation,
+ InsertDocDrawingCommand,
+ RemoveDocDrawingCommand,
+ SetDocDrawingCommand,
+ SidebarDocDrawingOperation,
+ ClearDocDrawingTransformerOperation,
+ EditDocDrawingOperation,
+ GroupDocDrawingCommand,
+ UngroupDocDrawingCommand,
+ MoveDocDrawingsCommand,
+ DeleteDocDrawingsCommand,
+ SetDocDrawingArrangeCommand,
+ ].forEach((command) => this.disposeWithMe(this._commandService.registerCommand(command)));
+ }
+
+ private _initShortcuts(): void {
+ [
+ // sheet drawing shortcuts
+ MoveDrawingDownShortcutItem,
+ MoveDrawingUpShortcutItem,
+ MoveDrawingLeftShortcutItem,
+ MoveDrawingRightShortcutItem,
+ DeleteDrawingsShortcutItem,
+ ].forEach((item) => {
+ this.disposeWithMe(this._shortcutService.registerShortcut(item));
+ });
+ }
+
+ private _init(): void {
+ this._initCommands();
+ this._initCustomComponents();
+ this._initMenus();
+ this._initShortcuts();
+ }
+}
diff --git a/packages/docs-drawing-ui/src/controllers/drawing-popup-menu.controller.ts b/packages/docs-drawing-ui/src/controllers/drawing-popup-menu.controller.ts
new file mode 100644
index 0000000000..edc47273eb
--- /dev/null
+++ b/packages/docs-drawing-ui/src/controllers/drawing-popup-menu.controller.ts
@@ -0,0 +1,179 @@
+/**
+ * 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 { DocumentDataModel, Nullable } from '@univerjs/core';
+import { ICommandService, IDrawingManagerService, IUniverInstanceService, LifecycleStages, LocaleService, OnLifecycle, RxDisposable, toDisposable, UniverInstanceType } from '@univerjs/core';
+import type { IDisposable } from '@wendellhu/redi';
+import { Inject, Injector } from '@wendellhu/redi';
+import type { BaseObject, Scene } from '@univerjs/engine-render';
+import { IRenderManagerService } from '@univerjs/engine-render';
+import { COMPONENT_IMAGE_POPUP_MENU, ImageResetSizeOperation, OpenImageCropOperation } from '@univerjs/drawing-ui';
+import { takeUntil } from 'rxjs';
+import { ImageCropperObject } from '@univerjs/drawing-ui/views/crop/image-cropper-object.js';
+import { DocCanvasPopManagerService } from '@univerjs/docs-ui';
+import { RemoveDocDrawingCommand } from '../commands/commands/remove-doc-drawing.command';
+import { EditDocDrawingOperation } from '../commands/operations/edit-doc-drawing.operation';
+
+@OnLifecycle(LifecycleStages.Rendered, DocDrawingPopupMenuController)
+export class DocDrawingPopupMenuController extends RxDisposable {
+ private _initImagePopupMenu = new Set<string>();
+
+ constructor(
+ @Inject(Injector) private readonly _injector: Injector,
+ @IDrawingManagerService private readonly _drawingManagerService: IDrawingManagerService,
+ @Inject(DocCanvasPopManagerService) private readonly _canvasPopManagerService: DocCanvasPopManagerService,
+ @IRenderManagerService private readonly _renderManagerService: IRenderManagerService,
+ @IUniverInstanceService private readonly _univerInstanceService: IUniverInstanceService,
+ @Inject(LocaleService) private readonly _localeService: LocaleService,
+ @ICommandService private readonly _commandService: ICommandService
+
+ ) {
+ super();
+
+ this._init();
+ }
+
+ private _init(): void {
+ this._univerInstanceService.getCurrentTypeOfUnit$<DocumentDataModel>(UniverInstanceType.UNIVER_DOC).pipe(takeUntil(this.dispose$)).subscribe((documentDataModel) => this._create(documentDataModel));
+ this._univerInstanceService.getTypeOfUnitDisposed$<DocumentDataModel>(UniverInstanceType.UNIVER_DOC).pipe(takeUntil(this.dispose$)).subscribe((documentDataModel) => this._dispose(documentDataModel));
+ this._univerInstanceService.getAllUnitsForType<DocumentDataModel>(UniverInstanceType.UNIVER_DOC).forEach((documentDataModel) => this._create(documentDataModel));
+ }
+
+ private _dispose(documentDataModel: DocumentDataModel) {
+ const unitId = documentDataModel.getUnitId();
+ this._renderManagerService.removeRender(unitId);
+ }
+
+ private _create(documentDataModel: Nullable<DocumentDataModel>) {
+ if (!documentDataModel) {
+ return;
+ }
+
+ const unitId = documentDataModel.getUnitId();
+ if (this._renderManagerService.has(unitId) && !this._initImagePopupMenu.has(unitId)) {
+ this._popupMenuListener(unitId);
+ this._initImagePopupMenu.add(unitId);
+ }
+ }
+
+ private _hasCropObject(scene: Scene) {
+ const objects = scene.getAllObjects();
+
+ for (const object of objects) {
+ if (object instanceof ImageCropperObject) {
+ return true;
+ }
+ }
+
+ return false;
+ }
+
+ private _popupMenuListener(unitId: string) {
+ const scene = this._renderManagerService.getRenderById(unitId)?.scene;
+ if (!scene) {
+ return;
+ }
+ const transformer = scene.getTransformerByCreate();
+ if (!transformer) {
+ return;
+ }
+
+ const disposePopups: IDisposable[] = [];
+
+ this.disposeWithMe(
+ toDisposable(
+ transformer.onCreateControlObservable.add(() => {
+ if (this._hasCropObject(scene)) {
+ return;
+ }
+
+ const selectedObjects = transformer.getSelectedObjectMap();
+ if (selectedObjects.size > 1) {
+ disposePopups.forEach((dispose) => dispose.dispose());
+ return;
+ }
+
+ const object = selectedObjects.values().next().value as Nullable<BaseObject>;
+ if (!object) {
+ return;
+ }
+
+ const oKey = object.oKey;
+ const drawingParam = this._drawingManagerService.getDrawingOKey(oKey);
+ if (!drawingParam) {
+ return;
+ }
+
+ const { unitId, subUnitId, drawingId } = drawingParam;
+
+ disposePopups.push(this.disposeWithMe(this._canvasPopManagerService.attachPopupToObject(object, {
+ componentKey: COMPONENT_IMAGE_POPUP_MENU,
+ direction: 'horizontal',
+ offset: [2, 0],
+ extraProps: {
+ menuItems: this._getImageMenuItems(unitId, subUnitId, drawingId),
+ },
+ })));
+ })
+ )
+ );
+
+ this.disposeWithMe(
+ toDisposable(
+ transformer.onClearControlObservable.add((changeSelf) => {
+ disposePopups.forEach((dispose) => dispose.dispose());
+
+ // if (changeSelf === true) {
+ // this._commandService.executeCommand(SidebarSheetDrawingOperation.id, { value: 'close' });
+ // }
+ })
+ )
+ );
+ }
+
+ private _getImageMenuItems(unitId: string, subUnitId: string, drawingId: string) {
+ return [
+ {
+ label: 'image-popup.edit',
+ index: 0,
+ commandId: EditDocDrawingOperation.id,
+ commandParams: { unitId, subUnitId, drawingId },
+ disable: false,
+ },
+ {
+ label: 'image-popup.delete',
+ index: 1,
+ commandId: RemoveDocDrawingCommand.id,
+ commandParams: { unitId, drawings: [{ unitId, subUnitId, drawingId }] },
+ disable: false,
+ },
+ {
+ label: 'image-popup.crop',
+ index: 2,
+ commandId: OpenImageCropOperation.id,
+ commandParams: { unitId, subUnitId, drawingId },
+ disable: false,
+ },
+ {
+ label: 'image-popup.reset',
+ index: 3,
+ commandId: ImageResetSizeOperation.id,
+ commandParams: [{ unitId, subUnitId, drawingId }],
+ disable: false,
+ },
+ ];
+ }
+}
diff --git a/packages/docs-drawing-ui/src/controllers/shortcuts/drawing.shortcut.ts b/packages/docs-drawing-ui/src/controllers/shortcuts/drawing.shortcut.ts
new file mode 100644
index 0000000000..2cb053d843
--- /dev/null
+++ b/packages/docs-drawing-ui/src/controllers/shortcuts/drawing.shortcut.ts
@@ -0,0 +1,86 @@
+/**
+ * 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 { IContextService } from '@univerjs/core';
+import { Direction, FOCUSING_COMMON_DRAWINGS, FOCUSING_UNIVER_EDITOR } from '@univerjs/core';
+import type { IShortcutItem } from '@univerjs/ui';
+import { KeyCode } from '@univerjs/ui';
+import { type IMoveDrawingsCommandParams, MoveDocDrawingsCommand } from '../../commands/commands/move-drawings.command';
+import { DeleteDocDrawingsCommand } from '../../commands/commands/delete-drawings.command';
+
+export function whenDocDrawingFocused(contextService: IContextService): boolean {
+ return (
+ !contextService.getContextValue(FOCUSING_UNIVER_EDITOR) &&
+ contextService.getContextValue(FOCUSING_COMMON_DRAWINGS)
+ );
+}
+
+export const MoveDrawingDownShortcutItem: IShortcutItem<IMoveDrawingsCommandParams> = {
+ id: MoveDocDrawingsCommand.id,
+ description: 'shortcut.doc.drawing-move-down',
+ group: '4_doc-drawing-view',
+ binding: KeyCode.ARROW_DOWN,
+ priority: 100,
+ preconditions: whenDocDrawingFocused,
+ staticParameters: {
+ direction: Direction.DOWN,
+ },
+};
+
+export const MoveDrawingUpShortcutItem: IShortcutItem<IMoveDrawingsCommandParams> = {
+ id: MoveDocDrawingsCommand.id,
+ description: 'shortcut.doc.drawing-move-up',
+ group: '4_doc-drawing-view',
+ binding: KeyCode.ARROW_UP,
+ priority: 100,
+ preconditions: whenDocDrawingFocused,
+ staticParameters: {
+ direction: Direction.UP,
+ },
+};
+
+export const MoveDrawingLeftShortcutItem: IShortcutItem<IMoveDrawingsCommandParams> = {
+ id: MoveDocDrawingsCommand.id,
+ description: 'shortcut.doc.drawing-move-left',
+ group: '4_doc-drawing-view',
+ binding: KeyCode.ARROW_LEFT,
+ priority: 100,
+ preconditions: whenDocDrawingFocused,
+ staticParameters: {
+ direction: Direction.LEFT,
+ },
+};
+
+export const MoveDrawingRightShortcutItem: IShortcutItem<IMoveDrawingsCommandParams> = {
+ id: MoveDocDrawingsCommand.id,
+ description: 'shortcut.doc.drawing-move-right',
+ group: '4_doc-drawing-view',
+ binding: KeyCode.ARROW_RIGHT,
+ priority: 100,
+ preconditions: whenDocDrawingFocused,
+ staticParameters: {
+ direction: Direction.RIGHT,
+ },
+};
+export const DeleteDrawingsShortcutItem: IShortcutItem = {
+ id: DeleteDocDrawingsCommand.id,
+ description: 'shortcut.doc.drawing-delete',
+ group: '4_doc-drawing-view',
+ // when focusing on any other input tag do not trigger this shortcut
+ preconditions: whenDocDrawingFocused,
+ binding: KeyCode.DELETE,
+ mac: KeyCode.BACKSPACE,
+};
diff --git a/packages/image/src/index.ts b/packages/docs-drawing-ui/src/index.ts
similarity index 81%
rename from packages/image/src/index.ts
rename to packages/docs-drawing-ui/src/index.ts
index 8d1df3fc70..13da4ea6e8 100644
--- a/packages/image/src/index.ts
+++ b/packages/docs-drawing-ui/src/index.ts
@@ -14,5 +14,4 @@
* limitations under the License.
*/
-export { UniverImagePlugin } from './plugin';
-export { ImageManagerService, IImageManagerService } from './services/image-manager.service';
+export { UniverDocsDrawingUIPlugin } from './plugin';
diff --git a/packages/docs-drawing-ui/src/locale/en-US.ts b/packages/docs-drawing-ui/src/locale/en-US.ts
new file mode 100644
index 0000000000..6e28db307d
--- /dev/null
+++ b/packages/docs-drawing-ui/src/locale/en-US.ts
@@ -0,0 +1,44 @@
+/**
+ * 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.
+ */
+
+const locale = {
+ docImage: {
+ title: 'Image',
+
+ upload: {
+ float: 'Insert Image',
+ },
+
+ panel: {
+ title: 'Edit Image',
+ },
+ },
+ 'image-popup': {
+ replace: 'Replace',
+ delete: 'Delete',
+ edit: 'Edit',
+ crop: 'Crop',
+ reset: 'Reset Size',
+ },
+ 'update-status': {
+ exceedMaxSize: 'Image size exceeds limit, limit is {0}M',
+ invalidImageType: 'Invalid image type',
+ exceedMaxCount: 'Only {0} images can be uploaded at a time',
+ invalidImage: 'Invalid image',
+ },
+};
+
+export default locale;
diff --git a/packages/docs-drawing-ui/src/locale/index.ts b/packages/docs-drawing-ui/src/locale/index.ts
new file mode 100644
index 0000000000..1eff5fc204
--- /dev/null
+++ b/packages/docs-drawing-ui/src/locale/index.ts
@@ -0,0 +1,18 @@
+/**
+ * Copyright 2023-present DreamNum Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+export { default as enUS } from './en-US';
+export { default as zhCN } from './zh-CN';
diff --git a/packages/docs-drawing-ui/src/locale/ru-RU.ts b/packages/docs-drawing-ui/src/locale/ru-RU.ts
new file mode 100644
index 0000000000..fcea4bc6cb
--- /dev/null
+++ b/packages/docs-drawing-ui/src/locale/ru-RU.ts
@@ -0,0 +1,46 @@
+/**
+ * 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 enUS from './en-US';
+
+const locale: typeof enUS = {
+ docImage: {
+ title: 'Изображение',
+
+ upload: {
+ float: 'Вставить изображение',
+ },
+
+ panel: {
+ title: 'Редактировать изображение',
+ },
+ },
+ 'image-popup': {
+ replace: 'Заменить',
+ delete: 'Удалить',
+ edit: 'Редактировать',
+ crop: 'Обрезать',
+ reset: 'Сбросить размер',
+ },
+ 'update-status': {
+ exceedMaxSize: 'Размер изображения превышает лимит, лимит составляет {0}М',
+ invalidImageType: 'Недопустимый тип изображения',
+ exceedMaxCount: 'За один раз можно загрузить только {0} изображений',
+ invalidImage: 'Недопустимое изображение',
+ },
+};
+
+export default locale;
diff --git a/packages/docs-drawing-ui/src/locale/zh-CN.ts b/packages/docs-drawing-ui/src/locale/zh-CN.ts
new file mode 100644
index 0000000000..3d2c99ff6d
--- /dev/null
+++ b/packages/docs-drawing-ui/src/locale/zh-CN.ts
@@ -0,0 +1,46 @@
+/**
+ * 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 enUS from './en-US';
+
+const locale: typeof enUS = {
+ docImage: {
+ title: '图片',
+
+ upload: {
+ float: '插入图片',
+ },
+
+ panel: {
+ title: '编辑图片',
+ },
+ },
+ 'image-popup': {
+ replace: '替换',
+ delete: '删除',
+ edit: '编辑',
+ crop: '裁剪',
+ reset: '重置大小',
+ },
+ 'update-status': {
+ exceedMaxSize: '图片大小超过限制, 限制为{0}M',
+ invalidImageType: '图片类型错误',
+ exceedMaxCount: '图片只能一次上传{0}张',
+ invalidImage: '无效图片',
+ },
+};
+
+export default locale;
diff --git a/packages/docs-drawing-ui/src/plugin.ts b/packages/docs-drawing-ui/src/plugin.ts
new file mode 100644
index 0000000000..a801e754db
--- /dev/null
+++ b/packages/docs-drawing-ui/src/plugin.ts
@@ -0,0 +1,60 @@
+/**
+ * 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 { LocaleService, Plugin, UniverInstanceType } from '@univerjs/core';
+import type { Dependency } from '@wendellhu/redi';
+import { Inject, Injector } from '@wendellhu/redi';
+import { enUS, zhCN } from './locale';
+import { DocDrawingPopupMenuController } from './controllers/drawing-popup-menu.controller';
+import { DocDrawingUIController } from './controllers/doc-drawing.controller';
+import { DocDrawingUpdateController } from './controllers/doc-drawing-update.controller';
+
+const PLUGIN_NAME = 'Docs_Drawing_UI_PLUGIN';
+
+export class UniverDocsDrawingUIPlugin extends Plugin {
+ static override type = UniverInstanceType.UNIVER_DOC;
+ static override pluginName = PLUGIN_NAME;
+ constructor(
+ config: undefined,
+ @Inject(Injector) protected _injector: Injector,
+ @Inject(LocaleService) private readonly _localeService: LocaleService
+ ) {
+ super();
+
+ this._localeService.load({
+ zhCN,
+ enUS,
+ });
+ }
+
+ override onStarting(_injector: Injector): void {
+ this._initDependencies(_injector);
+ }
+
+ private _initDependencies(injector: Injector): void {
+ const dependencies: Dependency[] = [
+
+ // services
+
+ // controllers
+ [DocDrawingUIController],
+ [DocDrawingUpdateController],
+ [DocDrawingPopupMenuController],
+ ];
+
+ dependencies.forEach((dependency) => injector.add(dependency));
+ }
+}
diff --git a/packages/docs-drawing-ui/src/views/doc-image-panel/DocDrawingAnchor.tsx b/packages/docs-drawing-ui/src/views/doc-image-panel/DocDrawingAnchor.tsx
new file mode 100644
index 0000000000..4ccbaa200a
--- /dev/null
+++ b/packages/docs-drawing-ui/src/views/doc-image-panel/DocDrawingAnchor.tsx
@@ -0,0 +1,160 @@
+/**
+ * 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 { IDrawingParam, Nullable } from '@univerjs/core';
+import { ICommandService, IDrawingManagerService, LocaleService } from '@univerjs/core';
+import { useDependency } from '@wendellhu/redi/react-bindings';
+import React, { useEffect, useState } from 'react';
+import clsx from 'clsx';
+import styles from '@univerjs/drawing-ui/views/panel/index.module.less';
+import type { BaseObject } from '@univerjs/engine-render';
+import { IRenderManagerService } from '@univerjs/engine-render';
+import type { IDocDrawing } from '@univerjs/docs';
+import { SetDocDrawingCommand } from '../../commands/commands/set-doc-drawing.command';
+
+export interface IDocDrawingAnchorProps {
+ drawings: IDrawingParam[];
+}
+
+export const DocDrawingAnchor = (props: IDocDrawingAnchorProps) => {
+ const commandService = useDependency(ICommandService);
+ const localeService = useDependency(LocaleService);
+ const drawingManagerService = useDependency(IDrawingManagerService);
+ const renderManagerService = useDependency(IRenderManagerService);
+
+ const { drawings } = props;
+
+ const drawingParam = drawings[0] as IDocDrawing;
+
+ if (drawingParam == null) {
+ return;
+ }
+
+ const { unitId } = drawingParam;
+
+ const renderObject = renderManagerService.getRenderById(unitId);
+ const scene = renderObject?.scene;
+ if (scene == null) {
+ return;
+ }
+ const transformer = scene.getTransformerByCreate();
+
+ const [anchorShow, setAnchorShow] = useState(true);
+
+ // const type = drawingParam.anchorType ?? SheetDrawingAnchorType.Position;
+ const [value, setValue] = useState('');
+
+ function getUpdateParams(objects: Map<string, BaseObject>, drawingManagerService: IDrawingManagerService): Nullable<IDocDrawing>[] {
+ const params: Nullable<IDocDrawing>[] = [];
+ objects.forEach((object) => {
+ const { oKey } = object;
+
+ const searchParam = drawingManagerService.getDrawingOKey(oKey);
+
+ if (searchParam == null) {
+ params.push(null);
+ return true;
+ }
+
+ // const { unitId, subUnitId, drawingId, drawingType, anchorType, docTransform } = searchParam as IDocDrawing;
+
+ // params.push({
+ // unitId,
+ // subUnitId,
+ // drawingId,
+ // anchorType,
+ // sheetTransform,
+ // drawingType,
+ // });
+ });
+
+ return params;
+ }
+
+ useEffect(() => {
+ const onClearControlObserver = transformer.onClearControlObservable.add((changeSelf) => {
+ if (changeSelf === true) {
+ setAnchorShow(false);
+ }
+ });
+
+ const onChangeStartObserver = transformer.onChangeStartObservable.add((state) => {
+ const { objects } = state;
+ const params = getUpdateParams(objects, drawingManagerService);
+
+ // if (params.length === 0) {
+ // setAnchorShow(false);
+ // } else if (params.length >= 1) {
+ // setAnchorShow(true);
+ // const anchorType = params[0]?.anchorType || SheetDrawingAnchorType.Position;
+ // setValue(anchorType);
+ // }
+ });
+
+ return () => {
+ onChangeStartObserver?.dispose();
+ onClearControlObserver?.dispose();
+ };
+ }, []);
+
+ function handleChange(value: string | number | boolean) {
+ setValue((value as string));
+
+ const focusDrawings = drawingManagerService.getFocusDrawings();
+ if (focusDrawings.length === 0) {
+ return;
+ }
+
+ const updateParams = focusDrawings.map((drawing) => {
+ return {
+ unitId: drawing.unitId,
+ subUnitId: drawing.subUnitId,
+ drawingId: drawing.drawingId,
+ anchorType: value,
+ };
+ });
+
+ commandService.executeCommand(SetDocDrawingCommand.id, {
+ unitId: focusDrawings[0].unitId,
+ drawings: updateParams,
+ });
+ }
+
+ const gridDisplay = (isShow: boolean) => {
+ return isShow ? 'block' : 'none';
+ };
+
+ return (
+ <div className={clsx(styles.imageCommonPanelGrid, styles.imageCommonPanelBorder)} style={{ display: gridDisplay(anchorShow) }}>
+ <div className={styles.imageCommonPanelRow}>
+ <div className={clsx(styles.imageCommonPanelColumn, styles.imageCommonPanelTitle)}>
+ <div>{localeService.t('drawing-anchor.title')}</div>
+ </div>
+ </div>
+ <div className={clsx(styles.imageCommonPanelRow)}>
+ <div className={clsx(styles.imageCommonPanelColumn)}>
+ {
+ // <RadioGroup value={value} onChange={handleChange} direction="vertical">
+ // <Radio value={SheetDrawingAnchorType.Both}>{localeService.t('drawing-anchor.both')}</Radio>
+ // <Radio value={SheetDrawingAnchorType.Position}>{localeService.t('drawing-anchor.position')}</Radio>
+ // <Radio value={SheetDrawingAnchorType.None}>{localeService.t('drawing-anchor.none')}</Radio>
+ // </RadioGroup>
+ }
+ </div>
+ </div>
+ </div>
+ );
+};
diff --git a/packages/docs-drawing-ui/src/views/doc-image-panel/DocDrawingPanel.tsx b/packages/docs-drawing-ui/src/views/doc-image-panel/DocDrawingPanel.tsx
new file mode 100644
index 0000000000..2268d85d80
--- /dev/null
+++ b/packages/docs-drawing-ui/src/views/doc-image-panel/DocDrawingPanel.tsx
@@ -0,0 +1,52 @@
+/**
+ * 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 { IDrawingParam } from '@univerjs/core';
+import { IDrawingManagerService } from '@univerjs/core';
+import { useDependency } from '@wendellhu/redi/react-bindings';
+import React, { useEffect, useState } from 'react';
+import { DrawingCommonPanel } from '@univerjs/drawing-ui';
+import styles from '@univerjs/drawing-ui/views/panel/index.module.less';
+import { DocDrawingAnchor } from './DocDrawingAnchor';
+
+export const DocDrawingPanel = () => {
+ const drawingManagerService = useDependency(IDrawingManagerService);
+ const focusDrawings = drawingManagerService.getFocusDrawings();
+
+ if (focusDrawings == null || focusDrawings.length === 0) {
+ return;
+ }
+
+ const [drawings, setDrawings] = useState<IDrawingParam[]>(focusDrawings);
+
+ useEffect(() => {
+ const focusDispose = drawingManagerService.focus$.subscribe((drawings) => {
+ setDrawings(drawings);
+ });
+
+ return () => {
+ focusDispose.unsubscribe();
+ };
+ }, []);
+
+ return (
+ <div className={styles.imageCommonPanel}>
+ <DrawingCommonPanel drawings={drawings} />
+ <DocDrawingAnchor drawings={drawings} />
+ </div>
+ );
+};
+
diff --git a/packages/docs-drawing-ui/src/views/doc-image-panel/component-name.ts b/packages/docs-drawing-ui/src/views/doc-image-panel/component-name.ts
new file mode 100644
index 0000000000..fc2116f27d
--- /dev/null
+++ b/packages/docs-drawing-ui/src/views/doc-image-panel/component-name.ts
@@ -0,0 +1,17 @@
+/**
+ * Copyright 2023-present DreamNum Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+export const COMPONENT_DOC_DRAWING_PANEL = 'COMPONENT_DOC_DRAWING_PANEL';
diff --git a/packages/docs-drawing-ui/src/views/doc-image-panel/index.module.less b/packages/docs-drawing-ui/src/views/doc-image-panel/index.module.less
new file mode 100644
index 0000000000..703b56678d
--- /dev/null
+++ b/packages/docs-drawing-ui/src/views/doc-image-panel/index.module.less
@@ -0,0 +1,12 @@
+.sheet-image {
+ &-menu {
+ position: absolute;
+ height: 100%;
+ width: 100%;
+ text-align: center;
+
+ &-input {
+ display: none;
+ }
+ }
+}
diff --git a/packages/docs-drawing-ui/src/views/menu/image.menu.ts b/packages/docs-drawing-ui/src/views/menu/image.menu.ts
new file mode 100644
index 0000000000..2dca82b4f9
--- /dev/null
+++ b/packages/docs-drawing-ui/src/views/menu/image.menu.ts
@@ -0,0 +1,50 @@
+/**
+ * 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 { getMenuHiddenObservable, type IMenuItem, MenuGroup, MenuItemType, MenuPosition } from '@univerjs/ui';
+import type { IAccessor } from '@wendellhu/redi';
+import { UniverInstanceType } from '@univerjs/core';
+
+import { COMPONENT_DOC_UPLOAD_FILE_MENU } from '../upload-component/component-name';
+import { InsertDocImageOperation } from '../../commands/operations/insert-image.operation';
+
+export const ImageUploadIcon = 'addition-and-subtraction-single';
+const IMAGE_MENU_ID = 'doc.menu.image';
+
+export function ImageMenuFactory(accessor: IAccessor): IMenuItem {
+ return {
+ id: IMAGE_MENU_ID,
+ type: MenuItemType.SUBITEMS,
+ positions: [MenuPosition.TOOLBAR_START],
+ group: MenuGroup.TOOLBAR_LAYOUT,
+ icon: ImageUploadIcon,
+ tooltip: 'docImage.title',
+ hidden$: getMenuHiddenObservable(accessor, UniverInstanceType.UNIVER_DOC),
+ };
+}
+
+export function UploadFloatImageMenuFactory(_accessor: IAccessor): IMenuItem {
+ return {
+ id: InsertDocImageOperation.id,
+ title: 'docImage.upload.float',
+ type: MenuItemType.SELECTOR,
+ label: {
+ name: COMPONENT_DOC_UPLOAD_FILE_MENU,
+ },
+ positions: [IMAGE_MENU_ID],
+ hidden$: getMenuHiddenObservable(_accessor, UniverInstanceType.UNIVER_DOC),
+ };
+}
diff --git a/packages/docs-drawing-ui/src/views/upload-component/UploadFile.tsx b/packages/docs-drawing-ui/src/views/upload-component/UploadFile.tsx
new file mode 100644
index 0000000000..710464d268
--- /dev/null
+++ b/packages/docs-drawing-ui/src/views/upload-component/UploadFile.tsx
@@ -0,0 +1,63 @@
+/**
+ * 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 { ICommandService } from '@univerjs/core';
+import { useDependency } from '@wendellhu/redi/react-bindings';
+import React, { useRef } from 'react';
+import { DRAWING_IMAGE_ALLOW_IMAGE_LIST } from '@univerjs/drawing';
+import { InsertDocImageOperation } from '../../commands/operations/insert-image.operation';
+import styles from './index.module.less';
+
+export const UploadFileMenu = () => {
+ const commandService = useDependency(ICommandService);
+
+ const fileInputRef = useRef<HTMLInputElement>(null);
+
+ const handleButtonClick = () => {
+ fileInputRef.current?.click();
+ };
+
+ const imageAccept = DRAWING_IMAGE_ALLOW_IMAGE_LIST.map((image) => `.${image.replace('image/', '')}`).join(',');
+
+ const handleFileChange = (event: React.ChangeEvent<HTMLInputElement>) => {
+ const fileList = event.target.files;
+
+ if (fileList == null) {
+ return;
+ }
+
+ const files: File[] = Array.from(fileList);
+
+ commandService.executeCommand(InsertDocImageOperation.id, { files });
+
+ if (fileInputRef.current) {
+ fileInputRef.current.value = '';
+ }
+ };
+
+ return (
+ <div onClick={handleButtonClick} className={styles.uploadFileMenu}>
+ <input
+ type="file"
+ className={styles.uploadFileMenuInput}
+ ref={fileInputRef}
+ onChange={handleFileChange}
+ accept={imageAccept}
+ multiple
+ />
+ </div>
+ );
+};
diff --git a/packages/docs-drawing-ui/src/views/upload-component/component-name.ts b/packages/docs-drawing-ui/src/views/upload-component/component-name.ts
new file mode 100644
index 0000000000..d268d7573a
--- /dev/null
+++ b/packages/docs-drawing-ui/src/views/upload-component/component-name.ts
@@ -0,0 +1,17 @@
+/**
+ * Copyright 2023-present DreamNum Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+export const COMPONENT_DOC_UPLOAD_FILE_MENU = 'COMPONENT_DOC_UPLOAD_FILE_MENU';
diff --git a/packages/docs-drawing-ui/src/views/upload-component/index.module.less b/packages/docs-drawing-ui/src/views/upload-component/index.module.less
new file mode 100644
index 0000000000..963abf12ee
--- /dev/null
+++ b/packages/docs-drawing-ui/src/views/upload-component/index.module.less
@@ -0,0 +1,12 @@
+.upload-file {
+ &-menu {
+ position: absolute;
+ height: 100%;
+ width: 100%;
+ text-align: center;
+
+ &-input {
+ display: none;
+ }
+ }
+}
diff --git a/packages/docs-drawing-ui/src/vite-env.d.ts b/packages/docs-drawing-ui/src/vite-env.d.ts
new file mode 100644
index 0000000000..11f02fe2a0
--- /dev/null
+++ b/packages/docs-drawing-ui/src/vite-env.d.ts
@@ -0,0 +1 @@
+/// <reference types="vite/client" />
diff --git a/packages/image/tsconfig.json b/packages/docs-drawing-ui/tsconfig.json
similarity index 100%
rename from packages/image/tsconfig.json
rename to packages/docs-drawing-ui/tsconfig.json
diff --git a/packages/image/tsconfig.node.json b/packages/docs-drawing-ui/tsconfig.node.json
similarity index 100%
rename from packages/image/tsconfig.node.json
rename to packages/docs-drawing-ui/tsconfig.node.json
diff --git a/packages/docs-drawing-ui/vite.config.ts b/packages/docs-drawing-ui/vite.config.ts
new file mode 100644
index 0000000000..925b530b4d
--- /dev/null
+++ b/packages/docs-drawing-ui/vite.config.ts
@@ -0,0 +1,12 @@
+import createViteConfig from '@univerjs/shared/vite';
+import pkg from './package.json';
+
+export default ({ mode }) => createViteConfig({}, {
+ mode,
+ pkg,
+ features: {
+ react: false,
+ css: true,
+ dom: true,
+ },
+});
diff --git a/packages/docs-ui/src/basics/transform-position.ts b/packages/docs-ui/src/basics/transform-position.ts
new file mode 100644
index 0000000000..c28c013b43
--- /dev/null
+++ b/packages/docs-ui/src/basics/transform-position.ts
@@ -0,0 +1,117 @@
+/**
+ * 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 IDocDrawingPosition, type ITransformState, type Nullable, ObjectRelativeFromH, ObjectRelativeFromV } from '@univerjs/core';
+import type { ITextSelectionRenderManager } from '@univerjs/engine-render';
+
+export function docDrawingPositionToTransform(position: IDocDrawingPosition, textSelectionRenderService: ITextSelectionRenderManager): Nullable<ITransformState> {
+ // const { from, to } = position;
+ // const { column: fromColumn, columnOffset: fromColumnOffset, row: fromRow, rowOffset: fromRowOffset } = from;
+ // const { column: toColumn, columnOffset: toColumnOffset, row: toRow, rowOffset: toRowOffset } = to;
+
+ // const startSelectionCell = selectionRenderService.attachRangeWithCoord({
+ // startColumn: fromColumn,
+ // endColumn: fromColumn,
+ // startRow: fromRow,
+ // endRow: fromRow,
+ // });
+
+ // if (startSelectionCell == null) {
+ // return;
+ // }
+
+ // const endSelectionCell = selectionRenderService.attachRangeWithCoord({
+ // startColumn: toColumn,
+ // endColumn: toColumn,
+ // startRow: toRow,
+ // endRow: toRow,
+ // });
+
+ // if (endSelectionCell == null) {
+ // return;
+ // }
+
+ // const { startX: startSelectionX, startY: startSelectionY } = startSelectionCell;
+
+ // const { startX: endSelectionX, startY: endSelectionY } = endSelectionCell;
+
+ // const left = precisionTo(startSelectionX + fromColumnOffset, 1);
+ // const top = precisionTo(startSelectionY + fromRowOffset, 1);
+
+ // const width = precisionTo(endSelectionX + toColumnOffset - left, 1);
+ // const height = precisionTo(endSelectionY + toRowOffset - top, 1);
+
+ // return {
+ // left,
+ // top,
+ // width,
+ // height,
+ // };
+
+ return {
+ left: position.positionH.posOffset,
+ top: position.positionV.posOffset,
+ width: position.size.width,
+ height: position.size.height,
+ };
+}
+
+// use transform and originSize convert to ISheetDrawingPosition
+export function transformToDocDrawingPosition(transform: ITransformState, marginLeft: number = 0, marginTop: number = 0): Nullable<IDocDrawingPosition> {
+ // const { left = 0, top = 0, width = 0, height = 0 } = transform;
+
+ // const startSelectionCell = selectionRenderService.getSelectionCellByPosition(left, top);
+
+ // if (startSelectionCell == null) {
+ // return;
+ // }
+
+ // const from = {
+ // column: startSelectionCell.actualColumn,
+ // columnOffset: precisionTo(left - startSelectionCell.startX, 1),
+ // row: startSelectionCell.actualRow,
+ // rowOffset: precisionTo(top - startSelectionCell.startY, 1),
+ // };
+
+ // const endSelectionCell = selectionRenderService.getSelectionCellByPosition(left + width, top + height);
+
+ // if (endSelectionCell == null) {
+ // return;
+ // }
+
+ // const to = {
+ // column: endSelectionCell.actualColumn,
+ // columnOffset: precisionTo(left + width - endSelectionCell.startX, 1),
+ // row: endSelectionCell.actualRow,
+ // rowOffset: precisionTo(top + height - endSelectionCell.startY, 1),
+ // };
+
+ return {
+ size: {
+ width: transform.width,
+ height: transform.height,
+ },
+ positionH: {
+ relativeFrom: ObjectRelativeFromH.MARGIN,
+ posOffset: (transform.left || 0) - marginLeft,
+ },
+ positionV: {
+ relativeFrom: ObjectRelativeFromV.PAGE,
+ posOffset: (transform.top || 0) - marginTop,
+ },
+ angle: transform.angle || 0,
+ };
+}
diff --git a/packages/docs-ui/src/controllers/doc-floating-object.controller.ts b/packages/docs-ui/src/controllers/doc-floating-object.controller.ts
index ad57ec71dc..9567211579 100644
--- a/packages/docs-ui/src/controllers/doc-floating-object.controller.ts
+++ b/packages/docs-ui/src/controllers/doc-floating-object.controller.ts
@@ -14,13 +14,13 @@
* limitations under the License.
*/
-import type { ICommandInfo, IFloatingObjectManagerParam } from '@univerjs/core';
+import type { ICommandInfo } from '@univerjs/core';
import {
BooleanNumber,
DEFAULT_DOCUMENT_SUB_COMPONENT_ID,
Disposable,
ICommandService,
- IFloatingObjectManagerService,
+ IDrawingManagerService,
IUniverInstanceService,
LifecycleStages,
OnLifecycle,
@@ -44,7 +44,7 @@ export class DocFloatingObjectController extends Disposable {
@IUniverInstanceService private readonly _univerInstanceService: IUniverInstanceService,
@IRenderManagerService private readonly _renderManagerService: IRenderManagerService,
@ICommandService private readonly _commandService: ICommandService,
- @IFloatingObjectManagerService private readonly _floatingObjectManagerService: IFloatingObjectManagerService,
+ @IDrawingManagerService private readonly _drawingManagerService: IDrawingManagerService,
@IEditorService private readonly _editorService: IEditorService
) {
super();
@@ -61,51 +61,51 @@ export class DocFloatingObjectController extends Disposable {
}
private _updateOnPluginChange() {
- this._floatingObjectManagerService.pluginUpdate$.subscribe((params) => {
- const docsSkeletonObject = this._docSkeletonManagerService.getCurrent();
+ // this._drawingManagerService.pluginUpdate$.subscribe((params) => {
+ // const docsSkeletonObject = this._docSkeletonManagerService.getCurrent();
- if (docsSkeletonObject == null) {
- return;
- }
+ // if (docsSkeletonObject == null) {
+ // return;
+ // }
- const { unitId, skeleton } = docsSkeletonObject;
+ // const { unitId, skeleton } = docsSkeletonObject;
- const currentRender = this._renderManagerService.getRenderById(unitId);
+ // const currentRender = this._renderManagerService.getRenderById(unitId);
- if (currentRender == null) {
- return;
- }
+ // if (currentRender == null) {
+ // return;
+ // }
- const { mainComponent, components, scene } = currentRender;
+ // const { mainComponent, components, scene } = currentRender;
- const docsComponent = mainComponent as Documents;
+ // const docsComponent = mainComponent as Documents;
- const { left: docsLeft, top: docsTop } = docsComponent;
+ // const { left: docsLeft, top: docsTop } = docsComponent;
- params.forEach((param) => {
- const { unitId, subUnitId, floatingObjectId, floatingObject } = param;
+ // params.forEach((param) => {
+ // const { unitId, subUnitId, drawingId, drawing } = param;
- const { left = 0, top = 0, width = 0, height = 0, angle, flipX, flipY, skewX, skewY } = floatingObject;
+ // const { left = 0, top = 0, width = 0, height = 0, angle, flipX, flipY, skewX, skewY } = drawing;
- const cache = this._pageMarginCache.get(floatingObjectId);
+ // const cache = this._pageMarginCache.get(drawingId);
- const marginLeft = cache?.marginLeft || 0;
- const marginTop = cache?.marginTop || 0;
+ // const marginLeft = cache?.marginLeft || 0;
+ // const marginTop = cache?.marginTop || 0;
- skeleton
- ?.getViewModel()
- .getDataModel()
- .updateDrawing(floatingObjectId, {
- left: left - docsLeft - marginLeft,
- top: top - docsTop - marginTop,
- height,
- width,
- });
- });
+ // skeleton
+ // ?.getViewModel()
+ // .getDataModel()
+ // .updateDrawing(drawingId, {
+ // left: left - docsLeft - marginLeft,
+ // top: top - docsTop - marginTop,
+ // height,
+ // width,
+ // });
+ // });
- skeleton?.calculate();
- mainComponent?.makeDirty();
- });
+ // skeleton?.calculate();
+ // mainComponent?.makeDirty();
+ // });
}
private _initialRenderRefresh() {
@@ -129,7 +129,7 @@ export class DocFloatingObjectController extends Disposable {
// TODO: Why NEED change skeleton here?
docsComponent.changeSkeleton(documentSkeleton);
- this._refreshFloatingObject(unitId, documentSkeleton, currentRender);
+ this._refreshDrawing(unitId, documentSkeleton, currentRender);
});
}
@@ -165,7 +165,7 @@ export class DocFloatingObjectController extends Disposable {
return;
}
- this._refreshFloatingObject(unitId, skeleton, currentRender);
+ this._refreshDrawing(unitId, skeleton, currentRender);
// this.calculatePagePosition(currentRender);
}
@@ -173,7 +173,7 @@ export class DocFloatingObjectController extends Disposable {
);
}
- private _refreshFloatingObject(unitId: string, skeleton: DocumentSkeleton, currentRender: IRender) {
+ private _refreshDrawing(unitId: string, skeleton: DocumentSkeleton, currentRender: IRender) {
const skeletonData = skeleton?.getSkeletonData();
const { mainComponent, scene } = currentRender;
@@ -188,7 +188,7 @@ export class DocFloatingObjectController extends Disposable {
const { pages } = skeletonData;
- const floatObjects: IFloatingObjectManagerParam[] = [];
+ const floatObjects: any[] = []; // IFloatingObjectManagerParam
const { scaleX, scaleY } = scene.getAncestorScale();
@@ -212,13 +212,13 @@ export class DocFloatingObjectController extends Disposable {
this._liquid.translatePagePadding(page);
skeDrawings.forEach((drawing) => {
- const { aLeft, aTop, height, width, objectId, drawingOrigin } = drawing;
+ const { aLeft, aTop, height, width, drawingId, drawingOrigin } = drawing;
const behindText = drawingOrigin.layoutType === PositionedObjectLayoutType.WRAP_NONE && drawingOrigin.behindDoc === BooleanNumber.TRUE;
floatObjects.push({
unitId,
subUnitId: DEFAULT_DOCUMENT_SUB_COMPONENT_ID,
- floatingObjectId: objectId,
+ floatingObjectId: drawingId,
behindText,
floatingObject: {
left: aLeft + docsLeft + this._liquid.x,
@@ -228,7 +228,7 @@ export class DocFloatingObjectController extends Disposable {
},
});
- this._pageMarginCache.set(objectId, {
+ this._pageMarginCache.set(drawingId, {
marginLeft: this._liquid.x,
marginTop: this._liquid.y,
});
@@ -239,6 +239,6 @@ export class DocFloatingObjectController extends Disposable {
this._liquid.translatePage(page, pageLayoutType, pageMarginLeft, pageMarginTop);
}
- this._floatingObjectManagerService.batchAddOrUpdate(floatObjects);
+ // this._floatingObjectManagerService.batchAddOrUpdate(floatObjects);
}
}
diff --git a/packages/docs-ui/src/controllers/doc-ui.controller.ts b/packages/docs-ui/src/controllers/doc-ui.controller.ts
index 9fb24de79e..abfe932659 100644
--- a/packages/docs-ui/src/controllers/doc-ui.controller.ts
+++ b/packages/docs-ui/src/controllers/doc-ui.controller.ts
@@ -14,14 +14,15 @@
* limitations under the License.
*/
-import type { DocumentDataModel } from '@univerjs/core';
-import { Disposable, IUniverInstanceService, LifecycleStages, OnLifecycle, UniverInstanceType } from '@univerjs/core';
+import type { DocumentDataModel, IDrawingMapItemData } from '@univerjs/core';
+import { Disposable, IDrawingManagerService, IUniverInstanceService, LifecycleStages, OnLifecycle, UniverInstanceType } from '@univerjs/core';
import type { IMenuItemFactory } from '@univerjs/ui';
import { BuiltInUIPart, ComponentManager, IEditorService, ILayoutService, IMenuService, IUIPartsService } from '@univerjs/ui';
import { Inject, Injector } from '@wendellhu/redi';
import { connectInjector } from '@wendellhu/redi/react-bindings';
import { ITextSelectionRenderManager } from '@univerjs/engine-render';
+import { type IDocDrawing, IDocDrawingService } from '@univerjs/docs';
import { COLOR_PICKER_COMPONENT, ColorPicker } from '../components/color-picker';
import {
FONT_FAMILY_COMPONENT,
@@ -32,6 +33,7 @@ import {
import { FONT_SIZE_COMPONENT, FontSize } from '../components/font-size';
import { DocBackground } from '../views/doc-background/DocBackground';
import type { IUniverDocsUIConfig } from '../basics';
+import { docDrawingPositionToTransform } from '../basics/transform-position';
import {
AlignCenterMenuItemFactory,
AlignJustifyMenuItemFactory,
@@ -63,7 +65,10 @@ export class DocUIController extends Disposable {
@IEditorService private readonly _editorService: IEditorService,
@IMenuService private readonly _menuService: IMenuService,
@IUIPartsService private readonly _uiPartsService: IUIPartsService,
- @IUniverInstanceService private readonly _univerInstanceService: IUniverInstanceService
+ @IUniverInstanceService private readonly _univerInstanceService: IUniverInstanceService,
+ @Inject(ITextSelectionRenderManager) private readonly _textSelectionRenderManager: ITextSelectionRenderManager,
+ @IDocDrawingService private readonly _docDrawingService: IDocDrawingService,
+ @IDrawingManagerService private readonly _drawingManagerService: IDrawingManagerService
) {
super();
@@ -112,6 +117,7 @@ export class DocUIController extends Disposable {
this._initMenus();
this._initDocBackground();
this._initFocusHandler();
+ this._initDataLoader();
}
private _initDocBackground() {
@@ -136,4 +142,41 @@ export class DocUIController extends Disposable {
})
);
}
+
+ private _initDataLoader() {
+ const dataModel = this._univerInstanceService.getCurrentUnitForType<DocumentDataModel>(UniverInstanceType.UNIVER_DOC);
+ if (!dataModel) {
+ return false;
+ }
+
+ const unitId = dataModel.getUnitId();
+ const subUnitId = unitId;
+
+ const drawingDataModels = dataModel.getDrawings();
+ const drawingOrderModel = dataModel.getDrawingsOrder();
+
+ if (!drawingDataModels || !drawingOrderModel) {
+ return false;
+ }
+
+ Object.keys(drawingDataModels).forEach((drawingId) => {
+ const drawingDataModel = drawingDataModels[drawingId];
+ const docTransform = drawingDataModel.docTransform;
+ const transform = docDrawingPositionToTransform(docTransform, this._textSelectionRenderManager);
+
+ drawingDataModels[drawingId] = { ...drawingDataModel, transform } as IDocDrawing;
+ });
+
+ const subDrawings = {
+ [subUnitId]: {
+ unitId,
+ subUnitId,
+ data: drawingDataModels as IDrawingMapItemData<IDocDrawing>,
+ order: drawingOrderModel,
+ },
+ };
+
+ this._docDrawingService.registerDrawingData(unitId, subDrawings);
+ this._drawingManagerService.registerDrawingData(unitId, subDrawings);
+ }
}
diff --git a/packages/docs-ui/src/controllers/drawing.controller.ts b/packages/docs-ui/src/controllers/drawing.controller.ts
new file mode 100644
index 0000000000..9567211579
--- /dev/null
+++ b/packages/docs-ui/src/controllers/drawing.controller.ts
@@ -0,0 +1,244 @@
+/**
+ * Copyright 2023-present DreamNum Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { ICommandInfo } from '@univerjs/core';
+import {
+ BooleanNumber,
+ DEFAULT_DOCUMENT_SUB_COMPONENT_ID,
+ Disposable,
+ ICommandService,
+ IDrawingManagerService,
+ IUniverInstanceService,
+ LifecycleStages,
+ OnLifecycle,
+ PositionedObjectLayoutType,
+} from '@univerjs/core';
+import type { IRichTextEditingMutationParams } from '@univerjs/docs';
+import { DocSkeletonManagerService, RichTextEditingMutation, SetDocZoomRatioOperation } from '@univerjs/docs';
+import type { Documents, DocumentSkeleton, IRender } from '@univerjs/engine-render';
+import { IRenderManagerService, Liquid } from '@univerjs/engine-render';
+import { IEditorService } from '@univerjs/ui';
+import { Inject } from '@wendellhu/redi';
+
+@OnLifecycle(LifecycleStages.Steady, DocFloatingObjectController)
+export class DocFloatingObjectController extends Disposable {
+ private _liquid = new Liquid();
+
+ private _pageMarginCache = new Map<string, { marginLeft: number; marginTop: number }>();
+
+ constructor(
+ @Inject(DocSkeletonManagerService) private readonly _docSkeletonManagerService: DocSkeletonManagerService,
+ @IUniverInstanceService private readonly _univerInstanceService: IUniverInstanceService,
+ @IRenderManagerService private readonly _renderManagerService: IRenderManagerService,
+ @ICommandService private readonly _commandService: ICommandService,
+ @IDrawingManagerService private readonly _drawingManagerService: IDrawingManagerService,
+ @IEditorService private readonly _editorService: IEditorService
+ ) {
+ super();
+
+ this._initialize();
+
+ this._commandExecutedListener();
+ }
+
+ private _initialize() {
+ this._initialRenderRefresh();
+
+ this._updateOnPluginChange();
+ }
+
+ private _updateOnPluginChange() {
+ // this._drawingManagerService.pluginUpdate$.subscribe((params) => {
+ // const docsSkeletonObject = this._docSkeletonManagerService.getCurrent();
+
+ // if (docsSkeletonObject == null) {
+ // return;
+ // }
+
+ // const { unitId, skeleton } = docsSkeletonObject;
+
+ // const currentRender = this._renderManagerService.getRenderById(unitId);
+
+ // if (currentRender == null) {
+ // return;
+ // }
+
+ // const { mainComponent, components, scene } = currentRender;
+
+ // const docsComponent = mainComponent as Documents;
+
+ // const { left: docsLeft, top: docsTop } = docsComponent;
+
+ // params.forEach((param) => {
+ // const { unitId, subUnitId, drawingId, drawing } = param;
+
+ // const { left = 0, top = 0, width = 0, height = 0, angle, flipX, flipY, skewX, skewY } = drawing;
+
+ // const cache = this._pageMarginCache.get(drawingId);
+
+ // const marginLeft = cache?.marginLeft || 0;
+ // const marginTop = cache?.marginTop || 0;
+
+ // skeleton
+ // ?.getViewModel()
+ // .getDataModel()
+ // .updateDrawing(drawingId, {
+ // left: left - docsLeft - marginLeft,
+ // top: top - docsTop - marginTop,
+ // height,
+ // width,
+ // });
+ // });
+
+ // skeleton?.calculate();
+ // mainComponent?.makeDirty();
+ // });
+ }
+
+ private _initialRenderRefresh() {
+ this._docSkeletonManagerService.currentSkeleton$.subscribe((param) => {
+ if (param == null) {
+ return;
+ }
+
+ const { skeleton: documentSkeleton, unitId } = param;
+
+ const currentRender = this._renderManagerService.getRenderById(unitId);
+
+ if (currentRender == null) {
+ return;
+ }
+
+ const { mainComponent } = currentRender;
+
+ const docsComponent = mainComponent as Documents;
+
+ // TODO: Why NEED change skeleton here?
+ docsComponent.changeSkeleton(documentSkeleton);
+
+ this._refreshDrawing(unitId, documentSkeleton, currentRender);
+ });
+ }
+
+ private _commandExecutedListener() {
+ const updateCommandList = [RichTextEditingMutation.id, SetDocZoomRatioOperation.id];
+
+ this.disposeWithMe(
+ this._commandService.onCommandExecuted((command: ICommandInfo) => {
+ if (updateCommandList.includes(command.id)) {
+ const params = command.params as IRichTextEditingMutationParams;
+ const { unitId: commandUnitId } = params;
+
+ const docsSkeletonObject = this._docSkeletonManagerService.getCurrent();
+
+ if (docsSkeletonObject == null) {
+ return;
+ }
+
+ const { unitId, skeleton } = docsSkeletonObject;
+
+ if (commandUnitId !== unitId) {
+ return;
+ }
+
+ const currentRender = this._renderManagerService.getRenderById(unitId);
+
+ if (currentRender == null) {
+ return;
+ }
+
+ if (this._editorService.isEditor(unitId)) {
+ currentRender.mainComponent?.makeDirty();
+ return;
+ }
+
+ this._refreshDrawing(unitId, skeleton, currentRender);
+
+ // this.calculatePagePosition(currentRender);
+ }
+ })
+ );
+ }
+
+ private _refreshDrawing(unitId: string, skeleton: DocumentSkeleton, currentRender: IRender) {
+ const skeletonData = skeleton?.getSkeletonData();
+
+ const { mainComponent, scene } = currentRender;
+
+ const documentComponent = mainComponent as Documents;
+
+ if (!skeletonData) {
+ return;
+ }
+
+ const { left: docsLeft, top: docsTop, pageLayoutType, pageMarginLeft, pageMarginTop } = documentComponent;
+
+ const { pages } = skeletonData;
+
+ const floatObjects: any[] = []; // IFloatingObjectManagerParam
+
+ const { scaleX, scaleY } = scene.getAncestorScale();
+
+ this._liquid.reset();
+
+ this._pageMarginCache.clear();
+
+ // const objectList: BaseObject[] = [];
+ // const pageMarginCache = new Map<string, { marginLeft: number; marginTop: number }>();
+
+ // const cumPageLeft = 0;
+ // const cumPageTop = 0;
+ /**
+ * TODO: @DR-Univer We should not refresh all floating elements, but instead make a diff.
+ */
+ 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, drawingId, drawingOrigin } = drawing;
+ const behindText = drawingOrigin.layoutType === PositionedObjectLayoutType.WRAP_NONE && drawingOrigin.behindDoc === BooleanNumber.TRUE;
+
+ floatObjects.push({
+ unitId,
+ subUnitId: DEFAULT_DOCUMENT_SUB_COMPONENT_ID,
+ floatingObjectId: drawingId,
+ behindText,
+ floatingObject: {
+ left: aLeft + docsLeft + this._liquid.x,
+ top: aTop + docsTop + this._liquid.y,
+ width,
+ height,
+ },
+ });
+
+ this._pageMarginCache.set(drawingId, {
+ marginLeft: this._liquid.x,
+ marginTop: this._liquid.y,
+ });
+ });
+
+ this._liquid.restorePagePadding(page);
+
+ this._liquid.translatePage(page, pageLayoutType, pageMarginLeft, pageMarginTop);
+ }
+
+ // this._floatingObjectManagerService.batchAddOrUpdate(floatObjects);
+ }
+}
diff --git a/packages/docs-ui/src/controllers/zoom.controller.ts b/packages/docs-ui/src/controllers/zoom.controller.ts
index b966fb5c4a..30d07efac6 100644
--- a/packages/docs-ui/src/controllers/zoom.controller.ts
+++ b/packages/docs-ui/src/controllers/zoom.controller.ts
@@ -186,7 +186,7 @@ export class ZoomController extends Disposable {
this._textSelectionManagerService.refreshSelection();
}
- docObject.scene.getTransformer()?.hideControl();
+ docObject.scene.getTransformer()?.clearSelectedObjects();
}
private _calculatePagePosition(currentRender: IDocObjectParam, zoomRatio: number) {
diff --git a/packages/docs-ui/src/index.ts b/packages/docs-ui/src/index.ts
index d7d5e163fa..212d79eed9 100644
--- a/packages/docs-ui/src/index.ts
+++ b/packages/docs-ui/src/index.ts
@@ -19,3 +19,4 @@ export * from './docs-ui-plugin';
export { DocCanvasView } from './views/doc-canvas-view';
export * from './services';
export { DocCanvasPopManagerService } from './services/doc-popup-manager.service';
+export { docDrawingPositionToTransform, transformToDocDrawingPosition } from './basics/transform-position';
diff --git a/packages/docs-ui/src/shortcuts/utils.ts b/packages/docs-ui/src/shortcuts/utils.ts
index 141050b628..cdd79056c2 100644
--- a/packages/docs-ui/src/shortcuts/utils.ts
+++ b/packages/docs-ui/src/shortcuts/utils.ts
@@ -15,12 +15,12 @@
*/
import type { IContextService } from '@univerjs/core';
-import { FOCUSING_DOC, FOCUSING_UNIVER_EDITOR, FOCUSING_UNIVER_EDITOR_STANDALONE_SINGLE_MODE } from '@univerjs/core';
+import { FOCUSING_COMMON_DRAWINGS, FOCUSING_DOC, FOCUSING_UNIVER_EDITOR, FOCUSING_UNIVER_EDITOR_STANDALONE_SINGLE_MODE } from '@univerjs/core';
export function whenDocAndEditorFocused(contextService: IContextService): boolean {
- return contextService.getContextValue(FOCUSING_DOC) && contextService.getContextValue(FOCUSING_UNIVER_EDITOR);
+ return contextService.getContextValue(FOCUSING_DOC) && contextService.getContextValue(FOCUSING_UNIVER_EDITOR) && !contextService.getContextValue(FOCUSING_COMMON_DRAWINGS);
}
export function whenDocAndEditorFocusedWithBreakLine(contextService: IContextService): boolean {
- return contextService.getContextValue(FOCUSING_DOC) && contextService.getContextValue(FOCUSING_UNIVER_EDITOR) && !contextService.getContextValue(FOCUSING_UNIVER_EDITOR_STANDALONE_SINGLE_MODE);
+ return contextService.getContextValue(FOCUSING_DOC) && contextService.getContextValue(FOCUSING_UNIVER_EDITOR) && !contextService.getContextValue(FOCUSING_UNIVER_EDITOR_STANDALONE_SINGLE_MODE) && !contextService.getContextValue(FOCUSING_COMMON_DRAWINGS);
}
diff --git a/packages/docs-ui/src/views/doc-canvas-view.ts b/packages/docs-ui/src/views/doc-canvas-view.ts
index 62ed751b58..d39f3db66f 100644
--- a/packages/docs-ui/src/views/doc-canvas-view.ts
+++ b/packages/docs-ui/src/views/doc-canvas-view.ts
@@ -98,8 +98,6 @@ export class DocCanvasView extends RxDisposable {
const { scene, engine } = currentRender;
- scene.openTransformer();
-
this._scene = scene;
const viewMain = new Viewport(VIEWPORT_KEY.VIEW_MAIN, scene, {
diff --git a/packages/docs/package.json b/packages/docs/package.json
index cb6daf3de0..5df63b1865 100644
--- a/packages/docs/package.json
+++ b/packages/docs/package.json
@@ -70,6 +70,7 @@
},
"devDependencies": {
"@univerjs/core": "workspace:*",
+ "@univerjs/drawing": "workspace:*",
"@univerjs/engine-render": "workspace:*",
"@univerjs/shared": "workspace:*",
"@wendellhu/redi": "0.15.2",
diff --git a/packages/docs/src/commands/commands/insert-floating-object.command.ts b/packages/docs/src/commands/commands/insert-floating-object.command.ts
deleted file mode 100644
index 140ee2dfb9..0000000000
--- a/packages/docs/src/commands/commands/insert-floating-object.command.ts
+++ /dev/null
@@ -1,72 +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 { ICommand } from '@univerjs/core';
-import { CommandType, ICommandService, IUndoRedoService, IUniverInstanceService } from '@univerjs/core';
-import type { IAccessor } from '@wendellhu/redi';
-
-import type { IInsertDrawingMutation } from '../mutations/insert-floating-object.mutation';
-import { InsertDrawingMutation } from '../mutations/insert-floating-object.mutation';
-import { RemoveDrawingMutation } from '../mutations/remove-floating-object.mutation';
-
-export const InsertDrawingCommand: ICommand = {
- type: CommandType.COMMAND,
- id: 'doc.command.insert-drawing',
-
- handler: async (accessor: IAccessor, params?: IInsertDrawingMutation) => {
- const commandService = accessor.get(ICommandService);
- const undoRedoService = accessor.get(IUndoRedoService);
- const univerInstanceService = accessor.get(IUniverInstanceService);
-
- if (params == null) {
- return false;
- }
-
- const { documentId } = params;
-
- const documentModel = univerInstanceService.getUniverDocInstance(documentId);
- if (!documentModel) return false;
-
- const snapshot = documentModel.getSnapshot();
- if (snapshot == null || snapshot.drawings == null) return false;
-
- const { objectId, drawing } = params;
-
- const redoMutationParams: IInsertDrawingMutation = {
- documentId,
- objectId,
- drawing,
- };
-
- const undoMutationParams = {
- documentId,
- objectId,
- };
- const result = commandService.syncExecuteCommand(InsertDrawingMutation.id, redoMutationParams);
-
- if (result) {
- undoRedoService.pushUndoRedo({
- unitID: documentId,
- undoMutations: [{ id: RemoveDrawingMutation.id, params: undoMutationParams }],
- redoMutations: [{ id: InsertDrawingMutation.id, params: redoMutationParams }],
- });
-
- return true;
- }
-
- return false;
- },
-};
diff --git a/packages/docs/src/commands/commands/remove-floating-object.command.ts b/packages/docs/src/commands/commands/remove-floating-object.command.ts
deleted file mode 100644
index 8c8391ec2b..0000000000
--- a/packages/docs/src/commands/commands/remove-floating-object.command.ts
+++ /dev/null
@@ -1,72 +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 { ICommand } from '@univerjs/core';
-import { CommandType, ICommandService, IUndoRedoService, IUniverInstanceService } from '@univerjs/core';
-import type { IAccessor } from '@wendellhu/redi';
-
-import type { IInsertDrawingMutation } from '../mutations/insert-floating-object.mutation';
-import { InsertDrawingMutation } from '../mutations/insert-floating-object.mutation';
-import { RemoveDrawingMutation } from '../mutations/remove-floating-object.mutation';
-import type { ISeachDrawingMutation } from '../mutations/set-floating-object.mutation';
-
-export const RemoveDrawingCommand: ICommand = {
- type: CommandType.COMMAND,
- id: 'doc.command.remove-drawing',
-
- handler: async (accessor: IAccessor, params?: ISeachDrawingMutation) => {
- const commandService = accessor.get(ICommandService);
- const undoRedoService = accessor.get(IUndoRedoService);
- const univerInstanceService = accessor.get(IUniverInstanceService);
-
- if (params == null) {
- return false;
- }
-
- const { documentId } = params;
-
- const documentModel = univerInstanceService.getUniverDocInstance(documentId);
- if (!documentModel) return false;
-
- const snapshot = documentModel.getSnapshot();
- if (snapshot == null || snapshot.drawings == null) return false;
-
- const { objectId } = params;
-
- const redoMutationParams: ISeachDrawingMutation = {
- documentId,
- objectId,
- };
-
- const undoMutationParams: IInsertDrawingMutation = {
- documentId,
- objectId,
- drawing: snapshot.drawings[objectId],
- };
- const result = commandService.syncExecuteCommand(RemoveDrawingMutation.id, redoMutationParams);
-
- if (result) {
- undoRedoService.pushUndoRedo({
- unitID: documentId,
- undoMutations: [{ id: InsertDrawingMutation.id, params: undoMutationParams }],
- redoMutations: [{ id: RemoveDrawingMutation.id, params: redoMutationParams }],
- });
- return true;
- }
-
- return false;
- },
-};
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.ts
deleted file mode 100644
index 11a259cef7..0000000000
--- a/packages/docs/src/commands/commands/set-floating-object-transform.command.ts
+++ /dev/null
@@ -1,129 +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 { ICommand, IObjectPositionH, IObjectPositionV, ISize } from '@univerjs/core';
-import { CommandType, ICommandService, IUndoRedoService, IUniverInstanceService } from '@univerjs/core';
-import type { IAccessor } from '@wendellhu/redi';
-
-import type { IDrawingTransformMutation } from '../mutations/set-floating-object.mutation';
-import {
- SetDrawingTransformMutation,
- SetDrawingTransformMutationFactory,
-} from '../mutations/set-floating-object.mutation';
-
-export interface ISetDrawingSizeCommandParams {
- documentId: string;
- objectId: string;
- size: ISize;
-}
-
-export const SetDrawingSizeCommand: ICommand = {
- type: CommandType.COMMAND,
- id: 'doc.command.set-drawing-size',
-
- handler: async (accessor: IAccessor, params?: ISetDrawingSizeCommandParams) => {
- const commandService = accessor.get(ICommandService);
- const undoRedoService = accessor.get(IUndoRedoService);
- const univerInstanceService = accessor.get(IUniverInstanceService);
-
- if (params == null) {
- return false;
- }
-
- const documentId = params.documentId;
-
- const documentModel = univerInstanceService.getUniverDocInstance(documentId);
- if (!documentModel) return false;
-
- const snapshot = documentModel.getSnapshot();
- if (snapshot == null) return false;
-
- const { objectId, size } = params;
-
- const redoMutationParams: IDrawingTransformMutation = {
- documentId,
- objectId,
- size,
- };
-
- const undoMutationParams = SetDrawingTransformMutationFactory(accessor, redoMutationParams);
- const result = commandService.syncExecuteCommand(SetDrawingTransformMutation.id, redoMutationParams);
-
- if (result) {
- undoRedoService.pushUndoRedo({
- unitID: documentId,
- undoMutations: [{ id: SetDrawingTransformMutation.id, params: undoMutationParams }],
- redoMutations: [{ id: SetDrawingTransformMutation.id, params: redoMutationParams }],
- });
- return true;
- }
-
- return false;
- },
-};
-
-export interface ISetDrawingPositionCommandParams {
- documentId: string;
- objectId: string;
- positionH: IObjectPositionH;
- positionV: IObjectPositionV;
-}
-
-export const SetDrawingPositionCommand: ICommand = {
- type: CommandType.COMMAND,
- id: 'doc.command.set-drawing-size',
-
- handler: async (accessor: IAccessor, params?: ISetDrawingPositionCommandParams) => {
- const commandService = accessor.get(ICommandService);
- const undoRedoService = accessor.get(IUndoRedoService);
- const univerInstanceService = accessor.get(IUniverInstanceService);
-
- if (params == null) {
- return false;
- }
-
- const documentId = params.documentId;
-
- const documentModel = univerInstanceService.getUniverDocInstance(documentId);
- if (!documentModel) return false;
-
- const snapshot = documentModel.getSnapshot();
- if (snapshot == null) return false;
-
- const { objectId, positionH, positionV } = params;
-
- const redoMutationParams: IDrawingTransformMutation = {
- documentId,
- objectId,
- positionH,
- positionV,
- };
-
- const undoMutationParams = SetDrawingTransformMutationFactory(accessor, redoMutationParams);
- const result = commandService.syncExecuteCommand(SetDrawingTransformMutation.id, redoMutationParams);
-
- if (result) {
- undoRedoService.pushUndoRedo({
- unitID: documentId,
- undoMutations: [{ id: SetDrawingTransformMutation.id, params: undoMutationParams }],
- redoMutations: [{ id: SetDrawingTransformMutation.id, params: redoMutationParams }],
- });
- return true;
- }
-
- return false;
- },
-};
diff --git a/packages/docs/src/commands/mutations/insert-floating-object.mutation.ts b/packages/docs/src/commands/mutations/insert-floating-object.mutation.ts
deleted file mode 100644
index 64b2709ebe..0000000000
--- a/packages/docs/src/commands/mutations/insert-floating-object.mutation.ts
+++ /dev/null
@@ -1,49 +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, IMutation } from '@univerjs/core';
-import { CommandType, IUniverInstanceService } from '@univerjs/core';
-
-import type { ISeachDrawingMutation } from './set-floating-object.mutation';
-
-export interface IInsertDrawingMutation extends ISeachDrawingMutation {
- drawing: IDrawing;
-}
-
-export const InsertDrawingMutation: IMutation<IInsertDrawingMutation> = {
- id: 'doc.mutation.insert-drawing',
- type: CommandType.MUTATION,
- handler: (accessor, params) => {
- const univerdoc = accessor.get(IUniverInstanceService).getUniverDocInstance(params.documentId);
-
- if (univerdoc == null) {
- return false;
- }
-
- let drawings = univerdoc.getSnapshot().drawings;
-
- if (drawings == null) {
- drawings = {};
- univerdoc.getSnapshot().drawings = drawings;
- }
-
- const { objectId, drawing } = params;
-
- drawings[objectId] = drawing;
-
- return true;
- },
-};
diff --git a/packages/docs/src/commands/mutations/set-drawing-apply.mutation.ts b/packages/docs/src/commands/mutations/set-drawing-apply.mutation.ts
new file mode 100644
index 0000000000..a42b3afb12
--- /dev/null
+++ b/packages/docs/src/commands/mutations/set-drawing-apply.mutation.ts
@@ -0,0 +1,80 @@
+/**
+ * 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 { DocumentDataModel, IDrawingGroupUpdateParam, IDrawingOrderMapParam, IDrawings, IDrawingSearch, IMutation } from '@univerjs/core';
+import { CommandType, IDrawingManagerService, IUniverInstanceService } from '@univerjs/core';
+import type { IDrawingJson1Type } from '@univerjs/drawing';
+import { IDocDrawingService } from '../../services/doc-drawing.service';
+
+export enum DocDrawingApplyType {
+ INSERT,
+ REMOVE,
+ UPDATE,
+ ARRANGE,
+ GROUP,
+ UNGROUP,
+}
+
+export interface ISetDrawingApplyMutationParams extends IDrawingJson1Type {
+ type: DocDrawingApplyType;
+}
+
+export const SetDocDrawingApplyMutation: IMutation<ISetDrawingApplyMutationParams> = {
+ id: 'doc.mutation.set-drawing-json-apply',
+ type: CommandType.MUTATION,
+ handler: (accessor, params) => {
+ const drawingManagerService = accessor.get(IDrawingManagerService);
+ const docDrawingService = accessor.get(IDocDrawingService);
+ const univerInstanceService = accessor.get(IUniverInstanceService);
+
+ const { op, unitId, subUnitId, type, objects } = params;
+
+ drawingManagerService.applyJson1(unitId, subUnitId, op);
+ docDrawingService.applyJson1(unitId, subUnitId, op);
+
+ switch (type) {
+ case DocDrawingApplyType.INSERT:
+ drawingManagerService.addNotification(objects as IDrawingSearch[]);
+ docDrawingService.addNotification(objects as IDrawingSearch[]);
+ break;
+ case DocDrawingApplyType.REMOVE:
+ drawingManagerService.removeNotification(objects as IDrawingSearch[]);
+ docDrawingService.removeNotification(objects as IDrawingSearch[]);
+ break;
+ case DocDrawingApplyType.UPDATE:
+ drawingManagerService.updateNotification(objects as IDrawingSearch[]);
+ docDrawingService.updateNotification(objects as IDrawingSearch[]);
+ break;
+ case DocDrawingApplyType.ARRANGE:
+ drawingManagerService.orderNotification(objects as IDrawingOrderMapParam);
+ docDrawingService.orderNotification(objects as IDrawingOrderMapParam);
+ break;
+ case DocDrawingApplyType.GROUP:
+ drawingManagerService.groupUpdateNotification(objects as IDrawingGroupUpdateParam[]);
+ break;
+ case DocDrawingApplyType.UNGROUP:
+ drawingManagerService.ungroupUpdateNotification(objects as IDrawingGroupUpdateParam[]);
+ break;
+ }
+
+ // TODO: @Jocs Update the document snapshot
+ const documentDataModel = univerInstanceService.getUnit(unitId) as DocumentDataModel;
+ documentDataModel.getSnapshot().drawings = drawingManagerService.getDrawingData(unitId, subUnitId) as IDrawings;
+ documentDataModel.getSnapshot().drawingsOrder = drawingManagerService.getDrawingOrder(unitId, subUnitId);
+
+ return true;
+ },
+};
diff --git a/packages/docs/src/commands/mutations/set-floating-object.mutation.ts b/packages/docs/src/commands/mutations/set-floating-object.mutation.ts
deleted file mode 100644
index 3ef3b6b828..0000000000
--- a/packages/docs/src/commands/mutations/set-floating-object.mutation.ts
+++ /dev/null
@@ -1,212 +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 {
- BooleanNumber,
- IMutation,
- IObjectPositionH,
- IObjectPositionV,
- ISize,
- PositionedObjectLayoutType,
- WrapTextType,
-} from '@univerjs/core';
-import { CommandType, IUniverInstanceService } from '@univerjs/core';
-import type { IAccessor } from '@wendellhu/redi';
-
-export interface ISeachDrawingMutation {
- documentId: string;
- objectId: string;
-}
-
-export interface IDrawingTransformMutation extends ISeachDrawingMutation {
- size?: ISize;
- positionH?: IObjectPositionH;
- positionV?: IObjectPositionV;
- angle?: number;
-}
-
-export const SetDrawingTransformMutationFactory = (
- accessor: IAccessor,
- params: IDrawingTransformMutation
-): IDrawingTransformMutation => {
- const { documentId, objectId } = params;
- const documentModel = accessor.get(IUniverInstanceService).getUniverDocInstance(documentId);
- if (documentModel == null) {
- throw new Error('documentModel is null error!');
- }
-
- const drawings = documentModel.getSnapshot().drawings;
-
- if (drawings == null) {
- return {
- documentId,
- objectId,
- };
- }
-
- const drawing = drawings[objectId];
-
- if (drawing == null) {
- return {
- documentId,
- objectId,
- };
- }
-
- return {
- size: drawing.objectTransform.size,
- positionH: drawing.objectTransform.positionH,
- positionV: drawing.objectTransform.positionV,
- angle: drawing.objectTransform.angle,
- documentId,
- objectId,
- };
-};
-
-export const SetDrawingTransformMutation: IMutation<IDrawingTransformMutation> = {
- id: 'doc.mutation.set-drawing-transform',
- type: CommandType.MUTATION,
- handler: (accessor, params) => {
- const univerdoc = accessor.get(IUniverInstanceService).getUniverDocInstance(params.documentId);
-
- if (univerdoc == null) {
- return false;
- }
-
- let drawings = univerdoc.getSnapshot().drawings;
-
- if (drawings == null) {
- drawings = {};
- univerdoc.getSnapshot().drawings = drawings;
- }
-
- const { objectId, size, positionH, positionV, angle } = params;
-
- const drawing = drawings[objectId];
-
- if (drawing == null) {
- return false;
- }
-
- if (size != null) drawing.objectTransform.size = size;
-
- if (positionH != null) drawing.objectTransform.positionH = positionH;
-
- if (positionV != null) drawing.objectTransform.positionV = positionV;
-
- if (angle != null) drawing.objectTransform.angle = angle;
-
- return true;
- },
-};
-
-export interface IDrawingLayoutMutation extends ISeachDrawingMutation {
- layoutType?: PositionedObjectLayoutType;
-
- behindDoc?: BooleanNumber; // wrapNone
- start?: number[]; // wrapPolygon
- lineTo?: number[][]; // wrapPolygon
- wrapText?: WrapTextType; // wrapSquare | wrapThrough | wrapTight
- distL?: number; // wrapSquare | wrapThrough | wrapTight
- distR?: number; // wrapSquare | wrapThrough | wrapTight
- distT?: number; // wrapSquare | wrapTopAndBottom
- distB?: number; // wrapSquare | wrapTopAndBottom
-}
-
-export const SetDrawingLayoutMutation: IMutation<IDrawingLayoutMutation> = {
- id: 'doc.mutation.set-drawing-layout',
- type: CommandType.MUTATION,
- handler: (accessor, params) => {
- const univerdoc = accessor.get(IUniverInstanceService).getUniverDocInstance(params.documentId);
-
- if (univerdoc == null) {
- return false;
- }
-
- let drawings = univerdoc.getSnapshot().drawings;
-
- if (drawings == null) {
- drawings = {};
- univerdoc.getSnapshot().drawings = drawings;
- }
-
- const { objectId, layoutType, behindDoc, start, lineTo, wrapText, distL, distR, distT, distB } = params;
-
- const drawing = drawings[objectId];
-
- if (drawing == null) {
- return false;
- }
-
- layoutType && (drawing.layoutType = layoutType);
-
- behindDoc && (drawing.behindDoc = behindDoc);
-
- start && (drawing.start = start);
-
- lineTo && (drawing.lineTo = lineTo);
-
- wrapText && (drawing.wrapText = wrapText);
-
- distL && (drawing.distL = distL);
-
- distR && (drawing.distR = distR);
-
- distT && (drawing.distT = distT);
-
- distB && (drawing.distB = distB);
-
- return true;
- },
-};
-
-export interface IDrawingInfoMutation extends ISeachDrawingMutation {
- title?: string;
- description?: string;
-}
-
-export const SetDrawingInfoMutation: IMutation<IDrawingInfoMutation> = {
- id: 'doc.mutation.set-drawing-info',
- type: CommandType.MUTATION,
- handler: (accessor, params) => {
- const univerdoc = accessor.get(IUniverInstanceService).getUniverDocInstance(params.documentId);
-
- if (univerdoc == null) {
- return false;
- }
-
- let drawings = univerdoc.getSnapshot().drawings;
-
- if (drawings == null) {
- drawings = {};
- univerdoc.getSnapshot().drawings = drawings;
- }
-
- const { objectId, title, description } = params;
-
- const drawing = drawings[objectId];
-
- if (drawing == null) {
- return false;
- }
-
- title && (drawing.title = title);
-
- description && (drawing.description = description);
-
- return true;
- },
-};
diff --git a/packages/docs/src/controllers/doc-drawing-data.controller.ts b/packages/docs/src/controllers/doc-drawing-data.controller.ts
new file mode 100644
index 0000000000..36d1b8b9de
--- /dev/null
+++ b/packages/docs/src/controllers/doc-drawing-data.controller.ts
@@ -0,0 +1,85 @@
+/**
+ * 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 { DocumentDataModel, IDrawingMapItem, IDrawingSubunitMap } from '@univerjs/core';
+import { Disposable, IDrawingManagerService, IResourceManagerService, IUniverInstanceService, LifecycleStages, OnLifecycle, UniverInstanceType } from '@univerjs/core';
+import { type IDocDrawing, IDocDrawingService } from '../services/doc-drawing.service';
+
+export const DOC_DRAWING_PLUGIN = 'DOC_DRAWING_PLUGIN';
+@OnLifecycle(LifecycleStages.Rendered, DocDrawingDataController)
+export class DocDrawingDataController extends Disposable {
+ constructor(
+ @IDocDrawingService private readonly _docDrawingService: IDocDrawingService,
+ @IDrawingManagerService private readonly _drawingManagerService: IDrawingManagerService,
+ @IResourceManagerService private _resourceManagerService: IResourceManagerService,
+ @IUniverInstanceService private _univerInstanceService: IUniverInstanceService
+ ) {
+ super();
+
+ this._init();
+ }
+
+ private _init(): void {
+ this._initSnapshot();
+ }
+
+ private _initSnapshot() {
+ const toJson = (unitId: string) => {
+ const map = this._docDrawingService.getDrawingDataForUnit(unitId);
+ if (map) {
+ return JSON.stringify(map);
+ }
+ return '';
+ };
+ const parseJson = (json: string): IDrawingSubunitMap<IDocDrawing> => {
+ if (!json) {
+ return {};
+ }
+ try {
+ return JSON.parse(json);
+ } catch (err) {
+ return {};
+ }
+ };
+ this.disposeWithMe(
+ this._resourceManagerService.registerPluginResource<IDrawingSubunitMap<IDocDrawing>>({
+ pluginName: DOC_DRAWING_PLUGIN,
+ businesses: [UniverInstanceType.UNIVER_DOC],
+ toJson: (unitId) => toJson(unitId),
+ parseJson: (json) => parseJson(json),
+ onUnLoad: (unitId) => {
+ this._docDrawingService.removeDrawingDataForUnit(unitId);
+ this._drawingManagerService.removeDrawingDataForUnit(unitId);
+ this._setDrawingDataForUnit(unitId, { data: {}, order: [] });
+ },
+ onLoad: (unitId, value) => {
+ this._docDrawingService.registerDrawingData(unitId, value);
+ this._drawingManagerService.registerDrawingData(unitId, value);
+ this._setDrawingDataForUnit(unitId, value[unitId]);
+ },
+ })
+ );
+ }
+
+ private _setDrawingDataForUnit(unitId: string, drawingMapItem: IDrawingMapItem<IDocDrawing>) {
+ const documentDataModel = this._univerInstanceService.getUnit<DocumentDataModel>(unitId);
+ if (documentDataModel == null) {
+ return;
+ }
+
+ documentDataModel.resetDrawing(drawingMapItem.data, drawingMapItem.order);
+ }
+}
diff --git a/packages/docs/src/doc-plugin.ts b/packages/docs/src/doc-plugin.ts
index 63007198f3..2129972b8a 100644
--- a/packages/docs/src/doc-plugin.ts
+++ b/packages/docs/src/doc-plugin.ts
@@ -58,6 +58,9 @@ import { IMEInputManagerService } from './services/ime-input-manager.service';
import { TextSelectionManagerService } from './services/text-selection-manager.service';
import { DocStateChangeManagerService } from './services/doc-state-change-manager.service';
import { AlignCenterCommand, AlignJustifyCommand, AlignLeftCommand, AlignOperationCommand, AlignRightCommand } from './commands/commands/paragraph-align.command';
+import { SetDocDrawingApplyMutation } from './commands/mutations/set-drawing-apply.mutation';
+import { DocDrawingService, IDocDrawingService } from './services/doc-drawing.service';
+import { DocDrawingDataController } from './controllers/doc-drawing-data.controller';
export interface IUniverDocsConfig {
hasScroll?: boolean;
@@ -120,6 +123,7 @@ export class UniverDocsPlugin extends Plugin {
AlignRightCommand,
AlignOperationCommand,
AlignJustifyCommand,
+ SetDocDrawingApplyMutation,
] as ICommand[]
).forEach((command) => {
this._injector.get(ICommandService).registerCommand(command);
@@ -141,11 +145,13 @@ export class UniverDocsPlugin extends Plugin {
},
],
[TextSelectionManagerService],
+ [IDocDrawingService, { useClass: DocDrawingService }],
// controllers
[NormalInputController],
[IMEInputController],
[MoveCursorController],
+ [DocDrawingDataController],
] as Dependency[]
).forEach((d) => docInjector.add(d));
}
diff --git a/packages/docs/src/index.ts b/packages/docs/src/index.ts
index 8901e66dcc..fa25116ab2 100644
--- a/packages/docs/src/index.ts
+++ b/packages/docs/src/index.ts
@@ -14,6 +14,13 @@
* limitations under the License.
*/
+export {
+ IDocDrawingService,
+ DocDrawingService,
+ type IDocUpdateDrawing,
+ type IDocDrawing,
+} from './services/doc-drawing.service';
+
export type { IDocObjectParam } from './basics/component-tools';
export { getDocObject, getDocObjectById } from './basics/component-tools';
export * from './basics/docs-view-key';
@@ -65,3 +72,4 @@ export { SelectAllOperation } from './commands/operations/select-all.operation';
export { CutContentCommand, InnerPasteCommand } from './commands/commands/clipboard.inner.command';
export { SetDocZoomRatioOperation, type ISetDocZoomRatioOperationParams } from './commands/operations/set-doc-zoom-ratio.operation';
export { SetDocZoomRatioCommand } from './commands/commands/set-doc-zoom-ratio.command';
+export { SetDocDrawingApplyMutation, DocDrawingApplyType } from './commands/mutations/set-drawing-apply.mutation';
diff --git a/packages/docs/src/services/doc-drawing.service.ts b/packages/docs/src/services/doc-drawing.service.ts
new file mode 100644
index 0000000000..3f2d3d7f7d
--- /dev/null
+++ b/packages/docs/src/services/doc-drawing.service.ts
@@ -0,0 +1,41 @@
+/**
+ * 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 { IDocDrawingBase, IUnitDrawingService } from '@univerjs/core';
+import { createIdentifier } from '@wendellhu/redi';
+import { type IImageData, UnitDrawingService } from '@univerjs/drawing';
+
+export interface IDocImage extends IImageData, IDocDrawingBase {
+
+}
+
+/**
+ * test type
+ */
+export interface IDocShape extends IDocDrawingBase {
+
+}
+
+export type IDocDrawing = IDocImage | IDocShape;
+
+type OptionalField<T, K extends keyof T> = Omit<T, K> & Partial<Pick<T, K>>;
+export type IDocUpdateDrawing = OptionalField<IDocDrawing, 'drawingType' | 'layoutType' | 'docTransform' | 'description' | 'title'>;
+
+export class DocDrawingService extends UnitDrawingService<IDocDrawing> {}
+
+export interface IDocDrawingService extends IUnitDrawingService<IDocDrawing> {}
+
+export const IDocDrawingService = createIdentifier<IDocDrawingService>('univer.doc.plugin.doc-drawing.service');
diff --git a/packages/docs/src/services/text-selection-manager.service.ts b/packages/docs/src/services/text-selection-manager.service.ts
index b6a7d8df7d..de9248098e 100644
--- a/packages/docs/src/services/text-selection-manager.service.ts
+++ b/packages/docs/src/services/text-selection-manager.service.ts
@@ -122,6 +122,16 @@ export class TextSelectionManagerService extends RxDisposable {
return this._getTextRanges(this._currentSelection)?.textRanges;
}
+ getActiveTextRange(): Nullable<TextRange> {
+ const selectionInfo = this._getTextRanges(this._currentSelection);
+ if (selectionInfo == null) {
+ return;
+ }
+
+ const { textRanges } = selectionInfo;
+ return textRanges.find((textRange) => textRange.isActive());
+ }
+
getActiveRange(): Nullable<ITextActiveRange> {
const selectionInfo = this._getTextRanges(this._currentSelection);
if (selectionInfo == null) {
diff --git a/packages/drawing-ui/README.md b/packages/drawing-ui/README.md
new file mode 100644
index 0000000000..d9da15b2af
--- /dev/null
+++ b/packages/drawing-ui/README.md
@@ -0,0 +1,16 @@
+# @univerjs/drawing-ui
+
+[![npm version](https://img.shields.io/npm/v/@univerjs/drawing-ui)](https://npmjs.org/packages/@univerjs/drawing-ui)
+[![license](https://img.shields.io/npm/l/@univerjs/drawing-ui)](https://img.shields.io/npm/l/@univerjs/drawing-ui)
+
+## Introduction
+
+> TODO: Introduction
+
+## Usage
+
+### Installation
+
+```shell
+npm i @univerjs/drawing-ui
+```
diff --git a/packages/drawing-ui/package.json b/packages/drawing-ui/package.json
new file mode 100644
index 0000000000..01094bd417
--- /dev/null
+++ b/packages/drawing-ui/package.json
@@ -0,0 +1,92 @@
+{
+ "name": "@univerjs/drawing-ui",
+ "version": "0.0.1",
+ "private": true,
+ "description": "",
+ "author": "DreamNum <[email protected]>",
+ "license": "Apache-2.0",
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/univer"
+ },
+ "homepage": "https://univer.ai",
+ "repository": {
+ "type": "git",
+ "url": "https://github.com/dream-num/univer"
+ },
+ "bugs": {
+ "url": "https://github.com/dream-num/univer/issues"
+ },
+ "keywords": [],
+ "sideEffects": [
+ "**/*.css"
+ ],
+ "exports": {
+ ".": "./src/index.ts",
+ "./*": "./src/*",
+ "./locale/*": "./src/locale/*.ts"
+ },
+ "main": "./lib/cjs/index.js",
+ "module": "./lib/es/index.js",
+ "types": "./lib/types/index.d.ts",
+ "publishConfig": {
+ "access": "public",
+ "main": "./lib/cjs/index.js",
+ "module": "./lib/es/index.js",
+ "exports": {
+ ".": {
+ "import": "./lib/es/index.js",
+ "require": "./lib/cjs/index.js",
+ "types": "./lib/types/index.d.ts"
+ },
+ "./*": {
+ "import": "./lib/es/*",
+ "require": "./lib/cjs/*",
+ "types": "./lib/types/index.d.ts"
+ },
+ "./locale/*": "./lib/locale/*.json",
+ "./lib/*": "./lib/*"
+ }
+ },
+ "directories": {
+ "lib": "lib"
+ },
+ "files": [
+ "lib"
+ ],
+ "scripts": {
+ "test": "vitest run",
+ "test:watch": "vitest",
+ "coverage": "vitest run --coverage",
+ "lint:types": "tsc --noEmit",
+ "build": "tsc && vite build"
+ },
+ "peerDependencies": {
+ "@univerjs/core": "workspace:*",
+ "@univerjs/design": "workspace:*",
+ "@univerjs/ui": "workspace:*",
+ "@wendellhu/redi": "0.15.2",
+ "clsx": ">=2.0.0",
+ "react": ">=16.9.0",
+ "rxjs": ">=7.0.0"
+ },
+ "dependencies": {
+ "@univerjs/icons": "^0.1.52"
+ },
+ "devDependencies": {
+ "@univerjs/core": "workspace:*",
+ "@univerjs/design": "workspace:*",
+ "@univerjs/drawing": "workspace:*",
+ "@univerjs/engine-render": "workspace:*",
+ "@univerjs/shared": "workspace:*",
+ "@univerjs/ui": "workspace:*",
+ "@wendellhu/redi": "0.15.2",
+ "clsx": "^2.1.0",
+ "less": "^4.2.0",
+ "react": "^18.2.0",
+ "rxjs": "^7.8.1",
+ "typescript": "^5.3.3",
+ "vite": "^5.1.4",
+ "vitest": "^1.3.1"
+ }
+}
diff --git a/packages/drawing-ui/src/commands/operations/drawing-align.operation.ts b/packages/drawing-ui/src/commands/operations/drawing-align.operation.ts
new file mode 100644
index 0000000000..dcf137fdb8
--- /dev/null
+++ b/packages/drawing-ui/src/commands/operations/drawing-align.operation.ts
@@ -0,0 +1,42 @@
+/**
+ * Copyright 2023-present DreamNum Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { IOperation } from '@univerjs/core';
+import { CommandType } from '@univerjs/core';
+
+export enum AlignType {
+ default = '0',
+ left = '1',
+ center = '2',
+ right = '3',
+ top = '4',
+ middle = '5',
+ bottom = '6',
+ horizon = '7',
+ vertical = '8',
+}
+
+export interface ISetDrawingAlignOperationParams {
+ alignType: AlignType;
+}
+
+export const SetDrawingAlignOperation: IOperation<ISetDrawingAlignOperationParams> = {
+ id: 'sheet.operation.set-image-align',
+ type: CommandType.OPERATION,
+ handler: (accessor, params) => {
+ return true;
+ },
+};
diff --git a/packages/drawing-ui/src/commands/operations/image-crop.operation.ts b/packages/drawing-ui/src/commands/operations/image-crop.operation.ts
new file mode 100644
index 0000000000..cb7b4949f4
--- /dev/null
+++ b/packages/drawing-ui/src/commands/operations/image-crop.operation.ts
@@ -0,0 +1,59 @@
+/**
+ * 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 { IDrawingSearch, IOperation } from '@univerjs/core';
+import { CommandType } from '@univerjs/core';
+
+export const OpenImageCropOperation: IOperation<IDrawingSearch> = {
+ id: 'sheet.operation.open-image-crop',
+ type: CommandType.OPERATION,
+ handler: (accessor, params) => {
+ return true;
+ },
+};
+
+export const CloseImageCropOperation: IOperation<{ isAuto?: boolean }> = {
+ id: 'sheet.operation.close-image-crop',
+ type: CommandType.OPERATION,
+ handler: (accessor, params) => {
+ return true;
+ },
+};
+
+export enum CropType {
+ FREE = '0',
+ R1_1 = '1',
+ R16_9 = '2',
+ R9_16 = '3',
+ R5_4 = '4',
+ R4_5 = '5',
+ R4_3 = '6',
+ R3_4 = '7',
+ R3_2 = '8',
+ R2_3 = '9',
+}
+
+export interface IOpenImageCropOperationBySrcRectParams {
+ cropType: CropType;
+}
+
+export const AutoImageCropOperation: IOperation<IOpenImageCropOperationBySrcRectParams> = {
+ id: 'sheet.operation.Auto-image-crop',
+ type: CommandType.OPERATION,
+ handler: (accessor, params) => {
+ return true;
+ },
+};
diff --git a/packages/drawing-ui/src/commands/operations/image-reset-size.operation.ts b/packages/drawing-ui/src/commands/operations/image-reset-size.operation.ts
new file mode 100644
index 0000000000..0d78058903
--- /dev/null
+++ b/packages/drawing-ui/src/commands/operations/image-reset-size.operation.ts
@@ -0,0 +1,25 @@
+/**
+ * Copyright 2023-present DreamNum Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { CommandType, type IDrawingSearch, type IOperation } from '@univerjs/core';
+
+export const ImageResetSizeOperation: IOperation<IDrawingSearch[]> = {
+ id: 'sheet.operation.image-reset-size',
+ type: CommandType.OPERATION,
+ handler: (accessor, params) => {
+ return true;
+ },
+};
diff --git a/packages/drawing-ui/src/controllers/drawing-ui.controller.ts b/packages/drawing-ui/src/controllers/drawing-ui.controller.ts
new file mode 100644
index 0000000000..582e1c3665
--- /dev/null
+++ b/packages/drawing-ui/src/controllers/drawing-ui.controller.ts
@@ -0,0 +1,81 @@
+/**
+ * Copyright 2023-present DreamNum Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { Disposable, ICommandService, LifecycleStages, LocaleService, OnLifecycle } from '@univerjs/core';
+import { ComponentManager, IMenuService } from '@univerjs/ui';
+import { Inject, Injector } from '@wendellhu/redi';
+import { COMPONENT_IMAGE_POPUP_MENU } from '../views/image-popup-menu/component-name';
+import { ImagePopupMenu } from '../views/image-popup-menu/ImagePopupMenu';
+import zhCN from '../locale/zh-CN';
+import enUS from '../locale/en-US';
+import { AutoImageCropOperation, CloseImageCropOperation, OpenImageCropOperation } from '../commands/operations/image-crop.operation';
+import { ImageViewer } from '../views/image-viewer/ImageViewer';
+import { COMPONENT_IMAGE_VIEWER } from '../views/image-viewer/component-name';
+import { ImageResetSizeOperation } from '../commands/operations/image-reset-size.operation';
+import { SetDrawingAlignOperation } from '../commands/operations/drawing-align.operation';
+
+@OnLifecycle(LifecycleStages.Rendered, DrawingUIController)
+export class DrawingUIController extends Disposable {
+ constructor(
+ @Inject(Injector) private readonly _injector: Injector,
+ @Inject(ComponentManager) private readonly _componentManager: ComponentManager,
+ @IMenuService private readonly _menuService: IMenuService,
+ @ICommandService private readonly _commandService: ICommandService,
+ @Inject(LocaleService) private readonly _localeService: LocaleService
+ ) {
+ super();
+
+ this._localeService.load({
+ zhCN,
+ enUS,
+ });
+
+ this._init();
+ }
+
+ private _initCustomComponents(): void {
+ const componentManager = this._componentManager;
+ this.disposeWithMe(componentManager.register(COMPONENT_IMAGE_POPUP_MENU, ImagePopupMenu));
+ this.disposeWithMe(componentManager.register(COMPONENT_IMAGE_VIEWER, ImageViewer));
+ }
+
+ private _initMenus(): void {
+ // init menus
+ // (
+ // [
+
+ // ] as IMenuItemFactory[]
+ // ).forEach((factory) => {
+ // this.disposeWithMe(this._menuService.addMenuItem(this._injector.invoke(factory)));
+ // });
+ }
+
+ private _initCommands() {
+ [
+ OpenImageCropOperation,
+ CloseImageCropOperation,
+ ImageResetSizeOperation,
+ SetDrawingAlignOperation,
+ AutoImageCropOperation,
+ ].forEach((command) => this.disposeWithMe(this._commandService.registerCommand(command)));
+ }
+
+ private _init(): void {
+ this._initCommands();
+ this._initCustomComponents();
+ this._initMenus();
+ }
+}
diff --git a/packages/drawing-ui/src/controllers/drawing-update.controller.ts b/packages/drawing-ui/src/controllers/drawing-update.controller.ts
new file mode 100644
index 0000000000..5bb9bf57a0
--- /dev/null
+++ b/packages/drawing-ui/src/controllers/drawing-update.controller.ts
@@ -0,0 +1,837 @@
+/**
+ * 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 { DrawingTypeEnum, ICommandInfo, IDrawingGroupUpdateParam, IDrawingOrderMapParam, IDrawingParam, IDrawingSearch, ITransformState,
+ Nullable } from '@univerjs/core';
+import {
+ checkIfMove,
+ Disposable,
+ ICommandService,
+ IDrawingManagerService,
+ IUniverInstanceService,
+ LifecycleStages,
+ OnLifecycle,
+ toDisposable,
+} from '@univerjs/core';
+import type { BaseObject, IShapeProps, Scene, Shape } from '@univerjs/engine-render';
+import { DRAWING_OBJECT_LAYER_INDEX, Group, IRenderManagerService, RENDER_CLASS_TYPE } from '@univerjs/engine-render';
+import { getDrawingShapeKeyByDrawingSearch } from '@univerjs/drawing';
+import type { ISetDrawingAlignOperationParams } from '../commands/operations/drawing-align.operation';
+import { AlignType, SetDrawingAlignOperation } from '../commands/operations/drawing-align.operation';
+import { CloseImageCropOperation } from '../commands/operations/image-crop.operation';
+import { getUpdateParams } from '../utils/get-update-params';
+import { getCurrentUnitInfo } from './utils';
+
+interface IDrawingTransformCache {
+ unitId: string;
+ subUnitId: string;
+ drawingId: string;
+ drawingType: DrawingTypeEnum;
+ transform: ITransformState;
+}
+
+@OnLifecycle(LifecycleStages.Rendered, DrawingUpdateController)
+export class DrawingUpdateController extends Disposable {
+ constructor(
+ @IUniverInstanceService private readonly _currentUniverService: IUniverInstanceService,
+ @ICommandService private readonly _commandService: ICommandService,
+ @IRenderManagerService private readonly _renderManagerService: IRenderManagerService,
+ @IDrawingManagerService private readonly _drawingManagerService: IDrawingManagerService
+ ) {
+ super();
+
+ this._initialize();
+ }
+
+ override dispose(): void {
+ super.dispose();
+ }
+
+ private _initialize() {
+ this._recoveryImages();
+
+ this._drawingAddListener();
+
+ this._drawingRemoveListener();
+
+ this._drawingUpdateListener();
+
+ this._commandExecutedListener();
+
+ this._drawingArrangeListener();
+
+ this._drawingGroupListener();
+
+ this._drawingRefreshListener();
+
+ this._drawingVisibleListener();
+ }
+
+ private _recoveryImages() {
+ const drawingList = this._drawingManagerService.drawingManagerData;
+
+ const info = getCurrentUnitInfo(this._currentUniverService);
+ if (info == null) {
+ return;
+ }
+
+ const { unitId: currentUnitId, subUnitId: currentSubUnitId } = info;
+
+ Object.keys(drawingList).forEach((unitId) => {
+ Object.keys(drawingList[unitId]).forEach((subUnitId) => {
+ const drawingMap = drawingList[unitId][subUnitId].data;
+ if (drawingMap == null || unitId !== currentUnitId || subUnitId !== currentSubUnitId) {
+ return;
+ }
+ Object.keys(drawingMap).forEach((drawingId) => {
+ const drawing = drawingMap[drawingId];
+ if (drawing) {
+ this._insertDrawing([{ unitId, subUnitId, drawingId }]);
+ }
+ });
+ });
+ });
+ }
+
+ private _commandExecutedListener() {
+ this.disposeWithMe(
+ this._commandService.onCommandExecuted((command: ICommandInfo) => {
+ if (command.id === SetDrawingAlignOperation.id) {
+ const params = command.params as ISetDrawingAlignOperationParams;
+ if (params == null) {
+ return;
+ }
+ this._drawingAlign(params);
+ }
+ })
+ );
+ }
+
+ private _drawingGroupListener() {
+ this.disposeWithMe(
+ this._drawingManagerService.group$.subscribe((params) => {
+ this._groupDrawings(params);
+ })
+ );
+
+ this.disposeWithMe(
+ this._drawingManagerService.ungroup$.subscribe((params) => {
+ this._ungroupDrawings(params);
+ })
+ );
+ }
+
+ // private _drawingGroup(params: ISetImageGroupOperationParams) {
+ // const { groupType } = params;
+ // const drawings = this._drawingManagerService.getFocusDrawings();
+
+ // if (drawings.length === 0) {
+ // return;
+ // }
+
+ // switch (groupType) {
+ // case GroupType.group:
+ // this._groupDrawings(drawings);
+ // break;
+ // case GroupType.regroup:
+ // this._regroupDrawings(drawings);
+ // break;
+ // case GroupType.ungroup:
+ // this._ungroupDrawings(drawings);
+ // break;
+ // default:
+ // break;
+ // }
+ // }
+
+ private _getSceneAndTransformerByDrawingSearch(unitId: Nullable<string>) {
+ if (unitId == null) {
+ return;
+ }
+
+ const renderObject = this._renderManagerService.getRenderById(unitId);
+
+ const scene = renderObject?.scene;
+
+ if (scene == null) {
+ return null;
+ }
+
+ const transformer = scene.getTransformerByCreate();
+
+ return { scene, transformer };
+ }
+
+ private _groupDrawings(drawings: IDrawingGroupUpdateParam[]) {
+ drawings.forEach((drawing) => {
+ this._groupDrawing(drawing);
+ });
+ }
+
+ private _groupDrawing(params: IDrawingGroupUpdateParam) {
+ const { parent, children } = params;
+
+ const { unitId, subUnitId, drawingId } = parent;
+
+ const renderObject = this._getSceneAndTransformerByDrawingSearch(parent.unitId);
+
+ if (renderObject == null) {
+ return;
+ }
+
+ const { scene, transformer } = renderObject;
+
+ this._commandService.syncExecuteCommand(CloseImageCropOperation.id);
+
+ const objects: BaseObject[] = [];
+
+ children.forEach((drawing) => {
+ const drawingShapeKey = getDrawingShapeKeyByDrawingSearch(drawing);
+ const object = scene.getObjectIncludeInGroup(drawingShapeKey);
+
+ if (object == null || objects.includes(object)) {
+ return;
+ }
+
+ objects.push(object);
+
+ const { transform } = drawing;
+
+ if (transform == null) {
+ return;
+ }
+
+ if (object.classType === RENDER_CLASS_TYPE.GROUP) {
+ object.transformByState({ left: transform.left, top: transform.top });
+ } else {
+ object.transformByState(transform);
+ }
+
+ // const group = object?.ancestorGroup;
+ // if (group != null && objects.includes(group) === false) {
+ // objects.push(group);
+ // } else if (object != null && objects.includes(object) === false) {
+ // objects.push(object);
+ // }
+ });
+
+ if (objects.length === 0) {
+ return;
+ }
+
+ const groupKey = getDrawingShapeKeyByDrawingSearch({ unitId, subUnitId, drawingId });
+ const group = new Group(groupKey);
+
+ scene.addObject(group, DRAWING_OBJECT_LAYER_INDEX).attachTransformerTo(group);
+
+ group.addObjects(...objects);
+ // group.reCalculateObjects();
+ parent.transform && group.transformByState({ left: parent.transform.left, top: parent.transform.top });
+
+ transformer.clearSelectedObjects();
+ transformer.setSelectedControl(group);
+ }
+
+ // private _regroupDrawings(drawings: IDrawingSearch[]) {
+ // const renderObject = this._getSceneAndTransformerByDrawingSearch(drawings[0].unitId);
+
+ // if (renderObject == null) {
+ // return;
+ // }
+
+ // const { scene, transformer } = renderObject;
+
+ // const objects: BaseObject[] = [];
+
+ // let firstGroup: Nullable<Group> = null;
+
+ // drawings.forEach((drawing) => {
+ // const imageShapeKey = getDrawingShapeKeyByDrawingSearch(drawing);
+ // const o = scene.getObject(imageShapeKey);
+
+ // if (o == null) {
+ // return true;
+ // }
+
+ // const group = o.ancestorGroup as Nullable<Group>;
+
+ // if (group != null && firstGroup == null) {
+ // firstGroup = group;
+ // } else if (group != null && !objects.includes(group)) {
+ // objects.push(group);
+ // } else if (!objects.includes(o)) {
+ // objects.push(o);
+ // }
+ // });
+
+ // if (firstGroup == null) {
+ // return;
+ // }
+
+ // if (objects.length === 0) {
+ // return;
+ // }
+
+ // (firstGroup as Group).addObjects(...objects);
+
+ // (firstGroup as Group).reCalculateObjects();
+
+ // transformer.clearSelectedObjects();
+
+ // transformer.setSelectedControl(firstGroup);
+ // }
+
+ private _ungroupDrawings(drawings: IDrawingGroupUpdateParam[]) {
+ drawings.forEach((drawing) => {
+ this._ungroupDrawing(drawing);
+ });
+ }
+
+ private _ungroupDrawing(drawing: IDrawingGroupUpdateParam) {
+ const { parent, children } = drawing;
+
+ const renderObject = this._getSceneAndTransformerByDrawingSearch(parent.unitId);
+
+ if (renderObject == null) {
+ return;
+ }
+
+ const { scene, transformer } = renderObject;
+
+ // const objects: BaseObject[] = [];
+
+ children.forEach((drawing) => {
+ const drawingKey = getDrawingShapeKeyByDrawingSearch(drawing);
+ const object = scene.getObjectIncludeInGroup(drawingKey);
+
+ if (object == null) {
+ return true;
+ }
+
+ if (object == null) {
+ return;
+ }
+
+ // objects.push(object);
+
+ const { transform } = drawing;
+
+ if (transform == null) {
+ return;
+ }
+
+ if (object.classType === RENDER_CLASS_TYPE.GROUP) {
+ object.transformByState({ left: transform.left, top: transform.top });
+ } else {
+ object.transformByState(transform);
+ }
+
+ // transform && object.transformByState(transform);
+
+ // const group = o.ancestorGroup as Nullable<Group>;
+ // if (group != null && !objects.includes(group)) {
+ // objects.push(group);
+ // } else if (o instanceof Group && !objects.includes(o)) {
+ // objects.push(o);
+ // }
+ });
+
+ const groupKey = getDrawingShapeKeyByDrawingSearch(parent);
+ const group = scene.getObject(groupKey) as Group;
+ const { width, height } = group;
+ group.getObjects().forEach((object) => {
+ group.removeSelfObjectAndTransform(object.oKey, width, height);
+ });
+ group.dispose();
+
+ // if (objects.length === 0) {
+ // return;
+ // }
+
+ // objects.forEach((group) => {
+ // const { width, height } = group;
+ // group.getObjects().forEach((object) => {
+ // group.removeSelfObjectAndTransform(object.oKey, width, height);
+ // });
+ // group.dispose();
+ // });
+
+ transformer.clearSelectedObjects();
+ }
+
+ private _drawingAlign(params: ISetDrawingAlignOperationParams) {
+ const { alignType } = params;
+ const drawings = this._drawingManagerService.getFocusDrawings();
+
+ if (alignType === AlignType.default) {
+ return;
+ }
+
+ const drawingTransformCaches: IDrawingTransformCache[] = [];
+ let minLeft = Number.POSITIVE_INFINITY;
+ let minTop = Number.POSITIVE_INFINITY;
+ let maxRight = Number.NEGATIVE_INFINITY;
+ let maxBottom = Number.NEGATIVE_INFINITY;
+ let drawingCount = 0;
+ drawings.forEach((drawing) => {
+ const { unitId, subUnitId, drawingId, drawingType } = drawing;
+ const drawingParam = this._drawingManagerService.getDrawingByParam({ unitId, subUnitId, drawingId });
+
+ if (drawingParam == null || drawingParam.transform == null) {
+ return;
+ }
+
+ drawingTransformCaches.push({
+ unitId,
+ subUnitId,
+ drawingId,
+ drawingType,
+ transform: drawingParam.transform,
+ });
+
+ const { left = 0, top = 0, width = 0, height = 0 } = drawingParam.transform;
+ minLeft = Math.min(minLeft, left);
+ minTop = Math.min(minTop, top);
+ maxRight = Math.max(maxRight, left + width);
+ maxBottom = Math.max(maxBottom, top + height);
+
+ drawingCount++;
+ });
+
+ if (drawingCount === 0) {
+ return;
+ }
+
+ this._sortDrawingTransform(drawingTransformCaches, alignType);
+
+ this._applyAlignType(drawingTransformCaches, alignType, minLeft, minTop, maxRight, maxBottom, drawingCount);
+ }
+
+ private _applyAlignType(drawingTransformCaches: IDrawingTransformCache[], alignType: AlignType, minLeft: number, minTop: number, maxRight: number, maxBottom: number, drawingCount: number) {
+ const averageHorizon = Math.round((maxRight - minLeft) / drawingCount * 10) / 10;
+ const averageVertical = Math.round((maxBottom - minTop) / drawingCount * 10) / 10;
+ const updateParams: IDrawingParam[] = [];
+
+ const renderObject = this._getSceneAndTransformerByDrawingSearch(drawingTransformCaches[0].unitId);
+
+ if (renderObject == null) {
+ return;
+ }
+ const { scene, transformer } = renderObject;
+
+ drawingTransformCaches.forEach((drawingTransformCache, index) => {
+ const { unitId, subUnitId, drawingId, transform, drawingType } = drawingTransformCache;
+
+ const { left = 0, top = 0, width = 0, height = 0 } = transform;
+
+ let newLeft = left;
+ let newTop = top;
+
+ switch (alignType) {
+ case AlignType.left:
+ newLeft = minLeft;
+ break;
+ case AlignType.center:
+ newLeft = minLeft + (maxRight - minLeft) / 2 - width / 2;
+ break;
+ case AlignType.right:
+ newLeft = maxRight - width;
+ break;
+ case AlignType.top:
+ newTop = minTop;
+ break;
+ case AlignType.middle:
+ newTop = minTop + (maxBottom - minTop) / 2 - height / 2;
+ break;
+ case AlignType.bottom:
+ newTop = maxBottom - height;
+ break;
+ case AlignType.horizon:
+ newLeft = minLeft + averageHorizon * index;
+ break;
+ case AlignType.vertical:
+ newTop = minTop + averageVertical * index;
+ break;
+ default:
+ break;
+ }
+
+ if (newLeft !== left || newTop !== top) {
+ updateParams.push({
+ unitId,
+ subUnitId,
+ drawingId,
+ drawingType,
+ transform: {
+ left: newLeft,
+ top: newTop,
+ },
+ });
+ }
+ });
+
+ this._drawingManagerService.featurePluginUpdateNotification(updateParams);
+
+ transformer.refreshControls().changeNotification();
+ }
+
+ private _sortDrawingTransform(drawingTransformCaches: IDrawingTransformCache[], alignType: AlignType) {
+ drawingTransformCaches.sort((a, b) => {
+ const aTransform = a.transform;
+ const bTransform = b.transform;
+
+ const {
+ left: aLeft = 0,
+ top: aTop = 0,
+ width: aWidth = 0,
+ height: aHeight = 0,
+ } = aTransform;
+
+ const {
+ left: bLeft = 0,
+ top: bTop = 0,
+ width: bWidth = 0,
+ height: bHeight = 0,
+ } = bTransform;
+
+ switch (alignType) {
+ case AlignType.left:
+ return aLeft - bLeft;
+ case AlignType.center:
+ return aLeft + aWidth / 2 - (bLeft + bWidth / 2);
+ case AlignType.right:
+ return aLeft + aWidth - (bLeft + bWidth);
+ case AlignType.top:
+ return aTop - bTop;
+ case AlignType.middle:
+ return aTop + aHeight / 2 - (bTop + bHeight / 2);
+ case AlignType.bottom:
+ return aTop + aHeight - (bTop + bHeight);
+ case AlignType.horizon:
+ return aLeft + aWidth / 2 - (bLeft + bWidth / 2);
+ case AlignType.vertical:
+ return aTop + aHeight / 2 - (bTop + bHeight / 2);
+ default:
+ return 0;
+ }
+ });
+ }
+
+ private _drawingArrangeListener() {
+ this.disposeWithMe(
+ this._drawingManagerService.order$.subscribe((params) => {
+ this._drawingArrange(params);
+ })
+ );
+ }
+
+ private _drawingArrange(params: IDrawingOrderMapParam) {
+ const { unitId, subUnitId, drawingIds } = params;
+
+ const renderObject = this._getSceneAndTransformerByDrawingSearch(unitId);
+
+ if (renderObject == null) {
+ return;
+ }
+ const { scene, transformer } = renderObject;
+
+ drawingIds.forEach((drawingId) => {
+ const oKey = getDrawingShapeKeyByDrawingSearch({ unitId, subUnitId, drawingId });
+ const object = scene.getObject(oKey) as Shape<IShapeProps>;
+ if (object == null) {
+ return;
+ }
+ const index = this._drawingManagerService.getDrawingOrder(unitId, subUnitId).indexOf(drawingId);
+ object.setProps({ zIndex: index });
+ object.makeDirty();
+ });
+ }
+
+ private _sceneListenerOnDrawingMap: WeakSet<Scene> = new WeakSet();
+
+ private _drawingAddListener() {
+ this.disposeWithMe(
+ this._drawingManagerService.add$.subscribe((params) => {
+ this._insertDrawing(params);
+ })
+ );
+ }
+
+ private _insertDrawing(params: IDrawingSearch[]) {
+ const sceneList: Scene[] = [];
+ (params).forEach((param) => {
+ const { unitId, subUnitId, drawingId } = param;
+
+ const drawingParam = this._drawingManagerService.getDrawingByParam(param) as IDrawingParam;
+
+ if (drawingParam == null) {
+ return;
+ }
+
+ const { transform, drawingType } = drawingParam;
+
+ const renderObject = this._getSceneAndTransformerByDrawingSearch(unitId);
+
+ if (renderObject == null) {
+ return;
+ }
+ const { scene, transformer } = renderObject;
+
+ if (!sceneList.includes(scene)) {
+ sceneList.push(scene);
+ }
+ });
+
+ sceneList.forEach((scene) => {
+ if (this._sceneListenerOnDrawingMap.has(scene)) {
+ return;
+ }
+ this._addListenerOnDrawing(scene);
+ this._sceneListenerOnDrawingMap.add(scene);
+ });
+ }
+
+ private _drawingRemoveListener() {
+ this.disposeWithMe(
+ this._drawingManagerService.remove$.subscribe((params) => {
+ (params).forEach((param) => {
+ const { unitId, subUnitId, drawingId } = param;
+
+ const renderObject = this._getSceneAndTransformerByDrawingSearch(unitId);
+
+ if (renderObject == null) {
+ return;
+ }
+ const { scene, transformer } = renderObject;
+
+ const drawingShapeKey = getDrawingShapeKeyByDrawingSearch({ unitId, subUnitId, drawingId });
+
+ const drawingShape = scene.getObject(drawingShapeKey);
+
+ if (drawingShape != null) {
+ drawingShape.dispose();
+ scene.getTransformer()?.clearSelectedObjects();
+ }
+ });
+ })
+ );
+ }
+
+ private _drawingUpdateListener() {
+ this.disposeWithMe(
+ this._drawingManagerService.update$.subscribe((params) => {
+ (params).forEach((param) => {
+ const { unitId, subUnitId, drawingId } = param;
+
+ const drawingParam = this._drawingManagerService.getDrawingByParam(param) as IDrawingParam;
+
+ if (drawingParam == null) {
+ return;
+ }
+
+ const { transform, drawingType } = drawingParam;
+
+ const renderObject = this._getSceneAndTransformerByDrawingSearch(unitId);
+
+ if (renderObject == null) {
+ return;
+ }
+ const { scene, transformer } = renderObject;
+
+ if (transform == null) {
+ return true;
+ }
+
+ const { left = 0, top = 0, width = 0, height = 0, angle = 0, flipX = false, flipY = false, skewX = 0, skewY = 0 } = transform;
+
+ const drawingShapeKey = getDrawingShapeKeyByDrawingSearch({ unitId, subUnitId, drawingId });
+
+ const drawingShape = scene.getObject(drawingShapeKey);
+
+ if (drawingShape == null) {
+ return true;
+ }
+
+ drawingShape.transformByState({ left, top, width, height, angle, flipX, flipY, skewX, skewY });
+ });
+ })
+ );
+ }
+
+ private _drawingRefreshListener() {
+ this.disposeWithMe(
+ this._drawingManagerService.refreshTransform$.subscribe((params) => {
+ (params).forEach((param) => {
+ const { unitId, subUnitId, drawingId } = param;
+
+ const renderObject = this._getSceneAndTransformerByDrawingSearch(unitId);
+ if (renderObject == null) {
+ return;
+ }
+ const { scene, transformer } = renderObject;
+
+ const drawingShapeKey = getDrawingShapeKeyByDrawingSearch({ unitId, subUnitId, drawingId });
+ const drawingShape = scene.getObject(drawingShapeKey);
+
+ const drawingParam = this._drawingManagerService.getDrawingByParam(param) as IDrawingParam;
+ if (drawingParam == null) {
+ return;
+ }
+ const { transform } = drawingParam;
+
+ if (transform == null) {
+ return true;
+ }
+
+ const { left = 0, top = 0, width = 0, height = 0, angle = 0, flipX = false, flipY = false, skewX = 0, skewY = 0 } = transform;
+
+ if (drawingShape == null) {
+ return true;
+ }
+
+ drawingShape.transformByState({ left, top, width, height, angle, flipX, flipY, skewX, skewY });
+ });
+ })
+ );
+ }
+
+ private _drawingVisibleListener() {
+ this.disposeWithMe(
+ this._drawingManagerService.visible$.subscribe((params) => {
+ (params).forEach((param) => {
+ const { unitId, subUnitId, drawingId, visible } = param;
+
+ const renderObject = this._getSceneAndTransformerByDrawingSearch(unitId);
+ if (renderObject == null) {
+ return;
+ }
+ const { scene, transformer } = renderObject;
+
+ const drawingShapeKey = getDrawingShapeKeyByDrawingSearch({ unitId, subUnitId, drawingId });
+ const drawingShape = scene.getObject(drawingShapeKey);
+
+ if (drawingShape == null) {
+ return true;
+ }
+
+ if (visible) {
+ drawingShape.show();
+ } else {
+ drawingShape.hide();
+ }
+ });
+ })
+ );
+ }
+
+ private _filterUpdateParams(params: Nullable<IDrawingParam>[], startTransforms: Nullable<ITransformState[]>) {
+ return params.filter((param, index) => {
+ if (param == null) {
+ return false;
+ }
+ const { transform } = param;
+ return checkIfMove(transform, startTransforms?.[index]);
+ }) as IDrawingParam[];
+ }
+
+ // group?.getObjects().forEach((o) => {
+ // const drawing = this._drawingManagerService.getDrawingOKey(o.oKey);
+ // if (drawing != null) {
+ // const { unitId, subUnitId, drawingId } = drawing;
+ // drawings.push({ unitId, subUnitId, drawingId });
+ // }
+ // });
+ private _addListenerOnDrawing(scene: Scene) {
+ const transformer = scene.getTransformerByCreate();
+
+ let startTransforms: Nullable<ITransformState[]> = null;
+
+ this.disposeWithMe(
+ toDisposable(
+ transformer.onChangeStartObservable.add((state) => {
+ const { objects } = state;
+ const objectArray = Array.from(objects.values());
+ const drawings: IDrawingSearch[] = [];
+ startTransforms = objectArray.map((object) => {
+ const { left, top, height, width, angle, oKey, groupKey, isInGroup } = object;
+ const drawing = this._drawingManagerService.getDrawingOKey(oKey);
+ if (isInGroup || object instanceof Group) {
+ let group = object.ancestorGroup as Group;
+ if (group == null && object instanceof Group) {
+ group = object;
+ }
+
+ if (group == null) {
+ return null;
+ }
+
+ const groupDrawing = this._drawingManagerService.getDrawingOKey(group.oKey);
+ if (groupDrawing) {
+ const { unitId, subUnitId, drawingId } = groupDrawing;
+ drawings.push({ unitId, subUnitId, drawingId });
+ const { left, top, height, width, angle } = group;
+ return { left, top, height, width, angle };
+ }
+ } else if (drawing != null) {
+ const { unitId, subUnitId, drawingId } = drawing;
+ drawings.push({ unitId, subUnitId, drawingId });
+
+ return { left, top, height, width, angle };
+ }
+ return null;
+ }).filter((transform) => transform != null) as ITransformState[];
+
+ if (drawings.length > 0) {
+ this._drawingManagerService.focusDrawing(drawings);
+ } else {
+ this._drawingManagerService.focusDrawing(null);
+ }
+ })
+ )
+ );
+
+ this.disposeWithMe(
+ toDisposable(
+ transformer.onChangingObservable.add((state) => {
+ const { objects } = state;
+ const params = getUpdateParams(objects, this._drawingManagerService);
+ if (params.length > 0) {
+ // this._drawingManagerService.batchUpdate(params.filter((param) => {
+ // if (param == null) {
+ // return false;
+ // }
+ // return true;
+ // }) as IDrawingParam[]);
+ }
+ })
+ )
+ );
+
+ this.disposeWithMe(
+ toDisposable(
+ transformer.onChangeEndObservable.add((state) => {
+ const { objects } = state;
+ const params = this._filterUpdateParams(getUpdateParams(objects, this._drawingManagerService), startTransforms);
+
+ if (params.length > 0) {
+ // this._drawingManagerService.batchUpdate(params);
+ this._drawingManagerService.featurePluginUpdateNotification(params);
+ }
+ })
+ )
+ );
+ }
+}
diff --git a/packages/drawing-ui/src/controllers/image-cropper.controller.ts b/packages/drawing-ui/src/controllers/image-cropper.controller.ts
new file mode 100644
index 0000000000..7ca79baeea
--- /dev/null
+++ b/packages/drawing-ui/src/controllers/image-cropper.controller.ts
@@ -0,0 +1,499 @@
+/**
+ * Copyright 2023-present DreamNum Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { ICommandInfo, IDrawingSearch, ISrcRect, ITransformState, Nullable } from '@univerjs/core';
+import { checkIfMove, Disposable, ICommandService, IDrawingManagerService, IUniverInstanceService, LifecycleStages, LocaleService, OnLifecycle, toDisposable } from '@univerjs/core';
+import type { IImageData } from '@univerjs/drawing';
+import { getDrawingShapeKeyByDrawingSearch } from '@univerjs/drawing';
+import type { BaseObject, Scene } from '@univerjs/engine-render';
+import { CURSOR_TYPE, degToRad, Image, IRenderManagerService, precisionTo, Vector2 } from '@univerjs/engine-render';
+import { IMessageService } from '@univerjs/ui';
+import { Inject } from '@wendellhu/redi';
+import { MessageType } from '@univerjs/design';
+import type { IOpenImageCropOperationBySrcRectParams } from '../commands/operations/image-crop.operation';
+import { AutoImageCropOperation, CloseImageCropOperation, CropType, OpenImageCropOperation } from '../commands/operations/image-crop.operation';
+import { ImageCropperObject } from '../views/crop/image-cropper-object';
+
+@OnLifecycle(LifecycleStages.Rendered, ImageCropperController)
+export class ImageCropperController extends Disposable {
+ private _sceneListenerOnImageMap: WeakSet<Scene> = new WeakSet();
+
+ constructor(
+ @ICommandService private readonly _commandService: ICommandService,
+ @IDrawingManagerService private readonly _drawingManagerService: IDrawingManagerService,
+ @IRenderManagerService private readonly _renderManagerService: IRenderManagerService,
+ @IUniverInstanceService private _univerInstanceService: IUniverInstanceService,
+ @IMessageService private readonly _messageService: IMessageService,
+ @Inject(LocaleService) private readonly _localeService: LocaleService
+ ) {
+ super();
+
+ this._init();
+ }
+
+ private _init(): void {
+ this._initOpenCrop();
+ this._initCloseCrop();
+ this._initAutoCrop();
+ }
+
+ private _initAutoCrop() {
+ this.disposeWithMe(
+ this._commandService.onCommandExecuted((command: ICommandInfo) => {
+ if (command.id !== AutoImageCropOperation.id) {
+ return;
+ }
+
+ const params = command.params as IOpenImageCropOperationBySrcRectParams;
+
+ if (params == null) {
+ return;
+ }
+
+ const { cropType } = params;
+
+ const drawingParams = this._drawingManagerService.getFocusDrawings();
+
+ if (drawingParams.length !== 1) {
+ return;
+ }
+
+ const drawingParam = drawingParams[0];
+
+ const { unitId, subUnitId, drawingId } = drawingParam;
+
+ const renderObject = this._renderManagerService.getRenderById(unitId);
+
+ const scene = renderObject?.scene;
+
+ if (scene == null) {
+ return true;
+ }
+
+ const imageCropperObject = this._searchCropObject(scene);
+ if (imageCropperObject != null) {
+ this._commandService.syncExecuteCommand(CloseImageCropOperation.id, { isAuto: true });
+ }
+
+ const imageShapeKey = getDrawingShapeKeyByDrawingSearch({ unitId, subUnitId, drawingId });
+
+ const imageShape = scene.getObject(imageShapeKey);
+
+ if (!(imageShape instanceof Image)) {
+ this._messageService.show({
+ type: MessageType.Error,
+ content: this._localeService.t('image-cropper.error'),
+ });
+ return;
+ }
+
+ if (imageShape == null) {
+ return;
+ }
+
+ this._updateCropperObject(cropType, imageShape);
+
+ this._commandService.executeCommand(OpenImageCropOperation.id, { unitId, subUnitId, drawingId });
+ })
+ );
+ }
+
+ private _calculateSrcRectByRatio(left: number, top: number, width: number, height: number, numerator: number, denominator: number) {
+ const srcRatio = width / height;
+ const ratio = numerator / denominator;
+
+ let newWidth = width;
+ let newHeight = height;
+
+ if (srcRatio > ratio) {
+ newWidth = height * ratio;
+ } else {
+ newHeight = width / ratio;
+ }
+
+ const newLeft = (width - newWidth) / 2;
+ const newTop = (height - newHeight) / 2;
+
+ return {
+ left: precisionTo(newLeft, 1),
+ top: precisionTo(newTop, 1),
+ right: precisionTo(width - (newLeft + newWidth), 1),
+ bottom: precisionTo(height - (newTop + newHeight), 1),
+ };
+ }
+
+ private _updateCropperObject(cropType: CropType, imageShape: Image) {
+ const { left, top, width, height } = imageShape.calculateTransformWithSrcRect();
+
+ let newSrcRect: Nullable<ISrcRect>;
+ switch (cropType) {
+ case CropType.R1_1:
+ // 1:1
+ newSrcRect = this._calculateSrcRectByRatio(left, top, width, height, 1, 1);
+ break;
+ case CropType.R16_9:
+ // 16:9
+ newSrcRect = this._calculateSrcRectByRatio(left, top, width, height, 16, 9);
+ break;
+ case CropType.R9_16:
+ // 9:16
+ newSrcRect = this._calculateSrcRectByRatio(left, top, width, height, 9, 16);
+ break;
+ case CropType.R5_4:
+ // 5:4
+ newSrcRect = this._calculateSrcRectByRatio(left, top, width, height, 5, 4);
+ break;
+ case CropType.R4_5:
+ // 4:5
+ newSrcRect = this._calculateSrcRectByRatio(left, top, width, height, 4, 5);
+ break;
+ case CropType.R4_3:
+ // 4:3
+ newSrcRect = this._calculateSrcRectByRatio(left, top, width, height, 4, 3);
+ break;
+ case CropType.R3_4:
+ // 3:4
+ newSrcRect = this._calculateSrcRectByRatio(left, top, width, height, 3, 4);
+ break;
+ case CropType.R3_2:
+ // 3:2
+ newSrcRect = this._calculateSrcRectByRatio(left, top, width, height, 3, 2);
+ break;
+ case CropType.R2_3:
+ // 2:3
+ newSrcRect = this._calculateSrcRectByRatio(left, top, width, height, 2, 3);
+ break;
+ case CropType.FREE:
+ default:
+ break;
+ }
+
+ if (newSrcRect == null) {
+ return;
+ }
+
+ imageShape.setSrcRect(newSrcRect);
+
+ const { left: newLeft = 0, top: newTop = 0, bottom: newBottom = 0, right: newRight = 0 } = newSrcRect;
+ imageShape.transformByStateCloseCropper({
+ left: left + newLeft,
+ top: top + newTop,
+ width: width - newRight - newLeft,
+ height: height - newBottom - newTop,
+ });
+ }
+
+ private _initOpenCrop() {
+ this.disposeWithMe(
+ this._commandService.onCommandExecuted((command: ICommandInfo) => {
+ if (command.id !== OpenImageCropOperation.id) {
+ return;
+ }
+
+ const params = command.params as IDrawingSearch;
+
+ if (params == null) {
+ return;
+ }
+
+ const { unitId, subUnitId, drawingId } = params;
+
+ const renderObject = this._renderManagerService.getRenderById(unitId);
+
+ const scene = renderObject?.scene;
+
+ if (scene == null) {
+ return true;
+ }
+
+ if (!this._sceneListenerOnImageMap.has(scene)) {
+ this._addListenerOnImage(scene);
+ this._sceneListenerOnImageMap.add(scene);
+ }
+
+ const imageData = this._drawingManagerService.getDrawingByParam({ unitId, subUnitId, drawingId });
+
+ if (imageData == null) {
+ return;
+ }
+
+ const imageShapeKey = getDrawingShapeKeyByDrawingSearch({ unitId, subUnitId, drawingId });
+
+ const imageShape = scene.getObject(imageShapeKey);
+
+ if (imageShape == null) {
+ return;
+ }
+
+ if (!(imageShape instanceof Image)) {
+ this._messageService.show({
+ type: MessageType.Error,
+ content: this._localeService.t('image-cropper.error'),
+ });
+ return;
+ }
+ const transformer = scene.getTransformer();
+
+ transformer?.clearControls();
+
+ const imageCropperObject = new ImageCropperObject(`${imageShapeKey}-crop`, {
+ srcRect: imageShape.srcRect,
+ prstGeom: imageShape.prstGeom,
+ applyTransform: imageShape.calculateTransformWithSrcRect(),
+ });
+
+ scene.addObject(imageCropperObject, imageShape.getLayerIndex() + 1).attachTransformerTo(imageCropperObject);
+ transformer?.createControlForCopper(imageCropperObject);
+ this._addHoverForImageCopper(imageCropperObject);
+
+ imageShape.openRenderByCropper();
+ transformer?.refreshControls();
+ imageCropperObject.makeDirty(true);
+
+ this._drawingManagerService.focusDrawing([{ unitId, subUnitId, drawingId }]);
+ })
+ );
+ }
+
+ private _searchCropObject(scene: Scene) {
+ const objects = scene.getAllObjects();
+
+ for (const object of objects) {
+ if (object instanceof ImageCropperObject) {
+ return object as ImageCropperObject;
+ }
+ }
+ }
+
+ private _initCloseCrop() {
+ this.disposeWithMe(
+ this._commandService.onCommandExecuted((command: ICommandInfo) => {
+ if (command.id !== CloseImageCropOperation.id) {
+ return;
+ }
+
+ const currentUnit = this._univerInstanceService.getFocusedUnit();
+
+ if (currentUnit == null) {
+ return;
+ }
+
+ const unitId = currentUnit.getUnitId();
+ const renderObject = this._renderManagerService.getRenderById(unitId);
+
+ const scene = renderObject?.scene;
+
+ if (scene == null) {
+ return true;
+ }
+
+ const imageCropperObject = this._searchCropObject(scene);
+ if (imageCropperObject == null) {
+ return;
+ }
+ const imageShape = this._getApplyObjectByCropObject(imageCropperObject);
+ if (imageShape == null) {
+ return;
+ }
+
+ const transformer = scene.getTransformerByCreate();
+ transformer.detachFrom(imageCropperObject);
+ transformer.clearCopperControl();
+
+ const srcRect = this._getSrcRectByTransformState(imageShape, imageCropperObject);
+
+ const drawingParam = this._drawingManagerService.getDrawingOKey(imageShape.oKey);
+ if (drawingParam != null) {
+ const { left, top, height, width } = imageCropperObject;
+ this._drawingManagerService.featurePluginUpdateNotification([{
+ ...drawingParam,
+ transform: {
+ ...drawingParam.transform,
+ left, top, height, width,
+ },
+ srcRect: srcRect.srcRectAngle,
+ }] as IImageData[]);
+ }
+ imageShape.setSrcRect({ ...srcRect.srcRectAngle });
+ imageShape.closeRenderByCropper();
+
+ imageShape.makeDirty(true);
+
+ imageCropperObject?.dispose();
+ })
+ );
+ }
+
+ private _getApplyObjectByCropObject(cropObject: ImageCropperObject): Nullable<Image> {
+ const cropOKey = cropObject.oKey;
+ const applyOKey = cropOKey.slice(0, cropOKey.length - 5);
+
+ const applyObject = cropObject.getScene().getObject(applyOKey) as Image;
+ if (applyObject == null) {
+ return null;
+ }
+
+ return applyObject;
+ }
+
+ private _addListenerOnImage(scene: Scene) {
+ const transformer = scene.getTransformerByCreate();
+
+ let startTransform: Nullable<ITransformState> = null;
+ this.disposeWithMe(
+ toDisposable(
+ transformer.onChangeStartObservable.add((state) => {
+ const { objects } = state;
+ const cropObject = objects.values().next().value as ImageCropperObject;
+ if (cropObject == null || !(cropObject instanceof ImageCropperObject)) {
+ return;
+ }
+
+ const { left, top, height, width, angle } = cropObject;
+
+ startTransform = { left, top, height, width, angle };
+
+ transformer.clearCopperControl();
+ })
+ )
+ );
+ // this.disposeWithMe(
+ // toDisposable(
+ // transformer.onChangingObservable.add((state) => {
+
+ // })
+ // )
+ // );
+ this.disposeWithMe(
+ toDisposable(
+ transformer.onChangeEndObservable.add((state) => {
+ const { objects } = state;
+ const cropObject = objects.values().next().value as ImageCropperObject;
+ if (cropObject == null || !(cropObject instanceof ImageCropperObject)) {
+ return;
+ }
+
+ const { left, top, height, width, angle } = cropObject;
+
+ if (!checkIfMove({ left, top, height, width, angle }, startTransform)) {
+ return;
+ }
+
+ const applyObject = this._getApplyObjectByCropObject(cropObject);
+
+ if (applyObject == null) {
+ return;
+ }
+
+ const srcRect = this._getSrcRectByTransformState(applyObject, cropObject);
+
+ cropObject.refreshSrcRect(srcRect.srcRect, applyObject.getState());
+
+ // cropObject.imageData = {
+ // ...cropObject.imageData,
+ // srcRect: srcRect.srcRect,
+ // } as IImageData;
+
+ transformer.createControlForCopper(cropObject);
+ })
+ )
+ );
+ this._endCropListener(scene);
+ }
+
+ private _addHoverForImageCopper(o: ImageCropperObject) {
+ this.disposeWithMe(
+ toDisposable(
+ o.onPointerEnterObserver.add(() => {
+ o.cursor = CURSOR_TYPE.MOVE;
+ })
+ )
+ );
+
+ this.disposeWithMe(
+ toDisposable(
+ o.onPointerLeaveObserver.add(() => {
+ o.cursor = CURSOR_TYPE.DEFAULT;
+ })
+ )
+ );
+ }
+
+ private _endCropListener(scene: Scene) {
+ const transformer = scene.getTransformerByCreate();
+
+ this.disposeWithMe(
+ toDisposable(
+ transformer.onClearControlObservable.add((changeSelf) => {
+ if (changeSelf === true) {
+ this._commandService.syncExecuteCommand(CloseImageCropOperation.id);
+ }
+ })
+ )
+ );
+ }
+
+ private _getSrcRectByTransformState(applyObject: BaseObject, imageCropperObject: ImageCropperObject) {
+ const { left, top, height, width, strokeWidth, angle: copperAngle } = imageCropperObject;
+
+ const { left: applyLeft, top: applyTop, width: applyWidth, height: applyHeight, angle: applyAngle, strokeWidth: applyStrokeWidth } = applyObject;
+
+ const newLeft = left - applyLeft;
+ const newTop = top - applyTop;
+
+ const srcRect = {
+ left: newLeft,
+ top: newTop,
+ right: applyWidth - newLeft - width,
+ bottom: applyHeight - newTop - height,
+ };
+
+ const srcRectAngle = { ...srcRect };
+
+ // const offsetPoint = new Vector2(0, 0);
+ if (applyAngle !== 0) {
+ /**
+ * Calculate the offset of the center rotation to correctly position the object entering the cropping.
+ */
+ const cx = left + width / 2;
+ const cy = top + height / 2;
+ const centerPoint = new Vector2(cx, cy);
+
+ const newCx = applyWidth / 2 + applyLeft;
+ const newCy = applyHeight / 2 + applyTop;
+ const newCenterPoint = new Vector2(newCx, newCy);
+
+ const vertexPoint = new Vector2(applyLeft, applyTop);
+ vertexPoint.rotateByPoint(degToRad(applyAngle), newCenterPoint);
+
+ const applyFinalPoint = vertexPoint.clone();
+ applyFinalPoint.rotateByPoint(degToRad(-applyAngle), centerPoint);
+
+ const newAngleLeft = left - applyFinalPoint.x;
+ const newAngleTop = top - applyFinalPoint.y;
+
+ srcRectAngle.left = newAngleLeft;
+ srcRectAngle.top = newAngleTop;
+ srcRectAngle.right = applyWidth - newAngleLeft - width;
+ srcRectAngle.bottom = applyHeight - newAngleTop - height;
+ }
+
+ return {
+ srcRect,
+ srcRectAngle,
+ };
+ }
+}
diff --git a/packages/drawing-ui/src/controllers/image-update.controller.ts b/packages/drawing-ui/src/controllers/image-update.controller.ts
new file mode 100644
index 0000000000..e7c6bd7182
--- /dev/null
+++ b/packages/drawing-ui/src/controllers/image-update.controller.ts
@@ -0,0 +1,394 @@
+/**
+ * Copyright 2023-present DreamNum Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { ICommandInfo, IDrawingSearch, Nullable } from '@univerjs/core';
+import { Disposable,
+ DrawingTypeEnum,
+ ICommandService,
+ IDrawingManagerService,
+ IImageIoService,
+ ImageSourceType,
+ IUniverInstanceService,
+ LifecycleStages,
+ OnLifecycle,
+ toDisposable,
+} from '@univerjs/core';
+import type { IImageProps, Scene } from '@univerjs/engine-render';
+import { CURSOR_TYPE, DRAWING_OBJECT_LAYER_INDEX, Image, IRenderManagerService } from '@univerjs/engine-render';
+import type { IImageData } from '@univerjs/drawing';
+import { getDrawingShapeKeyByDrawingSearch } from '@univerjs/drawing';
+import { IDialogService } from '@univerjs/ui';
+import { COMPONENT_IMAGE_VIEWER } from '../views/image-viewer/component-name';
+import { ImageResetSizeOperation } from '../commands/operations/image-reset-size.operation';
+import { getCurrentUnitInfo, insertGroupObject } from './utils';
+
+const IMAGE_VIEWER_DROPDOWN_PADDING = 50;
+
+@OnLifecycle(LifecycleStages.Rendered, ImageUpdateController)
+export class ImageUpdateController extends Disposable {
+ constructor(
+ @ICommandService private readonly _commandService: ICommandService,
+ @IRenderManagerService private readonly _renderManagerService: IRenderManagerService,
+ @IDrawingManagerService private readonly _drawingManagerService: IDrawingManagerService,
+ @IDialogService private readonly _dialogService: IDialogService,
+ @IImageIoService private readonly _imageIoService: IImageIoService,
+ @IUniverInstanceService private readonly _currentUniverService: IUniverInstanceService
+ ) {
+ super();
+
+ this._initialize();
+ }
+
+ override dispose(): void {
+ super.dispose();
+ }
+
+ private _initialize() {
+ this._recoveryImages();
+
+ this._drawingAddListener();
+
+ this._commandExecutedListener();
+
+ this._imageUpdateListener();
+ }
+
+ private _recoveryImages() {
+ const drawingList = this._drawingManagerService.drawingManagerData;
+ const info = getCurrentUnitInfo(this._currentUniverService);
+ if (info == null) {
+ return;
+ }
+
+ const { unitId: currentUnitId, subUnitId: currentSubUnitId } = info;
+
+ Object.keys(drawingList).forEach((unitId) => {
+ Object.keys(drawingList[unitId]).forEach((subUnitId) => {
+ const drawingMap = drawingList[unitId][subUnitId].data;
+ if (drawingMap == null || unitId !== currentUnitId || subUnitId !== currentSubUnitId) {
+ return;
+ }
+ Object.keys(drawingMap).forEach((drawingId) => {
+ const drawing = drawingMap[drawingId];
+ if (drawing) {
+ this._insertImages([{ unitId, subUnitId, drawingId }]);
+ }
+ });
+ });
+ });
+ }
+
+ private _commandExecutedListener() {
+ this.disposeWithMe(
+ this._commandService.onCommandExecuted((command: ICommandInfo) => {
+ if (command.id === ImageResetSizeOperation.id) {
+ const params = command.params as IDrawingSearch[];
+ if (params == null) {
+ return;
+ }
+ this._resetImageSize(params);
+ }
+ })
+ );
+ }
+
+ private _getSceneAndTransformerByDrawingSearch(unitId: Nullable<string>) {
+ if (unitId == null) {
+ return;
+ }
+
+ const renderObject = this._renderManagerService.getRenderById(unitId);
+
+ const scene = renderObject?.scene;
+
+ if (scene == null) {
+ return null;
+ }
+
+ const transformer = scene.getTransformerByCreate();
+
+ return { scene, transformer };
+ }
+
+ private _resetImageSize(params: IDrawingSearch[]) {
+ const updateParams: IImageData[] = [];
+ const sceneList: Scene[] = [];
+
+ params.forEach((param) => {
+ const { unitId, subUnitId, drawingId } = param;
+
+ const renderObject = this._getSceneAndTransformerByDrawingSearch(unitId);
+
+ if (renderObject == null) {
+ return;
+ }
+ const { scene, transformer } = renderObject;
+
+ const imageShapeKey = getDrawingShapeKeyByDrawingSearch({ unitId, subUnitId, drawingId });
+
+ const imageShape = scene.getObject(imageShapeKey);
+
+ if (imageShape == null) {
+ return true;
+ }
+
+ const imageData = this._drawingManagerService.getDrawingByParam(param);
+
+ if (imageData == null) {
+ return true;
+ }
+
+ if (imageData.drawingType !== DrawingTypeEnum.DRAWING_IMAGE) {
+ return;
+ }
+
+ (imageShape as Image).resetSize();
+
+ const { width, height } = (imageShape as Image).getNativeSize();
+
+ if (sceneList.includes(scene) === false) {
+ sceneList.push(scene);
+ }
+
+ updateParams.push({
+ ...imageData,
+ transform: {
+ ...imageData.transform,
+ height,
+ width,
+ angle: 0,
+ },
+ srcRect: null,
+ prstGeom: null,
+ } as IImageData);
+ });
+
+ this._drawingManagerService.featurePluginUpdateNotification(updateParams);
+
+ sceneList.forEach((scene) => {
+ const transformer = scene.getTransformerByCreate();
+ transformer.refreshControls().changeNotification();
+ });
+
+ this._drawingManagerService.focusDrawing(params);
+ }
+
+ private _drawingAddListener() {
+ this.disposeWithMe(
+ this._drawingManagerService.add$.subscribe((params) => {
+ this._insertImages(params);
+ })
+ );
+ }
+
+ private _insertImages(params: IDrawingSearch[]) {
+ (params).forEach(async (param) => {
+ const { unitId, subUnitId, drawingId } = param;
+ const imageParam = this._drawingManagerService.getDrawingByParam(param) as IImageData;
+ if (imageParam == null) {
+ return;
+ }
+
+ const { transform, drawingType, source, imageSourceType, srcRect, prstGeom, groupId } = imageParam;
+ if (drawingType !== DrawingTypeEnum.DRAWING_IMAGE) {
+ return;
+ }
+ const renderObject = this._getSceneAndTransformerByDrawingSearch(unitId);
+
+ if (renderObject == null) {
+ return;
+ }
+ const { scene, transformer } = renderObject;
+ if (transform == null) {
+ return true;
+ }
+
+ const { left, top, width, height, angle, flipX, flipY, skewX, skewY } = transform;
+ const imageShapeKey = getDrawingShapeKeyByDrawingSearch({ unitId, subUnitId, drawingId });
+ const imageShape = scene.getObject(imageShapeKey);
+
+ if (imageShape != null) {
+ imageShape.transformByState({ left, top, width, height, angle, flipX, flipY, skewX, skewY });
+ return;
+ }
+
+ const orders = this._drawingManagerService.getDrawingOrder(unitId, subUnitId);
+ const zIndex = orders.indexOf(drawingId);
+ const imageConfig: IImageProps = { ...transform, zIndex: zIndex === -1 ? (orders.length - 1) : zIndex };
+ const imageNativeCache = this._imageIoService.getImageSourceCache(source, imageSourceType);
+
+ let shouldBeCache = false;
+ if (imageNativeCache != null) {
+ imageConfig.image = imageNativeCache;
+ } else {
+ if (imageSourceType === ImageSourceType.UUID) {
+ try {
+ imageConfig.url = await this._imageIoService.getImage(source);
+ } catch (error) {
+ console.error(error);
+ return;
+ }
+ } else {
+ imageConfig.url = source;
+ }
+ shouldBeCache = true;
+ }
+
+ const image = new Image(imageShapeKey, imageConfig);
+ if (shouldBeCache) {
+ this._imageIoService.addImageSourceCache(source, imageSourceType, image.getNative());
+ }
+
+ scene.addObject(image, DRAWING_OBJECT_LAYER_INDEX).attachTransformerTo(image);
+
+ groupId && insertGroupObject({ drawingId: groupId, unitId, subUnitId }, image, scene, this._drawingManagerService);
+
+ if (prstGeom != null) {
+ image.setPrstGeom(prstGeom);
+ }
+ if (srcRect != null) {
+ image.setSrcRect(srcRect);
+ }
+
+ this._addHoverForImage(image);
+ this._addDialogForImage(image);
+ });
+ }
+
+ private _imageUpdateListener() {
+ this.disposeWithMe(
+ this._drawingManagerService.update$.subscribe((params) => {
+ (params).forEach((param) => {
+ const { unitId, subUnitId, drawingId } = param;
+
+ const drawingParam = this._drawingManagerService.getDrawingByParam(param) as IImageData;
+
+ if (drawingParam == null) {
+ return;
+ }
+
+ const { transform, drawingType, srcRect, prstGeom, source, imageSourceType } = drawingParam;
+
+ if (drawingType !== DrawingTypeEnum.DRAWING_IMAGE) {
+ return;
+ }
+
+ const renderObject = this._getSceneAndTransformerByDrawingSearch(unitId);
+
+ if (renderObject == null) {
+ return;
+ }
+ const { scene, transformer } = renderObject;
+
+ if (transform == null) {
+ return true;
+ }
+
+ const drawingShapeKey = getDrawingShapeKeyByDrawingSearch({ unitId, subUnitId, drawingId });
+
+ const imageShape = scene.getObject(drawingShapeKey) as Image;
+
+ if (imageShape == null) {
+ return true;
+ }
+
+ imageShape.setSrcRect(srcRect);
+ imageShape.setPrstGeom(prstGeom);
+ // if (source != null && source.length > 0 && (imageSourceType === ImageSourceType.BASE64 || imageSourceType === ImageSourceType.URL)) {
+ // imageShape.changeSource(source);
+ // }
+ });
+ })
+ );
+ }
+
+ private _addHoverForImage(o: Image) {
+ this.disposeWithMe(
+ toDisposable(
+ o.onPointerEnterObserver.add(() => {
+ o.cursor = CURSOR_TYPE.GRAB;
+ })
+ )
+ );
+
+ this.disposeWithMe(
+ toDisposable(
+ o.onPointerLeaveObserver.add(() => {
+ o.cursor = CURSOR_TYPE.DEFAULT;
+ })
+ )
+ );
+ }
+
+ private _addDialogForImage(o: Image) {
+ this.disposeWithMe(
+ toDisposable(
+ o.onDblclickObserver.add(() => {
+ const dialogId = `${o.oKey}-viewer-dialog`;
+
+ const nativeSize = o.getNativeSize();
+ const screenWidth = window.innerWidth - IMAGE_VIEWER_DROPDOWN_PADDING;
+ const screenHeight = window.innerHeight - IMAGE_VIEWER_DROPDOWN_PADDING;
+
+ const adjustSize = this._adjustImageSize(nativeSize.width, nativeSize.height, screenWidth, screenHeight);
+
+ const dialog = this._dialogService.open({
+ width: adjustSize.width,
+ id: dialogId,
+ style: { margin: '0', top: '50%', left: '50%', transform: 'translate(-50%, -50%)' },
+ children: {
+ label: {
+ name: COMPONENT_IMAGE_VIEWER,
+ props: {
+ src: o.getNative()?.src,
+ width: adjustSize.width,
+ height: adjustSize.height,
+ },
+ },
+ },
+ destroyOnClose: true,
+ draggable: false,
+ onClose: () => {
+ this._dialogService.close(dialogId);
+ dialog.dispose();
+ },
+ });
+ })
+ )
+ );
+ }
+
+ private _adjustImageSize(nativeWidth: number, nativeHeight: number, screenWidth: number, screenHeight: number) {
+ // Use native size if the image is smaller than the screen
+ if (nativeWidth <= screenWidth && nativeHeight <= screenHeight) {
+ return {
+ width: nativeWidth,
+ height: nativeHeight,
+ };
+ }
+
+ // Calculate scale ratios
+ const widthRatio = screenWidth / nativeWidth;
+ const heightRatio = screenHeight / nativeHeight;
+ const scale = Math.min(widthRatio, heightRatio); // Choose the smaller ratio to ensure the image fits within the screen
+
+ // Return new dimensions
+ return {
+ width: Math.floor(nativeWidth * scale),
+ height: Math.floor(nativeHeight * scale),
+ };
+ }
+}
diff --git a/packages/drawing-ui/src/controllers/utils.ts b/packages/drawing-ui/src/controllers/utils.ts
new file mode 100644
index 0000000000..85061c19d2
--- /dev/null
+++ b/packages/drawing-ui/src/controllers/utils.ts
@@ -0,0 +1,76 @@
+/**
+ * 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 { IDrawingManagerService, IDrawingSearch, IUniverInstanceService, Nullable, Workbook } from '@univerjs/core';
+import { UniverInstanceType } from '@univerjs/core';
+import { getDrawingShapeKeyByDrawingSearch } from '@univerjs/drawing';
+import type { BaseObject, Scene } from '@univerjs/engine-render';
+import { DRAWING_OBJECT_LAYER_INDEX, Group } from '@univerjs/engine-render';
+
+export function insertGroupObject(objectParam: IDrawingSearch, object: BaseObject, scene: Scene, drawingManagerService: IDrawingManagerService) {
+ const groupParam = drawingManagerService.getDrawingByParam(objectParam);
+ if (groupParam == null) {
+ return;
+ }
+
+ const groupKey = getDrawingShapeKeyByDrawingSearch(objectParam);
+ const groupObject = scene.getObject(groupKey);
+
+ if (groupObject && !(groupObject instanceof Group)) {
+ return;
+ }
+
+ if (groupObject != null) {
+ groupObject.addObject(object);
+ return;
+ }
+
+ const group = new Group(groupKey);
+
+ scene.addObject(group, DRAWING_OBJECT_LAYER_INDEX).attachTransformerTo(group);
+
+ group.addObject(object);
+
+ const { transform } = groupParam;
+
+ transform && group.transformByState(
+ {
+ left: transform.left,
+ top: transform.top,
+ angle: transform.angle,
+ }
+ );
+}
+
+export function getCurrentUnitInfo(currentUniverService: IUniverInstanceService) {
+ const current = currentUniverService.getFocusedUnit();
+ if (current == null) {
+ return;
+ }
+
+ const unitId = current.getUnitId();
+ let subUnitId: Nullable<string>;
+
+ if (current.type === UniverInstanceType.UNIVER_SHEET) {
+ subUnitId = (current as Workbook).getActiveSheet().getSheetId();
+ } else if (current.type === UniverInstanceType.UNIVER_DOC) {
+ subUnitId = unitId;
+ } else if (current.type === UniverInstanceType.UNIVER_SLIDE) {
+ subUnitId = unitId;
+ }
+
+ return { unitId, subUnitId };
+}
diff --git a/packages/drawing-ui/src/index.ts b/packages/drawing-ui/src/index.ts
new file mode 100644
index 0000000000..db2c2ada97
--- /dev/null
+++ b/packages/drawing-ui/src/index.ts
@@ -0,0 +1,23 @@
+/**
+ * Copyright 2023-present DreamNum Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+export { getUpdateParams } from './utils/get-update-params';
+export { ImageResetSizeOperation } from './commands/operations/image-reset-size.operation';
+export { CloseImageCropOperation, OpenImageCropOperation } from './commands/operations/image-crop.operation';
+export { DrawingCommonPanel } from './views/panel/DrawingCommonPanel';
+export { ImagePopupMenu } from './views/image-popup-menu/ImagePopupMenu';
+export { COMPONENT_IMAGE_POPUP_MENU } from './views/image-popup-menu/component-name';
+export { UniverDrawingUIPlugin } from './plugin';
diff --git a/packages/drawing-ui/src/locale/en-US.ts b/packages/drawing-ui/src/locale/en-US.ts
new file mode 100644
index 0000000000..24ce5f0f69
--- /dev/null
+++ b/packages/drawing-ui/src/locale/en-US.ts
@@ -0,0 +1,72 @@
+/**
+ * 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.
+ */
+
+const locale = {
+ 'image-popup': {
+ replace: 'Replace',
+ delete: 'Delete',
+ edit: 'Edit',
+ crop: 'Crop',
+ reset: 'Reset Size',
+ },
+ 'image-cropper': {
+ error: 'Cannot crop non-image objects.',
+ },
+ 'image-panel': {
+ arrange: {
+ title: 'Arrange',
+ forward: 'Bring Forward',
+ backward: 'Send Backward',
+ front: 'Bring to Front',
+ back: 'Send to Back',
+ },
+ transform: {
+ title: 'Transform',
+ rotate: 'Rotate (°)',
+ x: 'X (px)',
+ y: 'Y (px)',
+ width: 'Width (px)',
+ height: 'Height (px)',
+ lock: 'Lock Ratio (%)',
+ },
+ crop: {
+ title: 'Crop',
+ start: 'Start Crop',
+ mode: 'Free',
+ },
+ group: {
+ title: 'Group',
+ group: 'Group',
+ reGroup: 'Regroup',
+ unGroup: 'Ungroup',
+ },
+ align: {
+ title: 'Align',
+ default: 'Select Align Type',
+ left: 'Align Left',
+ center: 'Align Center',
+ right: 'Align Right',
+ top: 'Align Top',
+ middle: 'Align Middle',
+ bottom: 'Align Bottom',
+ horizon: 'Distribute Horizontally ',
+ vertical: 'Distribute Vertically ',
+ },
+ null: 'No Object Selection',
+ },
+};
+
+export default locale;
diff --git a/packages/drawing-ui/src/locale/index.ts b/packages/drawing-ui/src/locale/index.ts
new file mode 100644
index 0000000000..1eff5fc204
--- /dev/null
+++ b/packages/drawing-ui/src/locale/index.ts
@@ -0,0 +1,18 @@
+/**
+ * Copyright 2023-present DreamNum Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+export { default as enUS } from './en-US';
+export { default as zhCN } from './zh-CN';
diff --git a/packages/drawing-ui/src/locale/ru-RU.ts b/packages/drawing-ui/src/locale/ru-RU.ts
new file mode 100644
index 0000000000..135c4b49c8
--- /dev/null
+++ b/packages/drawing-ui/src/locale/ru-RU.ts
@@ -0,0 +1,74 @@
+/**
+ * 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 enUS from './en-US';
+
+const locale: typeof enUS = {
+ 'image-popup': {
+ replace: 'Заменить',
+ delete: 'Удалить',
+ edit: 'Редактировать',
+ crop: 'Обрезать',
+ reset: 'Сбросить размер',
+ },
+ 'image-cropper': {
+ error: 'Невозможно обрезать не изображения.',
+ },
+ 'image-panel': {
+ arrange: {
+ title: 'Расположение',
+ forward: 'Переместить вперёд',
+ backward: 'Переместить назад',
+ front: 'На передний план',
+ back: 'На задний план',
+ },
+ transform: {
+ title: 'Трансформация',
+ rotate: 'Повернуть (°)',
+ x: 'X (пкс)',
+ y: 'Y (пкс)',
+ width: 'Ширина (пкс)',
+ height: 'Высота (пкс)',
+ lock: 'Заблокировать пропорции (%)',
+ },
+ crop: {
+ title: 'Обрезка',
+ start: 'Начать обрезку',
+ mode: 'Свободный',
+ },
+ group: {
+ title: 'Группировка',
+ group: 'Сгруппировать',
+ reGroup: 'Перегруппировать',
+ unGroup: 'Разгруппировать',
+ },
+ align: {
+ title: 'Выравнивание',
+ default: 'Выберите тип выравнивания',
+ left: 'Выровнять по левому краю',
+ center: 'Выровнять по центру',
+ right: 'Выровнять по правому краю',
+ top: 'Выровнять по верхнему краю',
+ middle: 'Выровнять посередине',
+ bottom: 'Выровнять по нижнему краю',
+ horizon: 'Распределить горизонтально',
+ vertical: 'Распределить вертикально',
+ },
+ null: 'Нет выбранных объектов',
+ },
+};
+
+export default locale;
diff --git a/packages/drawing-ui/src/locale/zh-CN.ts b/packages/drawing-ui/src/locale/zh-CN.ts
new file mode 100644
index 0000000000..1fc84fb744
--- /dev/null
+++ b/packages/drawing-ui/src/locale/zh-CN.ts
@@ -0,0 +1,74 @@
+/**
+ * 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 enUS from './en-US';
+
+const locale: typeof enUS = {
+ 'image-popup': {
+ replace: '替换',
+ delete: '删除',
+ edit: '编辑',
+ crop: '裁剪',
+ reset: '重置大小',
+ },
+ 'image-cropper': {
+ error: '无法裁剪非图片元素',
+ },
+ 'image-panel': {
+ arrange: {
+ title: '排列',
+ forward: '上移一层',
+ backward: '下移一层',
+ front: '置于顶层',
+ back: '置于底层',
+ },
+ transform: {
+ title: '变换',
+ rotate: '旋转 (°)',
+ x: 'X (px)',
+ y: 'Y (px)',
+ width: '宽度 (px)',
+ height: '高度 (px)',
+ lock: '锁定比例 (%)',
+ },
+ crop: {
+ title: '裁剪',
+ start: '开始裁剪',
+ mode: '自由比例裁剪',
+ },
+ group: {
+ title: '组合',
+ group: '组合',
+ reGroup: '重新组合',
+ unGroup: '取消组合',
+ },
+ align: {
+ title: '对齐方式',
+ default: '选择对齐方式',
+ left: '左对齐',
+ center: '水平居中',
+ right: '右对齐',
+ top: '顶部对齐',
+ middle: '垂直居中',
+ bottom: '底部对齐',
+ horizon: '水平分布',
+ vertical: '垂直分布',
+ },
+ null: '未选中任何对象',
+ },
+};
+
+export default locale;
diff --git a/packages/drawing-ui/src/plugin.ts b/packages/drawing-ui/src/plugin.ts
new file mode 100644
index 0000000000..2e2589f71a
--- /dev/null
+++ b/packages/drawing-ui/src/plugin.ts
@@ -0,0 +1,56 @@
+/**
+ * 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 { LocaleService, Plugin } from '@univerjs/core';
+import type { Dependency } from '@wendellhu/redi';
+import { Inject, Injector } from '@wendellhu/redi';
+import { DrawingUpdateController } from './controllers/drawing-update.controller';
+import { DrawingUIController } from './controllers/drawing-ui.controller';
+import { ImageCropperController } from './controllers/image-cropper.controller';
+import { ImageUpdateController } from './controllers/image-update.controller';
+
+const PLUGIN_NAME = 'IMAGE_UI_PLUGIN';
+
+export class UniverDrawingUIPlugin extends Plugin {
+ static override pluginName = PLUGIN_NAME;
+
+ constructor(
+ config: undefined,
+ @Inject(Injector) protected _injector: Injector,
+ @Inject(LocaleService) private readonly _localeService: LocaleService
+ ) {
+ super();
+ }
+
+ override onStarting(_injector: Injector): void {
+ this._initDependencies(_injector);
+ }
+
+ private _initDependencies(injector: Injector): void {
+ const dependencies: Dependency[] = [
+
+ // services
+
+ // controllers
+ [DrawingUpdateController],
+ [DrawingUIController],
+ [ImageCropperController],
+ [ImageUpdateController],
+ ];
+
+ dependencies.forEach((dependency) => injector.add(dependency));
+ }
+}
diff --git a/packages/drawing-ui/src/utils/config.ts b/packages/drawing-ui/src/utils/config.ts
new file mode 100644
index 0000000000..cf6a05ff16
--- /dev/null
+++ b/packages/drawing-ui/src/utils/config.ts
@@ -0,0 +1,21 @@
+/**
+ * Copyright 2023-present DreamNum Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+export const MIN_DRAWING_WIDTH_LIMIT = 20;
+
+export const MIN_DRAWING_HEIGHT_LIMIT = 20;
+
+export const RANGE_DRAWING_ROTATION_LIMIT = [-3600, 3600];
diff --git a/packages/drawing-ui/src/utils/get-update-params.ts b/packages/drawing-ui/src/utils/get-update-params.ts
new file mode 100644
index 0000000000..709b68ebd0
--- /dev/null
+++ b/packages/drawing-ui/src/utils/get-update-params.ts
@@ -0,0 +1,57 @@
+/**
+ * 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 { DrawingTypeEnum, type IDrawingManagerService, type IDrawingParam, type Nullable } from '@univerjs/core';
+import type { IImageData } from '@univerjs/drawing';
+import type { BaseObject, Image } from '@univerjs/engine-render';
+
+export function getUpdateParams(objects: Map<string, BaseObject>, drawingManagerService: IDrawingManagerService): Nullable<IDrawingParam>[] {
+ const params: Nullable<IDrawingParam>[] = [];
+ objects.forEach((object) => {
+ const { oKey, left, top, height, width, angle } = object;
+
+ const searchParam = drawingManagerService.getDrawingOKey(oKey);
+
+ if (searchParam == null) {
+ params.push(null);
+ return true;
+ }
+
+ const { unitId, subUnitId, drawingId, drawingType } = searchParam;
+
+ const param = {
+ unitId,
+ subUnitId,
+ drawingId,
+ drawingType,
+ transform: {
+ left,
+ top,
+ height,
+ width,
+ angle,
+ },
+ } as IDrawingParam;
+
+ if (drawingType === DrawingTypeEnum.DRAWING_IMAGE) {
+ (param as IImageData).srcRect = (object as Image).srcRect;
+ }
+
+ params.push(param);
+ });
+
+ return params;
+}
diff --git a/packages/drawing-ui/src/views/crop/image-cropper-object.ts b/packages/drawing-ui/src/views/crop/image-cropper-object.ts
new file mode 100644
index 0000000000..0c35540964
--- /dev/null
+++ b/packages/drawing-ui/src/views/crop/image-cropper-object.ts
@@ -0,0 +1,254 @@
+/**
+ * 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 { ISrcRect, ITransformState, Nullable, PresetGeometryType } from '@univerjs/core';
+import type { Engine, IShapeProps, IViewportInfo, Scene, UniverRenderingContext, Vector2 } from '@univerjs/engine-render';
+import { Canvas, Rect, Shape } from '@univerjs/engine-render';
+
+export interface IImageCropperObjectProps extends IShapeProps {
+ /**
+ * 20.1.8.55 srcRect (Source Rectangle)
+ */
+ srcRect?: Nullable<ISrcRect>;
+
+ /**
+ * 20.1.9.18 prstGeom (Preset geometry)
+ */
+ prstGeom?: Nullable<PresetGeometryType>;
+ applyTransform?: ITransformState;
+ dragPadding?: number;
+}
+
+enum ImageCropperObjectType {
+ RECT,
+ PATH,
+}
+
+export class ImageCropperObject<T extends IImageCropperObjectProps = IImageCropperObjectProps> extends Shape<T> {
+ private _srcRect: Nullable<ISrcRect>;
+ private _prstGeom: Nullable<PresetGeometryType>;
+ private _applyTransform: Nullable<ITransformState>;
+
+ private _dragPadding = 8;
+
+ private _cacheCanvas: Nullable<Canvas>;
+
+ constructor(key?: string, props?: T) {
+ if (props == null) {
+ props = {} as T;
+ }
+ props.transformerConfig = {
+ keepRatio: false,
+ isCropper: true,
+ anchorFill: 'rgb(0, 0, 0)',
+ anchorStroke: 'rgb(255, 255, 255)',
+ anchorSize: 24,
+ };
+
+ super(key, props);
+
+ if (props?.srcRect) {
+ this._srcRect = props.srcRect;
+ }
+
+ if (props?.prstGeom) {
+ this._prstGeom = props.prstGeom;
+ }
+
+ if (props?.applyTransform) {
+ this._applyTransform = props.applyTransform;
+ }
+
+ if (props?.dragPadding) {
+ this._dragPadding = props.dragPadding;
+ }
+
+ this._applyProps();
+ }
+
+ refreshSrcRect(value: Nullable<ISrcRect>, transform: Nullable<ITransformState>) {
+ this._srcRect = value;
+ this._applyTransform = transform;
+ this._applyProps();
+ }
+
+ get srcRect() {
+ return this._srcRect;
+ }
+
+ override dispose() {
+ super.dispose();
+ this._cacheCanvas?.dispose();
+ this._srcRect = null;
+ }
+
+ override isHit(coord: Vector2) {
+ const oCoord = this.getInverseCoord(coord);
+ if (
+ oCoord.x >= -this.strokeWidth / 2 &&
+ oCoord.x <= this.width + this.strokeWidth / 2 &&
+ oCoord.y >= -this.strokeWidth / 2 &&
+ oCoord.y <= this.height + this.strokeWidth / 2 &&
+ !this._inSurround(oCoord)
+ ) {
+ return true;
+ }
+ return false;
+ }
+
+ private _inSurround(oCoord: Vector2) {
+ const padding = this._dragPadding;
+ if (
+ oCoord.x >= padding - this.strokeWidth / 2 &&
+ oCoord.x <= this.width + this.strokeWidth / 2 - padding &&
+ oCoord.y >= padding - this.strokeWidth / 2 &&
+ oCoord.y <= this.height + this.strokeWidth / 2 - padding
+ ) {
+ return true;
+ }
+
+ return false;
+ }
+
+ override render(mainCtx: UniverRenderingContext, bounds?: IViewportInfo) {
+ if (!this.visible) {
+ this.makeDirty(false);
+ return this;
+ }
+
+ mainCtx.save();
+ this._draw(mainCtx);
+ mainCtx.restore();
+ this.makeDirty(false);
+ return this;
+ }
+
+ protected override _draw(ctx: UniverRenderingContext) {
+ // const { left, top, width, height, angle } = applyObject;
+ const scene = this.getScene() as Scene;
+
+ const engine = scene.getEngine() as Engine;
+
+ const { width: engineWidth, height: engineHeight } = engine;
+
+ this._initialCacheCanvas();
+
+ // if (this._dirty) {
+ this._cacheCanvas?.clear();
+ const cacheCtx = this._cacheCanvas?.getContext();
+ if (cacheCtx == null) {
+ return;
+ }
+
+ cacheCtx.save();
+
+ Rect.drawWith(cacheCtx, {
+ left: 0,
+ top: 0,
+ width: engineWidth,
+ height: engineHeight,
+ fill: 'rgba(0, 0, 0, 0.5)',
+ });
+
+ cacheCtx.setTransform(ctx.getTransform());
+ this._clipForApplyObject(cacheCtx);
+ this._applyCache(ctx);
+ cacheCtx.restore();
+ // } else {
+ // this._applyCache(ctx);
+ // }
+ }
+
+ private _clipForApplyObject(cacheCtx: UniverRenderingContext) {
+ let objectType = ImageCropperObjectType.RECT;
+
+ if (this._prstGeom != null) {
+ objectType = ImageCropperObjectType.PATH;
+ }
+ cacheCtx.globalCompositeOperation = 'destination-out';
+ cacheCtx.beginPath();
+
+ if (objectType === ImageCropperObjectType.RECT) {
+ const m = this.transform.getMatrix();
+ cacheCtx.transform(m[0], m[1], m[2], m[3], m[4], m[5]);
+ cacheCtx.rect(0, 0, this.width, this.height);
+ cacheCtx.fill();
+ } else {
+ // const path = new Path2D(imageData.prstGeom);
+ // cacheCtx.fill(path);
+ }
+ }
+
+ private _applyProps() {
+ if (this._applyTransform == null) {
+ return;
+ }
+
+ let cropLeft = 0;
+ let cropTop = 0;
+ let cropRight = 0;
+ let cropBottom = 0;
+
+ const { left: applyLeft = 0, top: applyTop = 0, width: applyWidth = 0, height: applyHeight = 0, angle } = this._applyTransform;
+
+ if (this._srcRect != null) {
+ const { left = 0, top = 0, right = 0, bottom = 0 } = this._srcRect;
+ cropLeft = left;
+ cropTop = top;
+ cropRight = right;
+ cropBottom = bottom;
+ }
+
+ const left = applyLeft + cropLeft;
+ const top = applyTop + cropTop;
+
+ this.transformByState({
+ left,
+ top,
+ width: applyLeft + applyWidth - cropRight - left,
+ height: applyTop + applyHeight - cropBottom - top,
+ angle,
+ });
+ }
+
+ private _applyCache(ctx?: UniverRenderingContext) {
+ if (!ctx || this._cacheCanvas == null) {
+ return;
+ }
+ const cacheCtx = this._cacheCanvas.getContext();
+ cacheCtx.save();
+ ctx.save();
+ ctx.setTransform(1, 0, 0, 1, 0, 0);
+ cacheCtx.setTransform(1, 0, 0, 1, 0, 0);
+ ctx.drawImage(this._cacheCanvas.getCanvasEle(), 0, 0);
+ ctx.restore();
+ cacheCtx.restore();
+ }
+
+ private _initialCacheCanvas() {
+ if (this._cacheCanvas != null) {
+ return;
+ }
+ this._cacheCanvas = new Canvas();
+ const engine = this.getScene().getEngine() as Engine;
+ this._cacheCanvas.setSize(engine.width, engine.height);
+
+ this.getScene().getEngine().onTransformChangeObservable.add(() => {
+ this._cacheCanvas?.setSize(engine.width, engine.height);
+ this.makeDirty(true);
+ });
+ }
+}
diff --git a/packages/drawing-ui/src/views/crop/index.module.less b/packages/drawing-ui/src/views/crop/index.module.less
new file mode 100644
index 0000000000..8c433e5e91
--- /dev/null
+++ b/packages/drawing-ui/src/views/crop/index.module.less
@@ -0,0 +1,12 @@
+.drawing-crop {
+ &-menu {
+ position: absolute;
+ height: 100%;
+ width: 100%;
+ text-align: center;
+
+ &-input {
+ display: none;
+ }
+ }
+}
diff --git a/packages/drawing-ui/src/views/image-popup-menu/ImagePopupMenu.tsx b/packages/drawing-ui/src/views/image-popup-menu/ImagePopupMenu.tsx
new file mode 100644
index 0000000000..60a56078fe
--- /dev/null
+++ b/packages/drawing-ui/src/views/image-popup-menu/ImagePopupMenu.tsx
@@ -0,0 +1,116 @@
+/**
+ * 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 { IDrawingSearch } from '@univerjs/core';
+import { ICommandService, LocaleService } from '@univerjs/core';
+import { Dropdown } from '@univerjs/design';
+import { Autofill, MoreDownSingle } from '@univerjs/icons';
+import { useDependency } from '@wendellhu/redi/react-bindings';
+import clsx from 'clsx';
+import React, { useState } from 'react';
+import styles from './index.module.less';
+
+export interface IImagePopupMenuItem {
+ label: string;
+ index: number;
+ commandId: string;
+ commandParams?: IDrawingSearch[];
+ disable: boolean;
+}
+
+export interface IImagePopupMenuExtraProps {
+ menuItems: IImagePopupMenuItem[];
+}
+
+export interface IImagePopupMenuProps {
+ popup: {
+ extraProps?: IImagePopupMenuExtraProps;
+ };
+}
+
+export const ImagePopupMenu: React.FC<IImagePopupMenuProps> = (props: IImagePopupMenuProps) => {
+ const menuItems = props.popup?.extraProps?.menuItems;
+
+ if (!menuItems) {
+ return null;
+ }
+
+ const commandService = useDependency(ICommandService);
+ const localeService = useDependency(LocaleService);
+
+ const [visible, setVisible] = useState(false);
+ const [isHovered, setHovered] = useState(false);
+
+ const handleMouseEnter = () => {
+ setHovered(true);
+ };
+
+ const handleMouseLeave = () => {
+ setHovered(false);
+ };
+
+ const onVisibleChange = (visible: boolean) => {
+ setVisible(visible);
+ };
+
+ const handleClick = (item: IImagePopupMenuItem) => {
+ commandService.executeCommand(item.commandId, item.commandParams);
+ setVisible(false);
+ };
+
+ const showMore = visible || isHovered;
+
+ const availableMenu = menuItems.filter((item) => !item.disable);
+
+ return (
+ <div
+ onMouseEnter={handleMouseEnter}
+ onMouseLeave={handleMouseLeave}
+ >
+ <Dropdown
+ placement="bottomLeft"
+ trigger={['click']}
+ overlay={(
+ <ul className={styles.imagePopupMenu}>
+ {availableMenu.map((item) => (
+ <li
+ key={item.index}
+ onClick={() => handleClick(item)}
+ className={styles.imagePopupMenuItem}
+ >
+ <span className={styles.imagePopupMenuItemTitle}>{localeService.t(item.label)}</span>
+ </li>
+ ))}
+ </ul>
+ )}
+ visible={visible}
+ onVisibleChange={onVisibleChange}
+ >
+ <div
+ className={clsx(styles.btnContainer, {
+ [styles.btnContainerExpand]: visible,
+ })}
+ >
+ <Autofill
+ style={{ color: '#35322B' }}
+ extend={{ colorChannel1: 'rgb(var(--green-700, #409f11))' }}
+ />
+ {showMore && <MoreDownSingle style={{ color: '#CCCCCC', fontSize: '8px', marginLeft: '8px' }} />}
+ </div>
+ </Dropdown>
+ </div>
+ );
+};
diff --git a/packages/drawing-ui/src/views/image-popup-menu/component-name.ts b/packages/drawing-ui/src/views/image-popup-menu/component-name.ts
new file mode 100644
index 0000000000..9c60821de3
--- /dev/null
+++ b/packages/drawing-ui/src/views/image-popup-menu/component-name.ts
@@ -0,0 +1,18 @@
+/**
+ * Copyright 2023-present DreamNum Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+export const COMPONENT_IMAGE_POPUP_MENU = 'COMPONENT_IMAGE_POPUP_MENU';
+
diff --git a/packages/drawing-ui/src/views/image-popup-menu/index.module.less b/packages/drawing-ui/src/views/image-popup-menu/index.module.less
new file mode 100644
index 0000000000..982003b0c2
--- /dev/null
+++ b/packages/drawing-ui/src/views/image-popup-menu/index.module.less
@@ -0,0 +1,92 @@
+.image-popup-menu {
+ display: grid;
+ gap: var(--margin-xxs);
+ align-items: center;
+
+ box-sizing: border-box;
+
+ margin-top: 0;
+ margin-bottom: 0;
+ padding: var(--padding-sm);
+
+ font-size: var(--font-size-base);
+
+ background-color: rgb(var(--bg-color-secondary));
+ border: 1px solid rgb(var(--border-color));
+ border-radius: var(--border-radius-lg);
+ box-shadow: var(--box-shadow-lg);
+
+ li {
+ list-style: none;
+ }
+
+ &-item {
+ cursor: pointer;
+
+ position: relative;
+
+ display: flex;
+ align-items: center;
+
+ box-sizing: border-box;
+ height: 28px;
+
+ font-size: var(--font-size-base);
+ font-style: normal;
+ line-height: 20px; /* 153.846% */
+ text-align: left;
+
+ border-radius: 4px;
+ border-radius: var(--border-radius-base);
+
+ transition: background 0.2s;
+
+ &:hover {
+ background-color: rgb(var(--bg-color-hover));
+ }
+
+ &-icon {
+ position: absolute;
+ top: 50%;
+ left: var(--padding-xs);
+ transform: translateY(-50%);
+
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ }
+
+ &-title {
+ padding: var(--padding-xs) var(--padding-xs) var(--padding-xs) 0;
+ vertical-align: middle;
+ }
+
+ &-hide {
+ color: rgb(var(--text-color-secondary));
+ }
+
+ &:hover {
+ background: rgb(var(--grey-100));
+ }
+ }
+}
+
+.btn-container {
+ display: flex;
+ align-items: center;
+ justify-content: center;
+
+ padding: 3px;
+
+ background: white;
+ border: 1px solid rgb(var(--grey-200, #e5e5e5));
+ border-radius: 4px;
+
+ &:hover {
+ background: rgb(var(--grey-100, #f5f5f5));
+ }
+
+ &.btn-container-expand {
+ background: rgb(var(--grey-100, #f5f5f5));
+ }
+}
diff --git a/packages/image/src/models/image-model.ts b/packages/drawing-ui/src/views/image-viewer/ImageViewer.tsx
similarity index 52%
rename from packages/image/src/models/image-model.ts
rename to packages/drawing-ui/src/views/image-viewer/ImageViewer.tsx
index 1946282c36..74aba00f0c 100644
--- a/packages/image/src/models/image-model.ts
+++ b/packages/drawing-ui/src/views/image-viewer/ImageViewer.tsx
@@ -15,40 +15,22 @@
*/
import type { Nullable } from '@univerjs/core';
+import React from 'react';
-export interface IImageData {
- imageId: string;
- contentUrl: string;
+export interface IImageViewerProps {
+ src: Nullable<string>;
}
-export class ImageModel {
- private _imageShapeKey: Nullable<string>;
+export const ImageViewer: React.FC<IImageViewerProps> = (props: IImageViewerProps) => {
+ const { src } = props;
- constructor(private _imageData: IImageData) {
- // empty
+ if (!src) {
+ return null;
}
- getImageData() {
- return this._imageData;
- }
-
- getUrl() {
- return this._imageData.contentUrl;
- }
-
- getId() {
- return this._imageData.imageId;
- }
-
- setKey(key: string) {
- this._imageShapeKey = key;
- }
-
- getKey() {
- return this._imageShapeKey;
- }
-
- hasRender() {
- return this._imageShapeKey != null;
- }
-}
+ return (
+ <div>
+ <img src={src} alt="Univer Image Viewer" style={{ width: '100%', height: '100%', position: 'relative' }} />
+ </div>
+ );
+};
diff --git a/packages/drawing-ui/src/views/image-viewer/component-name.ts b/packages/drawing-ui/src/views/image-viewer/component-name.ts
new file mode 100644
index 0000000000..6fc69392ef
--- /dev/null
+++ b/packages/drawing-ui/src/views/image-viewer/component-name.ts
@@ -0,0 +1,18 @@
+/**
+ * Copyright 2023-present DreamNum Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+export const COMPONENT_IMAGE_VIEWER = 'COMPONENT_IMAGE_VIEWER';
+
diff --git a/packages/drawing-ui/src/views/panel/DrawingAlign.tsx b/packages/drawing-ui/src/views/panel/DrawingAlign.tsx
new file mode 100644
index 0000000000..558108c2a9
--- /dev/null
+++ b/packages/drawing-ui/src/views/panel/DrawingAlign.tsx
@@ -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 { IDrawingParam } from '@univerjs/core';
+import { ICommandService, LocaleService } from '@univerjs/core';
+import { useDependency } from '@wendellhu/redi/react-bindings';
+import React, { useState } from 'react';
+import { Select } from '@univerjs/design';
+import clsx from 'clsx';
+import { AlignType, SetDrawingAlignOperation } from '../../commands/operations/drawing-align.operation';
+import styles from './index.module.less';
+
+export interface IDrawingAlignProps {
+ drawings: IDrawingParam[];
+ alignShow: boolean;
+
+}
+
+export const DrawingAlign = (props: IDrawingAlignProps) => {
+ const commandService = useDependency(ICommandService);
+ const localeService = useDependency(LocaleService);
+
+ const { alignShow } = props;
+
+ const [alignValue, setAlignValue] = useState<string>(AlignType.default as string);
+ const alignOptions = [
+ {
+ label: localeService.t('image-panel.align.default'),
+ value: AlignType.default,
+ },
+ {
+ options: [
+ {
+ label: localeService.t('image-panel.align.left'),
+ value: AlignType.left,
+ }, {
+ label: localeService.t('image-panel.align.center'),
+ value: AlignType.center,
+ }, {
+ label: localeService.t('image-panel.align.right'),
+ value: AlignType.right,
+ },
+ ],
+ },
+ {
+ options: [
+ {
+ label: localeService.t('image-panel.align.top'),
+ value: AlignType.top,
+ }, {
+ label: localeService.t('image-panel.align.middle'),
+ value: AlignType.middle,
+ }, {
+ label: localeService.t('image-panel.align.bottom'),
+ value: AlignType.bottom,
+ },
+ ],
+ }, {
+ options: [
+ {
+ label: localeService.t('image-panel.align.horizon'),
+ value: AlignType.horizon,
+ }, {
+ label: localeService.t('image-panel.align.vertical'),
+ value: AlignType.vertical,
+ },
+ ],
+ },
+ ];
+
+ function handleAlignChange(value: string | number | boolean) {
+ setAlignValue((value as string));
+ commandService.executeCommand(SetDrawingAlignOperation.id, {
+ alignType: value as AlignType,
+ });
+ }
+
+ const gridDisplay = (isShow: boolean) => {
+ return isShow ? 'block' : 'none';
+ };
+
+ return (
+ <div className={clsx(styles.imageCommonPanelGrid, styles.imageCommonPanelBorder)} style={{ display: gridDisplay(alignShow) }}>
+ <div className={styles.imageCommonPanelRow}>
+ <div className={clsx(styles.imageCommonPanelColumn, styles.imageCommonPanelTitle)}>
+ <div>{localeService.t('image-panel.align.title')}</div>
+ </div>
+ </div>
+ <div className={styles.imageCommonPanelRow}>
+ <div className={clsx(styles.imageCommonPanelColumn)}>
+ <Select value={alignValue} options={alignOptions} onChange={handleAlignChange} />
+ </div>
+ </div>
+ </div>
+ );
+};
diff --git a/packages/drawing-ui/src/views/panel/DrawingArrange.tsx b/packages/drawing-ui/src/views/panel/DrawingArrange.tsx
new file mode 100644
index 0000000000..acc8c42d56
--- /dev/null
+++ b/packages/drawing-ui/src/views/panel/DrawingArrange.tsx
@@ -0,0 +1,117 @@
+/**
+ * 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 { IDrawingParam } from '@univerjs/core';
+import { ArrangeTypeEnum, ICommandService, IDrawingManagerService, LocaleService } from '@univerjs/core';
+import { useDependency } from '@wendellhu/redi/react-bindings';
+import React, { useEffect, useState } from 'react';
+import { BottomSingle, MoveDownSingle, MoveUpSingle, TopmostSingle } from '@univerjs/icons';
+import { Button } from '@univerjs/design';
+import clsx from 'clsx';
+import styles from './index.module.less';
+
+export interface IDrawingArrangeProps {
+ arrangeShow: boolean;
+ drawings: IDrawingParam[];
+}
+
+export const DrawingArrange = (props: IDrawingArrangeProps) => {
+ const { arrangeShow, drawings: focusDrawings } = props;
+
+ const commandService = useDependency(ICommandService);
+ const localeService = useDependency(LocaleService);
+ const drawingManagerService = useDependency(IDrawingManagerService);
+
+ const gridDisplay = (isShow: boolean) => {
+ return isShow ? 'block' : 'none';
+ };
+
+ const [drawings, setDrawings] = useState<IDrawingParam[]>(focusDrawings);
+
+ useEffect(() => {
+ const focusDispose = drawingManagerService.focus$.subscribe((drawings) => {
+ setDrawings(drawings);
+ });
+
+ return () => {
+ focusDispose.unsubscribe();
+ };
+ }, []);
+
+ const onArrangeBtnClick = (arrangeType: ArrangeTypeEnum) => {
+ // commandService.executeCommand(SetDrawingArrangeCommand.id, {
+ // unitId: drawings[0].unitId,
+ // subUnitId: drawings[0].subUnitId,
+ // drawingIds: drawings.map((drawing) => drawing.drawingId),
+ // arrangeType,
+ // });
+
+ const unitId = drawings[0].unitId;
+ const subUnitId = drawings[0].subUnitId;
+ const drawingIds = drawings.map((drawing) => drawing.drawingId);
+
+ drawingManagerService.featurePluginOrderUpdateNotification({ unitId, subUnitId, drawingIds, arrangeType });
+
+ // if (arrangeType === ArrangeType.forward) {
+ // drawingManagerService.forwardDrawings(unitId, subUnitId, drawingIds);
+ // } else if (arrangeType === ArrangeType.backward) {
+ // drawingManagerService.backwardDrawing(unitId, subUnitId, drawingIds);
+ // } else if (arrangeType === ArrangeType.front) {
+ // drawingManagerService.frontDrawing(unitId, subUnitId, drawingIds);
+ // } else if (arrangeType === ArrangeType.back) {
+ // drawingManagerService.backDrawing(unitId, subUnitId, drawingIds);
+ // }
+ };
+
+ return (
+ <div className={styles.imageCommonPanelGrid} style={{ display: gridDisplay(arrangeShow) }}>
+ <div className={styles.imageCommonPanelRow}>
+ <div className={clsx(styles.imageCommonPanelColumn, styles.imageCommonPanelTitle)}>
+ <div>{localeService.t('image-panel.arrange.title')}</div>
+ </div>
+ </div>
+ <div className={styles.imageCommonPanelRow}>
+ <div className={clsx(styles.imageCommonPanelColumn, styles.imageCommonPanelSpan2)}>
+ <Button size="small" onClick={() => { onArrangeBtnClick(ArrangeTypeEnum.forward); }}>
+ <div className={clsx(styles.imageCommonPanelInline)}><MoveUpSingle /></div>
+ <div className={clsx(styles.imageCommonPanelInline)}>{localeService.t('image-panel.arrange.forward')}</div>
+ </Button>
+ </div>
+ <div className={clsx(styles.imageCommonPanelColumn, styles.imageCommonPanelSpan2)}>
+ <Button size="small" onClick={() => { onArrangeBtnClick(ArrangeTypeEnum.backward); }}>
+ <div className={clsx(styles.imageCommonPanelInline)}><MoveDownSingle /></div>
+ <div className={clsx(styles.imageCommonPanelInline)}>{localeService.t('image-panel.arrange.backward')}</div>
+ </Button>
+ </div>
+ </div>
+ <div className={styles.imageCommonPanelRow}>
+ <div className={clsx(styles.imageCommonPanelColumn, styles.imageCommonPanelSpan2)}>
+ <Button size="small" onClick={() => { onArrangeBtnClick(ArrangeTypeEnum.front); }}>
+ <div className={clsx(styles.imageCommonPanelInline)}><TopmostSingle /></div>
+ <div className={clsx(styles.imageCommonPanelInline)}>{localeService.t('image-panel.arrange.front')}</div>
+ </Button>
+ </div>
+ <div className={clsx(styles.imageCommonPanelColumn, styles.imageCommonPanelSpan2)}>
+ <Button size="small" onClick={() => { onArrangeBtnClick(ArrangeTypeEnum.back); }}>
+ <div className={clsx(styles.imageCommonPanelInline)}><BottomSingle /></div>
+ <div className={clsx(styles.imageCommonPanelInline)}>{localeService.t('image-panel.arrange.back')}</div>
+ </Button>
+ </div>
+ </div>
+ </div>
+
+ );
+};
diff --git a/packages/drawing-ui/src/views/panel/DrawingCommonPanel.tsx b/packages/drawing-ui/src/views/panel/DrawingCommonPanel.tsx
new file mode 100644
index 0000000000..d8cb6a1ab5
--- /dev/null
+++ b/packages/drawing-ui/src/views/panel/DrawingCommonPanel.tsx
@@ -0,0 +1,148 @@
+/**
+ * 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 { IDrawingParam } from '@univerjs/core';
+import { IDrawingManagerService, LocaleService } from '@univerjs/core';
+import { useDependency } from '@wendellhu/redi/react-bindings';
+import React, { useEffect, useState } from 'react';
+import { IRenderManagerService } from '@univerjs/engine-render';
+import { getUpdateParams } from '../../utils/get-update-params';
+import { DrawingArrange } from './DrawingArrange';
+import { DrawingTransform } from './DrawingTransform';
+import { DrawingAlign } from './DrawingAlign';
+import { ImageCropper } from './ImageCropper';
+import { DrawingGroup } from './DrawingGroup';
+
+export interface IDrawingCommonPanelProps {
+ drawings: IDrawingParam[];
+ hasArrange?: boolean;
+ hasTransform?: boolean;
+ hasAlign?: boolean;
+ hasCropper?: boolean;
+ hasGroup?: boolean;
+}
+
+export const DrawingCommonPanel = (props: IDrawingCommonPanelProps) => {
+ const drawingManagerService = useDependency(IDrawingManagerService);
+ const renderManagerService = useDependency(IRenderManagerService);
+ const localeService = useDependency(LocaleService);
+
+ const { drawings, hasArrange = true, hasTransform = true, hasAlign = true, hasCropper = true, hasGroup = true } = props;
+
+ const drawingParam = drawings[0];
+
+ if (drawingParam == null) {
+ return;
+ }
+
+ const { unitId } = drawingParam;
+
+ const renderObject = renderManagerService.getRenderById(unitId);
+ const scene = renderObject?.scene;
+ if (scene == null) {
+ return;
+ }
+ const transformer = scene.getTransformerByCreate();
+
+ const [arrangeShow, setArrangeShow] = useState(true);
+ const [transformShow, setTransformShow] = useState(true);
+ const [alignShow, setAlignShow] = useState(false);
+ const [cropperShow, setCropperShow] = useState(true);
+ const [nullShow, setNullShow] = useState(false);
+ // const [groupShow, setGroupShow] = useState(false);
+
+ useEffect(() => {
+ const onClearControlObserver = transformer.onClearControlObservable.add((changeSelf) => {
+ if (changeSelf === true) {
+ setArrangeShow(false);
+ setTransformShow(false);
+ setAlignShow(false);
+ setCropperShow(false);
+ setNullShow(true);
+ }
+ });
+
+ const onChangeStartObserver = transformer.onChangeStartObservable.add((state) => {
+ const { objects } = state;
+ const params = getUpdateParams(objects, drawingManagerService);
+
+ if (params.length === 0) {
+ setArrangeShow(false);
+ setTransformShow(false);
+ setAlignShow(false);
+ setCropperShow(false);
+ setNullShow(true);
+ } else if (params.length === 1) {
+ setArrangeShow(true);
+ setTransformShow(true);
+ setAlignShow(false);
+ setCropperShow(true);
+ setNullShow(false);
+ } else {
+ setArrangeShow(true);
+ setTransformShow(false);
+ setAlignShow(true);
+ setCropperShow(false);
+ setNullShow(false);
+ }
+ });
+
+ const onFocusObserver = drawingManagerService.focus$.subscribe((drawings) => {
+ if (drawings.length === 0) {
+ setArrangeShow(false);
+ setTransformShow(false);
+ setAlignShow(false);
+ setCropperShow(false);
+ setNullShow(true);
+ } else if (drawings.length === 1) {
+ setArrangeShow(true);
+ setTransformShow(true);
+ setAlignShow(false);
+ setCropperShow(true);
+ setNullShow(false);
+ } else {
+ setArrangeShow(true);
+ setTransformShow(false);
+ setAlignShow(true);
+ setCropperShow(false);
+ setNullShow(false);
+ }
+ });
+
+ return () => {
+ onChangeStartObserver?.dispose();
+ onClearControlObserver?.dispose();
+ onFocusObserver?.unsubscribe();
+ };
+ }, []);
+
+ return (
+ <>
+ <div style={{ display: nullShow === true ? 'block' : 'none', height: '100%' }}>
+ <div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '100%', top: '50%', marginTop: '-100px' }}>
+ <span>
+ {localeService.t('image-panel.null')}
+ </span>
+ </div>
+ </div>
+ <DrawingArrange arrangeShow={hasArrange === true ? arrangeShow : false} drawings={drawings} />
+ <DrawingTransform transformShow={hasTransform === true ? transformShow : false} drawings={drawings} />
+ <DrawingAlign alignShow={hasAlign === true ? alignShow : false} drawings={drawings} />
+ <ImageCropper cropperShow={hasCropper === true ? cropperShow : false} drawings={drawings} />
+ <DrawingGroup hasGroup={hasGroup} drawings={drawings} />
+ </>
+ );
+};
diff --git a/packages/drawing-ui/src/views/panel/DrawingGroup.tsx b/packages/drawing-ui/src/views/panel/DrawingGroup.tsx
new file mode 100644
index 0000000000..6107921c84
--- /dev/null
+++ b/packages/drawing-ui/src/views/panel/DrawingGroup.tsx
@@ -0,0 +1,213 @@
+/**
+ * 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 { IDrawingGroupUpdateParam, IDrawingParam } from '@univerjs/core';
+import { DrawingTypeEnum, ICommandService, IDrawingManagerService, LocaleService, Tools } from '@univerjs/core';
+import { useDependency } from '@wendellhu/redi/react-bindings';
+import React, { useEffect, useState } from 'react';
+import { GroupSingle, UngroupSingle } from '@univerjs/icons';
+import { Button } from '@univerjs/design';
+import clsx from 'clsx';
+import { getGroupState, IRenderManagerService, transformObjectOutOfGroup } from '@univerjs/engine-render';
+import { getUpdateParams } from '../../utils/get-update-params';
+import styles from './index.module.less';
+
+export interface IDrawingGroupProps {
+ drawings: IDrawingParam[];
+ hasGroup: boolean;
+}
+
+export const DrawingGroup = (props: IDrawingGroupProps) => {
+ const commandService = useDependency(ICommandService);
+ const localeService = useDependency(LocaleService);
+ const renderManagerService = useDependency(IRenderManagerService);
+ const drawingManagerService = useDependency(IDrawingManagerService);
+
+ const { hasGroup, drawings } = props;
+
+ const [groupShow, setGroupShow] = useState(false);
+
+ const [groupBtnShow, setGroupBtnShow] = useState(true);
+ const [ungroupBtnShow, setUngroupBtnShow] = useState(true);
+
+ const gridDisplay = (isShow: boolean) => {
+ return isShow ? 'block' : 'none';
+ };
+
+ const onGroupBtnClick = () => {
+ const focusDrawings = drawingManagerService.getFocusDrawings();
+ const { unitId, subUnitId } = focusDrawings[0];
+ const groupId = Tools.generateRandomId(10);
+ const groupTransform = getGroupState(0, 0, focusDrawings.map((o) => o.transform || {}));
+ const groupParam = {
+ unitId,
+ subUnitId,
+ drawingId: groupId,
+ drawingType: DrawingTypeEnum.DRAWING_GROUP,
+ transform: groupTransform,
+ } as IDrawingParam;
+
+ const children = focusDrawings.map((drawing) => {
+ const transform = drawing.transform || { left: 0, top: 0 };
+ const { unitId, subUnitId, drawingId } = drawing;
+ return {
+ unitId, subUnitId, drawingId,
+ transform: {
+ ...transform,
+ left: transform.left! - groupTransform.left,
+ top: transform.top! - groupTransform.top,
+ },
+ groupId,
+ };
+ }) as IDrawingParam[];
+
+ drawingManagerService.featurePluginGroupUpdateNotification([{
+ parent: groupParam,
+ children,
+ }]);
+ };
+
+ const ungroup = (param: IDrawingParam) => {
+ if (param.drawingType !== DrawingTypeEnum.DRAWING_GROUP) {
+ return;
+ }
+
+ const { unitId, subUnitId, drawingId, transform: groupTransform = { width: 0, height: 0 } } = param;
+
+ if (groupTransform == null) {
+ return;
+ }
+
+ const objects = drawingManagerService.getDrawingsByGroup({ unitId, subUnitId, drawingId });
+
+ if (objects.length === 0) {
+ return;
+ }
+
+ const children = objects.map((object) => {
+ const { transform } = object;
+ const { unitId, subUnitId, drawingId } = object;
+ const newTransform = transformObjectOutOfGroup(transform || {}, groupTransform, groupTransform.width || 0, groupTransform.height || 0);
+ return {
+ unitId, subUnitId, drawingId,
+ transform: {
+ ...transform,
+ ...newTransform,
+ },
+ groupId: undefined,
+ };
+ });
+
+ return {
+ parent: param,
+ children,
+ } as IDrawingGroupUpdateParam;
+ };
+
+ const onUngroupBtnClick = () => {
+ const focusDrawings = drawingManagerService.getFocusDrawings();
+ const params = focusDrawings.map((drawing) =>
+ ungroup(drawing)
+ ).filter((o) => o != null) as IDrawingGroupUpdateParam[];
+
+ if (params.length === 0) {
+ return;
+ }
+
+ drawingManagerService.featurePluginUngroupUpdateNotification(params);
+ };
+
+ useEffect(() => {
+ const drawingParam = drawings[0];
+
+ if (drawingParam == null) {
+ return;
+ }
+
+ const { unitId } = drawingParam;
+
+ const renderObject = renderManagerService.getRenderById(unitId);
+ const scene = renderObject?.scene;
+ if (scene == null) {
+ return;
+ }
+ const transformer = scene.getTransformerByCreate();
+
+ const onClearControlObserver = transformer.onClearControlObservable.add((changeSelf) => {
+ if (changeSelf === true) {
+ setGroupShow(false);
+ }
+ });
+
+ const onChangeStartObserver = transformer.onChangeStartObservable.add((state) => {
+ const { objects } = state;
+ const params = getUpdateParams(objects, drawingManagerService);
+ const groupParams = params.filter((o) => o?.drawingType === DrawingTypeEnum.DRAWING_GROUP) as IDrawingParam[];
+
+ let groupBtnShow = false;
+ let ungroupBtnShow = false;
+
+ if (params.length > 1) {
+ groupBtnShow = true;
+ }
+
+ if (groupParams.length > 0) {
+ ungroupBtnShow = true;
+ }
+
+ const groupShow = groupBtnShow || ungroupBtnShow;
+
+ setGroupShow(groupShow);
+ setGroupBtnShow(groupBtnShow);
+ setUngroupBtnShow(ungroupBtnShow);
+ });
+
+ return () => {
+ onChangeStartObserver?.dispose();
+ onClearControlObserver?.dispose();
+ };
+ }, []);
+
+ return (
+ <div className={clsx(styles.imageCommonPanelGrid, styles.imageCommonPanelBorder)} style={{ display: gridDisplay(hasGroup === true ? groupShow : false) }}>
+ <div className={styles.imageCommonPanelRow}>
+ <div className={clsx(styles.imageCommonPanelColumn, styles.imageCommonPanelTitle)}>
+ <div>{localeService.t('image-panel.group.title')}</div>
+ </div>
+ </div>
+ <div className={styles.imageCommonPanelRow}>
+ <div className={clsx(styles.imageCommonPanelColumn, styles.imageCommonPanelSpan2, styles.imageCommonPanelColumnCenter)}>
+ <Button size="small" onClick={() => { onGroupBtnClick(); }} style={{ display: gridDisplay(groupBtnShow) }}>
+ <div className={clsx(styles.imageCommonPanelInline)}><GroupSingle /></div>
+ <div className={clsx(styles.imageCommonPanelInline)}>{localeService.t('image-panel.group.group')}</div>
+ </Button>
+ </div>
+ {/* <div className={clsx(styles.imageCommonPanelColumn, styles.imageCommonPanelSpan3)}>
+ <Button size="small" onClick={() => { onGroupBtnClick(GroupType.regroup); }} style={{ display: gridDisplay(groupBtnShow) }}>
+ <div className={clsx(styles.imageCommonPanelInline)}><CreateCopySingle /></div>
+ <div className={clsx(styles.imageCommonPanelInline)}>{localeService.t('image-panel.group.reGroup')}</div>
+ </Button>
+ </div> */}
+ <div className={clsx(styles.imageCommonPanelColumn, styles.imageCommonPanelSpan2, styles.imageCommonPanelColumnCenter)}>
+ <Button size="small" onClick={() => { onUngroupBtnClick(); }} style={{ display: gridDisplay(ungroupBtnShow) }}>
+ <div className={clsx(styles.imageCommonPanelInline)}><UngroupSingle /></div>
+ <div className={clsx(styles.imageCommonPanelInline)}>{localeService.t('image-panel.group.unGroup')}</div>
+ </Button>
+ </div>
+ </div>
+ </div>
+ );
+};
diff --git a/packages/drawing-ui/src/views/panel/DrawingTransform.tsx b/packages/drawing-ui/src/views/panel/DrawingTransform.tsx
new file mode 100644
index 0000000000..d4c1cc1005
--- /dev/null
+++ b/packages/drawing-ui/src/views/panel/DrawingTransform.tsx
@@ -0,0 +1,466 @@
+/**
+ * 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 { IDrawingParam, Nullable } from '@univerjs/core';
+import { debounce, ICommandService, IDrawingManagerService, LocaleService } from '@univerjs/core';
+import { useDependency } from '@wendellhu/redi/react-bindings';
+import React, { useEffect, useState } from 'react';
+import { Checkbox, InputNumber } from '@univerjs/design';
+import clsx from 'clsx';
+import type { IChangeObserverConfig, Scene } from '@univerjs/engine-render';
+import { IRenderManagerService } from '@univerjs/engine-render';
+import { getUpdateParams } from '../../utils/get-update-params';
+import { MIN_DRAWING_HEIGHT_LIMIT, MIN_DRAWING_WIDTH_LIMIT, RANGE_DRAWING_ROTATION_LIMIT } from '../../utils/config';
+import styles from './index.module.less';
+
+export interface IDrawingTransformProps {
+ transformShow: boolean;
+ drawings: IDrawingParam[];
+}
+
+const INPUT_DEBOUNCE_TIME = 300;
+
+export const DrawingTransform = (props: IDrawingTransformProps) => {
+ const commandService = useDependency(ICommandService);
+ const localeService = useDependency(LocaleService);
+ const drawingManagerService = useDependency(IDrawingManagerService);
+ const renderManagerService = useDependency(IRenderManagerService);
+
+ const { drawings, transformShow } = props;
+
+ const drawingParam = drawings[0];
+
+ if (drawingParam == null) {
+ return;
+ }
+
+ const transform = drawingParam.transform;
+ if (transform == null) {
+ return;
+ }
+
+ const { unitId, subUnitId, drawingId, drawingType } = drawingParam;
+
+ const renderObject = renderManagerService.getRenderById(unitId);
+ const scene = renderObject?.scene;
+ if (scene == null) {
+ return;
+ }
+
+ const topScene = scene.getEngine()?.activeScene as Nullable<Scene>;
+ if (topScene == null) {
+ return;
+ }
+
+ const transformer = scene.getTransformerByCreate();
+
+ const {
+ width: originWidth = 0,
+ height: originHeight = 0,
+ left: originX = 0,
+ top: originY = 0,
+ angle: originRotation = 0,
+ } = transform;
+
+ const [width, setWidth] = useState<number>(originWidth);
+ const [height, setHeight] = useState(originHeight);
+ const [xPosition, setXPosition] = useState(originX);
+ const [yPosition, setYPosition] = useState(originY);
+ const [rotation, setRotation] = useState(originRotation);
+ const [lockRatio, setLockRatio] = useState(transformer.keepRatio);
+
+ const checkMoveBoundary = (left: number, top: number, width: number, height: number) => {
+ const { width: topSceneWidth, height: topSceneHeight } = topScene;
+ const { ancestorLeft, ancestorTop } = scene;
+
+ let limitLeft = left;
+ let limitTop = top;
+ let limitWidth = width;
+ let limitHeight = height;
+
+ if (left + ancestorLeft < 0) {
+ limitLeft = -ancestorLeft;
+ }
+
+ if (top + ancestorTop < 0) {
+ limitTop = -ancestorTop;
+ }
+
+ if (limitLeft + width + ancestorLeft > topSceneWidth) {
+ limitWidth = topSceneWidth - limitLeft - ancestorLeft;
+ }
+
+ if (limitWidth < MIN_DRAWING_WIDTH_LIMIT) {
+ limitWidth = MIN_DRAWING_WIDTH_LIMIT;
+ }
+
+ if (limitTop + height + ancestorTop > topSceneHeight) {
+ limitHeight = topSceneHeight - limitTop - ancestorTop;
+ }
+
+ if (limitHeight < MIN_DRAWING_WIDTH_LIMIT) {
+ limitHeight = MIN_DRAWING_WIDTH_LIMIT;
+ }
+
+ if (left + limitWidth + ancestorLeft > topSceneWidth) {
+ limitLeft = topSceneWidth - width - ancestorLeft;
+ }
+
+ if (top + limitHeight + ancestorTop > topSceneHeight) {
+ limitTop = topSceneHeight - height - ancestorTop;
+ }
+
+ return {
+ limitLeft,
+ limitTop,
+ limitWidth,
+ limitHeight,
+ };
+ };
+
+ const changeObs = (state: IChangeObserverConfig) => {
+ const { objects } = state;
+ const params = getUpdateParams(objects, drawingManagerService);
+
+ if (params.length !== 1) {
+ return;
+ }
+
+ const drawingParam = params[0];
+
+ if (drawingParam == null) {
+ return;
+ }
+
+ const transform = drawingParam.transform;
+
+ if (transform == null) {
+ return;
+ }
+
+ const {
+ width: originWidth,
+ height: originHeight,
+ left: originX,
+ top: originY,
+ angle: originRotation,
+ } = transform;
+
+ if (originWidth != null) {
+ setWidth(originWidth);
+ }
+
+ if (originHeight != null) {
+ setHeight(originHeight);
+ }
+
+ if (originX != null) {
+ setXPosition(originX);
+ }
+
+ if (originY != null) {
+ setYPosition(originY);
+ }
+
+ if (originRotation != null) {
+ setRotation(originRotation);
+ }
+ };
+
+ useEffect(() => {
+ const onChangeStartObserver = transformer.onChangeStartObservable.add((state) => {
+ changeObs(state);
+ });
+
+ const onChangingObserver = transformer.onChangingObservable.add((state) => {
+ changeObs(state);
+ });
+
+ const onFocusObserver = drawingManagerService.focus$.subscribe((drawings) => {
+ if (drawings.length !== 1) {
+ return;
+ }
+
+ const drawingParam = drawingManagerService.getDrawingByParam(drawings[0]);
+
+ if (drawingParam == null) {
+ return;
+ }
+
+ const transform = drawingParam.transform;
+
+ if (transform == null) {
+ return;
+ }
+
+ const {
+ width: originWidth,
+ height: originHeight,
+ left: originX,
+ top: originY,
+ angle: originRotation,
+ } = transform;
+
+ if (originWidth != null) {
+ setWidth(originWidth);
+ }
+
+ if (originHeight != null) {
+ setHeight(originHeight);
+ }
+
+ if (originX != null) {
+ setXPosition(originX);
+ }
+
+ if (originY != null) {
+ setYPosition(originY);
+ }
+
+ if (originRotation != null) {
+ setRotation(originRotation);
+ }
+ });
+
+ return () => {
+ onChangingObserver?.dispose();
+ onChangeStartObserver?.dispose();
+ onFocusObserver?.unsubscribe();
+ };
+ }, []);
+
+ const handleWidthChange = debounce((val: number | null) => {
+ if (val == null) {
+ return;
+ }
+
+ val = Math.max(val, MIN_DRAWING_WIDTH_LIMIT);
+
+ const { limitWidth } = checkMoveBoundary(xPosition, yPosition, val, height);
+
+ val = limitWidth;
+
+ const updateParam: IDrawingParam = { unitId, subUnitId, drawingId, drawingType, transform: { width: val } };
+
+ if (lockRatio) {
+ let heightFix = (val / width) * height;
+ heightFix = Math.max(heightFix, MIN_DRAWING_HEIGHT_LIMIT);
+ setHeight(heightFix);
+ updateParam.transform!.height = heightFix;
+ }
+
+ setWidth(val);
+
+ drawingManagerService.featurePluginUpdateNotification([updateParam]);
+
+ transformer.refreshControls().changeNotification();
+ }, INPUT_DEBOUNCE_TIME);
+
+ const handleHeightChange = debounce((val: number | null) => {
+ if (val == null) {
+ return;
+ }
+
+ val = Math.max(val, MIN_DRAWING_WIDTH_LIMIT);
+
+ const { limitHeight } = checkMoveBoundary(xPosition, yPosition, width, val);
+
+ val = limitHeight;
+
+ const updateParam: IDrawingParam = { unitId, subUnitId, drawingId, drawingType, transform: { height: val } };
+
+ if (lockRatio) {
+ let widthFix = (val / height) * width;
+ widthFix = Math.max(widthFix, MIN_DRAWING_WIDTH_LIMIT);
+ setWidth(widthFix);
+ updateParam.transform!.width = widthFix;
+ }
+
+ setHeight(val);
+
+ drawingManagerService.featurePluginUpdateNotification([updateParam]);
+
+ transformer.refreshControls().changeNotification();
+ }, INPUT_DEBOUNCE_TIME);
+
+ const handleXChange = debounce((val: number | null) => {
+ if (val == null) {
+ return;
+ }
+
+ const { limitLeft } = checkMoveBoundary(val, yPosition, width, height);
+
+ val = limitLeft;
+
+ const updateParam: IDrawingParam = { unitId, subUnitId, drawingId, drawingType, transform: { left: val } };
+
+ setXPosition(val);
+
+ drawingManagerService.featurePluginUpdateNotification([updateParam]);
+
+ transformer.refreshControls().changeNotification();
+ }, INPUT_DEBOUNCE_TIME);
+
+ const handleYChange = debounce((val: number | null) => {
+ if (val == null) {
+ return;
+ }
+
+ const { limitTop } = checkMoveBoundary(xPosition, val, width, height);
+
+ val = limitTop;
+
+ const updateParam: IDrawingParam = { unitId, subUnitId, drawingId, drawingType, transform: { top: val } };
+
+ setYPosition(val);
+
+ drawingManagerService.featurePluginUpdateNotification([updateParam]);
+
+ transformer.refreshControls().changeNotification();
+ }, INPUT_DEBOUNCE_TIME);
+
+ const handleRotationChange = (val: number | null) => {
+ if (val == null) {
+ return;
+ }
+
+ const [min, max] = RANGE_DRAWING_ROTATION_LIMIT;
+
+ if (val < min) {
+ val = min;
+ }
+
+ if (val > max) {
+ val = max;
+ }
+
+ const updateParam: IDrawingParam = { unitId, subUnitId, drawingId, drawingType, transform: { angle: val } };
+
+ setRotation(val);
+
+ drawingManagerService.featurePluginUpdateNotification([updateParam]);
+
+ transformer.refreshControls().changeNotification();
+ };
+
+ const handleLockRatioChange = (val: string | number | boolean) => {
+ setLockRatio(val as boolean);
+ transformer.keepRatio = val as boolean;
+ };
+
+ const gridDisplay = (isShow: boolean) => {
+ return isShow ? 'block' : 'none';
+ };
+
+ return (
+ <div className={clsx(styles.imageCommonPanelGrid, styles.imageCommonPanelBorder)} style={{ display: gridDisplay(transformShow) }}>
+ <div className={styles.imageCommonPanelRow}>
+ <div className={clsx(styles.imageCommonPanelColumn, styles.imageCommonPanelTitle)}>
+ <div>{localeService.t('image-panel.transform.title')}</div>
+ </div>
+ </div>
+ <div className={styles.imageCommonPanelRow}>
+ <div className={clsx(styles.imageCommonPanelColumn, styles.imageCommonPanelSpan3)}>
+ <label>
+ <div className={styles.imageCommonPanelRow}>
+ <div className={styles.imageCommonPanelColumn}>
+ {localeService.t('image-panel.transform.width')}
+ </div>
+ </div>
+ <div className={styles.imageCommonPanelRow}>
+ <div className={styles.imageCommonPanelColumn}>
+ <InputNumber precision={1} value={width} onChange={(val) => { handleWidthChange(val); }} className={styles.imageCommonPanelInput} />
+ </div>
+ </div>
+ </label>
+ </div>
+ <div className={clsx(styles.imageCommonPanelColumn, styles.imageCommonPanelSpan3)}>
+ <label>
+ <div className={styles.imageCommonPanelRow}>
+ <div className={styles.imageCommonPanelColumn}>
+ {localeService.t('image-panel.transform.height')}
+ </div>
+ </div>
+ <div className={styles.imageCommonPanelRow}>
+ <div className={styles.imageCommonPanelColumn}>
+ <InputNumber precision={1} value={height} onChange={(val) => { handleHeightChange(val); }} className={styles.imageCommonPanelInput} />
+ </div>
+ </div>
+ </label>
+ </div>
+ <div className={clsx(styles.imageCommonPanelColumn, styles.imageCommonPanelSpan3)}>
+ <label>
+ <div className={styles.imageCommonPanelRow}>
+ <div className={styles.imageCommonPanelColumn}>
+ {localeService.t('image-panel.transform.lock')}
+ </div>
+ </div>
+ <div className={clsx(styles.imageCommonPanelRow, styles.imageCommonPanelRowVertical)}>
+ <div className={styles.imageCommonPanelColumn}>
+ <Checkbox checked={lockRatio} onChange={handleLockRatioChange}></Checkbox>
+ </div>
+ </div>
+ </label>
+ </div>
+ </div>
+ <div className={styles.imageCommonPanelRow}>
+ <div className={clsx(styles.imageCommonPanelColumn, styles.imageCommonPanelSpan3)}>
+ <label>
+ <div className={styles.imageCommonPanelRow}>
+ <div className={styles.imageCommonPanelColumn}>
+ {localeService.t('image-panel.transform.x')}
+ </div>
+ </div>
+ <div className={styles.imageCommonPanelRow}>
+ <div className={styles.imageCommonPanelColumn}>
+ <InputNumber precision={1} value={xPosition} onChange={(val) => { handleXChange(val); }} className={styles.imageCommonPanelInput} />
+ </div>
+ </div>
+ </label>
+ </div>
+ <div className={clsx(styles.imageCommonPanelColumn, styles.imageCommonPanelSpan3)}>
+ <label>
+ <div className={styles.imageCommonPanelRow}>
+ <div className={styles.imageCommonPanelColumn}>
+ {localeService.t('image-panel.transform.y')}
+ </div>
+ </div>
+ <div className={styles.imageCommonPanelRow}>
+ <div className={styles.imageCommonPanelColumn}>
+ <InputNumber precision={1} value={yPosition} onChange={(val) => { handleYChange(val); }} className={styles.imageCommonPanelInput} />
+ </div>
+ </div>
+ </label>
+ </div>
+ <div className={clsx(styles.imageCommonPanelColumn, styles.imageCommonPanelSpan3)}>
+ <label>
+ <div className={styles.imageCommonPanelRow}>
+ <div className={styles.imageCommonPanelColumn}>
+ {localeService.t('image-panel.transform.rotate')}
+ </div>
+ </div>
+ <div className={styles.imageCommonPanelRow}>
+ <div className={styles.imageCommonPanelColumn}>
+ <InputNumber precision={1} value={rotation} onChange={handleRotationChange} className={styles.imageCommonPanelInput} />
+ </div>
+ </div>
+ </label>
+ </div>
+ </div>
+ </div>
+
+ );
+};
diff --git a/packages/drawing-ui/src/views/panel/ImageCropper.tsx b/packages/drawing-ui/src/views/panel/ImageCropper.tsx
new file mode 100644
index 0000000000..1c7e239c92
--- /dev/null
+++ b/packages/drawing-ui/src/views/panel/ImageCropper.tsx
@@ -0,0 +1,137 @@
+/**
+ * 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 { IDrawingParam } from '@univerjs/core';
+import { ICommandService, LocaleService } from '@univerjs/core';
+import { useDependency } from '@wendellhu/redi/react-bindings';
+import React, { useEffect, useRef, useState } from 'react';
+import { CreateCopySingle } from '@univerjs/icons';
+import { Button, Select } from '@univerjs/design';
+import clsx from 'clsx';
+import { AutoImageCropOperation, CloseImageCropOperation, CropType } from '../../commands/operations/image-crop.operation';
+import styles from './index.module.less';
+
+export interface IImageCropperProps {
+ drawings: IDrawingParam[];
+ cropperShow: boolean;
+}
+
+export const ImageCropper = (props: IImageCropperProps) => {
+ const commandService = useDependency(ICommandService);
+ const localeService = useDependency(LocaleService);
+
+ const { drawings, cropperShow } = props;
+
+ const drawingParam = drawings[0];
+
+ if (drawingParam == null) {
+ return;
+ }
+
+ const [cropValue, setCropValue] = useState<string>(CropType.FREE as string);
+
+ const cropStateRef = useRef(false);
+
+ const cropOptions = [
+ {
+ label: localeService.t('image-panel.crop.mode'),
+ value: CropType.FREE,
+ }, {
+ label: '1:1',
+ value: CropType.R1_1,
+ }, {
+ label: '16:9',
+ value: CropType.R16_9,
+ }, {
+ label: '9:16',
+ value: CropType.R9_16,
+ }, {
+ label: '5:4',
+ value: CropType.R5_4,
+ }, {
+ label: '4:5',
+ value: CropType.R4_5,
+ }, {
+ label: '4:3',
+ value: CropType.R4_3,
+ }, {
+ label: '3:4',
+ value: CropType.R3_4,
+ }, {
+ label: '3:2',
+ value: CropType.R3_2,
+ }, {
+ label: '2:3',
+ value: CropType.R2_3,
+ },
+ ];
+
+ useEffect(() => {
+ const onChangeStartObserver = commandService.onCommandExecuted((command) => {
+ if (command.id === CloseImageCropOperation.id) {
+ const params = command.params as { isAuto?: boolean };
+ if (!params?.isAuto) {
+ cropStateRef.current = false;
+ }
+ }
+ });
+
+ return () => {
+ onChangeStartObserver?.dispose();
+ };
+ }, []);
+
+ function handleCropChange(value: string | number | boolean) {
+ setCropValue((value as string));
+ if (cropStateRef.current) {
+ commandService.executeCommand(AutoImageCropOperation.id, {
+ cropType: value as CropType,
+ });
+ }
+ }
+
+ const gridDisplay = (isShow: boolean) => {
+ return isShow ? 'block' : 'none';
+ };
+
+ const onCropperBtnClick = (val: CropType) => {
+ commandService.executeCommand(AutoImageCropOperation.id, {
+ cropType: val,
+ });
+ cropStateRef.current = true;
+ };
+
+ return (
+ <div className={clsx(styles.imageCommonPanelGrid, styles.imageCommonPanelBorder)} style={{ display: gridDisplay(cropperShow) }}>
+ <div className={styles.imageCommonPanelRow}>
+ <div className={clsx(styles.imageCommonPanelColumn, styles.imageCommonPanelTitle)}>
+ <div>{localeService.t('image-panel.crop.title')}</div>
+ </div>
+ </div>
+ <div className={clsx(styles.imageCommonPanelRow, styles.imageCommonPanelRowVertical)}>
+ <div className={clsx(styles.imageCommonPanelColumn, styles.imageCommonPanelSpan2)}>
+ <Button size="small" onClick={() => { onCropperBtnClick(cropValue as CropType); }}>
+ <div className={clsx(styles.imageCommonPanelInline)}><CreateCopySingle /></div>
+ <div className={clsx(styles.imageCommonPanelInline)}>{localeService.t('image-panel.crop.start')}</div>
+ </Button>
+ </div>
+ <div className={clsx(styles.imageCommonPanelColumn, styles.imageCommonPanelSpan2)}>
+ <Select value={cropValue} options={cropOptions} onChange={handleCropChange} />
+ </div>
+ </div>
+ </div>
+ );
+};
diff --git a/packages/drawing-ui/src/views/panel/index.module.less b/packages/drawing-ui/src/views/panel/index.module.less
new file mode 100644
index 0000000000..d8a19f5f57
--- /dev/null
+++ b/packages/drawing-ui/src/views/panel/index.module.less
@@ -0,0 +1,62 @@
+.image-common-panel {
+ position: absolute;
+ height: 100%;
+ width: 90%;
+ text-align: center;
+ font-size: var(--font-size-sm);
+ &-grid {
+ position: relative;
+ width: 100%;
+ }
+
+ &-border {
+ border-top: 1px solid rgb(var(--border-color));
+ margin-top: 20px;
+ }
+
+ &-title {
+ color: rgb(var(--text-color-secondary));
+ text-align: left;
+ }
+
+ &-row {
+ position: relative;
+ display: flex;
+ justify-content: flex-start;
+ align-items: flex-start;
+ height: 100%;
+ margin-top: 10px;
+
+ &-vertical {
+ justify-content: center;
+ align-items: center;
+ height: 36px;
+ }
+ }
+
+ &-column {
+ width: 100%;
+
+ &-center {
+ display: flex;
+ justify-content: center;
+ align-items: center;
+ }
+ }
+
+ &-inline {
+ display: inline-block;
+ }
+
+ &-span2 {
+ width: 50%;
+ }
+
+ &-span3 {
+ width: 33.33333333%;
+ }
+
+ &-input {
+ width: 90%;
+ }
+}
diff --git a/packages/drawing-ui/src/vite-env.d.ts b/packages/drawing-ui/src/vite-env.d.ts
new file mode 100644
index 0000000000..11f02fe2a0
--- /dev/null
+++ b/packages/drawing-ui/src/vite-env.d.ts
@@ -0,0 +1 @@
+/// <reference types="vite/client" />
diff --git a/packages/drawing-ui/tsconfig.json b/packages/drawing-ui/tsconfig.json
new file mode 100644
index 0000000000..d676ad2a20
--- /dev/null
+++ b/packages/drawing-ui/tsconfig.json
@@ -0,0 +1,9 @@
+{
+ "extends": "@univerjs/shared/tsconfigs/base",
+ "compilerOptions": {
+ "rootDir": "src",
+ "outDir": "lib/types"
+ },
+ "references": [{ "path": "./tsconfig.node.json" }],
+ "include": ["src"]
+}
diff --git a/packages/drawing-ui/tsconfig.node.json b/packages/drawing-ui/tsconfig.node.json
new file mode 100644
index 0000000000..e53dac8868
--- /dev/null
+++ b/packages/drawing-ui/tsconfig.node.json
@@ -0,0 +1,4 @@
+{
+ "extends": "@univerjs/shared/tsconfigs/node",
+ "include": ["vite.config.ts"]
+}
diff --git a/packages/drawing-ui/vite.config.ts b/packages/drawing-ui/vite.config.ts
new file mode 100644
index 0000000000..925b530b4d
--- /dev/null
+++ b/packages/drawing-ui/vite.config.ts
@@ -0,0 +1,12 @@
+import createViteConfig from '@univerjs/shared/vite';
+import pkg from './package.json';
+
+export default ({ mode }) => createViteConfig({}, {
+ mode,
+ pkg,
+ features: {
+ react: false,
+ css: true,
+ dom: true,
+ },
+});
diff --git a/packages/image/README-zh.md b/packages/drawing/README-zh.md
similarity index 100%
rename from packages/image/README-zh.md
rename to packages/drawing/README-zh.md
diff --git a/packages/drawing/README.md b/packages/drawing/README.md
new file mode 100644
index 0000000000..0898c4cf08
--- /dev/null
+++ b/packages/drawing/README.md
@@ -0,0 +1,16 @@
+# @univerjs/drawing
+
+[![npm version](https://img.shields.io/npm/v/@univerjs/drawing)](https://npmjs.org/packages/@univerjs/drawing)
+[![license](https://img.shields.io/npm/l/@univerjs/drawing)](https://img.shields.io/npm/l/@univerjs/drawing)
+
+## Introduction
+
+> TODO: Introduction
+
+## Usage
+
+### Installation
+
+```shell
+npm i @univerjs/drawing
+```
diff --git a/packages/image/package.json b/packages/drawing/package.json
similarity index 90%
rename from packages/image/package.json
rename to packages/drawing/package.json
index ba646fb0a3..62e211fae1 100644
--- a/packages/image/package.json
+++ b/packages/drawing/package.json
@@ -1,6 +1,6 @@
{
- "name": "@univerjs/image",
- "version": "0.1.12",
+ "name": "@univerjs/drawing",
+ "version": "0.1.9",
"private": true,
"description": "",
"author": "DreamNum <[email protected]>",
@@ -67,17 +67,16 @@
"rxjs": ">=7.0.0"
},
"dependencies": {
- "@univerjs/icons": "^0.1.52"
+ "@univerjs/icons": "^0.1.52",
+ "ot-json1": "^1.0.2"
},
"devDependencies": {
"@univerjs/core": "workspace:*",
- "@univerjs/design": "workspace:*",
- "@univerjs/engine-render": "workspace:*",
"@univerjs/shared": "workspace:*",
- "@univerjs/sheets": "workspace:*",
"@univerjs/ui": "workspace:*",
"@wendellhu/redi": "0.15.2",
"less": "^4.2.0",
+ "ot-json1": "^1.0.2",
"react": "18.2.0",
"rxjs": "^7.8.1",
"typescript": "^5.4.5",
diff --git a/packages/drawing/src/basics/config.ts b/packages/drawing/src/basics/config.ts
new file mode 100644
index 0000000000..393e3cf6b8
--- /dev/null
+++ b/packages/drawing/src/basics/config.ts
@@ -0,0 +1,25 @@
+/**
+ * Copyright 2023-present DreamNum Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+export const DRAWING_IMAGE_WIDTH_LIMIT = 500;
+
+export const DRAWING_IMAGE_HEIGHT_LIMIT = 500;
+
+export const DRAWING_IMAGE_COUNT_LIMIT = 10;
+
+export const DRAWING_IMAGE_ALLOW_SIZE = 5 * 1024 * 1024;
+
+export const DRAWING_IMAGE_ALLOW_IMAGE_LIST = ['image/png', 'image/jpeg', 'image/jpg', 'image/gif', 'image/bmp'];
diff --git a/packages/drawing/src/index.ts b/packages/drawing/src/index.ts
new file mode 100644
index 0000000000..2a897298a4
--- /dev/null
+++ b/packages/drawing/src/index.ts
@@ -0,0 +1,23 @@
+/**
+ * Copyright 2023-present DreamNum Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+export { DRAWING_IMAGE_WIDTH_LIMIT, DRAWING_IMAGE_HEIGHT_LIMIT, DRAWING_IMAGE_COUNT_LIMIT, DRAWING_IMAGE_ALLOW_SIZE, DRAWING_IMAGE_ALLOW_IMAGE_LIST } from './basics/config';
+export { DrawingManagerService, UnitDrawingService, type IDrawingJson1Type, type IDrawingJsonUndo1 } from './services/drawing-manager.service';
+export { getDrawingShapeKeyByDrawingSearch } from './utils/get-image-shape-key';
+export { getImageSize } from './utils/get-image-size';
+export { UniverDrawingPlugin } from './plugin';
+export { type IImageData } from './models/image-model-interface';
+
diff --git a/packages/drawing/src/models/image-model-interface.ts b/packages/drawing/src/models/image-model-interface.ts
new file mode 100644
index 0000000000..efc6d05cde
--- /dev/null
+++ b/packages/drawing/src/models/image-model-interface.ts
@@ -0,0 +1,31 @@
+/**
+ * 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 { IDrawingParam, ImageSourceType, ISrcRect, Nullable, PresetGeometryType } from '@univerjs/core';
+
+export interface IImageData extends IDrawingParam {
+ imageSourceType: ImageSourceType;
+ source: string;
+ /**
+ * 20.1.8.55 srcRect (Source Rectangle)
+ */
+ srcRect?: Nullable<ISrcRect>;
+ /**
+ * 20.1.9.18 prstGeom (Preset geometry)
+ */
+ prstGeom?: Nullable<PresetGeometryType>;
+}
+
diff --git a/packages/drawing/src/plugin.ts b/packages/drawing/src/plugin.ts
new file mode 100644
index 0000000000..dd54731588
--- /dev/null
+++ b/packages/drawing/src/plugin.ts
@@ -0,0 +1,58 @@
+/**
+ * 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 { DependencyOverride } from '@univerjs/core';
+import { IDrawingManagerService, IImageIoService, LocaleService, mergeOverrideWithDependencies, Plugin } from '@univerjs/core';
+import type { Dependency } from '@wendellhu/redi';
+import { Inject, Injector } from '@wendellhu/redi';
+
+import { ImageIoService } from './services/image-io.service';
+import { DrawingManagerService } from './services/drawing-manager.service';
+
+const PLUGIN_NAME = 'DRAWING_PLUGIN';
+
+export class UniverDrawingPlugin extends Plugin {
+ static override pluginName = PLUGIN_NAME;
+
+ constructor(
+ private _config: {
+ override?: DependencyOverride;
+ },
+ @Inject(Injector) protected _injector: Injector,
+ @Inject(LocaleService) private readonly _localeService: LocaleService
+ ) {
+ super();
+ }
+
+ override onStarting(_injector: Injector): void {
+ this._initDependencies(_injector);
+ }
+
+ private _initDependencies(injector: Injector): void {
+ const dependencies: Dependency[] = [
+ // services
+ [IImageIoService, { useClass: ImageIoService }],
+ [IDrawingManagerService, { useClass: DrawingManagerService }],
+ // controllers
+ // [ImageController],
+ ];
+
+ const dependency = mergeOverrideWithDependencies(dependencies, this._config?.override);
+ dependency.forEach((d) => {
+ this._injector.add(d);
+ });
+ }
+}
diff --git a/packages/drawing/src/services/drawing-manager.service.ts b/packages/drawing/src/services/drawing-manager.service.ts
new file mode 100644
index 0000000000..40171b483d
--- /dev/null
+++ b/packages/drawing/src/services/drawing-manager.service.ts
@@ -0,0 +1,747 @@
+/**
+ * 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 Observable, Subject } from 'rxjs';
+import type { IDrawingGroupUpdateParam, IDrawingMap, IDrawingOrderMapParam, IDrawingOrderUpdateParam, IDrawingParam, IDrawingSearch, IDrawingSubunitMap, IDrawingVisibleParam, IUnitDrawingService, Nullable } from '@univerjs/core';
+import { sortRules, sortRulesByDesc } from '@univerjs/core';
+import type { JSONOp, JSONOpList } from 'ot-json1';
+import * as json1 from 'ot-json1';
+
+export interface IDrawingJsonUndo1 {
+ undo: JSONOp;
+ redo: JSONOp;
+ unitId: string;
+ subUnitId: string;
+ objects: IDrawingSearch[] | IDrawingOrderMapParam | IDrawingGroupUpdateParam | IDrawingGroupUpdateParam[];
+}
+
+export interface IDrawingJson1Type {
+ op: JSONOp | JSONOpList;
+ unitId: string;
+ subUnitId: string;
+ objects: IDrawingSearch[] | IDrawingOrderMapParam | IDrawingGroupUpdateParam | IDrawingGroupUpdateParam[];
+}
+
+enum DrawingMapItemType {
+ data = 'data',
+ order = 'order',
+}
+
+/**
+ * unitId -> subUnitId -> drawingId -> drawingParam
+ */
+export class UnitDrawingService<T extends IDrawingParam> implements IUnitDrawingService<T> {
+ drawingManagerData: IDrawingMap<T> = {};
+
+ private _oldDrawingManagerData: IDrawingMap<T> = {};
+
+ private _focusDrawings: T[] = [];
+
+ private readonly _remove$ = new Subject<IDrawingSearch[]>();
+ readonly remove$ = this._remove$.asObservable();
+
+ private readonly _add$ = new Subject<IDrawingSearch[]>();
+ readonly add$ = this._add$.asObservable();
+
+ private readonly _update$ = new Subject<IDrawingSearch[]>();
+ readonly update$ = this._update$.asObservable();
+
+ private _order$ = new Subject<IDrawingOrderMapParam>();
+ readonly order$ = this._order$.asObservable();
+
+ private _group$ = new Subject<IDrawingGroupUpdateParam[]>();
+ readonly group$ = this._group$.asObservable();
+
+ private _ungroup$ = new Subject<IDrawingGroupUpdateParam[]>();
+ readonly ungroup$ = this._ungroup$.asObservable();
+
+ private _refreshTransform$ = new Subject<T[]>();
+ readonly refreshTransform$ = this._refreshTransform$.asObservable();
+
+ private _visible$ = new Subject<IDrawingVisibleParam[]>();
+ readonly visible$ = this._visible$.asObservable();
+
+ // private readonly _externalUpdate$ = new Subject<T[]>();
+ // readonly externalUpdate$ = this._externalUpdate$.asObservable();
+
+ private _focus$ = new Subject<T[]>();
+ focus$: Observable<T[]> = this._focus$.asObservable();
+
+ private readonly _featurePluginUpdate$ = new Subject<T[]>();
+ readonly featurePluginUpdate$: Observable<T[]> = this._featurePluginUpdate$.asObservable();
+
+ private readonly _featurePluginAdd$ = new Subject<T[]>();
+ readonly featurePluginAdd$: Observable<T[]> = this._featurePluginAdd$.asObservable();
+
+ private readonly _featurePluginRemove$ = new Subject<IDrawingSearch[]>();
+ readonly featurePluginRemove$: Observable<IDrawingSearch[]> = this._featurePluginRemove$.asObservable();
+
+ private readonly _featurePluginOrderUpdate$ = new Subject<IDrawingOrderUpdateParam>();
+ readonly featurePluginOrderUpdate$: Observable<IDrawingOrderUpdateParam> = this._featurePluginOrderUpdate$.asObservable();
+
+ private readonly _featurePluginGroupUpdate$ = new Subject<IDrawingGroupUpdateParam[]>();
+ readonly featurePluginGroupUpdate$: Observable<IDrawingGroupUpdateParam[]> = this._featurePluginGroupUpdate$.asObservable();
+
+ private readonly _featurePluginUngroupUpdate$ = new Subject<IDrawingGroupUpdateParam[]>();
+ readonly featurePluginUngroupUpdate$: Observable<IDrawingGroupUpdateParam[]> = this._featurePluginUngroupUpdate$.asObservable();
+
+ dispose(): void {
+ this._remove$.complete();
+ this._add$.complete();
+ this._update$.complete();
+ this._order$.complete();
+ this._focus$.complete();
+ this._featurePluginUpdate$.complete();
+ this._featurePluginAdd$.complete();
+ this._featurePluginRemove$.complete();
+ this._featurePluginOrderUpdate$.complete();
+
+ this.drawingManagerData = {};
+ this._oldDrawingManagerData = {};
+ }
+
+ visibleNotification(visibleParams: IDrawingVisibleParam[]) {
+ this._visible$.next(visibleParams);
+ }
+
+ refreshTransform(updateParams: T[]) {
+ updateParams.forEach((updateParam) => {
+ const drawing = this.getDrawingByParam(updateParam);
+ if (drawing == null) {
+ return;
+ }
+ const param = this._getCurrentBySearch(updateParam);
+ if (param == null) {
+ return;
+ }
+
+ param.transform = updateParam.transform;
+ });
+
+ this.refreshTransformNotification(updateParams);
+ }
+
+ getDrawingDataForUnit(unitId: string) {
+ return this.drawingManagerData[unitId];
+ }
+
+ removeDrawingDataForUnit(unitId: string) {
+ const subUnits = this.drawingManagerData[unitId];
+
+ if (subUnits == null) {
+ return;
+ }
+
+ delete this.drawingManagerData[unitId];
+
+ const drawings: IDrawingSearch[] = [];
+
+ Object.keys(subUnits).forEach((subUnitId) => {
+ const subUnit = subUnits[subUnitId];
+ if (subUnit?.data == null) {
+ return;
+ }
+ Object.keys(subUnit.data).forEach((drawingId) => {
+ drawings.push({ unitId, subUnitId, drawingId });
+ });
+ });
+ if (drawings.length > 0) {
+ this.removeNotification(drawings);
+ }
+ }
+
+ registerDrawingData(unitId: string, data: IDrawingSubunitMap<T>) {
+ this.drawingManagerData[unitId] = data;
+ const drawings: T[] = [];
+ Object.keys(data).forEach((subUnitId) => {
+ this._establishDrawingMap(unitId, subUnitId);
+
+ const subUnitData = data[subUnitId];
+
+ Object.keys(subUnitData.data).forEach((drawingId) => {
+ const drawing = subUnitData.data[drawingId];
+ drawings.push(drawing);
+ });
+ });
+
+ if (drawings.length > 0) {
+ this.addNotification(drawings);
+ }
+ }
+
+ getDrawingData(unitId: string, subUnitId: string) {
+ return this._getDrawingData(unitId, subUnitId);
+ }
+
+ getBatchAddOp(insertParams: T[]): IDrawingJsonUndo1 {
+ const objects: IDrawingSearch[] = [];
+ const ops: JSONOp[] = [];
+ const invertOps: JSONOp[] = [];
+ insertParams.forEach((insertParam) => {
+ const { op, invertOp } = this._addByParam(insertParam);
+ objects.push({ unitId: insertParam.unitId, subUnitId: insertParam.subUnitId, drawingId: insertParam.drawingId });
+ ops.push(op);
+ invertOps.push(invertOp);
+ });
+
+ const op = ops.reduce(json1.type.compose, null);
+ const invertOp = invertOps.reduce(json1.type.compose, null);
+
+ // this._add$.next(objects);
+
+ const { unitId, subUnitId } = insertParams[0];
+
+ return { undo: invertOp, redo: op, unitId, subUnitId, objects };
+ }
+
+ getBatchRemoveOp(removeParams: IDrawingSearch[]): IDrawingJsonUndo1 {
+ const ops: JSONOp[] = [];
+ const invertOps: JSONOp[] = [];
+ removeParams.forEach((removeParam) => {
+ const { op, invertOp } = this._removeByParam(removeParam);
+ ops.push(op);
+ invertOps.push(invertOp);
+ });
+
+ const op = ops.reduce(json1.type.compose, null);
+ const invertOp = invertOps.reduce(json1.type.compose, null);
+
+ // this._remove$.next(objects);
+
+ const { unitId, subUnitId } = removeParams[0];
+
+ return { undo: invertOp, redo: op, unitId, subUnitId, objects: removeParams };
+ }
+
+ getBatchUpdateOp(updateParams: T[]): IDrawingJsonUndo1 {
+ const objects: IDrawingSearch[] = [];
+ const ops: JSONOp[] = [];
+ const invertOps: JSONOp[] = [];
+ updateParams.forEach((updateParam) => {
+ const { op, invertOp } = this._updateByParam(updateParam);
+ objects.push({ unitId: updateParam.unitId, subUnitId: updateParam.subUnitId, drawingId: updateParam.drawingId });
+ ops.push(op);
+ invertOps.push(invertOp);
+ });
+
+ const op = ops.reduce(json1.type.compose, null);
+ const invertOp = invertOps.reduce(json1.type.compose, null);
+
+ // this._update$.next(objects);
+
+ const { unitId, subUnitId } = updateParams[0];
+
+ return { undo: invertOp, redo: op, unitId, subUnitId, objects };
+ }
+
+ removeNotification(removeParams: IDrawingSearch[]) {
+ this._remove$.next(removeParams);
+ }
+
+ addNotification(insertParams: IDrawingSearch[]) {
+ this._add$.next(insertParams);
+ }
+
+ updateNotification(updateParams: IDrawingSearch[]) {
+ this._update$.next(updateParams);
+ }
+
+ orderNotification(orderParams: IDrawingOrderMapParam) {
+ this._order$.next(orderParams);
+ }
+
+ groupUpdateNotification(groupParams: IDrawingGroupUpdateParam[]): void {
+ this._group$.next(groupParams);
+ }
+
+ ungroupUpdateNotification(groupParams: IDrawingGroupUpdateParam[]): void {
+ this._ungroup$.next(groupParams);
+ }
+
+ refreshTransformNotification(refreshParams: T[]) {
+ this._refreshTransform$.next(refreshParams);
+ }
+
+ getGroupDrawingOp(groupParams: IDrawingGroupUpdateParam[]): IDrawingJsonUndo1 {
+ const ops: JSONOp[] = [];
+ const { unitId, subUnitId } = groupParams[0].parent;
+ groupParams.forEach((groupParam) => {
+ ops.push(this._getGroupDrawingOp(groupParam));
+ });
+
+ const op = ops.reduce(json1.type.compose, null);
+
+ const invertOp = json1.type.invertWithDoc(op, this.drawingManagerData as unknown as json1.Doc);
+
+ return { undo: invertOp, redo: op, unitId, subUnitId, objects: groupParams };
+ }
+
+ getUngroupDrawingOp(groupParams: IDrawingGroupUpdateParam[]): IDrawingJsonUndo1 {
+ const ops: JSONOp[] = [];
+ const { unitId, subUnitId } = groupParams[0].parent;
+ groupParams.forEach((groupParam) => {
+ ops.push(this._getUngroupDrawingOp(groupParam));
+ });
+
+ const op = ops.reduce(json1.type.compose, null);
+
+ const invertOp = json1.type.invertWithDoc(op, this.drawingManagerData as unknown as json1.Doc);
+
+ return { undo: invertOp, redo: op, unitId, subUnitId, objects: groupParams };
+ }
+
+ getDrawingsByGroup(groupParam: IDrawingSearch): IDrawingParam[] {
+ const { unitId, subUnitId, drawingId } = groupParam;
+ const group = this.getDrawingByParam({ unitId, subUnitId, drawingId });
+
+ if (group == null) {
+ return [];
+ }
+
+ const drawings = this._getDrawingData(unitId, subUnitId);
+
+ const children: IDrawingParam[] = [];
+ Object.keys(drawings).forEach((key) => {
+ const drawing = drawings[key];
+ if (drawing.groupId === drawingId) {
+ children.push(drawing);
+ }
+ });
+
+ return children;
+ }
+
+ private _getGroupDrawingOp(groupParam: IDrawingGroupUpdateParam): JSONOp {
+ const { parent, children } = groupParam;
+ const { unitId: groupUnitId, subUnitId: groupSubUnitId, drawingId: groupDrawingId } = parent;
+
+ const ops: JSONOp[] = [];
+
+ ops.push(
+ json1.insertOp([groupUnitId, groupSubUnitId, DrawingMapItemType.data, groupDrawingId], parent as unknown as json1.Doc)
+ );
+ let maxChildIndex = Number.NEGATIVE_INFINITY;
+ children.forEach((child) => {
+ const { unitId, subUnitId, drawingId } = child;
+ const index = this._hasDrawingOrder({ unitId, subUnitId, drawingId });
+ maxChildIndex = Math.max(maxChildIndex, index);
+ ops.push(
+ ...this._getUpdateParamCompareOp(child as T, this.getDrawingByParam({ unitId, subUnitId, drawingId }) as T)
+ );
+ });
+
+ if (maxChildIndex === Number.NEGATIVE_INFINITY) {
+ maxChildIndex = this._getDrawingOrder(groupUnitId, groupSubUnitId).length;
+ }
+
+ ops.push(
+ json1.insertOp([groupUnitId, groupSubUnitId, DrawingMapItemType.order, maxChildIndex], groupDrawingId)
+ );
+
+ return ops.reduce(json1.type.compose, null);
+ }
+
+ private _getUngroupDrawingOp(groupParam: IDrawingGroupUpdateParam): JSONOp {
+ const { parent, children } = groupParam;
+
+ const { unitId: groupUnitId, subUnitId: groupSubUnitId, drawingId: groupDrawingId } = parent;
+
+ const ops: JSONOp[] = [];
+ children.forEach((child) => {
+ const { unitId, subUnitId, drawingId } = child;
+ ops.push(
+ ...this._getUpdateParamCompareOp(child as T, this.getDrawingByParam({ unitId, subUnitId, drawingId }) as T)
+ );
+ });
+ ops.push(
+ json1.removeOp([groupUnitId, groupSubUnitId, DrawingMapItemType.data, groupDrawingId], true)
+ );
+ ops.push(
+ json1.removeOp([groupUnitId, groupSubUnitId, DrawingMapItemType.order, this._getDrawingOrder(groupUnitId, groupSubUnitId).indexOf(groupDrawingId)], true)
+ );
+
+ return ops.reduce(json1.type.compose, null);
+ }
+
+ applyJson1(unitId: string, subUnitId: string, jsonOp: JSONOp) {
+ this._establishDrawingMap(unitId, subUnitId);
+ // this._fillMissingFields(jsonOp);
+ this._oldDrawingManagerData = { ...this.drawingManagerData };
+ this.drawingManagerData = json1.type.apply(this.drawingManagerData as unknown as json1.Doc, jsonOp) as unknown as IDrawingMap<T>;
+ }
+
+ // private _fillMissingFields(jsonOp: JSONOp) {
+ // if (jsonOp == null) {
+ // return;
+ // }
+
+ // let object: { [key: string]: {} } = this.drawingManagerData;
+ // for (let i = 0; i < jsonOp.length; i++) {
+ // const op = jsonOp[i];
+ // if (Array.isArray(op)) {
+ // const opKey = op[0] as string;
+ // if (!(opKey in object)) {
+ // object[opKey] = null as unknown as never;
+ // }
+ // } else if (typeof op === 'string') {
+ // object = object[op];
+ // if (object == null) {
+ // break;
+ // }
+ // }
+ // }
+ // }
+
+ featurePluginUpdateNotification(updateParams: T[]) {
+ this._featurePluginUpdate$.next(updateParams);
+ }
+
+ featurePluginOrderUpdateNotification(drawingOrderUpdateParam: IDrawingOrderUpdateParam) {
+ this._featurePluginOrderUpdate$.next(drawingOrderUpdateParam);
+ }
+
+ featurePluginAddNotification(insertParams: T[]) {
+ this._featurePluginAdd$.next(insertParams);
+ }
+
+ featurePluginRemoveNotification(removeParams: IDrawingSearch[]) {
+ this._featurePluginRemove$.next(removeParams);
+ }
+
+ featurePluginGroupUpdateNotification(groupParams: IDrawingGroupUpdateParam[]) {
+ this._featurePluginGroupUpdate$.next(groupParams);
+ }
+
+ featurePluginUngroupUpdateNotification(groupParams: IDrawingGroupUpdateParam[]) {
+ this._featurePluginUngroupUpdate$.next(groupParams);
+ }
+
+ getDrawingByParam(param: Nullable<IDrawingSearch>): Nullable<T> {
+ return this._getCurrentBySearch(param);
+ }
+
+ getOldDrawingByParam(param: Nullable<IDrawingSearch>): Nullable<T> {
+ return this._getOldBySearch(param);
+ }
+
+ getDrawingOKey(oKey: string): Nullable<T> {
+ const [unitId, subUnitId, drawingId] = oKey.split('#-#');
+ return this._getCurrentBySearch({ unitId, subUnitId, drawingId });
+ }
+
+ focusDrawing(params: Nullable<IDrawingSearch[]>): void {
+ if (params == null) {
+ this._focusDrawings = [];
+ this._focus$.next([]);
+ return;
+ }
+
+ const drawingParams: T[] = [];
+ params.forEach((param) => {
+ const { unitId, subUnitId, drawingId } = param;
+ const item = this._getDrawingData(unitId, subUnitId)?.[drawingId];
+ if (item != null) {
+ drawingParams.push(item);
+ }
+ });
+
+ if (drawingParams.length > 0) {
+ this._focusDrawings = drawingParams;
+ this._focus$.next(drawingParams);
+ }
+ }
+
+ getFocusDrawings() {
+ const drawingParams: T[] = [];
+ this._focusDrawings.forEach((param) => {
+ const { unitId, subUnitId, drawingId } = param;
+ const item = this._getDrawingData(unitId, subUnitId)?.[drawingId];
+ if (item != null) {
+ drawingParams.push(item);
+ }
+ });
+ return drawingParams;
+ }
+
+ getDrawingOrder(unitId: string, subUnitId: string) {
+ return this._getDrawingOrder(unitId, subUnitId);
+ }
+
+ orderUpdateNotification(orderParams: IDrawingOrderMapParam) {
+ this._order$.next(orderParams);
+ }
+
+ getForwardDrawingsOp(orderParams: IDrawingOrderMapParam): IDrawingJsonUndo1 {
+ const { unitId, subUnitId, drawingIds } = orderParams;
+ const ops: JSONOp[] = [];
+ const orders = this.getDrawingOrder(unitId, subUnitId);
+ const newIds = [...drawingIds];
+ drawingIds.forEach((drawingId) => {
+ const index = this._hasDrawingOrder({ unitId, subUnitId, drawingId });
+ if (index === -1 || index === orders.length - 1) {
+ return;
+ }
+ const op = json1.moveOp([unitId, subUnitId, DrawingMapItemType.order, index], [unitId, subUnitId, DrawingMapItemType.order, index + 1]);
+ ops.push(op);
+ if (!newIds.includes(orders[index + 1])) {
+ newIds.push(orders[index + 1]);
+ }
+ // this._moveDrawingOrder(unitId, subUnitId, drawingId, index + 1);
+ });
+
+ const op = ops.reduce(json1.type.compose, null);
+ const invertOp = json1.type.invertWithDoc(op, this.drawingManagerData as unknown as json1.Doc);
+
+ // this._order$.next({ unitId, subUnitId, drawingIds: this.getDrawingOrder(unitId, subUnitId) });
+
+ return { undo: invertOp, redo: op, unitId, subUnitId, objects: { ...orderParams, drawingIds: newIds } };
+ }
+
+ getBackwardDrawingOp(orderParams: IDrawingOrderMapParam): IDrawingJsonUndo1 {
+ const { unitId, subUnitId, drawingIds } = orderParams;
+ const ops: JSONOp[] = [];
+ const orders = this.getDrawingOrder(unitId, subUnitId);
+ const newIds = [...drawingIds];
+ drawingIds.forEach((drawingId) => {
+ const index = this._hasDrawingOrder({ unitId, subUnitId, drawingId });
+ if (index === -1 || index === 0) {
+ return;
+ }
+ // this._moveDrawingOrder(unitId, subUnitId, drawingId, index - 1);
+ const op = json1.moveOp([unitId, subUnitId, DrawingMapItemType.order, index], [unitId, subUnitId, DrawingMapItemType.order, index - 1]);
+ ops.push(op);
+ if (!newIds.includes(orders[index - 1])) {
+ newIds.push(orders[index - 1]);
+ }
+ });
+
+ const op = ops.reduce(json1.type.compose, null);
+ const invertOp = json1.type.invertWithDoc(op, this.drawingManagerData as unknown as json1.Doc);
+
+ // this._order$.next({ unitId, subUnitId, drawingIds: this.getDrawingOrder(unitId, subUnitId) });
+
+ return { undo: invertOp, redo: op, unitId, subUnitId, objects: { ...orderParams, drawingIds: newIds } };
+ }
+
+ getFrontDrawingsOp(orderParams: IDrawingOrderMapParam): IDrawingJsonUndo1 {
+ const { unitId, subUnitId, drawingIds } = orderParams;
+ const orderDrawingIds = this._getOrderFromSearchParams(unitId, subUnitId, drawingIds);
+ const newIds = [...drawingIds];
+ const orders = this.getDrawingOrder(unitId, subUnitId);
+ const ops: JSONOp[] = [];
+ orderDrawingIds.forEach((orderDrawingId) => {
+ const { drawingId } = orderDrawingId;
+ const index = this._getDrawingCount(unitId, subUnitId) - 1;
+
+ const op = json1.moveOp([unitId, subUnitId, DrawingMapItemType.order, this._getDrawingOrder(unitId, subUnitId).indexOf(drawingId)], [unitId, subUnitId, DrawingMapItemType.order, index]);
+ ops.push(op);
+ if (!newIds.includes(orders[index])) {
+ newIds.push(orders[index]);
+ }
+ // this._moveDrawingOrder(unitId, subUnitId, drawingId, index + 1);
+ });
+
+ const op = ops.reduce(json1.type.compose, null);
+ const invertOp = json1.type.invertWithDoc(op, this.drawingManagerData as unknown as json1.Doc);
+
+ return { undo: invertOp, redo: op, unitId, subUnitId, objects: { ...orderParams, drawingIds: newIds } };
+ }
+
+ getBackDrawingsOp(orderParams: IDrawingOrderMapParam): IDrawingJsonUndo1 {
+ const { unitId, subUnitId, drawingIds } = orderParams;
+ const orderSearchParams = this._getOrderFromSearchParams(unitId, subUnitId, drawingIds, true);
+ const newIds = [...drawingIds];
+ const orders = this.getDrawingOrder(unitId, subUnitId);
+ const ops: JSONOp[] = [];
+ orderSearchParams.forEach((orderSearchParam) => {
+ const { drawingId } = orderSearchParam;
+
+ const op = json1.moveOp([unitId, subUnitId, DrawingMapItemType.order, this._getDrawingOrder(unitId, subUnitId).indexOf(drawingId)], [unitId, subUnitId, DrawingMapItemType.order, 0]);
+ ops.push(op);
+
+ if (!newIds.includes(orders[0])) {
+ newIds.push(orders[0]);
+ }
+ });
+
+ const op = ops.reduce(json1.type.compose, null);
+ const invertOp = json1.type.invertWithDoc(op, this.drawingManagerData as unknown as json1.Doc);
+
+ return { undo: invertOp, redo: op, unitId, subUnitId, objects: { ...orderParams, drawingIds: newIds } };
+ }
+
+ private _getDrawingCount(unitId: string, subUnitId: string) {
+ return this.getDrawingOrder(unitId, subUnitId).length || 0;
+ }
+
+ private _getOrderFromSearchParams(unitId: string, subUnitId: string, drawingIds: string[], isDesc = false) {
+ return drawingIds.map((drawingId) => {
+ const zIndex = this._hasDrawingOrder({ unitId, subUnitId, drawingId });
+ return { drawingId, zIndex };
+ }).sort(isDesc === false ? sortRules : sortRulesByDesc);
+ }
+
+ private _hasDrawingOrder(searchParam: Nullable<IDrawingSearch>) {
+ if (searchParam == null) {
+ return -1;
+ }
+
+ const { unitId, subUnitId, drawingId } = searchParam;
+
+ this._establishDrawingMap(unitId, subUnitId);
+
+ return this._getDrawingOrder(unitId, subUnitId).indexOf(drawingId);
+ }
+
+ private _getCurrentBySearch(searchParam: Nullable<IDrawingSearch>): Nullable<T> {
+ if (searchParam == null) {
+ return;
+ }
+ const { unitId, subUnitId, drawingId } = searchParam;
+ return this.drawingManagerData[unitId]?.[subUnitId]?.data?.[drawingId] as T;
+ }
+
+ private _getOldBySearch(searchParam: Nullable<IDrawingSearch>): Nullable<T> {
+ if (searchParam == null) {
+ return;
+ }
+ const { unitId, subUnitId, drawingId } = searchParam;
+ return this._oldDrawingManagerData[unitId]?.[subUnitId]?.data?.[drawingId] as T;
+ }
+
+ private _establishDrawingMap(unitId: string, subUnitId: string, drawingId?: string) {
+ if (!this.drawingManagerData[unitId]) {
+ this.drawingManagerData[unitId] = {};
+ }
+
+ if (!this.drawingManagerData[unitId][subUnitId]) {
+ this.drawingManagerData[unitId][subUnitId] = {
+ data: {},
+ order: [],
+ };
+ }
+
+ if (drawingId == null) {
+ return null;
+ }
+ return this.drawingManagerData[unitId][subUnitId].data?.[drawingId];
+ }
+
+ private _addByParam(insertParam: T): { op: JSONOp; invertOp: JSONOp } {
+ const { unitId, subUnitId, drawingId } = insertParam;
+
+ this._establishDrawingMap(unitId, subUnitId, drawingId);
+
+ // this.drawingManagerInfo[unitId][subUnitId][drawingId] = insertParam;
+
+ // this._insertDrawingOrder({ unitId, subUnitId, drawingId });
+
+ const op1 = json1.insertOp([unitId, subUnitId, DrawingMapItemType.data, drawingId], insertParam as unknown as json1.Doc);
+ const op2 = json1.insertOp([unitId, subUnitId, DrawingMapItemType.order, this._getDrawingOrder(unitId, subUnitId).length], drawingId);
+ const op = [op1, op2].reduce(json1.type.compose, null);
+
+ const invertOp = json1.type.invertWithDoc(op, this.drawingManagerData as unknown as json1.Doc);
+
+ return { op, invertOp };
+ }
+
+ private _removeByParam(searchParam: Nullable<IDrawingSearch>): { op: JSONOp; invertOp: JSONOp } {
+ if (searchParam == null) {
+ return { op: [], invertOp: [] };
+ }
+ const { unitId, subUnitId, drawingId } = searchParam;
+
+ const object = this._establishDrawingMap(unitId, subUnitId, drawingId);
+
+ if (object == null) {
+ return { op: [], invertOp: [] };
+ }
+
+ // delete this.drawingManagerInfo[unitId][subUnitId][drawingId];
+
+ // this._removeDrawingOrder({ unitId, subUnitId, drawingId });
+
+ const op1 = json1.removeOp([unitId, subUnitId, DrawingMapItemType.data, drawingId], true);
+ const op2 = json1.removeOp([unitId, subUnitId, DrawingMapItemType.order, this._getDrawingOrder(unitId, subUnitId).indexOf(drawingId)], true);
+ const op = [op1, op2].reduce(json1.type.compose, null);
+
+ const invertOp = json1.type.invertWithDoc(op, this.drawingManagerData as unknown as json1.Doc);
+
+ return { op, invertOp };
+ }
+
+ private _updateByParam(updateParam: T): { op: JSONOp; invertOp: JSONOp } {
+ const { unitId, subUnitId, drawingId } = updateParam;
+
+ const object = this._establishDrawingMap(unitId, subUnitId, drawingId);
+
+ if (object == null) {
+ return { op: [], invertOp: [] };
+ }
+
+ // const oldParam = this._getCurrentBySearch({ unitId, subUnitId, drawingId });
+ // if (oldParam) {
+ // this._initializeDrawingData(updateParam, oldParam);
+ // }
+
+ const ops: JSONOp[] = this._getUpdateParamCompareOp(updateParam, object as T);
+
+ // this.drawingManagerInfo[unitId][subUnitId][drawingId] = newObject;
+
+ const op = ops.reduce(json1.type.compose, null);
+
+ const invertOp = json1.type.invertWithDoc(op, this.drawingManagerData as unknown as json1.Doc);
+
+ return { op, invertOp };
+ }
+
+ // private _initializeDrawingData(updateParam: T, oldParam: T) {
+ // Object.keys(updateParam).forEach((key) => {
+ // if (!(key in oldParam)) {
+ // oldParam[key as keyof IDrawingParam] = null as unknown as never;
+ // }
+ // });
+ // }
+
+ private _getUpdateParamCompareOp(newParam: T, oldParam: T) {
+ const { unitId, subUnitId, drawingId } = newParam;
+ const ops: JSONOp[] = [];
+ Object.keys(newParam as IDrawingParam).forEach((key) => {
+ const newVal = newParam[key as keyof IDrawingParam];
+
+ const oldVal = oldParam[key as keyof IDrawingParam];
+
+ if (oldVal === newVal) {
+ return;
+ }
+
+ ops.push(
+ json1.replaceOp([unitId, subUnitId, DrawingMapItemType.data, drawingId, key], oldVal as unknown as json1.Doc, newVal as unknown as json1.Doc)
+ );
+ });
+ return ops;
+ }
+
+ private _getDrawingData(unitId: string, subUnitId: string) {
+ return this.drawingManagerData[unitId]?.[subUnitId]?.data || {};
+ }
+
+ private _getDrawingOrder(unitId: string, subUnitId: string) {
+ return this.drawingManagerData[unitId]?.[subUnitId]?.order || [];
+ }
+}
+
+export class DrawingManagerService extends UnitDrawingService<IDrawingParam> {}
diff --git a/packages/drawing/src/services/image-io.service.ts b/packages/drawing/src/services/image-io.service.ts
new file mode 100644
index 0000000000..4a9308a2e6
--- /dev/null
+++ b/packages/drawing/src/services/image-io.service.ts
@@ -0,0 +1,97 @@
+/**
+ * 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 { IImageIoService, IImageIoServiceParam, Nullable } from '@univerjs/core';
+import { ImageSourceType, ImageUploadStatusType, Tools } from '@univerjs/core';
+import type { Observable } from 'rxjs';
+import { Subject } from 'rxjs';
+import { DRAWING_IMAGE_ALLOW_IMAGE_LIST, DRAWING_IMAGE_ALLOW_SIZE } from '../basics/config';
+
+export class ImageIoService implements IImageIoService {
+ private _waitCount = 0;
+
+ private _change$ = new Subject<number>();
+ change$ = this._change$ as Observable<number>;
+
+ setWaitCount(count: number) {
+ this._waitCount = count;
+ this._change$.next(count);
+ }
+
+ private _imageSourceCache: Map<string, HTMLImageElement> = new Map();
+ getImageSourceCache(source: string, imageSourceType: ImageSourceType) {
+ if (imageSourceType === ImageSourceType.BASE64) {
+ const image = new Image();
+ image.src = source;
+ return image;
+ }
+ return this._imageSourceCache.get(source);
+ }
+
+ addImageSourceCache(source: string, imageSourceType: ImageSourceType, imageSource: Nullable<HTMLImageElement>) {
+ if (imageSourceType === ImageSourceType.BASE64 || imageSource == null) {
+ return;
+ }
+ this._imageSourceCache.set(source, imageSource);
+ }
+
+ async getImage(imageId: string): Promise<string> {
+ return Promise.resolve(imageId);
+ }
+
+ async saveImage(imageFile: File): Promise<Nullable<IImageIoServiceParam>> {
+ return new Promise((resolve, reject) => {
+ if (!DRAWING_IMAGE_ALLOW_IMAGE_LIST.includes(imageFile.type)) {
+ reject(new Error(ImageUploadStatusType.ERROR_IMAGE_TYPE));
+ this._decreaseWaiting();
+ return;
+ }
+ if (imageFile.size > DRAWING_IMAGE_ALLOW_SIZE) {
+ reject(new Error(ImageUploadStatusType.ERROR_EXCEED_SIZE));
+ this._decreaseWaiting();
+ return;
+ }
+ // 获取上传的图片的宽高
+ const reader = new FileReader();
+ reader.readAsDataURL(imageFile);
+ reader.onload = (evt) => {
+ const replaceSrc = evt.target?.result as string;
+ if (replaceSrc == null) {
+ reject(new Error(ImageUploadStatusType.ERROR_IMAGE));
+ this._decreaseWaiting();
+ return;
+ }
+
+ const imageId = Tools.generateRandomId(6);
+ resolve({
+ imageId,
+ imageSourceType: ImageSourceType.BASE64,
+ source: replaceSrc,
+ base64Cache: replaceSrc,
+ status: ImageUploadStatusType.SUCCUSS,
+ });
+
+ this._decreaseWaiting();
+ };
+ });
+ }
+
+ private _decreaseWaiting() {
+ this._waitCount -= 1;
+ this._change$.next(this._waitCount);
+ }
+}
+
diff --git a/packages/drawing/src/utils/get-image-shape-key.ts b/packages/drawing/src/utils/get-image-shape-key.ts
new file mode 100644
index 0000000000..215633e6af
--- /dev/null
+++ b/packages/drawing/src/utils/get-image-shape-key.ts
@@ -0,0 +1,22 @@
+/**
+ * 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 { IDrawingSearch } from '@univerjs/core';
+
+export function getDrawingShapeKeyByDrawingSearch(param: IDrawingSearch): string {
+ const { unitId, subUnitId, drawingId } = param;
+ return `${unitId}#-#${subUnitId}#-#${drawingId}`;
+}
diff --git a/packages/drawing/src/utils/get-image-size.ts b/packages/drawing/src/utils/get-image-size.ts
new file mode 100644
index 0000000000..047fa83052
--- /dev/null
+++ b/packages/drawing/src/utils/get-image-size.ts
@@ -0,0 +1,38 @@
+/**
+ * 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 { ISize } from '@univerjs/core';
+
+interface IImageParam extends ISize {
+ image: HTMLImageElement;
+}
+
+export const getImageSize = async (src: string): Promise<Required<IImageParam>> => {
+ return new Promise((resolve, reject) => {
+ const image = new Image();
+ image.src = src;
+ image.onload = () => {
+ resolve({
+ width: image.width,
+ height: image.height,
+ image,
+ });
+ };
+ image.onerror = (error) => {
+ reject(error);
+ };
+ });
+};
diff --git a/packages/drawing/tsconfig.json b/packages/drawing/tsconfig.json
new file mode 100644
index 0000000000..d676ad2a20
--- /dev/null
+++ b/packages/drawing/tsconfig.json
@@ -0,0 +1,9 @@
+{
+ "extends": "@univerjs/shared/tsconfigs/base",
+ "compilerOptions": {
+ "rootDir": "src",
+ "outDir": "lib/types"
+ },
+ "references": [{ "path": "./tsconfig.node.json" }],
+ "include": ["src"]
+}
diff --git a/packages/drawing/tsconfig.node.json b/packages/drawing/tsconfig.node.json
new file mode 100644
index 0000000000..e53dac8868
--- /dev/null
+++ b/packages/drawing/tsconfig.node.json
@@ -0,0 +1,4 @@
+{
+ "extends": "@univerjs/shared/tsconfigs/node",
+ "include": ["vite.config.ts"]
+}
diff --git a/packages/image/vite.config.ts b/packages/drawing/vite.config.ts
similarity index 100%
rename from packages/image/vite.config.ts
rename to packages/drawing/vite.config.ts
diff --git a/packages/engine-formula/src/functions/base-function.ts b/packages/engine-formula/src/functions/base-function.ts
index d9b556a2ce..2b21e59c8c 100644
--- a/packages/engine-formula/src/functions/base-function.ts
+++ b/packages/engine-formula/src/functions/base-function.ts
@@ -514,7 +514,7 @@ export class BaseFunction extends Disposable {
referenceObject = new RangeReferenceObject(range, sheetId, unitId);
}
- return this._setReferenceDefault(reference, referenceObject); ;
+ return this._setReferenceDefault(reference, referenceObject);
}
private _setReferenceDefault(reference: BaseReferenceObject, object: BaseReferenceObject) {
diff --git a/packages/engine-formula/src/functions/lookup/xmatch/index.ts b/packages/engine-formula/src/functions/lookup/xmatch/index.ts
index c8b11deb67..e0fc61a652 100644
--- a/packages/engine-formula/src/functions/lookup/xmatch/index.ts
+++ b/packages/engine-formula/src/functions/lookup/xmatch/index.ts
@@ -90,7 +90,7 @@ export class Xmatch extends BaseFunction {
lookupArray,
matchModeValue,
searchModeValue
- ); ;
+ );
}
private _handleSingleObject(
diff --git a/packages/engine-render/src/base-object.ts b/packages/engine-render/src/base-object.ts
index 2cc0b4b1ef..49a979294a 100644
--- a/packages/engine-render/src/base-object.ts
+++ b/packages/engine-render/src/base-object.ts
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-import type { EventState, IKeyValue, Nullable, Observer } from '@univerjs/core';
+import type { EventState, IKeyValue, ITransformState, Nullable, Observer } from '@univerjs/core';
import { Disposable, Observable } from '@univerjs/core';
import type { EVENT_TYPE } from './basics/const';
@@ -27,6 +27,7 @@ import { Transform } from './basics/transform';
import type { IViewportInfo, Vector2 } from './basics/vector2';
import type { UniverRenderingContext } from './context';
import type { Layer } from './layer';
+import type { ITransformerConfig } from './basics/transformer-config';
export const BASE_OBJECT_ARRAY = [
'top',
@@ -45,31 +46,21 @@ export const BASE_OBJECT_ARRAY = [
export abstract class BaseObject extends Disposable {
groupKey?: string;
-
isInGroup: boolean = false;
onTransformChangeObservable = new Observable<ITransformChangeState>();
-
onPointerDownObserver = new Observable<IPointerEvent | IMouseEvent>();
-
onPointerMoveObserver = new Observable<IPointerEvent | IMouseEvent>();
-
onPointerUpObserver = new Observable<IPointerEvent | IMouseEvent>();
-
onDblclickObserver = new Observable<IPointerEvent | IMouseEvent>();
-
onTripleClickObserver = new Observable<IPointerEvent | IMouseEvent>();
-
onMouseWheelObserver = new Observable<IWheelEvent>();
// onKeyDownObservable = new Observable<IKeyboardEvent>();
// onKeyUpObservable = new Observable<IKeyboardEvent>();
onPointerOutObserver = new Observable<IPointerEvent | IMouseEvent>();
-
onPointerLeaveObserver = new Observable<IPointerEvent | IMouseEvent>();
-
onPointerOverObserver = new Observable<IPointerEvent | IMouseEvent>();
-
onPointerEnterObserver = new Observable<IPointerEvent | IMouseEvent>();
onDragLeaveObserver = new Observable<IDragEvent | IMouseEvent>();
@@ -81,7 +72,6 @@ export abstract class BaseObject extends Disposable {
onDropObserver = new Observable<IDragEvent | IMouseEvent>();
onIsAddedToParentObserver = new Observable<any>();
-
onDisposeObserver = new Observable<BaseObject>();
protected _oKey: string;
@@ -90,33 +80,26 @@ export abstract class BaseObject extends Disposable {
protected _forceDirty: boolean = true;
private _top: number = 0;
-
private _topOrigin: number | string = 0;
private _left: number = 0;
-
private _leftOrigin: number | string = 0;
private _width: number = 0;
-
private _widthOrigin: number | string = 0;
private _height: number = 0;
-
private _heightOrigin: number | string = 0;
private _angle: number = 0;
private _scaleX: number = 1;
-
private _scaleY: number = 1;
private _skewX: number = 0;
-
private _skewY: number = 0;
private _flipX: boolean = false;
-
private _flipY: boolean = false;
private _strokeWidth: number = 0;
@@ -135,7 +118,7 @@ export abstract class BaseObject extends Disposable {
private _cursor: CURSOR_TYPE = CURSOR_TYPE.DEFAULT;
- private _isTransformer = false;
+ private _transformerConfig: ITransformerConfig;
private _forceRender = false;
@@ -152,7 +135,24 @@ export abstract class BaseObject extends Disposable {
}
get transform() {
- return this._transform;
+ const transform = this._transform.clone();
+ return this.transformForAngle(transform);
+ }
+
+ transformForAngle(transform: Transform) {
+ /**
+ * If the object is center rotated, the coordinate needs to be rotated back to the original position.
+ */
+ if (this._angle !== 0) {
+ const cx = (this.width + this.strokeWidth) / 2;
+ const cy = (this.height + this.strokeWidth) / 2;
+ transform.rotate(-this._angle);
+ transform.translate(cx, cy);
+ transform.rotate(this.angle);
+ transform.translate(-cx, -cy);
+ }
+
+ return transform;
}
get topOrigin() {
@@ -217,6 +217,34 @@ export abstract class BaseObject extends Disposable {
return this.scaleY * pScale;
}
+ get ancestorLeft() {
+ return this.left + (this.getParent()?.ancestorLeft || 0);
+ }
+
+ get ancestorTop() {
+ return this.top + (this.getParent()?.ancestorTop || 0);
+ }
+
+ get ancestorTransform() {
+ const parent = this.getParent();
+ if (this.isInGroup && parent?.classType === RENDER_CLASS_TYPE.GROUP) {
+ return parent?.ancestorTransform.multiply(this.transform);
+ }
+ return this.transform;
+ }
+
+ get ancestorGroup() {
+ let group: Nullable<BaseObject> = null;
+ let parent = this.getParent();
+ while (parent != null) {
+ if (parent.classType === RENDER_CLASS_TYPE.GROUP) {
+ group = parent;
+ }
+ parent = parent.getParent();
+ }
+ return group;
+ }
+
get skewX() {
return this._skewX;
}
@@ -257,10 +285,6 @@ export abstract class BaseObject extends Disposable {
return this._debounceParentDirty;
}
- get isTransformer() {
- return this._isTransformer;
- }
-
get cursor() {
return this._cursor;
}
@@ -289,10 +313,6 @@ export abstract class BaseObject extends Disposable {
this._debounceParentDirty = state;
}
- set isTransformer(state: boolean) {
- this._isTransformer = state;
- }
-
set cursor(val: CURSOR_TYPE) {
this.setCursor(val);
}
@@ -353,6 +373,18 @@ export abstract class BaseObject extends Disposable {
this._skewY = skewY;
}
+ get transformerConfig() {
+ return this._transformerConfig;
+ }
+
+ set transformerConfig(config: ITransformerConfig) {
+ this._transformerConfig = config;
+ }
+
+ get maxZIndex() {
+ return this._zIndex;
+ }
+
makeDirty(state: boolean = true) {
this._dirty = state;
@@ -530,7 +562,7 @@ export abstract class BaseObject extends Disposable {
return this._parent;
}
- getState() {
+ getState(): ITransformState {
return {
left: this.left,
top: this.top,
@@ -561,7 +593,7 @@ export abstract class BaseObject extends Disposable {
}
isHit(coord: Vector2) {
- const oCoord = this._getInverseCoord(coord);
+ const oCoord = this.getInverseCoord(coord);
if (
oCoord.x >= -this.strokeWidth / 2 &&
oCoord.x <= this.width + this.strokeWidth / 2 &&
@@ -801,8 +833,23 @@ export abstract class BaseObject extends Disposable {
return [];
}
- protected _getInverseCoord(coord: Vector2) {
- return this._transform.clone().invert().applyPoint(coord);
+ getLayerIndex() {
+ if (this._layer == null) {
+ return 1;
+ }
+ return this._layer.zIndex;
+ }
+
+ applyTransform() {
+ this.getScene()?.attachTransformerTo(this);
+ }
+
+ removeTransform() {
+ this.getScene()?.detachTransformerFrom(this);
+ }
+
+ getInverseCoord(coord: Vector2): Vector2 {
+ return this.ancestorTransform.invert().applyPoint(coord);
}
protected _setTransForm() {
diff --git a/packages/engine-render/src/basics/const.ts b/packages/engine-render/src/basics/const.ts
index 3275797144..fc416b5910 100644
--- a/packages/engine-render/src/basics/const.ts
+++ b/packages/engine-render/src/basics/const.ts
@@ -154,10 +154,15 @@ export enum RENDER_CLASS_TYPE {
VIEWPORT = 'Viewport',
LAYER = 'Layer',
GROUP = 'Group',
+ IMAGE = 'Image',
+ SHAPE = 'Shape',
+ TEXT = 'Text',
}
-export const DEFAULT_SELECTION_LAYER_INDEX = 1000;
-
export const MAXIMUM_ROW_HEIGHT = 2000;
export const FIX_ONE_PIXEL_BLUR_OFFSET = 0.5;
+
+export const DRAWING_OBJECT_LOWER_LAYER_INDEX = 3;
+export const DRAWING_OBJECT_LAYER_INDEX = 4;
+export const DRAWING_OBJECT_UPPER_LAYER_INDEX = 5;
diff --git a/packages/engine-render/src/basics/group-transform.ts b/packages/engine-render/src/basics/group-transform.ts
new file mode 100644
index 0000000000..36e7abe27d
--- /dev/null
+++ b/packages/engine-render/src/basics/group-transform.ts
@@ -0,0 +1,69 @@
+/**
+ * Copyright 2023-present DreamNum Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { ITransformState } from '@univerjs/core';
+import { offsetRotationAxis } from './offset-rotation-axis';
+import { Vector2 } from './vector2';
+
+export function getGroupState(parentLeft: number, parentTop: number, objectStates: ITransformState[]) {
+ let groupLeft = Number.MAX_SAFE_INTEGER;
+ let groupTop = Number.MAX_SAFE_INTEGER;
+ let groupRight = Number.MIN_SAFE_INTEGER;
+ let groupBottom = Number.MIN_SAFE_INTEGER;
+
+ objectStates.forEach((o) => {
+ const { left = 0, top = 0, width = 0, height = 0 } = o;
+ groupLeft = Math.min(groupLeft, left);
+ groupTop = Math.min(groupTop, top);
+ groupRight = Math.max(groupRight, left + width);
+ groupBottom = Math.max(groupBottom, top + height);
+ });
+
+ const groupWidth = groupRight - groupLeft;
+ const groupHeight = groupBottom - groupTop;
+
+ return {
+ left: groupLeft + parentLeft,
+ top: groupTop + parentTop,
+ width: groupWidth,
+ height: groupHeight,
+ angle: 0,
+ scaleX: 1,
+ scaleY: 1,
+ };
+}
+
+export function transformObjectOutOfGroup(child: ITransformState, parent: ITransformState, groupOriginWidth: number, groupOriginHeight: number) {
+ const { left = 0, top = 0, width = 0, height = 0, angle = 0 } = child;
+ const { left: groupLeft = 0, top: groupTop = 0, angle: groupAngle = 0 } = parent;
+
+ const groupCenterX = groupLeft + groupOriginWidth / 2;
+ const groupCenterY = groupTop + groupOriginHeight / 2;
+
+ const objectX = left + groupLeft;
+ const objectY = top + groupTop;
+
+ const objectCenterX = objectX + width / 2;
+ const objectCenterY = objectY + height / 2;
+
+ const finalPoint = offsetRotationAxis(new Vector2(groupCenterX, groupCenterY), groupAngle, new Vector2(objectX, objectY), new Vector2(objectCenterX, objectCenterY));
+
+ return {
+ left: finalPoint.x,
+ top: finalPoint.y,
+ angle: groupAngle + angle,
+ };
+}
diff --git a/packages/engine-render/src/basics/i-document-skeleton-cached.ts b/packages/engine-render/src/basics/i-document-skeleton-cached.ts
index 152e2f56b1..74aae0ddec 100644
--- a/packages/engine-render/src/basics/i-document-skeleton-cached.ts
+++ b/packages/engine-render/src/basics/i-document-skeleton-cached.ts
@@ -18,8 +18,8 @@ import type {
BulletAlignment,
ColumnSeparatorType,
DataStreamTreeTokenType,
+ IDocDrawingBase,
IDocumentRenderConfig,
- IDrawing,
IIndentStart,
INestingLevel,
ITextStyle,
@@ -188,7 +188,7 @@ export interface IDocumentSkeletonGlyph {
parent?: IDocumentSkeletonDivide;
url?: string; // image url
featureId?: string; // support interaction for feature ,eg. hyperLine person
- objectId?: string; // drawing.objectId
+ drawingId?: string; // drawing.drawingId
}
export interface IDocumentSkeletonBullet extends IIndentStart {
@@ -207,14 +207,14 @@ export interface IDocumentSkeletonBullet extends IIndentStart {
}
export interface IDocumentSkeletonDrawing {
- objectId: string;
+ drawingId: string;
aLeft: number; // 相对于 page 的左方
aTop: number; // 相对于 page 的上方
width: number;
height: number;
angle: number; // 旋转
initialState: boolean; // 是否初始化
- drawingOrigin: IDrawing;
+ drawingOrigin: IDocDrawingBase;
}
export interface IDocumentSkeletonFontStyle {
diff --git a/packages/engine-render/src/basics/index.ts b/packages/engine-render/src/basics/index.ts
index ebc50be8a1..75dc244169 100644
--- a/packages/engine-render/src/basics/index.ts
+++ b/packages/engine-render/src/basics/index.ts
@@ -30,3 +30,4 @@ export * from './tools';
export * from './transform';
export * from './vector2';
export * from './text-rotation';
+export * from './group-transform';
diff --git a/packages/engine-render/src/basics/interfaces.ts b/packages/engine-render/src/basics/interfaces.ts
index ba43c1327c..bb5b053250 100644
--- a/packages/engine-render/src/basics/interfaces.ts
+++ b/packages/engine-render/src/basics/interfaces.ts
@@ -41,13 +41,14 @@ import type {
IDocumentSkeletonHeader,
} from './i-document-skeleton-cached';
import type { Vector2 } from './vector2';
+import type { ITransformerConfig } from './transformer-config';
export interface IObjectFullState extends ITransformState {
strokeWidth?: number;
zIndex?: number;
- isTransformer?: boolean;
forceRender?: boolean;
debounceParentDirty?: boolean;
+ transformerConfig?: ITransformerConfig;
}
export interface IRect extends ISize, IOffset {
@@ -67,19 +68,9 @@ export enum TRANSFORM_CHANGE_OBSERVABLE_TYPE {
export interface ITransformChangeState {
type: TRANSFORM_CHANGE_OBSERVABLE_TYPE;
- value:
- | number
- | string
- | boolean
- | { x: number | string | boolean; y: number | string | boolean }
- | IObjectFullState
+ value: IObjectFullState
| ISceneTransformState;
- preValue:
- | number
- | string
- | boolean
- | { x: number | string | boolean; y: number | string | boolean }
- | IObjectFullState
+ preValue: IObjectFullState
| ISceneTransformState;
}
diff --git a/packages/engine-render/src/basics/offset-rotation-axis.ts b/packages/engine-render/src/basics/offset-rotation-axis.ts
new file mode 100644
index 0000000000..ff71b90941
--- /dev/null
+++ b/packages/engine-render/src/basics/offset-rotation-axis.ts
@@ -0,0 +1,31 @@
+/**
+ * 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 { degToRad } from './tools';
+import type { Vector2 } from './vector2';
+
+export function offsetRotationAxis(referenceCoords: Vector2, angleDegree: number, vertexCoords: Vector2, centerCoords: Vector2): Vector2 {
+ const angleRad = degToRad(angleDegree);
+
+ const newVertexCoords = vertexCoords.clone().rotateByPoint(angleRad, referenceCoords);
+
+ const newCenterCoords = centerCoords.clone().rotateByPoint(angleRad, referenceCoords);
+
+ const finalPoint = newVertexCoords.clone();
+ finalPoint.rotateByPoint(degToRad(-angleDegree), newCenterCoords);
+
+ return finalPoint;
+}
diff --git a/packages/engine-render/src/basics/transformer-config.ts b/packages/engine-render/src/basics/transformer-config.ts
new file mode 100644
index 0000000000..b4a536687f
--- /dev/null
+++ b/packages/engine-render/src/basics/transformer-config.ts
@@ -0,0 +1,61 @@
+/**
+ * Copyright 2023-present DreamNum Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { Nullable } from '@univerjs/core';
+import type { BaseObject } from '../base-object';
+import type { IMouseEvent, IPointerEvent } from './i-events';
+
+export interface ITransformerConfig {
+ // for image copper
+ isCropper?: boolean;
+
+ hoverEnabled?: boolean;
+ hoverEnterFunc?: Nullable<(e: IPointerEvent | IMouseEvent) => void>;
+ hoverLeaveFunc?: Nullable<(e: IPointerEvent | IMouseEvent) => void>;
+
+ rotateEnabled?: boolean;
+ rotationSnaps?: number[];
+ rotationSnapTolerance?: number;
+ rotateAnchorOffset?: number;
+ rotateSize?: number;
+ rotateCornerRadius?: number;
+
+ borderEnabled?: boolean;
+ borderStroke?: string;
+ borderStrokeWidth?: number;
+ borderDash?: number[];
+ borderSpacing?: number;
+
+ resizeEnabled?: boolean;
+ enabledAnchors?: number[];
+ anchorFill?: string;
+ anchorStroke?: string;
+ anchorStrokeWidth?: number;
+ anchorSize?: number;
+ anchorCornerRadius?: number;
+
+ keepRatio?: boolean;
+ centeredScaling?: boolean;
+
+ flipEnabled?: boolean;
+ ignoreStroke?: boolean;
+ boundBoxFunc?: Nullable<(oldBox: BaseObject, newBox: BaseObject) => BaseObject>;
+ useSingleNodeRotation?: boolean;
+ shouldOverdrawWholeArea?: boolean;
+
+ zeroLeft?: number;
+ zeroTop?: number;
+}
diff --git a/packages/engine-render/src/canvas.ts b/packages/engine-render/src/canvas.ts
index 7714019d3c..4c51825416 100644
--- a/packages/engine-render/src/canvas.ts
+++ b/packages/engine-render/src/canvas.ts
@@ -144,7 +144,7 @@ export class Canvas {
canvsElement.style.height = `${this._height}px`;
}
- this.getContext().setTransform(this._pixelRatio, 0, 0, this._pixelRatio, 0, 0);
+ this.getContext()?.setTransform(this._pixelRatio, 0, 0, this._pixelRatio, 0, 0);
}
setPixelRatio(pixelRatio: number) {
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.ts
index f9222cc28b..ce2564f954 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
@@ -510,7 +510,7 @@ function _lineOperator(
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);
+ .filter((drawing) => drawing.drawingOrigin.docTransform.positionV.relativeFrom === ObjectRelativeFromV.LINE);
__updateAndPositionDrawings(ctx, line.top, line.lineHeight, column, relativeLineDrawings, line.paragraphIndex);
}
@@ -524,7 +524,7 @@ function _lineOperator(
if (paragraphAffectSkeDrawings != null && paragraphAffectSkeDrawings.size > 0) {
const targetDrawings = [...paragraphAffectSkeDrawings.values()]
- .filter((drawing) => drawing.drawingOrigin.objectTransform.positionV.relativeFrom !== ObjectRelativeFromV.LINE);
+ .filter((drawing) => drawing.drawingOrigin.docTransform.positionV.relativeFrom !== ObjectRelativeFromV.LINE);
__updateAndPositionDrawings(ctx, lineTop, lineHeight, column, targetDrawings, paragraphConfig.paragraphIndex, drawingAnchor?.get(paragraphIndex)?.top);
}
@@ -624,7 +624,7 @@ function _getCustomBlockIdsInLine(line: IDocumentSkeletonLine) {
for (const divide of line.divides) {
for (const glyph of divide.glyphGroup) {
if (glyph.streamType === DataStreamTreeTokenType.CUSTOM_BLOCK) {
- customBlockIds.push(glyph.objectId!);
+ customBlockIds.push(glyph.drawingId!);
}
}
}
@@ -649,7 +649,7 @@ function _reLayoutCheck(
// 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);
+ const drawingCache = ctx.drawingsCache.get(drawing.drawingId);
if (drawingCache == null) {
continue;
}
@@ -657,7 +657,7 @@ function _reLayoutCheck(
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);
+ drawingCache.page.skeDrawings.delete(drawing.drawingId);
lineIterator([drawingCache.page], (line) => {
const { lineHeight, top } = line;
@@ -692,11 +692,11 @@ function _reLayoutCheck(
for (const drawing of drawings.values()) {
let targetDrawing = drawing;
- if (ctx.drawingsCache.has(drawing.objectId)) {
+ if (ctx.drawingsCache.has(drawing.drawingId)) {
const needRePosition = checkRelativeDrawingNeedRePosition(ctx, drawing);
if (needRePosition) {
- targetDrawing = ctx.drawingsCache.get(drawing.objectId)?.drawing ?? drawing;
+ targetDrawing = ctx.drawingsCache.get(drawing.drawingId)?.drawing ?? drawing;
} else {
continue;
}
@@ -711,7 +711,7 @@ function _reLayoutCheck(
ctx.isDirty = true;
ctx.layoutStartPointer.paragraphIndex = Math.min(line.paragraphIndex, ctx.layoutStartPointer.paragraphIndex ?? Number.POSITIVE_INFINITY);
- let drawingCache = ctx.drawingsCache.get(drawing.objectId);
+ let drawingCache = ctx.drawingsCache.get(drawing.drawingId);
if (drawingCache == null) {
drawingCache = {
count: 0,
@@ -719,7 +719,7 @@ function _reLayoutCheck(
page,
};
- ctx.drawingsCache.set(drawing.objectId, drawingCache);
+ ctx.drawingsCache.set(drawing.drawingId, drawingCache);
}
drawingCache.count++;
@@ -734,8 +734,8 @@ function _reLayoutCheck(
// 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);
+ const { relativeFrom } = drawing.drawingOrigin.docTransform.positionV;
+ const drawingCache = ctx.drawingsCache.get(drawing.drawingId);
if (drawingCache == null) {
return false;
@@ -939,13 +939,13 @@ function __updatePreLineDrawingPosition(
for (const divide of line.divides) {
for (const glyph of divide.glyphGroup) {
if (glyph.streamType === DataStreamTreeTokenType.CUSTOM_BLOCK && glyph.width !== 0) {
- const { objectId } = glyph;
+ const { drawingId } = glyph;
- if (objectId == null) {
+ if (drawingId == null) {
continue;
}
- const drawing = paragraphInlineSkeDrawings?.get(objectId);
+ const drawing = paragraphInlineSkeDrawings?.get(drawingId);
const drawingOrigin = drawing?.drawingOrigin;
@@ -953,9 +953,9 @@ function __updatePreLineDrawingPosition(
continue;
}
- const { objectTransform } = drawingOrigin;
+ const { docTransform } = drawingOrigin;
- const { size, angle } = objectTransform;
+ const { size, angle } = docTransform;
const { width = 0, height = 0 } = size;
drawing.aLeft = glyph.left || 0;
@@ -964,7 +964,7 @@ function __updatePreLineDrawingPosition(
drawing.height = height;
drawing.angle = angle;
- drawings.set(drawing.objectId, drawing);
+ drawings.set(drawing.drawingId, drawing);
}
}
}
@@ -997,8 +997,8 @@ function __getDrawingPosition(
continue;
}
- const { objectTransform } = drawingOrigin;
- const { positionH, positionV, size, angle } = objectTransform;
+ const { docTransform } = drawingOrigin;
+ const { positionH, positionV, size, angle } = docTransform;
const { width = 0, height = 0 } = size;
drawing.aLeft = getPositionHorizon(positionH, column, page, width, isPageBreak) ?? 0;
@@ -1010,7 +1010,7 @@ function __getDrawingPosition(
drawing.angle = angle;
drawing.initialState = true;
- drawings.set(drawing.objectId, drawing);
+ drawings.set(drawing.drawingId, drawing);
}
// if (drawings.size) {
@@ -1028,19 +1028,19 @@ function __updateDrawingPosition(
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);
+ const originDrawing = page.skeDrawings.get(drawing.drawingId);
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);
+ page.skeDrawings.set(drawing.drawingId, lowerDrawing);
} else {
- page.skeDrawings.set(drawing.objectId, drawing);
+ page.skeDrawings.set(drawing.drawingId, drawing);
}
} else {
- page.skeDrawings.set(drawing.objectId, drawing);
+ page.skeDrawings.set(drawing.drawingId, drawing);
}
}
}
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.ts
index f73371ec68..d18da0360d 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,7 +14,7 @@
* limitations under the License.
*/
-import type { IBullet, IDrawing, IDrawings, Nullable } from '@univerjs/core';
+import type { IBullet, IDocDrawingBase, IDrawings, Nullable } from '@univerjs/core';
import { DataStreamTreeTokenType, PositionedObjectLayoutType } from '@univerjs/core';
import { BreakType } from '../../../../../basics/i-document-skeleton-cached';
import type { IDocumentSkeletonBullet, IDocumentSkeletonDrawing, IDocumentSkeletonPage } from '../../../../../basics/i-document-skeleton-cached';
@@ -83,18 +83,18 @@ function _changeDrawingToSkeletonFormat(
drawings: IDrawings
): Map<string, IDocumentSkeletonDrawing> {
const skeDrawings: Map<string, IDocumentSkeletonDrawing> = new Map();
- drawingIds.forEach((objectId) => {
- const drawingOrigin = drawings[objectId];
- drawingOrigin && skeDrawings.set(objectId, _getDrawingSkeletonFormat(drawingOrigin));
+ drawingIds.forEach((drawingId) => {
+ const drawingOrigin = drawings[drawingId];
+ drawingOrigin && skeDrawings.set(drawingId, _getDrawingSkeletonFormat(drawingOrigin));
});
return skeDrawings;
}
-function _getDrawingSkeletonFormat(drawingOrigin: IDrawing) {
- const objectId = drawingOrigin.objectId;
+function _getDrawingSkeletonFormat(drawingOrigin: IDocDrawingBase) {
+ const drawingId = drawingOrigin.drawingId;
return {
- objectId,
+ drawingId,
aLeft: 0,
aTop: 0,
width: 0,
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.ts
index 2cf739e886..b8b37da296 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
@@ -212,11 +212,11 @@ export function shaping(
const { blockId } = customBlock;
const drawingOrigin = drawings[blockId];
if (drawingOrigin.layoutType === PositionedObjectLayoutType.INLINE) {
- const { width, height } = drawingOrigin.objectTransform.size;
- const { objectId } = drawingOrigin;
- newGlyph = createSkeletonCustomBlockGlyph(config, width, height, objectId);
+ const { width, height } = drawingOrigin.docTransform.size;
+ const { drawingId } = drawingOrigin;
+ newGlyph = createSkeletonCustomBlockGlyph(config, width, height, drawingId);
} else {
- newGlyph = createSkeletonCustomBlockGlyph(config, 0, 0, drawingOrigin.objectId);
+ newGlyph = createSkeletonCustomBlockGlyph(config, 0, 0, drawingOrigin.drawingId);
}
}
diff --git a/packages/engine-render/src/components/docs/layout/model/glyph.ts b/packages/engine-render/src/components/docs/layout/model/glyph.ts
index 4f66d676c0..74d5d4168d 100644
--- a/packages/engine-render/src/components/docs/layout/model/glyph.ts
+++ b/packages/engine-render/src/components/docs/layout/model/glyph.ts
@@ -105,7 +105,7 @@ export function createHyphenDashGlyph(config: IFontCreateConfig) {
}
// 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 {
+export function createSkeletonCustomBlockGlyph(config: IFontCreateConfig, glyphWidth = 0, glyphHeight = 0, drawingId = ''): IDocumentSkeletonGlyph {
const { fontStyle, textStyle } = config;
const content = DT.CUSTOM_BLOCK;
@@ -133,7 +133,7 @@ export function createSkeletonCustomBlockGlyph(config: IFontCreateConfig, glyphW
glyphType: GlyphType.PLACEHOLDER,
streamType: content as DT,
count: 1,
- objectId,
+ drawingId,
};
}
diff --git a/packages/engine-render/src/components/docs/layout/model/line.ts b/packages/engine-render/src/components/docs/layout/model/line.ts
index b5b31df207..aa291e4883 100644
--- a/packages/engine-render/src/components/docs/layout/model/line.ts
+++ b/packages/engine-render/src/components/docs/layout/model/line.ts
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-import type { IDrawing, Nullable } from '@univerjs/core';
+import type { IDocDrawingBase, Nullable } from '@univerjs/core';
import { PositionedObjectLayoutType, WrapTextType } from '@univerjs/core';
import type {
@@ -367,7 +367,7 @@ function __getSplitWidthNoAngle(
lineTop: number,
lineHeight: number,
columnWidth: number,
- drawingOrigin: IDrawing
+ drawingOrigin: IDocDrawingBase
) {
const {
layoutType,
diff --git a/packages/engine-render/src/components/docs/text-selection/text-range.ts b/packages/engine-render/src/components/docs/text-selection/text-range.ts
index f8ff819eea..4c5ec12f53 100644
--- a/packages/engine-render/src/components/docs/text-selection/text-range.ts
+++ b/packages/engine-render/src/components/docs/text-selection/text-range.ts
@@ -198,6 +198,53 @@ export class TextRange {
return compare ? RANGE_DIRECTION.FORWARD : RANGE_DIRECTION.BACKWARD;
}
+ getAbsolutePosition() {
+ const anchor = this.anchorNodePosition;
+ const focus = this.focusNodePosition;
+ if (this._isEmpty()) {
+ return;
+ }
+
+ const documentOffsetConfig = this._document.getOffsetConfig();
+
+ const { docsLeft, docsTop } = documentOffsetConfig;
+
+ const convertor = new NodePositionConvertToCursor(documentOffsetConfig, this._docSkeleton);
+
+ if (this._isCollapsed()) {
+ const { contentBoxPointGroup, cursorList } = convertor.getRangePointData(anchor, anchor);
+
+ this._setCursorList(cursorList);
+ if (contentBoxPointGroup.length === 0) {
+ return;
+ }
+
+ const pos = getAnchorBounding(contentBoxPointGroup);
+
+ return {
+ ...pos,
+ left: pos.left + docsLeft,
+ top: pos.top + docsTop,
+ };
+ }
+
+ const { borderBoxPointGroup, cursorList } = convertor.getRangePointData(anchor, focus);
+
+ this._setCursorList(cursorList);
+
+ if (borderBoxPointGroup.length === 0) {
+ return;
+ }
+
+ const pos = getAnchorBounding(borderBoxPointGroup);
+
+ return {
+ ...pos,
+ left: pos.left + docsLeft,
+ top: pos.top + docsTop,
+ };
+ }
+
getAnchor() {
return this._anchorShape;
}
diff --git a/packages/engine-render/src/components/docs/text-selection/text-selection-render-manager.ts b/packages/engine-render/src/components/docs/text-selection/text-selection-render-manager.ts
index 74c2dd92a3..49ba336beb 100644
--- a/packages/engine-render/src/components/docs/text-selection/text-selection-render-manager.ts
+++ b/packages/engine-render/src/components/docs/text-selection/text-selection-render-manager.ts
@@ -513,6 +513,8 @@ export class TextSelectionRenderManager extends RxDisposable implements ITextSel
this._onSelectionStart$.next(this._getActiveRangeInstance()?.startNodePosition);
+ scene.getTransformer()?.clearSelectedObjects();
+
let preMoveOffsetX = evtOffsetX;
let preMoveOffsetY = evtOffsetY;
diff --git a/packages/engine-render/src/components/sheets/column-header.ts b/packages/engine-render/src/components/sheets/column-header.ts
index 7d70624ee0..f059a96b59 100644
--- a/packages/engine-render/src/components/sheets/column-header.ts
+++ b/packages/engine-render/src/components/sheets/column-header.ts
@@ -78,7 +78,7 @@ export class SpreadsheetColumnHeader extends SpreadsheetHeader {
}
override isHit(coord: Vector2): boolean {
- const oCoord = this._getInverseCoord(coord);
+ const oCoord = this.getInverseCoord(coord);
const skeleton = this.getSkeleton();
if (!skeleton) {
return false;
diff --git a/packages/engine-render/src/components/sheets/row-header.ts b/packages/engine-render/src/components/sheets/row-header.ts
index 29029e99a8..5e4cfa4d02 100644
--- a/packages/engine-render/src/components/sheets/row-header.ts
+++ b/packages/engine-render/src/components/sheets/row-header.ts
@@ -79,7 +79,7 @@ export class SpreadsheetRowHeader extends SpreadsheetHeader {
}
override isHit(coord: Vector2) {
- const oCoord = this._getInverseCoord(coord);
+ const oCoord = this.getInverseCoord(coord);
const skeleton = this.getSkeleton();
if (!skeleton) {
return false;
diff --git a/packages/engine-render/src/components/sheets/spreadsheet.ts b/packages/engine-render/src/components/sheets/spreadsheet.ts
index 0d5c12db55..1a6ff47c02 100644
--- a/packages/engine-render/src/components/sheets/spreadsheet.ts
+++ b/packages/engine-render/src/components/sheets/spreadsheet.ts
@@ -145,7 +145,7 @@ export class Spreadsheet extends SheetComponent {
}
override isHit(coord: Vector2) {
- const oCoord = this._getInverseCoord(coord);
+ const oCoord = this.getInverseCoord(coord);
const skeleton = this.getSkeleton();
if (!skeleton) {
return false;
diff --git a/packages/engine-render/src/group.ts b/packages/engine-render/src/group.ts
index fefb72b78e..cf4941cd82 100644
--- a/packages/engine-render/src/group.ts
+++ b/packages/engine-render/src/group.ts
@@ -24,9 +24,11 @@ import { isString } from './basics/tools';
import type { IViewportInfo, Vector2 } from './basics/vector2';
import type { UniverRenderingContext } from './context';
import type { ThinScene } from './thin-scene';
+import { getGroupState, transformObjectOutOfGroup } from './basics/group-transform';
export class Group extends BaseObject {
private _objects: BaseObject[] = [];
+ private _selfSizeMode = false;
constructor(key?: string, ...objects: BaseObject[]) {
super(key);
@@ -41,6 +43,102 @@ export class Group extends BaseObject {
this.setCursor(val);
}
+ override getState() {
+ if (this._selfSizeMode) {
+ return super.getState();
+ }
+ // let groupLeft = Number.MAX_SAFE_INTEGER;
+ // let groupTop = Number.MAX_SAFE_INTEGER;
+ // let groupRight = Number.MIN_SAFE_INTEGER;
+ // let groupBottom = Number.MIN_SAFE_INTEGER;
+
+ // this._objects.forEach((o) => {
+ // const { left, top, width, height } = o;
+ // groupLeft = Math.min(groupLeft, left);
+ // groupTop = Math.min(groupTop, top);
+ // groupRight = Math.max(groupRight, left + width);
+ // groupBottom = Math.max(groupBottom, top + height);
+ // });
+
+ // const groupWidth = groupRight - groupLeft;
+ // const groupHeight = groupBottom - groupTop;
+
+ return getGroupState(this.left, this.top, this._objects.map((o) => o.getState()));
+ }
+
+ override get width(): number {
+ if (this._selfSizeMode) {
+ return super.width;
+ }
+ return this.getState().width || 0;
+ }
+
+ override get height(): number {
+ if (this._selfSizeMode) {
+ return super.height;
+ }
+ return this.getState().height || 0;
+ }
+
+ override set width(val: number) {
+ if (this._selfSizeMode) {
+ super.width = val;
+ return;
+ }
+ const preWidth = this.width;
+ const numDelta = val - preWidth;
+ this._objects.forEach((o) => {
+ o.resize(o.width + numDelta);
+ });
+ }
+
+ override set height(val: number) {
+ if (this._selfSizeMode) {
+ super.height = val;
+ return;
+ }
+ const preHeight = this.height;
+ const numDelta = val - preHeight;
+ this._objects.forEach((o) => {
+ o.resize(undefined, o.height + numDelta);
+ });
+ }
+
+ override get maxZIndex() {
+ let maxZIndex = 0;
+ for (const object of this._objects) {
+ maxZIndex = Math.max(maxZIndex, object.zIndex);
+ }
+ return maxZIndex;
+ }
+
+ openSelfSizeMode() {
+ this._selfSizeMode = true;
+ }
+
+ closeSelfSizeMode() {
+ this._selfSizeMode = false;
+ }
+
+ reCalculateObjects() {
+ if (this._selfSizeMode) {
+ return;
+ }
+ const state = this.getState();
+ const { left = 0, top = 0 } = state;
+ for (const object of this._objects) {
+ object.transformByState({
+ left: object.left - left,
+ top: object.top - top,
+ });
+ }
+
+ this.transformByState({
+ left,
+ top,
+ });
+ }
+
addObjects(...objects: BaseObject[]) {
for (const object of objects) {
this.addObject(object);
@@ -100,11 +198,50 @@ export class Group extends BaseObject {
}
}
+ removeSelfObjectAndTransform(oKey: string, width?: number, height?: number, isTransform = false) {
+ const objects = [...this.getObjects()];
+ const objectsLength = objects.length;
+
+ if (width == null) {
+ width = this.width;
+ }
+
+ if (height == null) {
+ height = this.height;
+ }
+
+ for (let i = 0; i < objectsLength; i++) {
+ const o = objects[i];
+ if (o.oKey === oKey) {
+ objects.splice(i, 1);
+ isTransform && this._transformObject(o, width, height);
+ o.parent = this.parent;
+ o.groupKey = undefined;
+ o.isInGroup = false;
+
+ this._objects = objects;
+ return;
+ }
+ }
+ }
+
+ private _transformObject(object: BaseObject, groupWidth: number, groupHeight: number) {
+ const transform = transformObjectOutOfGroup(object.getState(), this.getState(), groupWidth, groupHeight);
+ if (object.classType === RENDER_CLASS_TYPE.GROUP) {
+ object.transformByState({
+ left: transform.left,
+ top: transform.top,
+ });
+ } else {
+ object.transformByState(transform);
+ }
+ }
+
getObjectsByOrder() {
const objects: BaseObject[] = [];
this._objects.sort(sortRules);
for (const o of this._objects) {
- if (!o.isInGroup && o.visible) {
+ if (o.visible) {
objects.push(o);
}
}
@@ -119,8 +256,8 @@ export class Group extends BaseObject {
ctx.save();
const m = this.transform.getMatrix();
ctx.transform(m[0], m[1], m[2], m[3], m[4], m[5]);
- this._objects.sort(sortRules);
- for (const object of this._objects) {
+ const objects = this.getObjectsByOrder();
+ for (const object of objects) {
object.render(ctx, this._transformBounds(bounds));
}
ctx.restore();
diff --git a/packages/engine-render/src/index.ts b/packages/engine-render/src/index.ts
index 19b1a4a6bc..54278e74f0 100644
--- a/packages/engine-render/src/index.ts
+++ b/packages/engine-render/src/index.ts
@@ -49,3 +49,4 @@ export type { IPageRenderConfig } from './components/docs/document';
export { DocumentSkeleton } from './components/docs/layout/doc-skeleton';
export { ThinEngine } from './thin-engine';
export { getCharSpaceApply, getNumberUnitValue } from './components/docs/layout/tools';
+export { type IChangeObserverConfig } from './scene.transformer';
diff --git a/packages/engine-render/src/layer.ts b/packages/engine-render/src/layer.ts
index 7058a0cd62..84400cc7fc 100644
--- a/packages/engine-render/src/layer.ts
+++ b/packages/engine-render/src/layer.ts
@@ -112,7 +112,6 @@ export class Layer extends Disposable {
this._objects.push(o);
this.scene.setObjectBehavior(o);
this._layerBehavior(o);
- this.scene.applyTransformer(o);
return this;
}
diff --git a/packages/engine-render/src/scene-viewer.ts b/packages/engine-render/src/scene-viewer.ts
index a05bad0df5..3cea8c5046 100644
--- a/packages/engine-render/src/scene-viewer.ts
+++ b/packages/engine-render/src/scene-viewer.ts
@@ -130,8 +130,7 @@ export class SceneViewer extends BaseObject {
return;
}
- const trans = this.transform.clone().invert();
- const tCoord = trans.applyPoint(coord);
+ const tCoord = this.transform.invert().applyPoint(coord);
return this._activeSubScene?.pick(tCoord);
}
diff --git a/packages/engine-render/src/scene.transformer.ts b/packages/engine-render/src/scene.transformer.ts
index da591ba2a5..54c79d6c32 100644
--- a/packages/engine-render/src/scene.transformer.ts
+++ b/packages/engine-render/src/scene.transformer.ts
@@ -14,8 +14,8 @@
* limitations under the License.
*/
-import type { IKeyValue, Nullable, Observer } from '@univerjs/core';
-import { Disposable, Observable, toDisposable } from '@univerjs/core';
+import type { IAbsoluteTransform, IKeyValue, Nullable, Observer } from '@univerjs/core';
+import { Disposable, MOVE_BUFFER_VALUE, Observable, requestImmediateMacroTask, toDisposable } from '@univerjs/core';
import type { BaseObject } from './base-object';
import { CURSOR_TYPE } from './basics/const';
@@ -23,8 +23,16 @@ import type { IMouseEvent, IPointerEvent } from './basics/i-events';
import { getCurrentScrollXY } from './basics/scroll-xy';
import { Group } from './group';
import { ScrollTimer } from './scroll-timer';
+import type { IRectProps } from './shape/rect';
import { Rect } from './shape/rect';
-import type { ThinScene } from './thin-scene';
+
+import { degToRad, precisionTo, radToDeg } from './basics/tools';
+import type { Scene } from './scene';
+import type { IPoint } from './basics/vector2';
+import { Vector2 } from './basics/vector2';
+import type { ITransformerConfig } from './basics/transformer-config';
+import { type IRegularPolygonProps, RegularPolygon } from './shape/regular-polygon';
+import { offsetRotationAxis } from './basics/offset-rotation-axis';
enum TransformerManagerType {
RESIZE_LT = '__SpreadsheetTransformerResizeLT__',
@@ -69,48 +77,20 @@ enum MoveObserverType {
MOVE_END,
}
-interface IChangeObserverConfig {
+export interface IChangeObserverConfig {
objects: Map<string, BaseObject>;
moveX?: number;
moveY?: number;
+ angle?: number;
type: MoveObserverType;
}
-export interface ITransformerConfig {
- hoverEnabled?: boolean;
- hoverEnterFunc?: Nullable<(e: IPointerEvent | IMouseEvent) => void>;
- hoverLeaveFunc?: Nullable<(e: IPointerEvent | IMouseEvent) => void>;
-
- rotateEnabled?: boolean;
- rotationSnaps?: number[];
- rotationSnapTolerance?: number;
- rotateAnchorOffset?: number;
- rotateSize?: number;
- rotateCornerRadius?: number;
-
- borderEnabled?: boolean;
- borderStroke?: string;
- borderStrokeWidth?: number;
- borderDash?: number[];
- borderSpacing: number;
-
- resizeEnabled?: boolean;
- enabledAnchors?: number[];
- anchorFill?: string;
- anchorStroke?: string;
- anchorStrokeWidth?: number;
- anchorSize?: number;
- anchorCornerRadius?: number;
-
- keepRatio?: boolean;
- centeredScaling?: boolean;
-
- flipEnabled?: boolean;
- ignoreStroke?: boolean;
- boundBoxFunc?: Nullable<(oldBox: BaseObject, newBox: BaseObject) => BaseObject>;
- useSingleNodeRotation?: boolean;
- shouldOverdrawWholeArea?: boolean;
-}
+const DEFAULT_TRANSFORMER_LAYER_INDEX = 2;
+
+const MINI_WIDTH_LIMIT = 20;
+const MINI_HEIGHT_LIMIT = 20;
+
+const DEFAULT_CONTROL_PLUS_INDEX = 5000;
/**
* Transformer constructor. Transformer is a special type of group that allow you transform
@@ -118,50 +98,40 @@ export interface ITransformerConfig {
* when you resize them. Instead it changes `scaleX` and `scaleY` properties.
*/
export class Transformer extends Disposable implements ITransformerConfig {
- hoverEnabled = false;
+ isCropper: boolean = false;
+ hoverEnabled = false;
hoverEnterFunc: Nullable<(e: IPointerEvent | IMouseEvent) => void>;
-
hoverLeaveFunc: Nullable<(e: IPointerEvent | IMouseEvent) => void>;
resizeEnabled = true;
rotateEnabled = true;
-
rotationSnaps: number[] = [];
-
rotationSnapTolerance = 5;
-
rotateAnchorOffset = 50;
-
rotateSize = 10;
rotateCornerRadius = 10;
-
borderEnabled = true;
borderStroke = 'rgb(97, 97, 97)';
-
borderStrokeWidth = 1;
-
borderDash: number[] = [];
-
- borderSpacing = 10;
+ borderSpacing = 0;
anchorFill = 'rgb(255,255,255)';
-
anchorStroke = 'rgb(185,185,185)';
-
anchorStrokeWidth = 1;
-
anchorSize = 10;
-
anchorCornerRadius = 10;
keepRatio = true;
-
centeredScaling = false;
+ zeroLeft = 0;
+ zeroTop = 0;
+
/**
* leftTop centerTop rightTop
* leftMiddle rightMiddle
@@ -176,116 +146,267 @@ export class Transformer extends Disposable implements ITransformerConfig {
boundBoxFunc: Nullable<(oldBox: BaseObject, newBox: BaseObject) => BaseObject>;
useSingleNodeRotation: boolean = false;
-
shouldOverdrawWholeArea: boolean = false;
onChangeStartObservable = new Observable<IChangeObserverConfig>();
-
onChangingObservable = new Observable<IChangeObserverConfig>();
-
onChangeEndObservable = new Observable<IChangeObserverConfig>();
- onClearControlObservable = new Observable<null>();
-
+ onClearControlObservable = new Observable<boolean>();
onCreateControlObservable = new Observable<Group>();
private _startOffsetX: number = -1;
-
private _startOffsetY: number = -1;
- private _viewportScrollX: number = -1;
+ private _startStateMap = new Map<string, IAbsoluteTransform>();
+ private _viewportScrollX: number = -1;
private _viewportScrollY: number = -1;
private _moveObserver: Nullable<Observer<IPointerEvent | IMouseEvent>>;
-
private _upObserver: Nullable<Observer<IPointerEvent | IMouseEvent>>;
-
private _cancelFocusObserver: Nullable<Observer<IPointerEvent | IMouseEvent>>;
private _transformerControlMap = new Map<string, Group>();
-
private _selectedObjectMap = new Map<string, BaseObject>();
+ private _observerObjectMap = new Map<string, Nullable<Observer<IPointerEvent | IMouseEvent>>>();
+ private _copperControl: Nullable<Group>;
+ private _copperSelectedObject: Nullable<BaseObject>;
+
+ private _moveBufferSkip = false;
+
+ private _debounceClearFunc: Nullable<() => void>;
constructor(
- private _scene: ThinScene,
+ private _scene: Scene,
config?: ITransformerConfig
) {
super();
this._initialProps(config);
}
+ changeNotification() {
+ this.onChangingObservable.notifyObservers({
+ objects: this._selectedObjectMap,
+ type: MoveObserverType.MOVE_START,
+ });
+ return this;
+ }
+
+ getSelectedObjectMap() {
+ return this._selectedObjectMap;
+ }
+
+ resetProps(config?: ITransformerConfig) {
+ this._initialProps(config);
+ }
+
getScene() {
return this._scene;
}
- hideControl() {
- this._hideControl();
+ clearControls(changeSelf = false) {
+ this._clearControls(changeSelf);
}
- attachTo(applyObject: BaseObject) {
- if (!applyObject.isTransformer) {
- return;
+ updateControl() {
+ this._updateControl();
+ }
+
+ debounceRefreshControls() {
+ if (this._debounceClearFunc) {
+ this._debounceClearFunc();
+ }
+
+ // To prevent multiple refreshes caused by setting values for multiple object instances at once.
+ this._debounceClearFunc = requestImmediateMacroTask(() => {
+ this.refreshControls();
+ this._debounceClearFunc = null;
+ });
+ }
+
+ clearSelectedObjects() {
+ this._selectedObjectMap.clear();
+ this._cancelFocusObserver?.dispose();
+ this._clearControls(true);
+ }
+
+ refreshControls() {
+ this._clearControlMap();
+ this._selectedObjectMap.forEach((object) => {
+ this._createControl(object);
+ });
+ return this;
+ }
+
+ createControlForCopper(applyObject: BaseObject) {
+ this._createControl(applyObject, false);
+ }
+
+ clearCopperControl() {
+ this._copperControl?.dispose();
+ this._copperControl = null;
+ }
+
+ setSelectedControl(applyObject: BaseObject) {
+ applyObject = this._findGroupObject(applyObject);
+ this._selectedObjectMap.set(applyObject.oKey, applyObject);
+ this._createControl(applyObject);
+ }
+
+ // eslint-disable-next-line complexity
+ private _getConfig(applyObject: BaseObject) {
+ const objectTransformerConfig = applyObject.transformerConfig;
+ let {
+ isCropper, hoverEnabled, hoverEnterFunc, hoverLeaveFunc, resizeEnabled,
+ rotateEnabled, rotationSnaps, rotationSnapTolerance, rotateAnchorOffset, rotateSize, rotateCornerRadius,
+ borderEnabled, borderStroke, borderStrokeWidth, borderDash, borderSpacing,
+ anchorFill, anchorStroke, anchorStrokeWidth, anchorSize, anchorCornerRadius,
+ keepRatio, centeredScaling, enabledAnchors, flipEnabled, ignoreStroke,
+ boundBoxFunc, useSingleNodeRotation, shouldOverdrawWholeArea,
+ } = this;
+ if (objectTransformerConfig != null) {
+ isCropper = objectTransformerConfig.isCropper ?? isCropper;
+ hoverEnabled = objectTransformerConfig.hoverEnabled ?? hoverEnabled;
+ hoverEnterFunc = objectTransformerConfig.hoverEnterFunc ?? hoverEnterFunc;
+ hoverLeaveFunc = objectTransformerConfig.hoverLeaveFunc ?? hoverLeaveFunc;
+ resizeEnabled = objectTransformerConfig.resizeEnabled ?? resizeEnabled;
+ rotateEnabled = objectTransformerConfig.rotateEnabled ?? rotateEnabled;
+ rotationSnaps = objectTransformerConfig.rotationSnaps ?? rotationSnaps;
+ rotationSnapTolerance = objectTransformerConfig.rotationSnapTolerance ?? rotationSnapTolerance;
+ rotateAnchorOffset = objectTransformerConfig.rotateAnchorOffset ?? rotateAnchorOffset;
+ rotateSize = objectTransformerConfig.rotateSize ?? rotateSize;
+ rotateCornerRadius = objectTransformerConfig.rotateCornerRadius ?? rotateCornerRadius;
+ borderEnabled = objectTransformerConfig.borderEnabled ?? borderEnabled;
+ borderStroke = objectTransformerConfig.borderStroke ?? borderStroke;
+ borderStrokeWidth = objectTransformerConfig.borderStrokeWidth ?? borderStrokeWidth;
+ borderDash = objectTransformerConfig.borderDash ?? borderDash;
+ borderSpacing = objectTransformerConfig.borderSpacing ?? borderSpacing;
+ anchorFill = objectTransformerConfig.anchorFill ?? anchorFill;
+ anchorStroke = objectTransformerConfig.anchorStroke ?? anchorStroke;
+ anchorStrokeWidth = objectTransformerConfig.anchorStrokeWidth ?? anchorStrokeWidth;
+ anchorSize = objectTransformerConfig.anchorSize ?? anchorSize;
+ anchorCornerRadius = objectTransformerConfig.anchorCornerRadius ?? anchorCornerRadius;
+ keepRatio = objectTransformerConfig.keepRatio ?? keepRatio;
+ centeredScaling = objectTransformerConfig.centeredScaling ?? centeredScaling;
+ enabledAnchors = objectTransformerConfig.enabledAnchors ?? enabledAnchors;
+ flipEnabled = objectTransformerConfig.flipEnabled ?? flipEnabled;
+ ignoreStroke = objectTransformerConfig.ignoreStroke ?? ignoreStroke;
+ boundBoxFunc = objectTransformerConfig.boundBoxFunc ?? boundBoxFunc;
+ useSingleNodeRotation = objectTransformerConfig.useSingleNodeRotation ?? useSingleNodeRotation;
+ shouldOverdrawWholeArea = objectTransformerConfig.shouldOverdrawWholeArea ?? shouldOverdrawWholeArea;
}
+ return {
+ isCropper, hoverEnabled, hoverEnterFunc, hoverLeaveFunc, resizeEnabled,
+ rotateEnabled, rotationSnaps, rotationSnapTolerance, rotateAnchorOffset, rotateSize, rotateCornerRadius,
+ borderEnabled, borderStroke, borderStrokeWidth, borderDash, borderSpacing,
+ anchorFill, anchorStroke, anchorStrokeWidth, anchorSize, anchorCornerRadius,
+ keepRatio, centeredScaling, enabledAnchors, flipEnabled, ignoreStroke,
+ boundBoxFunc, useSingleNodeRotation, shouldOverdrawWholeArea,
+ };
+ }
+
+ // eslint-disable-next-line max-lines-per-function
+ attachTo(applyObject: BaseObject) {
if (this.hoverEnabled) {
this.hoverEnterFunc && applyObject.onPointerEnterObserver.add(this.hoverEnterFunc);
this.hoverLeaveFunc && applyObject.onPointerLeaveObserver.add(this.hoverLeaveFunc);
}
- this.disposeWithMe(
- toDisposable(
- applyObject.onPointerDownObserver.add((evt: IPointerEvent | IMouseEvent, state) => {
- const { offsetX: evtOffsetX, offsetY: evtOffsetY } = evt;
- this._startOffsetX = evtOffsetX;
- this._startOffsetY = evtOffsetY;
+ const observer = applyObject.onPointerDownObserver.add((evt: IPointerEvent | IMouseEvent, state) => {
+ const { offsetX: evtOffsetX, offsetY: evtOffsetY } = evt;
+ this._startOffsetX = evtOffsetX;
+ this._startOffsetY = evtOffsetY;
- const scene = this._getTopScene();
+ const { isCropper } = this._getConfig(applyObject);
- if (!scene) {
- return;
- }
+ const scene = this._getTopScene();
- this._addCancelObserver(scene);
+ if (!scene) {
+ return;
+ }
- scene.disableEvent();
+ this._addCancelObserver(scene);
- const scrollTimer = ScrollTimer.create(scene);
- scrollTimer.startScroll(evtOffsetX, evtOffsetY);
+ scene.disableEvent();
- const { scrollX, scrollY } = getCurrentScrollXY(scrollTimer);
+ const scrollTimer = ScrollTimer.create(scene);
+ scrollTimer.startScroll(evtOffsetX, evtOffsetY);
- this._viewportScrollX = scrollX;
- this._viewportScrollY = scrollY;
+ const { scrollX, scrollY } = getCurrentScrollXY(scrollTimer);
- this._updateActiveObjectList(applyObject, evt);
+ this._viewportScrollX = scrollX;
+ this._viewportScrollY = scrollY;
- this._moveObserver = scene.onPointerMoveObserver.add((moveEvt: IPointerEvent | IMouseEvent) => {
- const { offsetX: moveOffsetX, offsetY: moveOffsetY } = moveEvt;
- this._moving(moveOffsetX, moveOffsetY, scrollTimer);
- this._hideControl();
- scrollTimer.scrolling(moveOffsetX, moveOffsetY, () => {
- this._moving(moveOffsetX, moveOffsetY, scrollTimer);
- });
- });
+ if (!isCropper) {
+ this._updateActiveObjectList(applyObject, evt);
+ } else {
+ this._copperSelectedObject = applyObject;
+ }
- this._upObserver = scene.onPointerUpObserver.add(() => {
- scene.onPointerMoveObserver.remove(this._moveObserver);
- scene.onPointerUpObserver.remove(this._upObserver);
- scene.enableEvent();
- this._updateControl();
- scrollTimer.dispose();
+ if (!isCropper) {
+ this.onChangeStartObservable.notifyObservers({
+ objects: this._selectedObjectMap,
+ type: MoveObserverType.MOVE_START,
+ });
+ } else {
+ this.onChangeStartObservable.notifyObservers({
+ objects: new Map([[applyObject.oKey, applyObject]]) as Map<string, BaseObject>,
+ type: MoveObserverType.MOVE_START,
+ });
+ }
- this.onChangeEndObservable.notifyObservers({
- objects: this._selectedObjectMap,
- type: MoveObserverType.MOVE_END,
- });
+ this._moveBufferSkip = false;
+
+ const moveObserver = scene.onPointerMoveObserver.add((moveEvt: IPointerEvent | IMouseEvent) => {
+ const { offsetX: moveOffsetX, offsetY: moveOffsetY } = moveEvt;
+ this._moving(moveOffsetX, moveOffsetY, scrollTimer, isCropper);
+
+ !isCropper && this._clearControlMap();
+
+ scrollTimer.scrolling(moveOffsetX, moveOffsetY, () => {
+ this._moving(moveOffsetX, moveOffsetY, scrollTimer, isCropper);
+ });
+ });
+
+ const upObserver = scene.onPointerUpObserver.add(() => {
+ moveObserver?.dispose();
+ upObserver?.dispose();
+ scene.enableEvent();
+ !isCropper && this.refreshControls();
+ scrollTimer.dispose();
+
+ if (!isCropper) {
+ this.onChangeEndObservable.notifyObservers({
+ objects: this._selectedObjectMap,
+ type: MoveObserverType.MOVE_END,
+ });
+ } else {
+ this.onChangeEndObservable.notifyObservers({
+ objects: new Map([[applyObject.oKey, applyObject]]) as Map<string, BaseObject>,
+ type: MoveObserverType.MOVE_END,
});
+ }
+ });
- state.stopPropagation();
- })
- )
- );
+ state.stopPropagation();
+ });
+
+ this.disposeWithMe(toDisposable(observer));
+
+ this._observerObjectMap.set(applyObject.oKey, observer);
+
+ return applyObject;
+ }
+
+ detachFrom(applyObject: BaseObject) {
+ const observer = this._observerObjectMap.get(applyObject.oKey);
+
+ if (observer) {
+ observer.dispose();
+ this._observerObjectMap.delete(applyObject.oKey);
+ }
return applyObject;
}
@@ -330,186 +451,575 @@ export class Transformer extends Disposable implements ITransformerConfig {
});
}
- private _updateControlChildren() {
- this._updateControlIterator((control, applyObject) => {
- const { left, top, width, height, scaleX, scaleY } = applyObject.getState();
- const children = control.getObjects();
- children.forEach((o: BaseObject) => {
- const key = o.oKey;
- const type = this._checkTransformerType(key);
-
- if (!type) {
- return true;
- }
+ private _checkMoveBoundary(moveObject: BaseObject, moveLeft: number, moveTop: number, ancestorLeft: number, ancestorTop: number, topSceneWidth: number, topSceneHeight: number) {
+ const { left, top, width, height } = moveObject;
- if (type === TransformerManagerType.OUTLINE) {
- o.transformByState(this._getOutlinePosition(width, height, scaleX, scaleY));
- } else {
- const { left, top } = this._getRotateAnchorPosition(type, height, width);
- o.transformByState({
- left,
- top,
- });
- }
+ if (moveLeft + left + ancestorLeft < this.zeroLeft) {
+ moveLeft = -ancestorLeft;
+ }
+
+ if (moveTop + top + ancestorTop < this.zeroTop) {
+ moveTop = -ancestorTop;
+ }
+
+ if (moveLeft + left + width + ancestorLeft > topSceneWidth) {
+ moveLeft = topSceneWidth - width - left - ancestorLeft;
+ }
+
+ if (moveTop + top + height + ancestorTop > topSceneHeight) {
+ moveTop = topSceneHeight - height - top - ancestorTop;
+ }
+
+ return {
+ moveLeft,
+ moveTop,
+ };
+ }
+
+ private _moving(moveOffsetX: number, moveOffsetY: number, scrollTimer: ScrollTimer, isCropper = false) {
+ const { scrollX, scrollY } = getCurrentScrollXY(scrollTimer);
+ const x = moveOffsetX - this._viewportScrollX + scrollX;
+ const y = moveOffsetY - this._viewportScrollY + scrollY;
+
+ const { ancestorScaleX, ancestorScaleY, ancestorLeft, ancestorTop } = this._scene;
+
+ let moveLeft = this._smoothAccuracy((x - this._startOffsetX) / ancestorScaleX, isCropper);
+ let moveTop = this._smoothAccuracy((y - this._startOffsetY) / ancestorScaleY, isCropper);
+
+ if (this._moveBufferBlocker(moveOffsetX, moveOffsetY)) {
+ return;
+ }
+
+ const topScene = this._getTopScene();
+ if (!topScene) {
+ return;
+ }
+
+ const { width: topSceneWidth, height: topSceneHeight } = topScene;
+
+ if (!isCropper) {
+ const selectedObjects = Array.from(this._selectedObjectMap.values());
+ // move boundary check
+ for (let i = 0; i < selectedObjects.length; i++) {
+ const moveObject = selectedObjects[i];
+ const boundary = this._checkMoveBoundary(moveObject, moveLeft, moveTop, ancestorLeft, ancestorTop, topSceneWidth, topSceneHeight);
+
+ moveLeft = boundary.moveLeft;
+ moveTop = boundary.moveTop;
+ }
+
+ this._selectedObjectMap.forEach((moveObject) => {
+ moveObject.translate(moveLeft + moveObject.left, moveTop + moveObject.top);
});
- control.transformByState({
- left,
- top,
+ this.onChangingObservable.notifyObservers({
+ objects: this._selectedObjectMap,
+ moveX: moveLeft,
+ moveY: moveTop,
+ type: MoveObserverType.MOVING,
});
- });
+ } else if (this._copperSelectedObject) {
+ const cropper = this._copperSelectedObject;
+ // move boundary check
+ const boundary = this._checkMoveBoundary(cropper, moveLeft, moveTop, ancestorLeft, ancestorTop, topSceneWidth, topSceneHeight);
+
+ moveLeft = boundary.moveLeft;
+ moveTop = boundary.moveTop;
+
+ cropper.translate(moveLeft + cropper.left, moveTop + cropper.top);
+ this.onChangingObservable.notifyObservers({
+ objects: new Map([[cropper.oKey, cropper]]) as Map<string, BaseObject>,
+ moveX: moveLeft,
+ moveY: moveTop,
+ type: MoveObserverType.MOVING,
+ });
+ }
+
+ this._startOffsetX = x;
+ this._startOffsetY = y;
+ }
+
+ private _moveBufferBlocker(x: number, y: number) {
+ if (!this._moveBufferSkip && Math.abs(x - this._startOffsetX) < MOVE_BUFFER_VALUE && Math.abs(y - this._startOffsetY) < MOVE_BUFFER_VALUE) {
+ return true;
+ }
+ this._moveBufferSkip = true;
+ return false;
}
private _anchorMoving(
type: TransformerManagerType,
moveOffsetX: number,
moveOffsetY: number,
- scrollTimer: ScrollTimer
+ scrollTimer: ScrollTimer,
+ keepRatio: boolean,
+ isCropper = false,
+ applyObject: BaseObject
) {
const { scrollX, scrollY } = getCurrentScrollXY(scrollTimer);
const x = moveOffsetX - this._viewportScrollX + scrollX;
const y = moveOffsetY - this._viewportScrollY + scrollY;
- const moveLeft = x - this._startOffsetX;
- const moveTop = y - this._startOffsetY;
+ if (this._moveBufferBlocker(moveOffsetX, moveOffsetY)) {
+ return;
+ }
- this._selectedObjectMap.forEach((moveObject) => {
- // console.log(moveLeft + moveObject.width, moveTop + moveObject.height);
- const { left, top, width, height } = moveObject;
- const state: ITransformState = {};
+ const isGroup = applyObject instanceof Group;
+ if (!isCropper) {
+ this._selectedObjectMap.forEach((moveObject) => {
+ this._moveFunc(moveObject, type, x, y, keepRatio, isCropper, isGroup);
+ });
+ this.onChangingObservable.notifyObservers({
+ objects: this._selectedObjectMap,
+ type: MoveObserverType.MOVING,
+ });
+ } else {
+ // for cropper
+ this._moveFunc(applyObject, type, x, y, keepRatio, isCropper, isGroup);
+ this.onChangingObservable.notifyObservers({
+ objects: new Map([[applyObject.oKey, applyObject]]) as Map<string, BaseObject>,
+ type: MoveObserverType.MOVING,
+ });
+ }
+
+ if (!(keepRatio && type !== TransformerManagerType.RESIZE_CT && type !== TransformerManagerType.RESIZE_CB && type !== TransformerManagerType.RESIZE_LM && type !== TransformerManagerType.RESIZE_RM && !isGroup)) {
+ this._startOffsetX = x;
+ this._startOffsetY = y;
+ }
+ }
+
+ private _moveFunc(moveObject: BaseObject, type: TransformerManagerType, x: number, y: number, keepRatio: boolean, isCropper: boolean = false, isGroup: boolean = false) {
+ const { left, top, width, height, angle } = moveObject;
+ const originState = this._startStateMap.get(moveObject.oKey) || {};
+ let state: ITransformState = {};
+
+ const { moveLeft, moveTop } = this._getMovePoint(x, y, moveObject);
+
+ if (keepRatio && type !== TransformerManagerType.RESIZE_CT && type !== TransformerManagerType.RESIZE_CB && type !== TransformerManagerType.RESIZE_LM && type !== TransformerManagerType.RESIZE_RM && !isGroup) {
switch (type) {
case TransformerManagerType.RESIZE_LT:
- state.left = left + moveLeft;
- state.top = top + moveTop;
- state.width = width - moveLeft;
- state.height = height - moveTop;
- break;
- case TransformerManagerType.RESIZE_CT:
- state.top = top + moveTop;
- state.height = height - moveTop;
+ state = this._resizeLeftTop(moveObject, moveLeft, moveTop, originState);
break;
case TransformerManagerType.RESIZE_RT:
- state.top = top + moveTop;
- state.width = width + moveLeft;
- state.height = height - moveTop;
- break;
- case TransformerManagerType.RESIZE_LM:
- state.left = left + moveLeft;
- state.width = width - moveLeft;
- break;
- case TransformerManagerType.RESIZE_RM:
- state.width = moveLeft + width;
+ state = this._resizeRightTop(moveObject, moveLeft, moveTop, originState);
break;
case TransformerManagerType.RESIZE_LB:
- state.left = left + moveLeft;
- state.width = width - moveLeft;
- state.height = height + moveTop;
- break;
- case TransformerManagerType.RESIZE_CB:
- state.height = moveTop + height;
+ state = this._resizeLeftBottom(moveObject, moveLeft, moveTop, originState);
break;
case TransformerManagerType.RESIZE_RB:
- state.width = moveLeft + width;
- state.height = moveTop + height;
+ state = this._resizeRightBottom(moveObject, moveLeft, moveTop, originState);
break;
}
- moveObject.transformByState(state);
- });
+ } else {
+ state = this._updateCloseKeepRatioState(type, left, top, width, height, moveLeft, moveTop);
+ }
- this._updateControlChildren();
+ moveObject.transformByState(this._applyRotationForResult(state, { left, top, width, height }, angle, isCropper));
+ };
- this.onChangingObservable.notifyObservers({
- objects: this._selectedObjectMap,
- moveX: moveLeft,
- moveY: moveTop,
- type: MoveObserverType.MOVING,
- });
+ private _getMovePoint(x: number, y: number, moveObject: BaseObject) {
+ const { ancestorScaleX, ancestorScaleY } = this._scene;
+ const { left, top, width, height, angle } = moveObject;
- this._startOffsetX = x;
- this._startOffsetY = y;
+ const cx = left + width / 2;
+ const cy = top + height / 2;
+ const centerPoint = new Vector2(cx, cy);
+
+ const xyPoint = new Vector2(x, y);
+ xyPoint.rotateByPoint(degToRad(-angle), centerPoint);
+
+ const startPoint = new Vector2(this._startOffsetX, this._startOffsetY);
+ startPoint.rotateByPoint(degToRad(-angle), centerPoint);
+
+ const moveLeft = (xyPoint.x - startPoint.x) / ancestorScaleX;
+ const moveTop = (xyPoint.y - startPoint.y) / ancestorScaleY;
+
+ return {
+ moveLeft,
+ moveTop,
+ };
+ }
+
+ /**
+ *
+ */
+ private _applyRotationForResult(newsState: ITransformState, oldState: ITransformState, angle: number, isCropper = false) {
+ if (angle === 0) {
+ return newsState;
+ }
+
+ const { left = 0, top = 0, width = 0, height = 0 } = newsState;
+ const { left: oldLeft = 0, top: oldTop = 0, width: oldWidth = 0, height: oldHeight = 0 } = oldState;
+
+ const oldCx = oldWidth / 2;
+ const oldCy = oldHeight / 2;
+
+ const newCx = width / 2 + left - oldLeft;
+ const newCy = height / 2 + top - oldTop;
+
+ const finalPoint = offsetRotationAxis(new Vector2(oldCx, oldCy), angle, new Vector2(left, top), new Vector2(newCx, newCy));
+
+ return {
+ width: this._smoothAccuracy(width, isCropper),
+ height: this._smoothAccuracy(height, isCropper),
+ left: this._smoothAccuracy(finalPoint.x, isCropper),
+ top: this._smoothAccuracy(finalPoint.y, isCropper),
+ };
+ }
+
+ // eslint-disable-next-line complexity
+ private _updateCloseKeepRatioState(type: TransformerManagerType, left: number, top: number, width: number, height: number, moveLeft: number, moveTop: number) {
+ const state: ITransformState = { left, top, width, height };
+
+ switch (type) {
+ case TransformerManagerType.RESIZE_LT:
+ state.width = width - moveLeft < MINI_WIDTH_LIMIT ? MINI_WIDTH_LIMIT : width - moveLeft;
+ state.height = height - moveTop < MINI_HEIGHT_LIMIT ? MINI_HEIGHT_LIMIT : height - moveTop;
+ state.left = left + width - state.width;
+ state.top = top + height - state.height;
+ break;
+ case TransformerManagerType.RESIZE_CT:
+ state.height = height - moveTop < MINI_HEIGHT_LIMIT ? MINI_HEIGHT_LIMIT : height - moveTop;
+ state.top = top + height - state.height;
+ break;
+ case TransformerManagerType.RESIZE_RT:
+ state.width = width + moveLeft < MINI_WIDTH_LIMIT ? MINI_WIDTH_LIMIT : width + moveLeft;
+ state.height = height - moveTop < MINI_HEIGHT_LIMIT ? MINI_HEIGHT_LIMIT : height - moveTop;
+ state.top = top + height - state.height;
+ break;
+ case TransformerManagerType.RESIZE_LM:
+ state.width = width - moveLeft < MINI_WIDTH_LIMIT ? MINI_WIDTH_LIMIT : width - moveLeft;
+ state.left = left + width - state.width;
+ break;
+ case TransformerManagerType.RESIZE_RM:
+ state.width = moveLeft + width < MINI_WIDTH_LIMIT ? MINI_WIDTH_LIMIT : moveLeft + width;
+ break;
+ case TransformerManagerType.RESIZE_LB:
+ state.width = width - moveLeft < MINI_WIDTH_LIMIT ? MINI_WIDTH_LIMIT : width - moveLeft;
+ state.height = height + moveTop < MINI_HEIGHT_LIMIT ? MINI_HEIGHT_LIMIT : height + moveTop;
+ state.left = left + moveLeft;
+ break;
+ case TransformerManagerType.RESIZE_CB:
+ state.height = moveTop + height < MINI_HEIGHT_LIMIT ? MINI_HEIGHT_LIMIT : moveTop + height;
+ break;
+ case TransformerManagerType.RESIZE_RB:
+ state.width = moveLeft + width < MINI_WIDTH_LIMIT ? MINI_WIDTH_LIMIT : moveLeft + width;
+ state.height = moveTop + height < MINI_HEIGHT_LIMIT ? MINI_HEIGHT_LIMIT : moveTop + height;
+ break;
+ }
+
+ return state;
+ }
+
+ private _getLimitedSize(newWidth: number, newHeight: number) {
+ let limitWidth = MINI_WIDTH_LIMIT;
+ let limitHeight = MINI_HEIGHT_LIMIT;
+ if (newWidth > newHeight) {
+ limitWidth = limitWidth * Math.abs(newWidth / newHeight);
+ } else {
+ limitHeight = limitHeight * Math.abs(newHeight / newWidth);
+ }
+
+ return {
+ limitWidth,
+ limitHeight,
+ };
+ }
+
+ private _resizeLeftTop(moveObject: BaseObject, moveLeft: number, moveTop: number, originState: IAbsoluteTransform): ITransformState {
+ const { left = 0, top = 0, width = 0, height = 0 } = moveObject.getState();
+ const { width: originWidth = width, height: originHeight = height, left: originLeft = left, top: originTop = top } = originState;
+ const aspectRatio = originWidth / originHeight;
+
+ const { moveLeft: moveLeftFix, moveTop: moveTopFix } = this._fixMoveLtRb(moveLeft, moveTop, originWidth, originHeight, aspectRatio);
+
+ let newWidth = originWidth - moveLeftFix;
+ let newHeight = originHeight - moveTopFix;
+
+ const { limitWidth, limitHeight } = this._getLimitedSize(originWidth, originHeight);
+ if (newWidth < limitWidth) {
+ newWidth = limitWidth;
+ }
+ if (newHeight < limitHeight) {
+ newHeight = limitHeight;
+ }
+
+ return {
+ left: left + width - newWidth,
+ top: top + height - newHeight,
+ width: newWidth,
+ height: newHeight,
+ };
+ }
+
+ private _resizeRightBottom(moveObject: BaseObject, moveLeft: number, moveTop: number, originState: IAbsoluteTransform): ITransformState {
+ const { left = 0, top = 0, width = 0, height = 0 } = moveObject.getState();
+ const { width: originWidth = width, height: originHeight = height, left: originLeft = left, top: originTop = top } = originState;
+ const aspectRatio = originWidth / originHeight;
+
+ const { moveLeft: moveLeftFix, moveTop: moveTopFix } = this._fixMoveLtRb(moveLeft, moveTop, originWidth, originHeight, aspectRatio);
+
+ let newWidth = originWidth + moveLeftFix;
+ let newHeight = originHeight + moveTopFix;
+
+ const { limitWidth, limitHeight } = this._getLimitedSize(originWidth, originHeight);
+ if (newWidth < limitWidth) {
+ newWidth = limitWidth;
+ }
+ if (newHeight < limitHeight) {
+ newHeight = limitHeight;
+ }
+
+ return {
+ left,
+ top,
+ width: newWidth,
+ height: newHeight,
+ };
+ }
+
+ private _resizeLeftBottom(moveObject: BaseObject, moveLeft: number, moveTop: number, originState: IAbsoluteTransform): ITransformState {
+ const { left = 0, top = 0, width = 0, height = 0 } = moveObject.getState();
+ const { width: originWidth = width, height: originHeight = height, left: originLeft = left, top: originTop = top } = originState;
+ const aspectRatio = originWidth / originHeight;
+
+ const { moveLeft: moveLeftFix, moveTop: moveTopFix } = this._fixMoveLbRt(moveLeft, moveTop, originWidth, originHeight, aspectRatio);
+
+ let newWidth = originWidth - moveLeftFix;
+ let newHeight = originHeight + moveTopFix;
+
+ const { limitWidth, limitHeight } = this._getLimitedSize(originWidth, originHeight);
+ if (newWidth < limitWidth) {
+ newWidth = limitWidth;
+ }
+ if (newHeight < limitHeight) {
+ newHeight = limitHeight;
+ }
+
+ return {
+ left: left + width - newWidth,
+ top,
+ width: newWidth,
+ height: newHeight,
+ };
+ }
+
+ private _resizeRightTop(moveObject: BaseObject, moveLeft: number, moveTop: number, originState: IAbsoluteTransform): ITransformState {
+ const { left = 0, top = 0, width = 0, height = 0 } = moveObject.getState();
+ const { width: originWidth = width, height: originHeight = height, left: originLeft = left, top: originTop = top } = originState;
+ const aspectRatio = originWidth / originHeight;
+
+ const { moveLeft: moveLeftFix, moveTop: moveTopFix } = this._fixMoveLbRt(moveLeft, moveTop, originWidth, originHeight, aspectRatio);
+
+ let newWidth = originWidth + moveLeftFix;
+ let newHeight = originHeight - moveTopFix;
+
+ const { limitWidth, limitHeight } = this._getLimitedSize(originWidth, originHeight);
+ if (newWidth < limitWidth) {
+ newWidth = limitWidth;
+ }
+ if (newHeight < limitHeight) {
+ newHeight = limitHeight;
+ }
+
+ return {
+ left,
+ top: top + height - newHeight,
+ width: newWidth,
+ height: newHeight,
+ };
+ }
+
+ private _fixMoveLtRb(moveLeft: number, moveTop: number, originWidth: number, originHeight: number, aspectRatio: number) {
+ let moveLeftFix = moveLeft;
+ let moveTopFix = moveTop;
+
+ if ((originWidth + moveLeftFix) / (originHeight + moveTopFix) > aspectRatio) {
+ moveTopFix = moveLeftFix / aspectRatio;
+ } else {
+ moveLeftFix = moveTopFix * aspectRatio;
+ }
+
+ return {
+ moveLeft: moveLeftFix,
+ moveTop: moveTopFix,
+ };
}
- private _attachEventToAnchor(anchor: Rect, type = TransformerManagerType.RESIZE_LT) {
+ private _fixMoveLbRt(moveLeft: number, moveTop: number, originWidth: number, originHeight: number, aspectRatio: number) {
+ let moveLeftFix = moveLeft;
+ let moveTopFix = moveTop;
+
+ if (Math.abs((originWidth - moveLeftFix) / (originHeight + moveTopFix)) > aspectRatio) {
+ moveTopFix = -moveLeftFix / aspectRatio;
+ } else {
+ moveLeftFix = -moveTopFix * aspectRatio;
+ }
+
+ return {
+ moveLeft: moveLeftFix,
+ moveTop: moveTopFix,
+ };
+ }
+
+ private _attachEventToAnchor(anchor: BaseObject, type = TransformerManagerType.RESIZE_LT, applyObject: BaseObject) {
this.disposeWithMe(
toDisposable(
anchor.onPointerDownObserver.add((evt: IPointerEvent | IMouseEvent, state) => {
const { offsetX: evtOffsetX, offsetY: evtOffsetY } = evt;
this._startOffsetX = evtOffsetX;
this._startOffsetY = evtOffsetY;
-
- const scene = this._getTopScene();
-
- if (scene == null) {
+ const topScene = this._getTopScene();
+ const { keepRatio, isCropper } = this._getConfig(applyObject);
+ if (topScene == null) {
return;
}
-
- scene.disableEvent();
-
- const scrollTimer = ScrollTimer.create(scene);
+ topScene.disableEvent();
+ const scrollTimer = ScrollTimer.create(topScene);
scrollTimer.startScroll(evtOffsetX, evtOffsetY);
-
const { scrollX, scrollY } = getCurrentScrollXY(scrollTimer);
-
this._viewportScrollX = scrollX;
this._viewportScrollY = scrollY;
+ const { ancestorLeft, ancestorTop } = this._scene;
+ const { width: topSceneWidth, height: topSceneHeight } = topScene;
const cursor = this._getRotateAnchorCursor(type);
+ if (!isCropper) {
+ this._clearControlMap();
+ this.onChangeStartObservable.notifyObservers({
+ objects: this._selectedObjectMap,
+ type: MoveObserverType.MOVE_START,
+ });
+ this._selectedObjectMap.forEach((moveObject) => {
+ const { width, height, left, top } = moveObject.getState();
+ this._startStateMap.set(moveObject.oKey, { width, height, left, top });
+ });
+ } else {
+ // for cropper
+ this.onChangeStartObservable.notifyObservers({
+ objects: new Map([[applyObject.oKey, applyObject]]) as Map<string, BaseObject>,
+ type: MoveObserverType.MOVE_START,
+ });
+ const { width, height, left, top } = applyObject.getState();
+ this._startStateMap.set(applyObject.oKey, { width, height, left, top });
+ }
- this._moveObserver = scene.onPointerMoveObserver.add((moveEvt: IPointerEvent | IMouseEvent) => {
+ this._moveBufferSkip = false;
+ this._moveObserver = topScene.onPointerMoveObserver.add((moveEvt: IPointerEvent | IMouseEvent) => {
const { offsetX: moveOffsetX, offsetY: moveOffsetY } = moveEvt;
- this._anchorMoving(type, moveOffsetX, moveOffsetY, scrollTimer);
+ this._anchorMoving(type, moveOffsetX, moveOffsetY, scrollTimer, keepRatio, isCropper, applyObject);
scrollTimer.scrolling(moveOffsetX, moveOffsetY, () => {
- this._anchorMoving(type, moveOffsetX, moveOffsetY, scrollTimer);
+ this._anchorMoving(type, moveOffsetX, moveOffsetY, scrollTimer, keepRatio, isCropper, applyObject);
});
- scene.setCursor(cursor);
+ topScene.setCursor(cursor);
});
- this._upObserver = scene.onPointerUpObserver.add(() => {
- scene.onPointerMoveObserver.remove(this._moveObserver);
- scene.onPointerUpObserver.remove(this._upObserver);
- scene.enableEvent();
- scene.resetCursor();
+ this._upObserver = topScene.onPointerUpObserver.add(() => {
+ topScene.onPointerMoveObserver.remove(this._moveObserver);
+ topScene.onPointerUpObserver.remove(this._upObserver);
+ topScene.enableEvent();
+ topScene.resetCursor();
scrollTimer.dispose();
-
- this.onChangeEndObservable.notifyObservers({
- objects: this._selectedObjectMap,
- type: MoveObserverType.MOVE_END,
- });
+ this._startStateMap.clear();
+ if (!isCropper) {
+ this._recoverySizeBoundary(Array.from(this._selectedObjectMap.values()), ancestorLeft, ancestorTop, topSceneWidth, topSceneHeight);
+ this.onChangeEndObservable.notifyObservers({
+ objects: this._selectedObjectMap,
+ type: MoveObserverType.MOVE_END,
+ });
+ } else {
+ this._recoverySizeBoundary([applyObject], ancestorLeft, ancestorTop, topSceneWidth, topSceneHeight);
+ this.onChangeEndObservable.notifyObservers({
+ objects: new Map([[applyObject.oKey, applyObject]]) as Map<string, BaseObject>,
+ type: MoveObserverType.MOVE_END,
+ });
+ }
+ this.refreshControls();
});
-
state.stopPropagation();
})
)
);
}
- private _attachEventToRotate(rotateControl: Rect) {
+ private _recoverySizeBoundary(selectedObjects: BaseObject[], ancestorLeft: number, ancestorTop: number, topSceneWidth: number, topSceneHeight: number) {
+ for (let i = 0; i < selectedObjects.length; i++) {
+ const moveObject = selectedObjects[i];
+ const { left, top, width, height } = moveObject;
+
+ const newTransform: ITransformState = {};
+
+ if (left + ancestorLeft < this.zeroLeft) {
+ newTransform.left = -ancestorLeft;
+ newTransform.width = width + left;
+ } else if (left + width + ancestorLeft > topSceneWidth) {
+ newTransform.width = topSceneWidth - left - ancestorLeft;
+ }
+
+ if (top + ancestorTop < this.zeroTop) {
+ newTransform.top = -ancestorTop;
+ newTransform.height = height + top;
+ } else if (top + height + ancestorTop > topSceneHeight) {
+ newTransform.height = topSceneHeight - top - ancestorTop;
+ }
+
+ moveObject.transformByState(newTransform);
+ }
+ }
+
+ private _attachEventToRotate(rotateControl: Rect, applyObject: BaseObject) {
this.disposeWithMe(
toDisposable(
rotateControl.onPointerDownObserver.add((evt: IPointerEvent | IMouseEvent, state) => {
const { offsetX: evtOffsetX, offsetY: evtOffsetY } = evt;
+
this._startOffsetX = evtOffsetX;
this._startOffsetY = evtOffsetY;
- const scene = this._getTopScene();
+ const topScene = this._getTopScene() as Scene;
- if (scene == null) {
+ if (topScene == null) {
return;
}
- scene.disableEvent();
+ topScene.disableEvent();
- this._viewportScrollX = scrollX;
- this._viewportScrollY = scrollY;
+ const viewportActualXY = topScene.getScrollXYByRelativeCoords(Vector2.create(evtOffsetX, evtOffsetY));
+
+ this._viewportScrollX = viewportActualXY.x;
+ this._viewportScrollY = viewportActualXY.y;
+
+ const cursor = this._getRotateAnchorCursor(TransformerManagerType.ROTATE_LINE);
+
+ const { ancestorLeft, ancestorTop, width, height, angle: agentOrigin } = applyObject;
+
+ const centerX = (width / 2) + ancestorLeft;
+ const centerY = (height / 2) + ancestorTop;
+ this._clearControlMap();
+
+ this.onChangeStartObservable.notifyObservers({
+ objects: this._selectedObjectMap,
+ type: MoveObserverType.MOVE_START,
+ });
+
+ this._moveBufferSkip = false;
+ const moveObserver = topScene.onPointerMoveObserver.add((moveEvt: IPointerEvent | IMouseEvent) => {
+ const { offsetX: moveOffsetX, offsetY: moveOffsetY } = moveEvt;
+ this._rotateMoving(moveOffsetX, moveOffsetY, centerX, centerY, agentOrigin);
+ topScene.setCursor(cursor);
+ });
- // this._moveObserver = scene.onPointerMoveObserver.add((moveEvt: IPointerEvent | IMouseEvent) => {
- // const { offsetX: moveOffsetX, offsetY: moveOffsetY } = moveEvt;
- // });
+ const upObserver = topScene.onPointerUpObserver.add(() => {
+ moveObserver?.dispose();
+ upObserver?.dispose();
+ topScene.enableEvent();
+ topScene.resetCursor();
+ this.refreshControls();
- this._upObserver = scene.onPointerUpObserver.add(() => {
- scene.onPointerMoveObserver.remove(this._moveObserver);
- scene.onPointerUpObserver.remove(this._upObserver);
- scene.enableEvent();
+ this.onChangeEndObservable.notifyObservers({
+ objects: this._selectedObjectMap,
+ type: MoveObserverType.MOVE_END,
+ });
});
state.stopPropagation();
@@ -518,12 +1028,49 @@ export class Transformer extends Disposable implements ITransformerConfig {
);
}
- private _getOutlinePosition(width: number, height: number, scaleX: number, scaleY: number) {
+ private _rotateMoving(moveOffsetX: number, moveOffsetY: number, centerX: number, centerY: number, agentOrigin: number) {
+ const { ancestorScaleX, ancestorScaleY } = this._scene;
+
+ if (this._moveBufferBlocker(moveOffsetX, moveOffsetY)) {
+ return;
+ }
+
+ const angle1 = Math.atan2(
+ (moveOffsetY - centerY) / ancestorScaleY + this._viewportScrollY,
+ (moveOffsetX - centerX) / ancestorScaleX + this._viewportScrollX
+ );
+
+ const angle2 = Math.atan2(
+ (this._startOffsetY - centerY) / ancestorScaleY + this._viewportScrollY,
+ (this._startOffsetX - centerX) / ancestorScaleX + this._viewportScrollX
+ );
+
+ let angle = agentOrigin + radToDeg(angle1 - angle2);
+
+ if (angle < 0) {
+ angle = 360 + angle;
+ }
+ angle %= 360;
+
+ angle = this._smoothAccuracy(angle);
+
+ this._selectedObjectMap.forEach((moveObject) => {
+ moveObject.transformByState({ angle });
+ });
+
+ this.onChangingObservable.notifyObservers({
+ objects: this._selectedObjectMap,
+ angle,
+ type: MoveObserverType.MOVING,
+ });
+ }
+
+ private _getOutlinePosition(width: number, height: number, borderSpacing: number, borderStrokeWidth: number) {
return {
- left: -this.borderSpacing - this.borderStrokeWidth,
- top: -this.borderSpacing - this.borderStrokeWidth,
- width: width + this.borderSpacing * 2,
- height: height + this.borderSpacing * 2,
+ left: borderSpacing - borderStrokeWidth,
+ top: -borderSpacing - this.borderStrokeWidth,
+ width: width + borderSpacing * 2,
+ height: height + borderSpacing * 2,
};
}
@@ -564,58 +1111,117 @@ export class Transformer extends Disposable implements ITransformerConfig {
return cursor;
}
- private _getRotateAnchorPosition(type: TransformerManagerType, height: number, width: number) {
- let left = -this.anchorSize / 2;
- let top = -this.anchorSize / 2;
+ private _getCopperAnchorPosition(type: TransformerManagerType, height: number, width: number, applyObject: BaseObject) {
+ const { borderStrokeWidth, borderSpacing, anchorSize } = this._getConfig(applyObject);
+
+ let left = 0;
+ let top = 0;
+
+ const longEdge = anchorSize;
+ const shortEdge = anchorSize / 4;
+
+ switch (type) {
+ case TransformerManagerType.RESIZE_LT:
+ left += -borderSpacing - borderStrokeWidth;
+ top += -borderSpacing - borderStrokeWidth;
+ break;
+ case TransformerManagerType.RESIZE_CT:
+ left += width / 2 - longEdge / 2;
+ top += -borderSpacing - borderStrokeWidth;
+
+ break;
+ case TransformerManagerType.RESIZE_RT:
+ left += width + borderSpacing - borderStrokeWidth - longEdge;
+ top += -borderSpacing - borderStrokeWidth;
+
+ break;
+ case TransformerManagerType.RESIZE_LM:
+ left += borderSpacing - borderStrokeWidth;
+ top += height / 2 - longEdge / 2;
+
+ break;
+ case TransformerManagerType.RESIZE_RM:
+ left += width + borderSpacing - borderStrokeWidth - shortEdge;
+ top += height / 2 - longEdge / 2;
+
+ break;
+ case TransformerManagerType.RESIZE_LB:
+ left += -this.borderSpacing - borderStrokeWidth;
+ top += height + borderSpacing - borderStrokeWidth - longEdge;
+
+ break;
+ case TransformerManagerType.RESIZE_CB:
+ left += width / 2 - longEdge / 2;
+ top += height + borderSpacing - borderStrokeWidth - shortEdge;
+
+ break;
+ case TransformerManagerType.RESIZE_RB:
+ left += width + borderSpacing - borderStrokeWidth - longEdge;
+ top += height + borderSpacing - borderStrokeWidth - longEdge;
+
+ break;
+ }
+
+ return {
+ left,
+ top,
+ };
+ }
+
+ private _getRotateAnchorPosition(type: TransformerManagerType, height: number, width: number, applyObject: BaseObject) {
+ const { rotateAnchorOffset, rotateSize, borderStrokeWidth, borderSpacing, anchorSize } = this._getConfig(applyObject);
+
+ let left = -anchorSize / 2;
+ let top = -anchorSize / 2;
switch (type) {
case TransformerManagerType.ROTATE:
- left = width / 2 - this.rotateSize / 2;
- top = -this.rotateAnchorOffset - this.borderSpacing - this.borderStrokeWidth * 2 - this.rotateSize;
+ left = width / 2 - rotateSize / 2;
+ top = -rotateAnchorOffset - borderSpacing - borderStrokeWidth * 2 - rotateSize;
break;
case TransformerManagerType.ROTATE_LINE:
left = width / 2;
- top = -this.rotateAnchorOffset - this.borderSpacing - this.borderStrokeWidth;
+ top = -rotateAnchorOffset - borderSpacing - borderStrokeWidth;
break;
case TransformerManagerType.RESIZE_LT:
- left += -this.borderSpacing - this.borderStrokeWidth;
- top += -this.borderSpacing - this.borderStrokeWidth;
+ left += -borderSpacing - borderStrokeWidth;
+ top += -borderSpacing - borderStrokeWidth;
break;
case TransformerManagerType.RESIZE_CT:
left += width / 2;
- top += -this.borderSpacing - this.borderStrokeWidth;
+ top += -borderSpacing - borderStrokeWidth;
break;
case TransformerManagerType.RESIZE_RT:
- left += width + this.borderSpacing - this.borderStrokeWidth;
- top += -this.borderSpacing - this.borderStrokeWidth;
+ left += width + borderSpacing - borderStrokeWidth;
+ top += -borderSpacing - borderStrokeWidth;
break;
case TransformerManagerType.RESIZE_LM:
- left += -this.borderSpacing - this.borderStrokeWidth;
+ left += borderSpacing - borderStrokeWidth;
top += height / 2;
break;
case TransformerManagerType.RESIZE_RM:
- left += width + this.borderSpacing - this.borderStrokeWidth;
+ left += width + borderSpacing - borderStrokeWidth;
top += height / 2;
break;
case TransformerManagerType.RESIZE_LB:
- left += -this.borderSpacing - this.borderStrokeWidth;
- top += height + this.borderSpacing - this.borderStrokeWidth;
+ left += -this.borderSpacing - borderStrokeWidth;
+ top += height + borderSpacing - borderStrokeWidth;
break;
case TransformerManagerType.RESIZE_CB:
left += width / 2;
- top += height + this.borderSpacing - this.borderStrokeWidth;
+ top += height + borderSpacing - borderStrokeWidth;
break;
case TransformerManagerType.RESIZE_RB:
- left += width + this.borderSpacing - this.borderStrokeWidth;
- top += height + this.borderSpacing - this.borderStrokeWidth;
+ left += width + borderSpacing - borderStrokeWidth;
+ top += height + borderSpacing - borderStrokeWidth;
break;
}
@@ -627,20 +1233,22 @@ export class Transformer extends Disposable implements ITransformerConfig {
}
private _createResizeAnchor(type: TransformerManagerType, applyObject: BaseObject, zIndex: number) {
- const { height, width, scaleX, scaleY } = applyObject.getState();
+ const { height = 0, width = 0, scaleX = 1, scaleY = 1 } = applyObject.getState();
- const { left, top } = this._getRotateAnchorPosition(type, height, width);
+ const { anchorFill, anchorStroke, anchorStrokeWidth, anchorCornerRadius, anchorSize } = this._getConfig(applyObject);
+
+ const { left, top } = this._getRotateAnchorPosition(type, height, width, applyObject);
const cursor = this._getRotateAnchorCursor(type);
const anchor = new Rect(`${type}_${zIndex}`, {
zIndex: zIndex - 1,
- fill: this.anchorFill,
- stroke: this.anchorStroke,
- strokeWidth: this.anchorStrokeWidth,
- width: this.anchorSize,
- height: this.anchorSize,
- radius: this.anchorCornerRadius,
+ fill: anchorFill,
+ stroke: anchorStroke,
+ strokeWidth: anchorStrokeWidth,
+ width: anchorSize,
+ height: anchorSize,
+ radius: anchorCornerRadius,
left,
top,
});
@@ -651,6 +1259,121 @@ export class Transformer extends Disposable implements ITransformerConfig {
return anchor;
}
+ private _createCopperResizeAnchor(type: TransformerManagerType, applyObject: BaseObject, zIndex: number) {
+ const { height = 0, width = 0, scaleX = 1, scaleY = 1 } = applyObject.getState();
+
+ const { anchorFill, anchorStroke, anchorStrokeWidth, anchorSize } = this._getConfig(applyObject);
+
+ const { left, top } = this._getCopperAnchorPosition(type, height, width, applyObject);
+
+ const cursor = this._getRotateAnchorCursor(type);
+
+ let anchor: BaseObject;
+ const oKey = `${type}_${zIndex}`;
+ const config: IRectProps | IRegularPolygonProps = {
+ zIndex: zIndex - 1,
+ fill: anchorFill,
+ stroke: anchorStroke,
+ strokeWidth: anchorStrokeWidth,
+ width: anchorSize,
+ height: anchorSize,
+ left,
+ top,
+ };
+ const longEdge = anchorSize;
+ const shortEdge = anchorSize / 4;
+ if (cursor === CURSOR_TYPE.EAST_RESIZE) {
+ config.width = shortEdge;
+ config.height = longEdge;
+ anchor = new Rect(oKey, config);
+ } else if (cursor === CURSOR_TYPE.WEST_RESIZE) {
+ config.width = shortEdge;
+ config.height = longEdge;
+ anchor = new Rect(oKey, config);
+ } else if (cursor === CURSOR_TYPE.NORTH_RESIZE) {
+ config.width = longEdge;
+ config.height = shortEdge;
+ anchor = new Rect(oKey, config);
+ } else if (cursor === CURSOR_TYPE.SOUTH_RESIZE) {
+ config.width = longEdge;
+ config.height = shortEdge;
+ anchor = new Rect(oKey, config);
+ } else if (cursor === CURSOR_TYPE.NORTH_EAST_RESIZE) {
+ (config as IRegularPolygonProps).pointsGroup = this._getNorthEastPoints(longEdge, shortEdge);
+ anchor = new RegularPolygon(oKey, config as IRegularPolygonProps);
+ } else if (cursor === CURSOR_TYPE.NORTH_WEST_RESIZE) {
+ (config as IRegularPolygonProps).pointsGroup = this._getNorthWestPoints(longEdge, shortEdge);
+ anchor = new RegularPolygon(oKey, config as IRegularPolygonProps);
+ } else if (cursor === CURSOR_TYPE.SOUTH_EAST_RESIZE) {
+ (config as IRegularPolygonProps).pointsGroup = this._getSouthEastPoints(longEdge, shortEdge);
+ anchor = new RegularPolygon(oKey, config as IRegularPolygonProps);
+ } else if (cursor === CURSOR_TYPE.SOUTH_WEST_RESIZE) {
+ (config as IRegularPolygonProps).pointsGroup = this._getSouthWestPoints(longEdge, shortEdge);
+ anchor = new RegularPolygon(oKey, config as IRegularPolygonProps);
+ }
+
+ this._attachHover(anchor!, cursor, CURSOR_TYPE.DEFAULT);
+
+ return anchor!;
+ }
+
+ private _getNorthEastPoints(longEdge: number, shortEdge: number): IPoint[][] {
+ const minusL_S = longEdge - shortEdge;
+ return [
+ [
+ { x: 0, y: 0 },
+ { x: longEdge, y: 0 },
+ { x: longEdge, y: longEdge },
+ { x: minusL_S, y: longEdge },
+ { x: minusL_S, y: shortEdge },
+ { x: 0, y: shortEdge },
+ ],
+ ];
+ }
+
+ private _getNorthWestPoints(longEdge: number, shortEdge: number): IPoint[][] {
+ return [
+ [
+ { x: 0, y: 0 },
+ { x: longEdge, y: 0 },
+ { x: longEdge, y: shortEdge },
+ { x: shortEdge, y: shortEdge },
+ { x: shortEdge, y: longEdge },
+ { x: 0, y: longEdge },
+ ],
+ ];
+ }
+
+ private _getSouthEastPoints(longEdge: number, shortEdge: number): IPoint[][] {
+ const minusL_S = longEdge - shortEdge;
+ return [
+ [
+ { x: minusL_S, y: 0 },
+ { x: longEdge, y: 0 },
+ { x: longEdge, y: longEdge },
+ { x: 0, y: longEdge },
+ { x: 0, y: minusL_S },
+ { x: minusL_S, y: minusL_S },
+ { x: minusL_S, y: 0 },
+ ],
+ ];
+ }
+
+ private _getSouthWestPoints(longEdge: number, shortEdge: number): IPoint[][] {
+ const minusL_S = longEdge - shortEdge;
+ return [
+ [
+ { x: 0, y: 0 },
+ { x: shortEdge, y: 0 },
+ { x: shortEdge, y: minusL_S },
+ { x: longEdge, y: minusL_S },
+ { x: longEdge, y: longEdge },
+ { x: 0, y: longEdge },
+ { x: 0, y: 0 },
+ ],
+ ];
+ }
+
private _checkTransformerType(oKey: string) {
if (oKey.indexOf(TransformerManagerType.OUTLINE) > -1) {
return TransformerManagerType.OUTLINE;
@@ -689,7 +1412,7 @@ export class Transformer extends Disposable implements ITransformerConfig {
}
}
- private _updateControlIterator(func: (control: Group, applyObject: BaseObject) => void) {
+ private _updateControlIterator(func: (control: BaseObject, applyObject: BaseObject) => void) {
this._transformerControlMap.forEach((control, oKey) => {
const applyObject = this._selectedObjectMap.get(oKey);
if (!applyObject) {
@@ -702,10 +1425,13 @@ export class Transformer extends Disposable implements ITransformerConfig {
private _updateControl() {
this._updateControlIterator((control, applyObject) => {
- const { left, top } = applyObject.getState();
+ const { left, top, height, width, angle } = applyObject.getState();
control.transformByState({
left,
top,
+ height,
+ width,
+ angle,
});
control.show();
control.makeDirty(true);
@@ -737,152 +1463,148 @@ export class Transformer extends Disposable implements ITransformerConfig {
);
}
- private _clearControl() {
+ private _clearControls(changeSelf = false) {
+ this._clearControlMap();
+
+ this.onClearControlObservable.notifyObservers(changeSelf);
+ }
+
+ private _clearControlMap() {
this._transformerControlMap.forEach((control) => {
control.dispose();
});
this._transformerControlMap.clear();
-
- this.onClearControlObservable.notifyObservers(null);
}
- private _createControl(applyObject: BaseObject) {
- const { left, top, height, width, angle, scaleX, scaleY, skewX, skewY, flipX, flipY } = applyObject.getState();
+ private _createControl(applyObject: BaseObject, isSkipOnCropper = true) {
+ const { left = 0, top = 0, height = 0, width = 0 } = applyObject.getState();
+ const angle = applyObject.angle;
+ const { isCropper, resizeEnabled, rotateAnchorOffset, rotateSize, rotateCornerRadius, borderEnabled, borderStroke, borderStrokeWidth, borderSpacing, enabledAnchors } = this._getConfig(applyObject);
+ if (isSkipOnCropper && isCropper) {
+ return;
+ }
const oKey = applyObject.oKey;
- const zIndex = this._selectedObjectMap.size;
-
+ const zIndex = this._selectedObjectMap.size + applyObject.maxZIndex + DEFAULT_CONTROL_PLUS_INDEX;
+ const layerIndex = applyObject.getLayerIndex() || DEFAULT_TRANSFORMER_LAYER_INDEX;
const groupElements: BaseObject[] = [];
- // width *= scaleX;
-
- // height *= scaleY;
-
- if (this.borderEnabled) {
+ if (borderEnabled && !isCropper) {
const outline = new Rect(`${TransformerManagerType.OUTLINE}_${zIndex}`, {
- zIndex: zIndex - 1,
- evented: false,
- strokeWidth: this.borderStrokeWidth,
- stroke: this.borderStroke,
- ...this._getOutlinePosition(width, height, scaleX, scaleY),
+ zIndex: zIndex - 1, evented: false, strokeWidth: borderStrokeWidth, stroke: borderStroke,
+ ...this._getOutlinePosition(width, height, borderSpacing, borderStrokeWidth),
});
groupElements.push(outline);
}
-
- if (this.resizeEnabled) {
+ if (resizeEnabled && !isCropper) {
const { left: lineLeft, top: lineTop } = this._getRotateAnchorPosition(
- TransformerManagerType.ROTATE_LINE,
- height,
- width
+ TransformerManagerType.ROTATE_LINE, height, width, applyObject
);
+
const rotateLine = new Rect(`${TransformerManagerType.ROTATE_LINE}_${zIndex}`, {
- zIndex: zIndex - 1,
- evented: false,
- left: lineLeft,
- top: lineTop,
- height: this.rotateAnchorOffset,
- width: 1,
- strokeWidth: this.borderStrokeWidth,
- stroke: this.borderStroke,
- });
+ zIndex: zIndex - 1, evented: false, left: lineLeft, top: lineTop, height: rotateAnchorOffset, width: 1,
+ strokeWidth: borderStrokeWidth, stroke: borderStroke });
+
+ const { left, top } = this._getRotateAnchorPosition(TransformerManagerType.ROTATE, height, width, applyObject);
- const { left, top } = this._getRotateAnchorPosition(TransformerManagerType.ROTATE, height, width);
const cursor = this._getRotateAnchorCursor(TransformerManagerType.ROTATE);
+
const rotate = new Rect(`${TransformerManagerType.ROTATE}_${zIndex}`, {
- zIndex: zIndex - 1,
- left,
- top,
- height: this.rotateSize,
- width: this.rotateSize,
- radius: this.rotateCornerRadius,
- strokeWidth: this.borderStrokeWidth * 2,
- stroke: this.borderStroke,
- });
- this._attachEventToRotate(rotate);
+ zIndex: zIndex - 1, left, top, height: rotateSize, width: rotateSize,
+ radius: rotateCornerRadius, strokeWidth: borderStrokeWidth * 2, stroke: borderStroke });
+ this._attachEventToRotate(rotate, applyObject);
this._attachHover(rotate, cursor, CURSOR_TYPE.DEFAULT);
groupElements.push(rotateLine, rotate);
}
-
- if (this.resizeEnabled) {
- for (let i = 0, len = this.enabledAnchors.length; i < len; i++) {
- const isEnable = this.enabledAnchors[i];
+ if (resizeEnabled) {
+ for (let i = 0, len = enabledAnchors.length; i < len; i++) {
+ const isEnable = enabledAnchors[i];
if (isEnable !== 1) {
continue;
}
const type = TransformerManagerTypeArray[i];
- const anchor = this._createResizeAnchor(type, applyObject, zIndex);
- this._attachEventToAnchor(anchor, type);
+ let anchor: BaseObject;
+ if (!isCropper) {
+ anchor = this._createResizeAnchor(type, applyObject, zIndex);
+ } else {
+ anchor = this._createCopperResizeAnchor(type, applyObject, zIndex);
+ }
+
+ this._attachEventToAnchor(anchor, type, applyObject);
groupElements.push(anchor);
}
}
- const transformerControl = new Group(`${TransformerManagerType.GROUP}_${zIndex}`, ...groupElements);
-
+ const transformerControl = new Group(`${TransformerManagerType.GROUP}_${oKey}`, ...groupElements);
transformerControl.zIndex = zIndex;
-
transformerControl.evented = false;
-
- transformerControl.transformByState({
- left,
- top,
- });
-
+ transformerControl.openSelfSizeMode();
+ transformerControl.transformByState({ left, top, angle, width, height });
const scene = this.getScene();
- scene.addObject(transformerControl, 2);
+ scene.addObject(transformerControl, layerIndex);
- this._transformerControlMap.set(oKey, transformerControl);
-
- this.onCreateControlObservable.notifyObservers(transformerControl);
+ if (!isCropper) {
+ if (this._transformerControlMap.has(oKey)) {
+ this._transformerControlMap.get(oKey)!.dispose();
+ }
+ this._transformerControlMap.set(oKey, transformerControl);
+ this.onCreateControlObservable.notifyObservers(transformerControl);
+ } else {
+ this._copperControl = transformerControl;
+ }
return transformerControl;
}
private _getTopScene() {
const currentScene = this.getScene();
- return currentScene.getEngine()?.activeScene as ThinScene | null;
+ return currentScene.getEngine()?.activeScene as Nullable<Scene>;
}
- private _moving(moveOffsetX: number, moveOffsetY: number, scrollTimer: ScrollTimer) {
- const { scrollX, scrollY } = getCurrentScrollXY(scrollTimer);
- const x = moveOffsetX - this._viewportScrollX + scrollX;
- const y = moveOffsetY - this._viewportScrollY + scrollY;
-
- const moveLeft = x - this._startOffsetX;
- const moveTop = y - this._startOffsetY;
-
- this._selectedObjectMap.forEach((moveObject) => {
- moveObject.translate(moveLeft + moveObject.left, moveTop + moveObject.top);
- });
-
- this.onChangingObservable.notifyObservers({
- objects: this._selectedObjectMap,
- moveX: moveLeft,
- moveY: moveTop,
- type: MoveObserverType.MOVING,
- });
+ private _updateActiveObjectList(applyObject: BaseObject, evt: IPointerEvent | IMouseEvent) {
+ const { isCropper } = this._getConfig(applyObject);
- this._startOffsetX = x;
- this._startOffsetY = y;
- }
+ applyObject = this._findGroupObject(applyObject);
- private _updateActiveObjectList(applyObject: BaseObject, evt: IPointerEvent | IMouseEvent) {
if (this._selectedObjectMap.has(applyObject.oKey)) {
return;
}
if (!evt.ctrlKey) {
this._selectedObjectMap.clear();
- this._clearControl();
+ this._clearControlMap();
}
- this._selectedObjectMap.set(applyObject.oKey, applyObject);
+
+ if (!isCropper) {
+ this._selectedObjectMap.set(applyObject.oKey, applyObject);
+ }
+
this._createControl(applyObject);
}
- private _addCancelObserver(scene: ThinScene) {
- scene.onPointerDownObserver.remove(this._cancelFocusObserver);
+ private _findGroupObject(applyObject: BaseObject) {
+ if (!applyObject.isInGroup) {
+ return applyObject;
+ }
+
+ const group = applyObject.ancestorGroup as Nullable<Group>;
+ if (!group) {
+ return applyObject;
+ } else {
+ return group;
+ }
+ }
+
+ private _addCancelObserver(scene: Scene) {
+ this._cancelFocusObserver?.dispose();
this._cancelFocusObserver = scene.onPointerDownObserver.add(() => {
- this._selectedObjectMap.clear();
- this._clearControl();
- scene.onPointerDownObserver.remove(this._cancelFocusObserver);
+ this.clearSelectedObjects();
});
}
+
+ private _smoothAccuracy(num: number, isCropper = false, accuracy: number = 1) {
+ if (isCropper) {
+ return precisionTo(num, 3);
+ }
+ return precisionTo(num, accuracy);
+ }
}
diff --git a/packages/engine-render/src/scene.ts b/packages/engine-render/src/scene.ts
index 8429b29056..777d45efd1 100644
--- a/packages/engine-render/src/scene.ts
+++ b/packages/engine-render/src/scene.ts
@@ -17,7 +17,6 @@
import type { IKeyValue, Nullable } from '@univerjs/core';
import { sortRules, sortRulesByDesc, toDisposable } from '@univerjs/core';
import { BehaviorSubject } from 'rxjs';
-
import type { BaseObject } from './base-object';
import { CURSOR_TYPE, RENDER_CLASS_TYPE } from './basics/const';
import type { IDragEvent, IKeyboardEvent, IMouseEvent, IPointerEvent, IWheelEvent } from './basics/i-events';
@@ -25,16 +24,16 @@ import type { IObjectFullState, ISceneTransformState, ITransformChangeState } fr
import { TRANSFORM_CHANGE_OBSERVABLE_TYPE } from './basics/interfaces';
import { precisionTo, requestNewFrame } from './basics/tools';
import { Transform } from './basics/transform';
-import { Vector2 } from './basics/vector2';
+import type { Vector2 } from './basics/vector2';
import type { UniverRenderingContext } from './context';
import { Layer } from './layer';
-import type { ITransformerConfig } from './scene.transformer';
import { Transformer } from './scene.transformer';
import { InputManager } from './scene.input-manager';
import type { SceneViewer } from './scene-viewer';
import type { ThinEngine } from './thin-engine';
import { ThinScene } from './thin-scene';
import type { Viewport } from './viewport';
+import type { ITransformerConfig } from './basics/transformer-config';
export class Scene extends ThinScene {
private _layers: Layer[] = [];
@@ -48,7 +47,6 @@ export class Scene extends ThinScene {
private _addObject$ = new BehaviorSubject<Scene>(this);
readonly addObject$ = this._addObject$.asObservable();
-
/**
* Transformer constructor. Transformer is a special type of group that allow you transform
* primitives and shapes. Transforming tool is not changing `width` and `height` properties of nodes
@@ -56,8 +54,6 @@ export class Scene extends ThinScene {
*/
private _transformer: Nullable<Transformer>;
- private _transformerOpenState = false;
-
/** @hidden */
private _inputManager: Nullable<InputManager>;
@@ -112,6 +108,24 @@ export class Scene extends ThinScene {
return this.scaleY * pScale;
}
+ get ancestorLeft() {
+ const p = this.getParent();
+ let pOffsetX = 0;
+ if (p.classType === RENDER_CLASS_TYPE.SCENE_VIEWER) {
+ pOffsetX = (p as SceneViewer).ancestorLeft;
+ }
+ return pOffsetX;
+ }
+
+ get ancestorTop() {
+ const p = this.getParent();
+ let pOffsetY = 0;
+ if (p.classType === RENDER_CLASS_TYPE.SCENE_VIEWER) {
+ pOffsetY = (p as SceneViewer).ancestorTop;
+ }
+ return pOffsetY;
+ }
+
set cursor(val: CURSOR_TYPE) {
this.setCursor(val);
}
@@ -438,6 +452,17 @@ export class Scene extends ThinScene {
}
}
+ getObjectIncludeInGroup(oKey: string) {
+ for (const layer of this._layers) {
+ const objects = layer.getObjects();
+ for (const object of objects) {
+ if (object.oKey === oKey) {
+ return object;
+ }
+ }
+ }
+ }
+
fuzzyMathObjects(oKey: string) {
const objects: BaseObject[] = [];
for (const layer of this._layers) {
@@ -500,27 +525,30 @@ export class Scene extends ThinScene {
});
}
- openTransformer(config?: ITransformerConfig) {
+ override attachTransformerTo(o: BaseObject) {
if (!this._transformer) {
- this._transformer = new Transformer(this, config);
+ this.initTransformer();
}
- this._transformerOpenState = true;
+ this._transformer?.attachTo(o);
}
- closeTransformer(isDestroyed = false) {
- if (isDestroyed) {
- this._transformer = null;
- }
-
- this._transformerOpenState = false;
+ override detachTransformerFrom(o: BaseObject) {
+ this._transformer?.detachFrom(o);
}
- override applyTransformer(o: BaseObject) {
- if (!this._transformerOpenState) {
+ initTransformer(config?: ITransformerConfig) {
+ if (this._transformer) {
+ this._transformer.resetProps(config);
return;
}
+ this._transformer = new Transformer(this, config);
+ }
- this._transformer?.attachTo(o);
+ getTransformerByCreate() {
+ if (!this._transformer) {
+ this.initTransformer();
+ }
+ return this._transformer!;
}
getTransformer() {
@@ -541,7 +569,6 @@ export class Scene extends ThinScene {
// }
// parent = parent?.getParent && parent?.getParent();
// }
-
coord = this.getRelativeCoord(coord);
return this.getActiveViewportByRelativeCoord(coord);
}
@@ -713,11 +740,11 @@ export class Scene extends ThinScene {
if (!o.visible || !o.evented || o.classType === RENDER_CLASS_TYPE.GROUP) {
continue;
}
- let svCoord = svCoordOrigin;
- if (o.isInGroup && o.parent.classType === RENDER_CLASS_TYPE.GROUP) {
- const { cumLeft, cumTop } = this._getGroupCumLeftRight(o);
- svCoord = svCoord.clone().add(Vector2.FromArray([-cumLeft, -cumTop]));
- }
+ const svCoord = svCoordOrigin;
+ // if (o.isInGroup && o.parent?.classType === RENDER_CLASS_TYPE.GROUP) {
+ // const { cumLeft, cumTop } = this._getGroupCumLeftRight(o);
+ // svCoord = svCoord.clone().add(Vector2.FromArray([-cumLeft, -cumTop]));
+ // }
if (o.isHit(svCoord)) {
if (o.classType === RENDER_CLASS_TYPE.SCENE_VIEWER) {
diff --git a/packages/engine-render/src/services/object-transform-manager.service.ts b/packages/engine-render/src/services/object-transform-manager.service.ts
deleted file mode 100644
index 9e44646fd2..0000000000
--- a/packages/engine-render/src/services/object-transform-manager.service.ts
+++ /dev/null
@@ -1,182 +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 { Nullable } from '@univerjs/core';
-import type { IDisposable } from '@wendellhu/redi';
-import { BehaviorSubject } from 'rxjs';
-
-export interface ITransformObject {
- unitId: string;
- objectId: string;
- top?: number;
- left?: number;
- width?: number;
- height?: number;
- angle?: number;
- scaleX?: number;
- scaleY?: number;
- skewX?: number;
- skewY?: number;
- flipX?: number;
- flipY?: number;
- strokeWidth?: number;
-}
-
-export interface IObjectTransformManagerSearch {
- unitId: string;
- objectId: string;
-}
-
-export interface IObjectTransformManagerInsert extends IObjectTransformManagerSearch {
- object: ITransformObject;
-}
-
-/**
- * This service is for worksheet build sheet skeleton.
- */
-export class ObjectTransformManagerService implements IDisposable {
- private _currentObject: IObjectTransformManagerSearch = {
- unitId: '',
- objectId: '',
- };
-
- private _objectParam: Map<string, Map<string, ITransformObject>> = new Map();
-
- private readonly _currentObject$ = new BehaviorSubject<Nullable<ITransformObject>>(null);
-
- readonly currentObject$ = this._currentObject$.asObservable();
-
- dispose(): void {
- this._currentObject$.complete();
- this._objectParam = new Map();
- }
-
- updateObject(transformObject: ITransformObject) {
- const {
- unitId,
- objectId,
- top,
- left,
- width,
- height,
- angle,
- scaleX,
- scaleY,
- skewX,
- skewY,
- flipX,
- flipY,
- strokeWidth,
- } = transformObject;
-
- const currentObject = this.getObjectBySearch({
- unitId,
- objectId,
- });
-
- if (currentObject == null) {
- return;
- }
-
- if (top != null) {
- currentObject.top = top;
- }
-
- if (left != null) {
- currentObject.top = top;
- }
-
- if (width != null) {
- currentObject.top = top;
- }
-
- if (height != null) {
- currentObject.top = top;
- }
-
- if (angle != null) {
- currentObject.top = top;
- }
-
- if (scaleX != null) {
- currentObject.top = top;
- }
-
- if (scaleY != null) {
- currentObject.top = top;
- }
-
- if (skewX != null) {
- currentObject.top = top;
- }
-
- if (skewY != null) {
- currentObject.top = top;
- }
-
- if (flipX != null) {
- currentObject.top = top;
- }
-
- if (flipY != null) {
- currentObject.top = top;
- }
-
- if (strokeWidth != null) {
- currentObject.top = top;
- }
- }
-
- setCurrent(searchParam: IObjectTransformManagerSearch) {
- const { unitId, objectId } = searchParam;
- this._currentObject = {
- unitId,
- objectId,
- };
-
- this._currentObject$.next(this.getObjectBySearch(this._currentObject));
- }
-
- getCurrentObject(): Nullable<ITransformObject> {
- return this.getObjectBySearch(this._currentObject);
- }
-
- setObject(insertParam: IObjectTransformManagerInsert): ITransformObject {
- const { unitId, object, objectId } = insertParam;
-
- if (!this._objectParam.has(unitId)) {
- this._objectParam.set(unitId, new Map());
- }
-
- const baseObjectData = this._objectParam.get(unitId)!;
-
- baseObjectData.set(objectId, object);
-
- this._currentObject = {
- unitId,
- objectId,
- };
-
- this._currentObject$.next(object);
-
- return object;
- }
-
- getObjectBySearch(searchParam: IObjectTransformManagerSearch): Nullable<ITransformObject> {
- const { unitId, objectId } = searchParam;
- return this._objectParam.get(unitId)?.get(objectId);
- }
-}
diff --git a/packages/engine-render/src/shape/image.ts b/packages/engine-render/src/shape/image.ts
new file mode 100644
index 0000000000..011d8ae9aa
--- /dev/null
+++ b/packages/engine-render/src/shape/image.ts
@@ -0,0 +1,347 @@
+/**
+ * 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 { ISrcRect, Nullable, PresetGeometryType } from '@univerjs/core';
+
+import type { UniverRenderingContext } from '../context';
+import type { IObjectFullState, ITransformChangeState, IViewportInfo } from '../basics';
+import { RENDER_CLASS_TYPE, Vector2 } from '../basics';
+import { offsetRotationAxis } from '../basics/offset-rotation-axis';
+import type { IShapeProps } from './shape';
+import { Shape } from './shape';
+
+export interface IImageProps extends IShapeProps {
+ image?: HTMLImageElement;
+ url?: string;
+ success?: () => void;
+ fail?: () => void;
+ /**
+ * 20.1.8.55 srcRect (Source Rectangle)
+ */
+ srcRect?: Nullable<ISrcRect>;
+
+ /**
+ * 20.1.9.18 prstGeom (Preset geometry)
+ */
+ prstGeom?: Nullable<PresetGeometryType>;
+}
+
+export class Image extends Shape<IImageProps> {
+ protected _props: IImageProps;
+
+ protected _native: Nullable<HTMLImageElement>;
+
+ private _renderByCropper: boolean = false;
+
+ private _transformCalculateSrcRect: boolean = true;
+
+ constructor(id: string, config: IImageProps) {
+ super(id, config);
+ this._props = {
+ ...config,
+ };
+
+ if (config.image) {
+ this._native = config.image;
+ this._native.crossOrigin = 'anonymous';
+ this.makeDirty(true);
+ } else if (config.url) {
+ this._native = document.createElement('img');
+ this._native.src = config.url;
+ this._native.crossOrigin = 'anonymous';
+ this._native.onload = () => {
+ config.success?.();
+ this.makeDirty(true);
+ this.getEngine()?.activeScene?.onFileLoadedObservable.notifyObservers(id);
+ };
+ this._native.onerror = () => {
+ if (config.fail) {
+ config.fail();
+ } else {
+ this._native!.src =
+ 'data:image/svg+xml;base64,PHN2ZyBjbGFzcz0iaWNvbiIgdmlld0JveD0iMCAwIDEwMjQgMTAyNCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB3aWR0aD0iMjAwIiBoZWlnaHQ9IjIwMCI+PHBhdGggZD0iTTMwNC4xMjggNDU2LjE5MmM0OC42NCAwIDg4LjA2NC0zOS40MjQgODguMDY0LTg4LjA2NHMtMzkuNDI0LTg4LjA2NC04OC4wNjQtODguMDY0LTg4LjA2NCAzOS40MjQtODguMDY0IDg4LjA2NCAzOS40MjQgODguMDY0IDg4LjA2NCA4OC4wNjR6bTAtMTE2LjIyNGMxNS4zNiAwIDI4LjE2IDEyLjI4OCAyOC4xNiAyOC4xNnMtMTIuMjg4IDI4LjE2LTI4LjE2IDI4LjE2LTI4LjE2LTEyLjI4OC0yOC4xNi0yOC4xNiAxMi4yODgtMjguMTYgMjguMTYtMjguMTZ6IiBmaWxsPSIjZTZlNmU2Ii8+PHBhdGggZD0iTTg4Ny4yOTYgMTU5Ljc0NEgxMzYuNzA0Qzk2Ljc2OCAxNTkuNzQ0IDY0IDE5MiA2NCAyMzIuNDQ4djU1OS4xMDRjMCAzOS45MzYgMzIuMjU2IDcyLjcwNCA3Mi43MDQgNzIuNzA0aDE5OC4xNDRMNTAwLjIyNCA2ODguNjRsLTM2LjM1Mi0yMjIuNzIgMTYyLjMwNC0xMzAuNTYtNjEuNDQgMTQzLjg3MiA5Mi42NzIgMjE0LjAxNi0xMDUuNDcyIDE3MS4wMDhoMzM1LjM2QzkyNy4yMzIgODY0LjI1NiA5NjAgODMyIDk2MCA3OTEuNTUyVjIzMi40NDhjMC0zOS45MzYtMzIuMjU2LTcyLjcwNC03Mi43MDQtNzIuNzA0em0tMTM4Ljc1MiA3MS42OHYuNTEySDg1Ny42YzE2LjM4NCAwIDMwLjIwOCAxMy4zMTIgMzAuMjA4IDMwLjIwOHYzOTkuODcyTDY3My4yOCA0MDguMDY0bDc1LjI2NC0xNzYuNjR6TTMwNC42NCA3OTIuMDY0SDE2NS44ODhjLTE2LjM4NCAwLTMwLjIwOC0xMy4zMTItMzAuMjA4LTMwLjIwOHYtOS43MjhsMTM4Ljc1Mi0xNjQuMzUyIDEwNC45NiAxMjQuNDE2LTc0Ljc1MiA3OS44NzJ6bTgxLjkyLTM1NS44NGwzNy4zNzYgMjI4Ljg2NC0uNTEyLjUxMi0xNDIuODQ4LTE2OS45ODRjLTMuMDcyLTMuNTg0LTkuMjE2LTMuNTg0LTEyLjI4OCAwTDEzNS42OCA2NTIuOFYyNjIuMTQ0YzAtMTYuMzg0IDEzLjMxMi0zMC4yMDggMzAuMjA4LTMwLjIwOGg0NzQuNjI0TDM4Ni41NiA0MzYuMjI0em01MDEuMjQ4IDMyNS42MzJjMCAxNi44OTYtMTMuMzEyIDMwLjIwOC0yOS42OTYgMzAuMjA4SDY4MC45Nmw1Ny4zNDQtOTMuMTg0LTg3LjU1Mi0yMDIuMjQgNy4xNjgtNy42OCAyMjkuODg4IDI3Mi44OTZ6IiBmaWxsPSIjZTZlNmU2Ii8+PC9zdmc+';
+ this.makeDirty(true);
+ }
+ };
+ }
+
+ this._init();
+ }
+
+ get srcRect() {
+ return this._props.srcRect;
+ }
+
+ get prstGeom() {
+ return this._props.prstGeom;
+ }
+
+ override get classType(): RENDER_CLASS_TYPE {
+ return RENDER_CLASS_TYPE.IMAGE;
+ }
+
+ transformByStateCloseCropper(option: IObjectFullState) {
+ this._transformCalculateSrcRect = false;
+ this.transformByState(option);
+ this._transformCalculateSrcRect = true;
+ }
+
+ changeSource(url: string) {
+ if (this._native == null) {
+ this._native = document.createElement('img');
+ }
+ this._native.src = url;
+ this._native.onload = () => {
+ this.makeDirty(true);
+ };
+ }
+
+ resetSize() {
+ if (this._native == null) {
+ return;
+ }
+ this.transformByState({
+ width: this._native.width,
+ height: this._native.height,
+ });
+ this.setSrcRect(null);
+ }
+
+ setPrstGeom(prstGeom?: Nullable<PresetGeometryType>) {
+ this._props.prstGeom = prstGeom;
+ }
+
+ setSrcRect(srcRect?: Nullable<ISrcRect>) {
+ this._props.srcRect = srcRect;
+
+ this.makeDirty(true);
+ }
+
+ getProps(): IImageProps {
+ return this._props;
+ }
+
+ getNative(): Nullable<HTMLImageElement> {
+ return this._native;
+ }
+
+ getNativeSize() {
+ if (this._native == null) {
+ return { width: this.width, height: this.height };
+ }
+ return { width: this._native.width, height: this._native.height };
+ }
+
+ closeRenderByCropper() {
+ this._renderByCropper = false;
+ }
+
+ openRenderByCropper() {
+ this._renderByCropper = true;
+ this._transformBySrcRect();
+ }
+
+ // override transformForAngle(transform: Transform) {
+ // if (this.angle === 0) {
+ // return transform;
+ // }
+
+ // let cx = (this.width + this.strokeWidth) / 2;
+ // let cy = (this.height + this.strokeWidth) / 2;
+ // if (this.srcRect != null) {
+ // const { left = 0, top = 0, right = 0, bottom = 0 } = this.srcRect;
+ // cx = (this.width + left + right + this.strokeWidth) / 2;
+ // cy = (this.height + top + bottom + this.strokeWidth) / 2;
+ // }
+
+ // transform.rotate(-this.angle);
+ // transform.translate(cx, cy);
+ // transform.rotate(this.angle);
+ // transform.translate(-cx, -cy);
+
+ // return transform;
+ // }
+ calculateTransformWithSrcRect() {
+ const {
+ left: imageLeft,
+ top: imageTop,
+ width: imageWidth,
+ height: imageHeight,
+ } = this;
+
+ if (this.srcRect == null) {
+ return {
+ left: imageLeft,
+ top: imageTop,
+ width: imageWidth,
+ height: imageHeight,
+ angle: this.angle,
+ };
+ }
+ const { left = 0, top = 0, right = 0, bottom = 0 } = this.srcRect;
+
+ const newLeft = imageLeft - left;
+ const newTop = imageTop - top;
+
+ const width = imageWidth + right + left;
+ const height = imageHeight + bottom + top;
+
+ return {
+ left: newLeft,
+ top: newTop,
+ width,
+ height,
+ angle: this.angle,
+ };
+ }
+
+ private _transformBySrcRect() {
+ if (this.srcRect == null) {
+ return;
+ }
+ const { left = 0, top = 0, right = 0, bottom = 0 } = this.srcRect;
+ const {
+ width: imageWidth,
+ height: imageHeight,
+ } = this;
+
+ // let newLeft = imageLeft - left;
+ // let newTop = imageTop - top;
+
+ // const width = imageWidth + right + left;
+ // const height = imageHeight + bottom + top;
+
+ let { left: newLeft, top: newTop, width, height } = this.calculateTransformWithSrcRect();
+
+ if (this.angle !== 0) {
+ /**
+ * Calculate the offset of the center rotation to correctly position the object entering the cropping.
+ */
+ const cx = (imageWidth + this.strokeWidth) / 2;
+ const cy = (imageHeight + this.strokeWidth) / 2;
+
+ const newCx = width / 2 - left;
+ const newCy = height / 2 - top;
+
+ const finalPoint = offsetRotationAxis(new Vector2(cx, cy), this.angle, new Vector2(newLeft, newTop), new Vector2(newCx, newCy));
+
+ newLeft = finalPoint.x;
+ newTop = finalPoint.y;
+ }
+
+ this.transformByState({
+ left: newLeft,
+ top: newTop,
+ width,
+ height,
+ });
+ }
+
+ override render(mainCtx: UniverRenderingContext, bounds?: IViewportInfo) {
+ if (!this.visible) {
+ this.makeDirty(false);
+ return this;
+ }
+
+ // Temporarily ignore the on-demand display of elements within a group:this.isInGroup
+ if (this.isRender(bounds)) {
+ const { top, left, bottom, right } = bounds!.viewBound;
+
+ if (
+ this.width + this.strokeWidth + this.left < left ||
+ right < this.left ||
+ this.height + this.strokeWidth + this.top < top ||
+ bottom < this.top
+ ) {
+ return this;
+ }
+ }
+
+ const m = this.transform.getMatrix();
+ mainCtx.save();
+ mainCtx.transform(m[0], m[1], m[2], m[3], m[4], m[5]);
+ this._draw(mainCtx);
+ mainCtx.restore();
+ this.makeDirty(false);
+ return this;
+ }
+
+ protected override _draw(ctx: UniverRenderingContext) {
+ if (this._native == null) {
+ return;
+ }
+ if (!this._renderByCropper && this.srcRect) {
+ const { left = 0, top = 0, right = 0, bottom = 0 } = this.srcRect;
+ ctx.beginPath();
+ ctx.rect(0, 0, this.width, this.height);
+ ctx.clip();
+ ctx.drawImage(this._native, -left, -top, this.width + right + left, this.height + bottom + top);
+ } else {
+ ctx.drawImage(this._native, 0, 0, this.width, this.height);
+ }
+ }
+
+ private _init(): void {
+ this.onTransformChangeObservable.add((state) => {
+ this._updateSrcRectByTransform(state);
+ });
+ }
+
+ private _updateSrcRectByTransform(state: ITransformChangeState) {
+ if (this.srcRect == null || !this._transformCalculateSrcRect) {
+ return;
+ }
+ const { width, height, left, top, angle } = this;
+ const { width: preWidth = 0, height: preHeight = 0, left: preLeft = 0, top: preTop = 0, angle: preAngle } = state.preValue as IObjectFullState;
+ const { left: srcLeft = 0, top: srcTop = 0, right: srcRight = 0, bottom: srcBottom = 0 } = this.srcRect;
+
+ let newLeft = srcLeft;
+ let newTop = srcTop;
+ let newRight = srcRight;
+ let newBottom = srcBottom;
+
+ let isChange = false;
+
+ if (preWidth !== 0 && preWidth !== width) {
+ const preLeftRatio = srcLeft / preWidth;
+ const preRightRatio = srcRight / preWidth;
+
+ newLeft = width * preLeftRatio;
+ newRight = width * preRightRatio;
+
+ isChange = true;
+ }
+
+ if (preHeight !== 0 && preHeight !== height) {
+ const preTopRatio = srcTop / preHeight;
+ const preBottomRatio = srcBottom / preHeight;
+
+ newTop = height * preTopRatio;
+ newBottom = height * preBottomRatio;
+
+ isChange = true;
+ }
+
+ if (isChange) {
+ this.setSrcRect({
+ left: newLeft,
+ top: newTop,
+ right: newRight,
+ bottom: newBottom,
+ });
+ }
+ }
+}
diff --git a/packages/engine-render/src/shape/index.ts b/packages/engine-render/src/shape/index.ts
index 07b721e3a8..8e822cc29c 100644
--- a/packages/engine-render/src/shape/index.ts
+++ b/packages/engine-render/src/shape/index.ts
@@ -18,7 +18,7 @@ export * from './circle';
export * from './control';
export * from './drawing';
export * from './path';
-export * from './picture';
+export * from './image';
export * from './rect';
export * from './regular-polygon';
export * from './rich-text';
diff --git a/packages/engine-render/src/shape/picture.ts b/packages/engine-render/src/shape/picture.ts
deleted file mode 100644
index 9a14cde28b..0000000000
--- a/packages/engine-render/src/shape/picture.ts
+++ /dev/null
@@ -1,104 +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 { Nullable } from '@univerjs/core';
-
-import type { UniverRenderingContext } from '../context';
-import type { IShapeProps } from './shape';
-import { Shape } from './shape';
-
-export interface IPictureProps extends IShapeProps {
- image?: HTMLImageElement;
- url?: string;
- success?: () => void;
- liX?: number;
- liY?: number;
- fail?: () => void;
- autoWidth?: boolean;
- autoHeight?: boolean;
-}
-
-export class Picture extends Shape<IPictureProps> {
- protected _props: IPictureProps;
-
- protected _native: Nullable<HTMLImageElement>;
-
- constructor(id: string, config: IPictureProps) {
- super(id, config);
- this._props = {
- autoWidth: false,
- autoHeight: false,
- ...config,
- };
- if (config.image) {
- this._native = config.image;
- this._native.crossOrigin = 'anonymous';
- this._init();
- } else if (config.url) {
- this._native = document.createElement('img');
- this._native.src = config.url;
- this._native.crossOrigin = 'anonymous';
- this._native.onload = () => {
- config.success?.();
- this._init();
- this.makeDirty(true);
- this.getEngine()?.activeScene?.onFileLoadedObservable.notifyObservers(id);
- };
- this._native.onerror = () => {
- if (config.fail) {
- config.fail();
- } else {
- this._native!.src =
- 'data:image/svg+xml;base64,PHN2ZyBjbGFzcz0iaWNvbiIgdmlld0JveD0iMCAwIDEwMjQgMTAyNCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB3aWR0aD0iMjAwIiBoZWlnaHQ9IjIwMCI+PHBhdGggZD0iTTMwNC4xMjggNDU2LjE5MmM0OC42NCAwIDg4LjA2NC0zOS40MjQgODguMDY0LTg4LjA2NHMtMzkuNDI0LTg4LjA2NC04OC4wNjQtODguMDY0LTg4LjA2NCAzOS40MjQtODguMDY0IDg4LjA2NCAzOS40MjQgODguMDY0IDg4LjA2NCA4OC4wNjR6bTAtMTE2LjIyNGMxNS4zNiAwIDI4LjE2IDEyLjI4OCAyOC4xNiAyOC4xNnMtMTIuMjg4IDI4LjE2LTI4LjE2IDI4LjE2LTI4LjE2LTEyLjI4OC0yOC4xNi0yOC4xNiAxMi4yODgtMjguMTYgMjguMTYtMjguMTZ6IiBmaWxsPSIjZTZlNmU2Ii8+PHBhdGggZD0iTTg4Ny4yOTYgMTU5Ljc0NEgxMzYuNzA0Qzk2Ljc2OCAxNTkuNzQ0IDY0IDE5MiA2NCAyMzIuNDQ4djU1OS4xMDRjMCAzOS45MzYgMzIuMjU2IDcyLjcwNCA3Mi43MDQgNzIuNzA0aDE5OC4xNDRMNTAwLjIyNCA2ODguNjRsLTM2LjM1Mi0yMjIuNzIgMTYyLjMwNC0xMzAuNTYtNjEuNDQgMTQzLjg3MiA5Mi42NzIgMjE0LjAxNi0xMDUuNDcyIDE3MS4wMDhoMzM1LjM2QzkyNy4yMzIgODY0LjI1NiA5NjAgODMyIDk2MCA3OTEuNTUyVjIzMi40NDhjMC0zOS45MzYtMzIuMjU2LTcyLjcwNC03Mi43MDQtNzIuNzA0em0tMTM4Ljc1MiA3MS42OHYuNTEySDg1Ny42YzE2LjM4NCAwIDMwLjIwOCAxMy4zMTIgMzAuMjA4IDMwLjIwOHYzOTkuODcyTDY3My4yOCA0MDguMDY0bDc1LjI2NC0xNzYuNjR6TTMwNC42NCA3OTIuMDY0SDE2NS44ODhjLTE2LjM4NCAwLTMwLjIwOC0xMy4zMTItMzAuMjA4LTMwLjIwOHYtOS43MjhsMTM4Ljc1Mi0xNjQuMzUyIDEwNC45NiAxMjQuNDE2LTc0Ljc1MiA3OS44NzJ6bTgxLjkyLTM1NS44NGwzNy4zNzYgMjI4Ljg2NC0uNTEyLjUxMi0xNDIuODQ4LTE2OS45ODRjLTMuMDcyLTMuNTg0LTkuMjE2LTMuNTg0LTEyLjI4OCAwTDEzNS42OCA2NTIuOFYyNjIuMTQ0YzAtMTYuMzg0IDEzLjMxMi0zMC4yMDggMzAuMjA4LTMwLjIwOGg0NzQuNjI0TDM4Ni41NiA0MzYuMjI0em01MDEuMjQ4IDMyNS42MzJjMCAxNi44OTYtMTMuMzEyIDMwLjIwOC0yOS42OTYgMzAuMjA4SDY4MC45Nmw1Ny4zNDQtOTMuMTg0LTg3LjU1Mi0yMDIuMjQgNy4xNjgtNy42OCAyMjkuODg4IDI3Mi44OTZ6IiBmaWxsPSIjZTZlNmU2Ii8+PC9zdmc+';
- this._init();
- this.makeDirty(true);
- }
- };
- }
- }
-
- static override drawWith(ctx: UniverRenderingContext, picture: Picture) {
- if (picture._native?.complete) {
- const { width, height } = picture;
- try {
- ctx.drawImage(picture._native, 0, 0, width, height);
- } catch (error) {
- console.error(error);
- }
- }
- }
-
- static create(id: string, url: string, callback?: () => void): Picture {
- return new Picture(id, { url, success: callback });
- }
-
- getPictureProps(): IPictureProps {
- return this._props;
- }
-
- protected override _draw(ctx: UniverRenderingContext) {
- Picture.drawWith(ctx, this);
- }
-
- protected _init(): void {
- if (this._props.autoWidth) {
- this.resize(this._native?.width || 0);
- }
- if (this._props.autoHeight) {
- this.resize(undefined, this._native?.height || 0);
- }
- }
-}
diff --git a/packages/engine-render/src/shape/regular-polygon.ts b/packages/engine-render/src/shape/regular-polygon.ts
index 9ffbfe90cd..52617ab594 100644
--- a/packages/engine-render/src/shape/regular-polygon.ts
+++ b/packages/engine-render/src/shape/regular-polygon.ts
@@ -18,7 +18,7 @@ import type { IKeyValue } from '@univerjs/core';
import type { IObjectFullState } from '../basics/interfaces';
import { TRANSFORM_CHANGE_OBSERVABLE_TYPE } from '../basics/interfaces';
-import type { IPoint } from '../basics/vector2';
+import type { IPoint, Vector2 } from '../basics/vector2';
import type { UniverRenderingContext } from '../context';
import type { IShapeProps } from './shape';
import { Shape } from './shape';
@@ -69,6 +69,59 @@ export class RegularPolygon extends Shape<IRegularPolygonProps> {
this._renderPaintInOrder(ctx, props);
}
+ override isHit(coord: Vector2) {
+ const oCoord = this.getInverseCoord(coord);
+ if (
+ oCoord.x >= -this.strokeWidth / 2 &&
+ oCoord.x <= this.width + this.strokeWidth / 2 &&
+ oCoord.y >= -this.strokeWidth / 2 &&
+ oCoord.y <= this.height + this.strokeWidth / 2 &&
+ this._contains(oCoord)
+ ) {
+ return true;
+ }
+ return false;
+ }
+
+ // 判断点是否在多边形内(包括处理洞)
+ private _contains(point: Vector2): boolean {
+ let inside = false;
+
+ for (const vertices of this._pointsGroup) {
+ let count = 0;
+ const n = vertices.length;
+ for (let i = 0; i < n; i++) {
+ const v1 = vertices[i];
+ const v2 = vertices[(i + 1) % n];
+
+ if (this._isOnLine(point, v1, v2)) {
+ return true; // 点在边界上
+ }
+
+ if ((v1.y > point.y) !== (v2.y > point.y)) {
+ const xCross = v1.x + (point.y - v1.y) * (v2.x - v1.x) / (v2.y - v1.y);
+ if (point.x < xCross) {
+ count++;
+ }
+ }
+ }
+ // 对于每个子路径,如果点在路径内部,我们需要切换inside的状态。
+ if (count % 2 !== 0) {
+ inside = !inside;
+ }
+ }
+
+ return inside;
+ }
+
+ // 辅助函数:判断点是否在给定的线段上
+ private _isOnLine(point: IPoint, v1: IPoint, v2: IPoint): boolean {
+ const area = (v1.x - point.x) * (v2.y - point.y) - (v2.x - point.x) * (v1.y - point.y);
+ if (area !== 0) return false;
+ return point.x >= Math.min(v1.x, v2.x) && point.x <= Math.max(v1.x, v2.x) &&
+ point.y >= Math.min(v1.y, v2.y) && point.y <= Math.max(v1.y, v2.y);
+ }
+
updatePointGroup(pointGroup: IPoint[][]) {
this._pointsGroup = pointGroup;
this._setFixBoundingBox();
diff --git a/packages/engine-render/src/shape/rich-text.ts b/packages/engine-render/src/shape/rich-text.ts
index 97591d3ad1..39be2a0519 100644
--- a/packages/engine-render/src/shape/rich-text.ts
+++ b/packages/engine-render/src/shape/rich-text.ts
@@ -39,7 +39,6 @@ export interface IRichTextProps extends ITransformState, IStyleBase {
text?: string;
richText?: IDocumentData;
zIndex: number;
- isTransformer?: boolean;
forceRender?: boolean;
}
diff --git a/packages/engine-render/src/shape/shape.ts b/packages/engine-render/src/shape/shape.ts
index b4e1a04551..52277fca84 100644
--- a/packages/engine-render/src/shape/shape.ts
+++ b/packages/engine-render/src/shape/shape.ts
@@ -84,7 +84,7 @@ export const SHAPE_OBJECT_ARRAY = [
'strokeMiterLimit',
];
-export abstract class Shape<T> extends BaseObject {
+export abstract class Shape<T extends IShapeProps> extends BaseObject {
private _hoverCursor: Nullable<string>;
private _moveCursor: string | null = null;
@@ -272,24 +272,30 @@ export abstract class Shape<T> extends BaseObject {
const { stroke, strokeWidth, strokeScaleEnabled } = props;
// let { scaleX, scaleY } = props;
- let { scaleX, scaleY } = ctx.getScale();
+ // const { scaleX = 1, scaleY = 1 } = ctx.getScale();
if (!stroke || strokeWidth === 0) {
return;
}
ctx.save();
- if (strokeScaleEnabled === false) {
- scaleX = scaleX ?? 1;
- scaleY = scaleY ?? 1;
- ctx.scale(1 / scaleX, 1 / scaleY);
- }
-
+ // if (strokeScaleEnabled === false) {
+ // scaleX = scaleX === 0 ? 1 : scaleX;
+ // scaleY = scaleY === 0 ? 1 : scaleY;
+ // ctx.scale(1 / scaleX, 1 / scaleY);
+ // }
+ // this._setLineDash(ctx);
this._setStrokeStyles(ctx, props);
ctx.stroke();
ctx.restore();
}
+ // private static _getObjectScaling() {
+ // return { scaleX: 1, scaleY: 1 };
+ // }
+
+ private static _removeShadow(ctx: UniverRenderingContext) {}
+
private static _setFillStyles(ctx: UniverRenderingContext, props: IShapeProps) {
ctx.fillStyle = props.fill!;
}
@@ -326,7 +332,6 @@ export abstract class Shape<T> extends BaseObject {
const m = this.transform.getMatrix();
mainCtx.save();
-
mainCtx.transform(m[0], m[1], m[2], m[3], m[4], m[5]);
this._draw(mainCtx);
mainCtx.restore();
diff --git a/packages/engine-render/src/thin-engine.ts b/packages/engine-render/src/thin-engine.ts
index d568a68ad8..fd209acbc0 100644
--- a/packages/engine-render/src/thin-engine.ts
+++ b/packages/engine-render/src/thin-engine.ts
@@ -97,6 +97,8 @@ export abstract class ThinEngine<T extends IDisposable> extends Disposable {
this._scenes = {};
}
+ getParent() {}
+
remainScene(key: string) {
const scenes = this.getScenes();
if (scenes[key]) {
diff --git a/packages/engine-render/src/thin-scene.ts b/packages/engine-render/src/thin-scene.ts
index 2fdcafbe0a..b46a9fb132 100644
--- a/packages/engine-render/src/thin-scene.ts
+++ b/packages/engine-render/src/thin-scene.ts
@@ -233,7 +233,9 @@ export abstract class ThinScene extends Disposable {
abstract setObjectBehavior(o: BaseObject): void;
- abstract applyTransformer(o: BaseObject): void;
+ attachTransformerTo(o: BaseObject) {}
+
+ detachTransformerFrom(o: BaseObject) {}
makeDirtyNoParent(state: boolean = true): ThinScene {
return this;
diff --git a/packages/facade/src/apis/docs/f-document.ts b/packages/facade/src/apis/docs/f-document.ts
index 88cbf07172..e47f744e3e 100644
--- a/packages/facade/src/apis/docs/f-document.ts
+++ b/packages/facade/src/apis/docs/f-document.ts
@@ -43,7 +43,7 @@ export class FDocument {
}
getSnapshot(): IDocumentData {
- return this._documentDataModel.getSnapshot();
+ return this._documentDataModel.getSnapshot() as IDocumentData;
}
undo(): Promise<boolean> {
diff --git a/packages/image/README.md b/packages/image/README.md
deleted file mode 100644
index 539d9abeda..0000000000
--- a/packages/image/README.md
+++ /dev/null
@@ -1,16 +0,0 @@
-# @univerjs/image
-
-[![npm version](https://img.shields.io/npm/v/@univerjs/image)](https://npmjs.org/packages/@univerjs/image)
-[![license](https://img.shields.io/npm/l/@univerjs/image)](https://img.shields.io/npm/l/@univerjs/image)
-
-## Introduction
-
-> TODO: Introduction
-
-## Usage
-
-### Installation
-
-```shell
-npm i @univerjs/image
-```
diff --git a/packages/image/src/controllers/image.load.controller.ts b/packages/image/src/controllers/image.load.controller.ts
deleted file mode 100644
index f29ebb7589..0000000000
--- a/packages/image/src/controllers/image.load.controller.ts
+++ /dev/null
@@ -1,200 +0,0 @@
-/**
- * Copyright 2023-present DreamNum Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-import type { ICommandInfo, IFloatingObjectManagerParam } from '@univerjs/core';
-import {
- Disposable,
- ICommandService,
- IFloatingObjectManagerService,
- IUniverInstanceService,
- LifecycleStages,
- OnLifecycle,
- toDisposable,
-} from '@univerjs/core';
-import type { Scene } from '@univerjs/engine-render';
-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(
- @IUniverInstanceService private readonly _currentUniverService: IUniverInstanceService,
- @ICommandService private readonly _commandService: ICommandService,
- @IRenderManagerService private readonly _renderManagerService: IRenderManagerService,
- @IImageManagerService private readonly _imageManagerService: IImageManagerService,
- @IImageRenderService private readonly _imageRenderService: IImageRenderService,
- @IFloatingObjectManagerService private readonly _floatingObjectManagerService: IFloatingObjectManagerService
- ) {
- super();
-
- this._initialize();
- }
-
- override dispose(): void {
- super.dispose();
- }
-
- private _initialize() {
- this._floatingObjectListener();
-
- this._commandExecutedListener();
- }
-
- private _commandExecutedListener() {
- const updateCommandList: string[] = [];
-
- this.disposeWithMe(
- this._commandService.onCommandExecuted((command: ICommandInfo) => {
- if (updateCommandList.includes(command.id)) {
- return true;
- }
- })
- );
- }
-
- private _floatingObjectListener() {
- this.disposeWithMe(
- toDisposable(
- this._floatingObjectManagerService.andOrUpdate$.subscribe((params) => {
- const sceneList: Scene[] = [];
- params.forEach((param) => {
- const { unitId, subUnitId, floatingObjectId, floatingObject, behindText } = param;
-
- const renderObject = this._renderManagerService.getRenderById(unitId);
-
- const scene = renderObject?.scene;
-
- if (scene == null) {
- return true;
- }
-
- const searchParam = {
- unitId,
- subUnitId,
- imageId: floatingObjectId,
- };
-
- const imageModel = this._imageManagerService.getImageByParam(searchParam)?.imageModel;
-
- if (imageModel == null) {
- return true;
- }
-
- const { left, top, width, height, angle, flipX, flipY, skewX, skewY } = floatingObject;
-
- const imageShapeKey = `${unitId}_${subUnitId}_${floatingObjectId}`;
-
- const imageShape = scene.getObject(imageShapeKey);
-
- if (imageShape != null) {
- imageShape.transformByState({
- left,
- top,
- width,
- height,
- angle,
- flipX,
- flipY,
- skewX,
- skewY,
- });
- return;
- }
-
- this._imageRenderService.add(imageShapeKey, searchParam);
-
- const image = new Picture(imageShapeKey, {
- url: imageModel.getUrl(),
- left,
- top,
- width,
- height,
- zIndex: 11,
- isTransformer: true,
- });
-
- if (!scene.getTransformer()) {
- scene.openTransformer();
- }
-
- scene.addObject(image, behindText ? IMAGE_BEHIND_TEXT_LAYER_INDEX : IMAGE_DEFAULT_LAYER_INDEX);
-
- if (!sceneList.includes(scene)) {
- sceneList.push(scene);
- }
- });
-
- sceneList.forEach((scene) => {
- this._addListenerOnImage(scene);
- scene.closeTransformer();
- });
- })
- )
- );
- }
-
- private _addListenerOnImage(scene: Scene) {
- scene.getTransformer()?.onChangingObservable.add((state) => {
- const { objects } = state;
-
- // const { docsLeft, docsTop } = documents;
- const params: IFloatingObjectManagerParam[] = [];
- objects.forEach((object) => {
- const { oKey, left, top, height, width } = object;
-
- const searchParam = this._imageRenderService.get(oKey);
-
- if (searchParam == null) {
- return true;
- }
-
- const { unitId, subUnitId, imageId } = searchParam;
-
- params.push({
- unitId,
- subUnitId,
- floatingObjectId: imageId,
- floatingObject: {
- left,
- top,
- height,
- width,
- },
- });
-
- // const cache = pageMarginCache.get(oKey);
- // const marginLeft = cache?.marginLeft || 0;
- // const marginTop = cache?.marginTop || 0;
-
- // console.log('onChangingObservable', top, docsTop, marginTop, top - docsTop - marginTop);
-
- // docsSkeleton?.getViewModel().updateDrawing(oKey, {
- // left: left - docsLeft - marginLeft,
- // top: top - docsTop - marginTop,
- // height,
- // width,
- // });
- });
-
- this._floatingObjectManagerService.pluginUpdateRefresh(params);
- });
- }
-}
diff --git a/packages/image/src/plugin.ts b/packages/image/src/plugin.ts
deleted file mode 100644
index ba1aa98bf4..0000000000
--- a/packages/image/src/plugin.ts
+++ /dev/null
@@ -1,129 +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 { DEFAULT_DOCUMENT_SUB_COMPONENT_ID, Plugin } from '@univerjs/core';
-import type { Dependency, Injector } from '@wendellhu/redi';
-
-import { ImageLoadController } from './controllers/image.load.controller';
-import { ImageModel } from './models/image-model';
-import { IImageManagerService, ImageManagerService } from './services/image-manager.service';
-import { IImageRenderService, ImageRenderService } from './services/image-render.service';
-
-const PLUGIN_NAME = 'IMAGE_PLUGIN';
-
-export class UniverImagePlugin extends Plugin {
- static override pluginName = PLUGIN_NAME;
-
- constructor(
- _config: undefined,
- protected _injector: Injector
- ) {
- super();
- }
-
- override onStarting(_injector: Injector): void {
- this._initDependencies(_injector);
- this._injector = _injector;
-
- this._mockAddImage();
- }
-
- 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://static01.nyt.com/images/2019/09/04/business/04chinaclone-01/merlin_160087014_de761d9a-4360-402d-a15b-ddeff775760d-master1050.jpg',
- });
- imageManagerService.add({
- unitId: 'd',
- subUnitId: DEFAULT_DOCUMENT_SUB_COMPONENT_ID,
- imageId: 'shapeTest1',
- 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',
- // },
-
- // imageProperties: {
- // contentUrl: 'https://minio.cnbabylon.com/univer/slide/hype-cycle-for-emerging-tech-2022.png',
- // },
- }
-
- private _initDependencies(injector: Injector): void {
- const dependencies: Dependency[] = [
- // legacy managers - deprecated
- // [ComponentManager],
- // [ZIndexManager],
- // services
- [IImageManagerService, { useClass: ImageManagerService }],
- [IImageRenderService, { useClass: ImageRenderService }],
- // controllers
- [ImageLoadController],
- // [SharedController],
- // [IUIController, { useClass: DesktopUIController }],
- ];
-
- dependencies.forEach((dependency) => injector.add(dependency));
- }
-}
diff --git a/packages/image/src/services/image-manager.service.ts b/packages/image/src/services/image-manager.service.ts
deleted file mode 100644
index 5912a4e498..0000000000
--- a/packages/image/src/services/image-manager.service.ts
+++ /dev/null
@@ -1,167 +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 { Nullable } from '@univerjs/core';
-import type { IDisposable } from '@wendellhu/redi';
-import { createIdentifier } from '@wendellhu/redi';
-import type { Observable } from 'rxjs';
-import { Subject } from 'rxjs';
-
-import type { ImageModel } from '../models/image-model';
-
-export interface IImageManagerSearchParam {
- unitId: string;
- subUnitId: string; //sheetId, pageId and so on, it has a default name in doc business
- imageId: string;
-}
-
-export interface IImageManagerParam extends IImageManagerSearchParam {
- imageModel: ImageModel;
-}
-
-export type ImageManagerInfo = Map<string, Map<string, Map<string, IImageManagerParam>>>;
-
-export interface IImageManagerService {
- readonly remove$: Observable<IImageManagerParam[]>;
-
- readonly andOrUpdate$: Observable<IImageManagerSearchParam[]>;
-
- dispose(): void;
-
- add(insertParam: IImageManagerParam): void;
-
- batchAdd(insertParams: IImageManagerParam[]): void;
-
- remove(searchParam: IImageManagerSearchParam): void;
-
- batchRemove(removeParams: IImageManagerSearchParam[]): void;
-
- setCurrent(searchParam: Nullable<IImageManagerSearchParam>): void;
-
- getCurrent(): Nullable<IImageManagerParam>;
-
- getImageByParam(param: Nullable<IImageManagerSearchParam>): Nullable<IImageManagerParam>;
-}
-
-/**
- *
- */
-export class ImageManagerService implements IDisposable, IImageManagerService {
- private _current: Nullable<IImageManagerSearchParam> = null;
-
- private _imageManagerInfo: ImageManagerInfo = new Map();
-
- private readonly _remove$ = new Subject<IImageManagerParam[]>();
- readonly remove$ = this._remove$.asObservable();
-
- private readonly _add$ = new Subject<IImageManagerSearchParam[]>();
- readonly andOrUpdate$ = this._add$.asObservable();
-
- dispose(): void {
- this._remove$.complete();
- this._add$.complete();
- this._imageManagerInfo.clear();
- }
-
- add(insertParam: IImageManagerParam) {
- this._add$.next(this._addByParam(insertParam));
- }
-
- batchAdd(insertParams: IImageManagerParam[]) {
- const objects: IImageManagerSearchParam[] = [];
- insertParams.forEach((insertParam) => {
- objects.push(...this._addByParam(insertParam));
- });
-
- this._add$.next(objects);
- }
-
- remove(searchParam: IImageManagerSearchParam) {
- this._remove$.next(this._removeByParam(searchParam));
- }
-
- batchRemove(removeParams: IImageManagerSearchParam[]) {
- const objects: IImageManagerParam[] = [];
- removeParams.forEach((removeParam) => {
- objects.push(...this._removeByParam(removeParam));
- });
-
- this._remove$.next(objects);
- }
-
- setCurrent(searchParam: Nullable<IImageManagerSearchParam>) {
- this._current = searchParam;
- }
-
- getCurrent(): Nullable<IImageManagerParam> {
- return this._getCurrentBySearch(this._current);
- }
-
- getImageByParam(param: Nullable<IImageManagerSearchParam>): Nullable<IImageManagerParam> {
- return this._getCurrentBySearch(param);
- }
-
- private _getCurrentBySearch(searchParam: Nullable<IImageManagerSearchParam>): Nullable<IImageManagerParam> {
- if (searchParam == null) {
- return;
- }
- const { unitId, subUnitId, imageId } = searchParam;
- return this._imageManagerInfo.get(unitId)?.get(subUnitId)?.get(imageId);
- }
-
- private _addByParam(insertParam: IImageManagerParam): IImageManagerSearchParam[] {
- const { unitId, subUnitId, imageId, imageModel } = insertParam;
-
- if (!this._imageManagerInfo.has(unitId)) {
- this._imageManagerInfo.set(unitId, new Map());
- }
-
- const subComponentData = this._imageManagerInfo.get(unitId)!;
-
- if (!subComponentData.has(subUnitId)) {
- subComponentData.set(subUnitId, new Map());
- }
-
- subComponentData.get(subUnitId)!.set(imageId, insertParam);
-
- return [{ unitId, subUnitId, imageId }];
- }
-
- private _removeByParam(searchParam: IImageManagerSearchParam): IImageManagerParam[] {
- if (searchParam == null) {
- return [];
- }
- const { unitId, subUnitId, imageId } = searchParam;
-
- const subComponentObjects = this._imageManagerInfo.get(unitId)?.get(subUnitId);
-
- if (subComponentObjects == null) {
- return [];
- }
-
- const object = subComponentObjects.get(imageId);
-
- if (object == null) {
- return [];
- }
-
- subComponentObjects.delete(imageId);
-
- return [{ ...searchParam, imageModel: object.imageModel }];
- }
-}
-
-export const IImageManagerService = createIdentifier<IImageManagerService>('univer.plugin.image-manager.service');
diff --git a/packages/image/src/services/image-render.service.ts b/packages/image/src/services/image-render.service.ts
deleted file mode 100644
index f6f4b03a27..0000000000
--- a/packages/image/src/services/image-render.service.ts
+++ /dev/null
@@ -1,60 +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 { Nullable } from '@univerjs/core';
-import type { IDisposable } from '@wendellhu/redi';
-import { createIdentifier } from '@wendellhu/redi';
-
-export interface IImageRenderParam {
- unitId: string;
- subUnitId: string; //sheetId, pageId and so on, it has a default name in doc business
- imageId: string;
-}
-
-export interface IImageRenderService {
- dispose(): void;
-
- add(key: string, param: IImageRenderParam): void;
-
- remove(key: string): void;
-
- get(key: string): Nullable<IImageRenderParam>;
-}
-
-/**
- *
- */
-export class ImageRenderService implements IDisposable, IImageRenderService {
- private _imageRenderInfo: Map<string, IImageRenderParam> = new Map();
-
- dispose(): void {
- this._imageRenderInfo.clear();
- }
-
- add(key: string, param: IImageRenderParam) {
- this._imageRenderInfo.set(key, param);
- }
-
- remove(key: string) {
- this._imageRenderInfo.delete(key);
- }
-
- get(key: string): Nullable<IImageRenderParam> {
- return this._imageRenderInfo.get(key);
- }
-}
-
-export const IImageRenderService = createIdentifier<IImageRenderService>('univer.plugin.image-render.service');
diff --git a/packages/sheets-drawing-ui/README.md b/packages/sheets-drawing-ui/README.md
new file mode 100644
index 0000000000..c6765be2d3
--- /dev/null
+++ b/packages/sheets-drawing-ui/README.md
@@ -0,0 +1,16 @@
+# @univerjs/sheets-drawing-ui
+
+[![npm version](https://img.shields.io/npm/v/@univerjs/sheets-drawing-ui)](https://npmjs.org/packages/@univerjs/sheets-drawing-ui)
+[![license](https://img.shields.io/npm/l/@univerjs/sheets-drawing-ui)](https://img.shields.io/npm/l/@univerjs/sheets-drawing-ui)
+
+## Introduction
+
+> TODO: Introduction
+
+## Usage
+
+### Installation
+
+```shell
+npm i @univerjs/sheets-drawing-ui
+```
diff --git a/packages/sheets-drawing-ui/package.json b/packages/sheets-drawing-ui/package.json
new file mode 100644
index 0000000000..18ee7715bc
--- /dev/null
+++ b/packages/sheets-drawing-ui/package.json
@@ -0,0 +1,99 @@
+{
+ "name": "@univerjs/sheets-drawing-ui",
+ "version": "0.0.1",
+ "private": true,
+ "description": "",
+ "author": "DreamNum <[email protected]>",
+ "license": "Apache-2.0",
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/univer"
+ },
+ "homepage": "https://univer.ai",
+ "repository": {
+ "type": "git",
+ "url": "https://github.com/dream-num/univer"
+ },
+ "bugs": {
+ "url": "https://github.com/dream-num/univer/issues"
+ },
+ "keywords": [],
+ "sideEffects": [
+ "**/*.css"
+ ],
+ "exports": {
+ ".": "./src/index.ts",
+ "./*": "./src/*",
+ "./locale/*": "./src/locale/*.ts"
+ },
+ "main": "./lib/cjs/index.js",
+ "module": "./lib/es/index.js",
+ "types": "./lib/types/index.d.ts",
+ "publishConfig": {
+ "access": "public",
+ "main": "./lib/cjs/index.js",
+ "module": "./lib/es/index.js",
+ "exports": {
+ ".": {
+ "import": "./lib/es/index.js",
+ "require": "./lib/cjs/index.js",
+ "types": "./lib/types/index.d.ts"
+ },
+ "./*": {
+ "import": "./lib/es/*",
+ "require": "./lib/cjs/*",
+ "types": "./lib/types/index.d.ts"
+ },
+ "./locale/*": "./lib/locale/*.json",
+ "./lib/*": "./lib/*"
+ }
+ },
+ "directories": {
+ "lib": "lib"
+ },
+ "files": [
+ "lib"
+ ],
+ "engines": {
+ "node": ">=16.0.0",
+ "npm": ">=8.0.0"
+ },
+ "scripts": {
+ "test": "vitest run",
+ "test:watch": "vitest",
+ "coverage": "vitest run --coverage",
+ "lint:types": "tsc --noEmit",
+ "build": "tsc && vite build"
+ },
+ "peerDependencies": {
+ "@univerjs/core": "workspace:*",
+ "@univerjs/design": "workspace:*",
+ "@univerjs/ui": "workspace:*",
+ "@wendellhu/redi": "0.15.2",
+ "clsx": ">=2.0.0",
+ "react": ">=16.9.0",
+ "rxjs": ">=7.0.0"
+ },
+ "dependencies": {
+ "@univerjs/icons": "^0.1.29"
+ },
+ "devDependencies": {
+ "@univerjs/core": "workspace:*",
+ "@univerjs/design": "workspace:*",
+ "@univerjs/drawing": "workspace:*",
+ "@univerjs/drawing-ui": "workspace:*",
+ "@univerjs/engine-render": "workspace:*",
+ "@univerjs/shared": "workspace:*",
+ "@univerjs/sheets": "workspace:*",
+ "@univerjs/sheets-ui": "workspace:*",
+ "@univerjs/ui": "workspace:*",
+ "@wendellhu/redi": "0.15.2",
+ "clsx": "^2.1.0",
+ "less": "^4.2.0",
+ "react": "^18.2.0",
+ "rxjs": "^7.8.1",
+ "typescript": "^5.3.3",
+ "vite": "^5.1.4",
+ "vitest": "^1.3.1"
+ }
+}
diff --git a/packages/sheets-drawing-ui/src/basics/transform-position.ts b/packages/sheets-drawing-ui/src/basics/transform-position.ts
new file mode 100644
index 0000000000..a7de44ea9c
--- /dev/null
+++ b/packages/sheets-drawing-ui/src/basics/transform-position.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 { ITransformState, Nullable } from '@univerjs/core';
+import { precisionTo } from '@univerjs/engine-render';
+import type { ISheetDrawingPosition } from '@univerjs/sheets';
+import type { ISelectionRenderService } from '@univerjs/sheets-ui';
+
+export function drawingPositionToTransform(position: ISheetDrawingPosition, selectionRenderService: ISelectionRenderService): Nullable<ITransformState> {
+ const { from, to } = position;
+ const { column: fromColumn, columnOffset: fromColumnOffset, row: fromRow, rowOffset: fromRowOffset } = from;
+ const { column: toColumn, columnOffset: toColumnOffset, row: toRow, rowOffset: toRowOffset } = to;
+
+ const startSelectionCell = selectionRenderService.attachRangeWithCoord({
+ startColumn: fromColumn,
+ endColumn: fromColumn,
+ startRow: fromRow,
+ endRow: fromRow,
+ });
+
+ if (startSelectionCell == null) {
+ return;
+ }
+
+ const endSelectionCell = selectionRenderService.attachRangeWithCoord({
+ startColumn: toColumn,
+ endColumn: toColumn,
+ startRow: toRow,
+ endRow: toRow,
+ });
+
+ if (endSelectionCell == null) {
+ return;
+ }
+
+ const { startX: startSelectionX, startY: startSelectionY } = startSelectionCell;
+
+ const { startX: endSelectionX, startY: endSelectionY } = endSelectionCell;
+
+ const left = precisionTo(startSelectionX + fromColumnOffset, 1);
+ const top = precisionTo(startSelectionY + fromRowOffset, 1);
+
+ let width = precisionTo(endSelectionX + toColumnOffset - left, 1);
+ let height = precisionTo(endSelectionY + toRowOffset - top, 1);
+
+ if (startSelectionCell.startX === endSelectionCell.endX) {
+ width = 0;
+ }
+
+ if (startSelectionCell.startY === endSelectionCell.endY) {
+ height = 0;
+ }
+
+ return {
+ left,
+ top,
+ width,
+ height,
+ };
+}
+
+// use transform and originSize convert to ISheetDrawingPosition
+export function transformToDrawingPosition(transform: ITransformState, selectionRenderService: ISelectionRenderService): Nullable<ISheetDrawingPosition> {
+ const { left = 0, top = 0, width = 0, height = 0 } = transform;
+
+ const startSelectionCell = selectionRenderService.getSelectionCellByPosition(left, top);
+
+ if (startSelectionCell == null) {
+ return;
+ }
+
+ const from = {
+ column: startSelectionCell.actualColumn,
+ columnOffset: precisionTo(left - startSelectionCell.startX, 1),
+ row: startSelectionCell.actualRow,
+ rowOffset: precisionTo(top - startSelectionCell.startY, 1),
+ };
+
+ const endSelectionCell = selectionRenderService.getSelectionCellByPosition(left + width, top + height);
+
+ if (endSelectionCell == null) {
+ return;
+ }
+
+ const to = {
+ column: endSelectionCell.actualColumn,
+ columnOffset: precisionTo(left + width - endSelectionCell.startX, 1),
+ row: endSelectionCell.actualRow,
+ rowOffset: precisionTo(top + height - endSelectionCell.startY, 1),
+ };
+
+ return {
+ from,
+ to,
+ };
+}
diff --git a/packages/sheets-drawing-ui/src/commands/commands/delete-drawings.command.ts b/packages/sheets-drawing-ui/src/commands/commands/delete-drawings.command.ts
new file mode 100644
index 0000000000..44785d2051
--- /dev/null
+++ b/packages/sheets-drawing-ui/src/commands/commands/delete-drawings.command.ts
@@ -0,0 +1,54 @@
+/**
+ * Copyright 2023-present DreamNum Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { CommandType, type ICommand, ICommandService } from '@univerjs/core';
+import type { ISheetDrawing } from '@univerjs/sheets';
+import { ISheetDrawingService } from '@univerjs/sheets';
+import type { IAccessor } from '@wendellhu/redi';
+import { RemoveSheetDrawingCommand } from './remove-sheet-drawing.command';
+import type { IDeleteDrawingCommandParams } from './interfaces';
+
+export const DeleteDrawingsCommand: ICommand = {
+ id: 'sheet.command.delete-drawing',
+ type: CommandType.COMMAND,
+ handler: (accessor: IAccessor) => {
+ const commandService = accessor.get(ICommandService);
+ const drawingManagerService = accessor.get(ISheetDrawingService);
+
+ const drawings = drawingManagerService.getFocusDrawings();
+
+ if (drawings.length === 0) {
+ return false;
+ }
+
+ const unitId = drawings[0].unitId;
+
+ const newDrawings = drawings.map((drawing) => {
+ const { unitId, subUnitId, drawingId, drawingType } = drawing as ISheetDrawing;
+
+ return {
+ unitId,
+ subUnitId,
+ drawingId,
+ drawingType,
+ };
+ });
+ return commandService.executeCommand<IDeleteDrawingCommandParams>(RemoveSheetDrawingCommand.id, {
+ unitId,
+ drawings: newDrawings,
+ });
+ },
+};
diff --git a/packages/sheets-drawing-ui/src/commands/commands/group-sheet-drawing.command.ts b/packages/sheets-drawing-ui/src/commands/commands/group-sheet-drawing.command.ts
new file mode 100644
index 0000000000..74dffc79f7
--- /dev/null
+++ b/packages/sheets-drawing-ui/src/commands/commands/group-sheet-drawing.command.ts
@@ -0,0 +1,76 @@
+/**
+ * Copyright 2023-present DreamNum Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { ICommand, IDrawingGroupUpdateParam } from '@univerjs/core';
+import {
+ CommandType,
+ ICommandService,
+ IUndoRedoService,
+} from '@univerjs/core';
+
+import { DrawingApplyType, ISheetDrawingService, SetDrawingApplyMutation } from '@univerjs/sheets';
+import type { IAccessor } from '@wendellhu/redi';
+import type { IDrawingJsonUndo1 } from '@univerjs/drawing';
+import { ClearSheetDrawingTransformerOperation } from '../operations/clear-drawing-transformer.operation';
+import { groupToUngroup } from './utils';
+
+/**
+ * The command to insert new defined name
+ */
+export const GroupSheetDrawingCommand: ICommand = {
+ id: 'sheet.command.group-sheet-image',
+ type: CommandType.COMMAND,
+ handler: (accessor: IAccessor, params?: IDrawingGroupUpdateParam[]) => {
+ const commandService = accessor.get(ICommandService);
+ const undoRedoService = accessor.get(IUndoRedoService);
+ const sheetDrawingService = accessor.get(ISheetDrawingService);
+
+ if (!params) return false;
+
+ const unitIds: string[] = [];
+ params.forEach(({ parent, children }) => {
+ unitIds.push(parent.unitId);
+ children.forEach((child) => {
+ unitIds.push(child.unitId);
+ });
+ });
+
+ // execute do mutations and add undo mutations to undo stack if completed
+ const jsonOp = sheetDrawingService.getGroupDrawingOp(params) as IDrawingJsonUndo1;
+
+ const { unitId, subUnitId, undo, redo, objects } = jsonOp;
+
+ const result = commandService.syncExecuteCommand(SetDrawingApplyMutation.id, { op: redo, unitId, subUnitId, objects, type: DrawingApplyType.GROUP });
+
+ if (result) {
+ undoRedoService.pushUndoRedo({
+ unitID: unitId,
+ undoMutations: [
+ { id: SetDrawingApplyMutation.id, params: { op: undo, unitId, subUnitId, objects: groupToUngroup(objects as IDrawingGroupUpdateParam[]), type: DrawingApplyType.UNGROUP } },
+ { id: ClearSheetDrawingTransformerOperation.id, params: unitIds },
+ ],
+ redoMutations: [
+ { id: SetDrawingApplyMutation.id, params: { op: redo, unitId, subUnitId, objects, type: DrawingApplyType.GROUP } },
+ { id: ClearSheetDrawingTransformerOperation.id, params: unitIds },
+ ],
+ });
+
+ return true;
+ }
+
+ return false;
+ },
+};
diff --git a/packages/sheets-drawing-ui/src/commands/commands/insert-sheet-drawing.command.ts b/packages/sheets-drawing-ui/src/commands/commands/insert-sheet-drawing.command.ts
new file mode 100644
index 0000000000..75f0fe4f65
--- /dev/null
+++ b/packages/sheets-drawing-ui/src/commands/commands/insert-sheet-drawing.command.ts
@@ -0,0 +1,75 @@
+/**
+ * Copyright 2023-present DreamNum Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { ICommand } from '@univerjs/core';
+import {
+ CommandType,
+ ICommandService,
+ IUndoRedoService,
+} from '@univerjs/core';
+
+import { DrawingApplyType, ISheetDrawingService, SetDrawingApplyMutation } from '@univerjs/sheets';
+import type { IAccessor } from '@wendellhu/redi';
+import type { IDrawingJsonUndo1 } from '@univerjs/drawing';
+import { ClearSheetDrawingTransformerOperation } from '../operations/clear-drawing-transformer.operation';
+import type { IInsertDrawingCommandParams } from './interfaces';
+
+/**
+ * The command to insert new defined name
+ */
+export const InsertSheetDrawingCommand: ICommand = {
+ id: 'sheet.command.insert-sheet-image',
+ type: CommandType.COMMAND,
+ handler: (accessor: IAccessor, params?: IInsertDrawingCommandParams) => {
+ const commandService = accessor.get(ICommandService);
+ const undoRedoService = accessor.get(IUndoRedoService);
+ const sheetDrawingService = accessor.get(ISheetDrawingService);
+
+ if (!params) return false;
+
+ // const { drawingParam, imageParam } = params;
+
+ const drawings = params.drawings;
+
+ // const sheetDrawingParams = drawings.map((param) => param.sheetDrawingParam);
+ const unitIds: string[] = drawings.map((param) => param.unitId);
+
+ // execute do mutations and add undo mutations to undo stack if completed
+ const jsonOp = sheetDrawingService.getBatchAddOp(drawings) as IDrawingJsonUndo1;
+
+ const { unitId, subUnitId, undo, redo, objects } = jsonOp;
+
+ const result = commandService.syncExecuteCommand(SetDrawingApplyMutation.id, { op: redo, unitId, subUnitId, objects, type: DrawingApplyType.INSERT });
+
+ if (result) {
+ undoRedoService.pushUndoRedo({
+ unitID: unitId,
+ undoMutations: [
+ { id: SetDrawingApplyMutation.id, params: { op: undo, unitId, subUnitId, objects, type: DrawingApplyType.REMOVE } },
+ { id: ClearSheetDrawingTransformerOperation.id, params: unitIds },
+ ],
+ redoMutations: [
+ { id: SetDrawingApplyMutation.id, params: { op: redo, unitId, subUnitId, objects, type: DrawingApplyType.INSERT } },
+ { id: ClearSheetDrawingTransformerOperation.id, params: unitIds },
+ ],
+ });
+
+ return true;
+ }
+
+ return false;
+ },
+};
diff --git a/packages/sheets-drawing-ui/src/commands/commands/interfaces.ts b/packages/sheets-drawing-ui/src/commands/commands/interfaces.ts
new file mode 100644
index 0000000000..750e00c284
--- /dev/null
+++ b/packages/sheets-drawing-ui/src/commands/commands/interfaces.ts
@@ -0,0 +1,40 @@
+/**
+ * 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 { DrawingTypeEnum } from '@univerjs/core';
+import type { ISheetDrawing } from '@univerjs/sheets';
+
+export interface IInsertDrawingCommandParams {
+ unitId: string;
+ drawings: ISheetDrawing[];
+}
+
+export interface IDeleteDrawingCommandParam {
+ unitId: string;
+ subUnitId: string;
+ drawingId: string;
+ drawingType: DrawingTypeEnum;
+}
+
+export interface IDeleteDrawingCommandParams {
+ unitId: string;
+ drawings: IDeleteDrawingCommandParam[];
+}
+
+export interface ISetDrawingCommandParams {
+ unitId: string;
+ drawings: Partial<ISheetDrawing>[];
+}
diff --git a/packages/sheets-drawing-ui/src/commands/commands/move-drawings.command.ts b/packages/sheets-drawing-ui/src/commands/commands/move-drawings.command.ts
new file mode 100644
index 0000000000..3c41109647
--- /dev/null
+++ b/packages/sheets-drawing-ui/src/commands/commands/move-drawings.command.ts
@@ -0,0 +1,89 @@
+/**
+ * Copyright 2023-present DreamNum Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { ICommand } from '@univerjs/core';
+import { CommandType, Direction, ICommandService } from '@univerjs/core';
+import type { ISheetDrawing } from '@univerjs/sheets';
+import { ISheetDrawingService } from '@univerjs/sheets';
+import type { IAccessor } from '@wendellhu/redi';
+import { ISelectionRenderService } from '@univerjs/sheets-ui';
+
+import { transformToDrawingPosition } from '../../basics/transform-position';
+import { ClearSheetDrawingTransformerOperation } from '../operations/clear-drawing-transformer.operation';
+import type { ISetDrawingCommandParams } from './interfaces';
+import { SetSheetDrawingCommand } from './set-sheet-drawing.command';
+
+export interface IMoveDrawingsCommandParams {
+ direction: Direction ;
+}
+
+export const MoveDrawingsCommand: ICommand = {
+ id: 'sheet.command.move-drawing',
+ type: CommandType.COMMAND,
+ handler: (accessor: IAccessor, params: IMoveDrawingsCommandParams) => {
+ const commandService = accessor.get(ICommandService);
+ const drawingManagerService = accessor.get(ISheetDrawingService);
+ const selectionRenderService = accessor.get(ISelectionRenderService);
+
+ const { direction } = params;
+
+ const drawings = drawingManagerService.getFocusDrawings();
+
+ if (drawings.length === 0) {
+ return false;
+ }
+
+ const unitId = drawings[0].unitId;
+
+ const newDrawings = drawings.map((drawing) => {
+ const { transform } = drawing as ISheetDrawing;
+ if (transform == null) {
+ return null;
+ }
+ const newTransform = { ...transform };
+
+ const { left = 0, top = 0 } = transform;
+
+ if (direction === Direction.UP) {
+ newTransform.top = top - 1;
+ } else if (direction === Direction.DOWN) {
+ newTransform.top = top + 1;
+ } else if (direction === Direction.LEFT) {
+ newTransform.left = left - 1;
+ } else if (direction === Direction.RIGHT) {
+ newTransform.left = left + 1;
+ }
+
+ return {
+ ...drawing,
+ transform: newTransform,
+ sheetTransform: transformToDrawingPosition(newTransform, selectionRenderService),
+ } as ISheetDrawing;
+ }).filter((drawing) => drawing != null) as ISheetDrawing[];
+
+ const result = commandService.syncExecuteCommand<ISetDrawingCommandParams>(SetSheetDrawingCommand.id, {
+ unitId,
+ drawings: newDrawings,
+ });
+
+ if (result) {
+ commandService.syncExecuteCommand(ClearSheetDrawingTransformerOperation.id, [unitId]);
+ return true;
+ }
+
+ return false;
+ },
+};
diff --git a/packages/sheets-drawing-ui/src/commands/commands/remove-sheet-drawing.command.ts b/packages/sheets-drawing-ui/src/commands/commands/remove-sheet-drawing.command.ts
new file mode 100644
index 0000000000..a06dc9d268
--- /dev/null
+++ b/packages/sheets-drawing-ui/src/commands/commands/remove-sheet-drawing.command.ts
@@ -0,0 +1,77 @@
+/**
+ * Copyright 2023-present DreamNum Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { ICommand } from '@univerjs/core';
+import {
+ CommandType,
+ ICommandService,
+ IUndoRedoService,
+} from '@univerjs/core';
+import { DrawingApplyType, ISheetDrawingService, SetDrawingApplyMutation } from '@univerjs/sheets';
+import type { IAccessor } from '@wendellhu/redi';
+import type { IDrawingJsonUndo1 } from '@univerjs/drawing';
+import { ClearSheetDrawingTransformerOperation } from '../operations/clear-drawing-transformer.operation';
+import type { IDeleteDrawingCommandParams } from './interfaces';
+
+/**
+ * The command to remove new sheet image
+ */
+export const RemoveSheetDrawingCommand: ICommand = {
+ id: 'sheet.command.remove-sheet-image',
+ type: CommandType.COMMAND,
+ handler: (accessor: IAccessor, params?: IDeleteDrawingCommandParams) => {
+ const commandService = accessor.get(ICommandService);
+ const undoRedoService = accessor.get(IUndoRedoService);
+
+ const sheetDrawingService = accessor.get(ISheetDrawingService);
+
+ if (!params) return false;
+
+ const { drawings } = params;
+
+ const unitIds: string[] = [];
+
+ drawings.forEach((param) => {
+ const { unitId } = param;
+ unitIds.push(unitId);
+ });
+
+ const jsonOp = sheetDrawingService.getBatchRemoveOp(drawings) as IDrawingJsonUndo1;
+
+ const { unitId, subUnitId, undo, redo, objects } = jsonOp;
+
+ // execute do mutations and add undo mutations to undo stack if completed
+ const result = commandService.syncExecuteCommand(SetDrawingApplyMutation.id, { unitId, subUnitId, op: redo, objects, type: DrawingApplyType.REMOVE });
+
+ if (result) {
+ undoRedoService.pushUndoRedo({
+ unitID: unitId,
+ undoMutations: [
+ { id: SetDrawingApplyMutation.id, params: { unitId, subUnitId, op: undo, objects, type: DrawingApplyType.INSERT } },
+ { id: ClearSheetDrawingTransformerOperation.id, params: unitIds },
+ ],
+ redoMutations: [
+ { id: SetDrawingApplyMutation.id, params: { unitId, subUnitId, op: redo, objects, type: DrawingApplyType.REMOVE } },
+ { id: ClearSheetDrawingTransformerOperation.id, params: unitIds },
+ ],
+ });
+
+ return true;
+ }
+
+ return false;
+ },
+};
diff --git a/packages/sheets-drawing-ui/src/commands/commands/set-drawing-arrange.command.ts b/packages/sheets-drawing-ui/src/commands/commands/set-drawing-arrange.command.ts
new file mode 100644
index 0000000000..3993866a4c
--- /dev/null
+++ b/packages/sheets-drawing-ui/src/commands/commands/set-drawing-arrange.command.ts
@@ -0,0 +1,84 @@
+/**
+ * Copyright 2023-present DreamNum Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { ICommand, IDrawingOrderMapParam, Nullable } from '@univerjs/core';
+import { ArrangeTypeEnum,
+ CommandType,
+ ICommandService,
+ IUndoRedoService,
+} from '@univerjs/core';
+import type { IDrawingJsonUndo1 } from '@univerjs/drawing';
+import { DrawingApplyType, ISheetDrawingService, SetDrawingApplyMutation } from '@univerjs/sheets';
+import type { IAccessor } from '@wendellhu/redi';
+
+export interface ISetDrawingArrangeCommandParams extends IDrawingOrderMapParam {
+ arrangeType: ArrangeTypeEnum;
+}
+
+/**
+ * The command to insert new defined name
+ */
+export const SetDrawingArrangeCommand: ICommand = {
+ id: 'sheet.command.set-drawing-arrange',
+ type: CommandType.COMMAND,
+ handler: (accessor: IAccessor, params?: ISetDrawingArrangeCommandParams) => {
+ const commandService = accessor.get(ICommandService);
+ const undoRedoService = accessor.get(IUndoRedoService);
+
+ if (!params) return false;
+
+ const sheetDrawingService = accessor.get(ISheetDrawingService);
+
+ const { unitId, subUnitId, drawingIds, arrangeType } = params;
+
+ const drawingOrderMapParam = { unitId, subUnitId, drawingIds } as IDrawingOrderMapParam;
+
+ let jsonOp: Nullable<IDrawingJsonUndo1>;
+ if (arrangeType === ArrangeTypeEnum.forward) {
+ jsonOp = sheetDrawingService.getForwardDrawingsOp(drawingOrderMapParam) as IDrawingJsonUndo1;
+ } else if (arrangeType === ArrangeTypeEnum.backward) {
+ jsonOp = sheetDrawingService.getBackwardDrawingOp(drawingOrderMapParam) as IDrawingJsonUndo1;
+ } else if (arrangeType === ArrangeTypeEnum.front) {
+ jsonOp = sheetDrawingService.getFrontDrawingsOp(drawingOrderMapParam) as IDrawingJsonUndo1;
+ } else if (arrangeType === ArrangeTypeEnum.back) {
+ jsonOp = sheetDrawingService.getBackDrawingsOp(drawingOrderMapParam) as IDrawingJsonUndo1;
+ }
+
+ if (jsonOp == null) {
+ return false;
+ }
+
+ const { objects, redo, undo } = jsonOp;
+
+ const result = commandService.syncExecuteCommand(SetDrawingApplyMutation.id, { op: redo, unitId, subUnitId, objects, type: DrawingApplyType.ARRANGE });
+
+ if (result) {
+ undoRedoService.pushUndoRedo({
+ unitID: unitId,
+ undoMutations: [
+ { id: SetDrawingApplyMutation.id, params: { op: undo, unitId, subUnitId, objects, type: DrawingApplyType.ARRANGE } },
+ ],
+ redoMutations: [
+ { id: SetDrawingApplyMutation.id, params: { op: redo, unitId, subUnitId, objects, type: DrawingApplyType.ARRANGE } },
+ ],
+ });
+
+ return true;
+ }
+
+ return false;
+ },
+};
diff --git a/packages/sheets-drawing-ui/src/commands/commands/set-sheet-drawing.command.ts b/packages/sheets-drawing-ui/src/commands/commands/set-sheet-drawing.command.ts
new file mode 100644
index 0000000000..931238911e
--- /dev/null
+++ b/packages/sheets-drawing-ui/src/commands/commands/set-sheet-drawing.command.ts
@@ -0,0 +1,74 @@
+/**
+ * Copyright 2023-present DreamNum Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { ICommand } from '@univerjs/core';
+import {
+ CommandType,
+ ICommandService,
+ IUndoRedoService,
+} from '@univerjs/core';
+
+import type { ISheetDrawing } from '@univerjs/sheets';
+import { DrawingApplyType, ISheetDrawingService, SetDrawingApplyMutation } from '@univerjs/sheets';
+import type { IAccessor } from '@wendellhu/redi';
+import type { IDrawingJsonUndo1 } from '@univerjs/drawing';
+import { ClearSheetDrawingTransformerOperation } from '../operations/clear-drawing-transformer.operation';
+import type { ISetDrawingCommandParams } from './interfaces';
+
+/**
+ * The command to update defined name
+ */
+export const SetSheetDrawingCommand: ICommand = {
+ id: 'sheet.command.set-sheet-image',
+ type: CommandType.COMMAND,
+ handler: (accessor: IAccessor, params?: ISetDrawingCommandParams) => {
+ const commandService = accessor.get(ICommandService);
+ const undoRedoService = accessor.get(IUndoRedoService);
+ const sheetDrawingService = accessor.get(ISheetDrawingService);
+
+ if (!params) return false;
+
+ const { drawings } = params;
+
+ // const newSheetDrawingParams = drawings.map((param) => param.newDrawing);
+ // const oldSheetDrawingParams = drawings.map((param) => param.oldDrawing);
+
+ const jsonOp = sheetDrawingService.getBatchUpdateOp(drawings as ISheetDrawing[]) as IDrawingJsonUndo1;
+
+ const { unitId, subUnitId, undo, redo, objects } = jsonOp;
+
+ // execute do mutations and add undo mutations to undo stack if completed
+ const result = commandService.syncExecuteCommand(SetDrawingApplyMutation.id, { unitId, subUnitId, op: redo, objects, type: DrawingApplyType.UPDATE });
+
+ if (result) {
+ undoRedoService.pushUndoRedo({
+ unitID: unitId,
+ undoMutations: [
+ { id: SetDrawingApplyMutation.id, params: { unitId, subUnitId, op: undo, objects, type: DrawingApplyType.UPDATE } },
+ { id: ClearSheetDrawingTransformerOperation.id, params: [unitId] },
+ ],
+ redoMutations: [
+ { id: SetDrawingApplyMutation.id, params: { unitId, subUnitId, op: redo, objects, type: DrawingApplyType.UPDATE } },
+ { id: ClearSheetDrawingTransformerOperation.id, params: [unitId] },
+ ],
+ });
+
+ return true;
+ }
+
+ return false;
+ },
+};
diff --git a/packages/sheets-drawing-ui/src/commands/commands/ungroup-sheet-drawing.command.ts b/packages/sheets-drawing-ui/src/commands/commands/ungroup-sheet-drawing.command.ts
new file mode 100644
index 0000000000..3c7edfbff7
--- /dev/null
+++ b/packages/sheets-drawing-ui/src/commands/commands/ungroup-sheet-drawing.command.ts
@@ -0,0 +1,76 @@
+/**
+ * Copyright 2023-present DreamNum Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { ICommand, IDrawingGroupUpdateParam } from '@univerjs/core';
+import {
+ CommandType,
+ ICommandService,
+ IUndoRedoService,
+} from '@univerjs/core';
+
+import { DrawingApplyType, ISheetDrawingService, SetDrawingApplyMutation } from '@univerjs/sheets';
+import type { IAccessor } from '@wendellhu/redi';
+import type { IDrawingJsonUndo1 } from '@univerjs/drawing';
+import { ClearSheetDrawingTransformerOperation } from '../operations/clear-drawing-transformer.operation';
+import { ungroupToGroup } from './utils';
+
+/**
+ * The command to insert new defined name
+ */
+export const UngroupSheetDrawingCommand: ICommand = {
+ id: 'sheet.command.ungroup-sheet-image',
+ type: CommandType.COMMAND,
+ handler: (accessor: IAccessor, params?: IDrawingGroupUpdateParam[]) => {
+ const commandService = accessor.get(ICommandService);
+ const undoRedoService = accessor.get(IUndoRedoService);
+ const sheetDrawingService = accessor.get(ISheetDrawingService);
+
+ if (!params) return false;
+
+ const unitIds: string[] = [];
+ params.forEach(({ parent, children }) => {
+ unitIds.push(parent.unitId);
+ children.forEach((child) => {
+ unitIds.push(child.unitId);
+ });
+ });
+
+ // execute do mutations and add undo mutations to undo stack if completed
+ const jsonOp = sheetDrawingService.getUngroupDrawingOp(params) as IDrawingJsonUndo1;
+
+ const { unitId, subUnitId, undo, redo, objects } = jsonOp;
+
+ const result = commandService.syncExecuteCommand(SetDrawingApplyMutation.id, { op: redo, unitId, subUnitId, objects, type: DrawingApplyType.UNGROUP });
+
+ if (result) {
+ undoRedoService.pushUndoRedo({
+ unitID: unitId,
+ undoMutations: [
+ { id: SetDrawingApplyMutation.id, params: { op: undo, unitId, subUnitId, objects: ungroupToGroup(objects as IDrawingGroupUpdateParam[]), type: DrawingApplyType.GROUP } },
+ { id: ClearSheetDrawingTransformerOperation.id, params: unitIds },
+ ],
+ redoMutations: [
+ { id: SetDrawingApplyMutation.id, params: { op: redo, unitId, subUnitId, objects, type: DrawingApplyType.UNGROUP } },
+ { id: ClearSheetDrawingTransformerOperation.id, params: unitIds },
+ ],
+ });
+
+ return true;
+ }
+
+ return false;
+ },
+};
diff --git a/packages/sheets-drawing-ui/src/commands/commands/utils.ts b/packages/sheets-drawing-ui/src/commands/commands/utils.ts
new file mode 100644
index 0000000000..f7860ab2fe
--- /dev/null
+++ b/packages/sheets-drawing-ui/src/commands/commands/utils.ts
@@ -0,0 +1,97 @@
+/**
+ * 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 { DrawingTypeEnum, type IDrawingGroupUpdateParam, type IDrawingParam } from '@univerjs/core';
+import { getGroupState, transformObjectOutOfGroup } from '@univerjs/engine-render';
+
+export function ungroupToGroup(ungroupParams: IDrawingGroupUpdateParam[]) {
+ const newGroupParams: IDrawingGroupUpdateParam[] = [];
+
+ ungroupParams.forEach((ungroupParam) => {
+ const { parent, children } = ungroupParam;
+ const { unitId, subUnitId, drawingId: groupId } = parent;
+ const groupTransform = getGroupState(0, 0, children.map((o) => o.transform || {}));
+
+ const newChildren = children.map((drawing) => {
+ const transform = drawing.transform || { left: 0, top: 0 };
+ const { unitId, subUnitId, drawingId } = drawing;
+ return {
+ unitId, subUnitId, drawingId,
+ transform: {
+ ...transform,
+ left: transform.left! - groupTransform.left,
+ top: transform.top! - groupTransform.top,
+ },
+ groupId,
+ };
+ }) as IDrawingParam[];
+
+ const groupParam = {
+ unitId,
+ subUnitId,
+ drawingId: groupId,
+ drawingType: DrawingTypeEnum.DRAWING_GROUP,
+ transform: groupTransform,
+ } as IDrawingParam;
+
+ newGroupParams.push({
+ parent: groupParam,
+ children: newChildren,
+ });
+ });
+
+ return newGroupParams;
+}
+
+export function groupToUngroup(groupParams: IDrawingGroupUpdateParam[]) {
+ const newGroupParams: IDrawingGroupUpdateParam[] = [];
+
+ groupParams.forEach((groupParam) => {
+ const { parent, children } = groupParam;
+ const { unitId, subUnitId, drawingId: groupId, transform: groupTransform = { width: 0, height: 0 } } = parent;
+ if (groupTransform == null) {
+ return;
+ }
+ const newChildren = children.map((object) => {
+ const { transform } = object;
+ const { unitId, subUnitId, drawingId } = object;
+ const newTransform = transformObjectOutOfGroup(transform || {}, groupTransform, groupTransform.width || 0, groupTransform.height || 0);
+ return {
+ unitId, subUnitId, drawingId,
+ transform: newTransform,
+ groupId: undefined,
+ };
+ }) as IDrawingParam[];
+
+ const ungroupParam = {
+ unitId,
+ subUnitId,
+ drawingId: groupId,
+ drawingType: DrawingTypeEnum.DRAWING_GROUP,
+ transform: {
+ left: 0,
+ top: 0,
+ },
+ } as IDrawingParam;
+
+ newGroupParams.push({
+ parent: ungroupParam,
+ children: newChildren,
+ });
+ });
+
+ return newGroupParams;
+}
diff --git a/packages/sheets-drawing-ui/src/commands/operations/clear-drawing-transformer.operation.ts b/packages/sheets-drawing-ui/src/commands/operations/clear-drawing-transformer.operation.ts
new file mode 100644
index 0000000000..20f2e376c0
--- /dev/null
+++ b/packages/sheets-drawing-ui/src/commands/operations/clear-drawing-transformer.operation.ts
@@ -0,0 +1,33 @@
+/**
+ * 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 { IMutation } from '@univerjs/core';
+import { CommandType } from '@univerjs/core';
+import { IRenderManagerService } from '@univerjs/engine-render';
+
+export const ClearSheetDrawingTransformerOperation: IMutation<string[]> = {
+ id: 'sheet.operation.clear-drawing-transformer',
+ type: CommandType.MUTATION,
+ handler: (accessor, params) => {
+ const renderManagerService = accessor.get(IRenderManagerService);
+
+ params.forEach((unitId) => {
+ renderManagerService.getRenderById(unitId)?.scene.getTransformer()?.debounceRefreshControls();
+ });
+
+ return true;
+ },
+};
diff --git a/packages/sheets-drawing-ui/src/commands/operations/edit-sheet-drawing.operation.ts b/packages/sheets-drawing-ui/src/commands/operations/edit-sheet-drawing.operation.ts
new file mode 100644
index 0000000000..db1153741e
--- /dev/null
+++ b/packages/sheets-drawing-ui/src/commands/operations/edit-sheet-drawing.operation.ts
@@ -0,0 +1,41 @@
+/**
+ * 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 { IDrawingSearch, IOperation } from '@univerjs/core';
+import {
+ CommandType,
+ ICommandService,
+ IDrawingManagerService,
+
+} from '@univerjs/core';
+import type { IAccessor } from '@wendellhu/redi';
+import { SidebarSheetDrawingOperation } from './open-drawing-panel.operation';
+
+export const EditSheetDrawingOperation: IOperation<IDrawingSearch> = {
+ id: 'sheet.operation.edit-sheet-image',
+ type: CommandType.OPERATION,
+ handler: (accessor: IAccessor, params?: IDrawingSearch) => {
+ const drawingManagerService = accessor.get(IDrawingManagerService);
+ const commandService = accessor.get(ICommandService);
+
+ if (params == null) {
+ return false;
+ }
+ drawingManagerService.focusDrawing([params]);
+ commandService.executeCommand(SidebarSheetDrawingOperation.id, { value: 'open' });
+ return true;
+ },
+};
diff --git a/packages/sheets-drawing-ui/src/commands/operations/insert-image.operation.ts b/packages/sheets-drawing-ui/src/commands/operations/insert-image.operation.ts
new file mode 100644
index 0000000000..2338996b42
--- /dev/null
+++ b/packages/sheets-drawing-ui/src/commands/operations/insert-image.operation.ts
@@ -0,0 +1,38 @@
+/**
+ * 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 { IOperation, Nullable } from '@univerjs/core';
+import { CommandType } from '@univerjs/core';
+
+export interface IInsertImageOperationParams {
+ files: Nullable<File[]>;
+};
+
+export const InsertFloatImageOperation: IOperation<IInsertImageOperationParams> = {
+ id: 'sheet.operation.insert-float-image',
+ type: CommandType.OPERATION,
+ handler: (accessor, params) => {
+ return true;
+ },
+};
+
+export const InsertCellImageOperation: IOperation<IInsertImageOperationParams> = {
+ id: 'sheet.operation.insert-cell-image',
+ type: CommandType.OPERATION,
+ handler: (accessor, params) => {
+ return true;
+ },
+};
diff --git a/packages/sheets-drawing-ui/src/commands/operations/open-drawing-panel.operation.ts b/packages/sheets-drawing-ui/src/commands/operations/open-drawing-panel.operation.ts
new file mode 100644
index 0000000000..beb649f6bc
--- /dev/null
+++ b/packages/sheets-drawing-ui/src/commands/operations/open-drawing-panel.operation.ts
@@ -0,0 +1,59 @@
+/**
+ * Copyright 2023-present DreamNum Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { ICommand } from '@univerjs/core';
+import { CommandType, IDrawingManagerService, IUniverInstanceService, LocaleService } from '@univerjs/core';
+import { ISidebarService } from '@univerjs/ui';
+import type { IAccessor } from '@wendellhu/redi';
+import { getSheetCommandTarget } from '@univerjs/sheets';
+import { COMPONENT_SHEET_DRAWING_PANEL } from '../../views/sheet-image-panel/component-name';
+
+export interface IUIComponentCommandParams {
+ value: string;
+}
+
+export const SidebarSheetDrawingOperation: ICommand = {
+ id: 'sidebar.operation.sheet-image',
+ type: CommandType.COMMAND,
+ handler: async (accessor: IAccessor, params: IUIComponentCommandParams) => {
+ const sidebarService = accessor.get(ISidebarService);
+ const localeService = accessor.get(LocaleService);
+ const univerInstanceService = accessor.get(IUniverInstanceService);
+ const drawingManagerService = accessor.get(IDrawingManagerService);
+
+ const target = getSheetCommandTarget(univerInstanceService);
+ if (!target) return false;
+
+ switch (params.value) {
+ case 'open':
+ sidebarService.open({
+ header: { title: localeService.t('sheetImage.panel.title') },
+ children: { label: COMPONENT_SHEET_DRAWING_PANEL },
+ onClose: () => {
+ drawingManagerService.focusDrawing(null);
+ },
+ width: 360,
+ });
+ break;
+ case 'close':
+ default:
+ sidebarService.close();
+ break;
+ }
+ return true;
+ },
+};
+
diff --git a/packages/sheets-drawing-ui/src/controllers/drawing-popup-menu.controller.ts b/packages/sheets-drawing-ui/src/controllers/drawing-popup-menu.controller.ts
new file mode 100644
index 0000000000..202cfda331
--- /dev/null
+++ b/packages/sheets-drawing-ui/src/controllers/drawing-popup-menu.controller.ts
@@ -0,0 +1,190 @@
+/**
+ * Copyright 2023-present DreamNum Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { Nullable, Workbook } from '@univerjs/core';
+import { FOCUSING_COMMON_DRAWINGS, ICommandService, IContextService, IDrawingManagerService, IUniverInstanceService, LifecycleStages, LocaleService, OnLifecycle, RxDisposable, toDisposable, UniverInstanceType } from '@univerjs/core';
+import type { IDisposable } from '@wendellhu/redi';
+import { Inject, Injector } from '@wendellhu/redi';
+import type { BaseObject, Scene } from '@univerjs/engine-render';
+import { IRenderManagerService } from '@univerjs/engine-render';
+import { COMPONENT_IMAGE_POPUP_MENU, ImageResetSizeOperation, OpenImageCropOperation } from '@univerjs/drawing-ui';
+import { SheetCanvasPopManagerService } from '@univerjs/sheets-ui';
+import { takeUntil } from 'rxjs';
+import { ImageCropperObject } from '@univerjs/drawing-ui/views/crop/image-cropper-object.js';
+import { RemoveSheetDrawingCommand } from '../commands/commands/remove-sheet-drawing.command';
+import { EditSheetDrawingOperation } from '../commands/operations/edit-sheet-drawing.operation';
+
+@OnLifecycle(LifecycleStages.Steady, DrawingPopupMenuController)
+export class DrawingPopupMenuController extends RxDisposable {
+ private _initImagePopupMenu = new Set<string>();
+
+ constructor(
+ @Inject(Injector) private readonly _injector: Injector,
+ @IDrawingManagerService private readonly _drawingManagerService: IDrawingManagerService,
+ @Inject(SheetCanvasPopManagerService) private readonly _canvasPopManagerService: SheetCanvasPopManagerService,
+ @IRenderManagerService private readonly _renderManagerService: IRenderManagerService,
+ @IUniverInstanceService private readonly _univerInstanceService: IUniverInstanceService,
+ @IContextService private readonly _contextService: IContextService,
+ @Inject(LocaleService) private readonly _localeService: LocaleService,
+ @ICommandService private readonly _commandService: ICommandService
+
+ ) {
+ super();
+
+ this._init();
+ }
+
+ private _init(): void {
+ this._univerInstanceService.getCurrentTypeOfUnit$<Workbook>(UniverInstanceType.UNIVER_SHEET).pipe(takeUntil(this.dispose$)).subscribe((workbook) => this._create(workbook));
+ this._univerInstanceService.getTypeOfUnitDisposed$<Workbook>(UniverInstanceType.UNIVER_SHEET).pipe(takeUntil(this.dispose$)).subscribe((workbook) => this._dispose(workbook));
+ this._univerInstanceService.getAllUnitsForType<Workbook>(UniverInstanceType.UNIVER_SHEET).forEach((workbook) => this._create(workbook));
+ }
+
+ private _dispose(workbook: Workbook) {
+ const unitId = workbook.getUnitId();
+ this._renderManagerService.removeRender(unitId);
+ }
+
+ private _create(workbook: Nullable<Workbook>) {
+ if (!workbook) {
+ return;
+ }
+
+ const unitId = workbook.getUnitId();
+ if (this._renderManagerService.has(unitId) && !this._initImagePopupMenu.has(unitId)) {
+ this._popupMenuListener(unitId);
+ this._initImagePopupMenu.add(unitId);
+ }
+ }
+
+ private _hasCropObject(scene: Scene) {
+ const objects = scene.getAllObjects();
+
+ for (const object of objects) {
+ if (object instanceof ImageCropperObject) {
+ return true;
+ }
+ }
+
+ return false;
+ }
+
+ private _popupMenuListener(unitId: string) {
+ const scene = this._renderManagerService.getRenderById(unitId)?.scene;
+ if (!scene) {
+ return;
+ }
+ const transformer = scene.getTransformerByCreate();
+ if (!transformer) {
+ return;
+ }
+ const disposePopups: IDisposable[] = [];
+ this.disposeWithMe(
+ toDisposable(
+ transformer.onCreateControlObservable.add(() => {
+ this._contextService.setContextValue(FOCUSING_COMMON_DRAWINGS, true);
+
+ if (this._hasCropObject(scene)) {
+ return;
+ }
+
+ const selectedObjects = transformer.getSelectedObjectMap();
+ if (selectedObjects.size > 1) {
+ disposePopups.forEach((dispose) => dispose.dispose());
+ return;
+ }
+
+ const object = selectedObjects.values().next().value as Nullable<BaseObject>;
+ if (!object) {
+ return;
+ }
+
+ const oKey = object.oKey;
+ const drawingParam = this._drawingManagerService.getDrawingOKey(oKey);
+ if (!drawingParam) {
+ return;
+ }
+
+ const { unitId, subUnitId, drawingId } = drawingParam;
+
+ disposePopups.push(this.disposeWithMe(this._canvasPopManagerService.attachPopupToObject(object, {
+ componentKey: COMPONENT_IMAGE_POPUP_MENU,
+ direction: 'horizontal',
+ offset: [2, 0],
+ extraProps: {
+ menuItems: this._getImageMenuItems(unitId, subUnitId, drawingId),
+ },
+ })));
+
+ this._drawingManagerService.focusDrawing([{
+ unitId,
+ subUnitId,
+ drawingId,
+ }]);
+ })
+ )
+ );
+ this.disposeWithMe(
+ toDisposable(
+ transformer.onClearControlObservable.add(() => {
+ disposePopups.forEach((dispose) => dispose.dispose());
+ this._contextService.setContextValue(FOCUSING_COMMON_DRAWINGS, false);
+ this._drawingManagerService.focusDrawing(null);
+ })
+ )
+ );
+ this.disposeWithMe(
+ toDisposable(
+ transformer.onChangingObservable.add(() => {
+ disposePopups.forEach((dispose) => dispose.dispose());
+ })
+ )
+ );
+ }
+
+ private _getImageMenuItems(unitId: string, subUnitId: string, drawingId: string) {
+ return [
+ {
+ label: 'image-popup.edit',
+ index: 0,
+ commandId: EditSheetDrawingOperation.id,
+ commandParams: { unitId, subUnitId, drawingId },
+ disable: false,
+ },
+ {
+ label: 'image-popup.delete',
+ index: 1,
+ commandId: RemoveSheetDrawingCommand.id,
+ commandParams: { unitId, drawings: [{ unitId, subUnitId, drawingId }] },
+ disable: false,
+ },
+ {
+ label: 'image-popup.crop',
+ index: 2,
+ commandId: OpenImageCropOperation.id,
+ commandParams: { unitId, subUnitId, drawingId },
+ disable: false,
+ },
+ {
+ label: 'image-popup.reset',
+ index: 3,
+ commandId: ImageResetSizeOperation.id,
+ commandParams: [{ unitId, subUnitId, drawingId }],
+ disable: false,
+ },
+ ];
+ }
+}
diff --git a/packages/sheets-drawing-ui/src/controllers/sheet-drawing-transform-affected.controller.ts b/packages/sheets-drawing-ui/src/controllers/sheet-drawing-transform-affected.controller.ts
new file mode 100644
index 0000000000..362ad2ff96
--- /dev/null
+++ b/packages/sheets-drawing-ui/src/controllers/sheet-drawing-transform-affected.controller.ts
@@ -0,0 +1,1110 @@
+/**
+ * Copyright 2023-present DreamNum Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { ICommandInfo, IDrawingParam, IMutationInfo, IRange, ITransformState, Nullable } from '@univerjs/core';
+import { Disposable, ICommandService, IDrawingManagerService, IUniverInstanceService, LifecycleStages, OnLifecycle, Rectangle } from '@univerjs/core';
+import { Inject } from '@wendellhu/redi';
+import type { IInsertColCommandParams, IInsertRowCommandParams, IRemoveRowColCommandParams, ISetColHiddenMutationParams, ISetColVisibleMutationParams, ISetRowHiddenMutationParams, ISetRowVisibleMutationParams, ISetSpecificColsVisibleCommandParams, ISetSpecificRowsVisibleCommandParams, ISetWorksheetActiveOperationParams, ISetWorksheetColWidthMutationParams, ISetWorksheetRowHeightMutationParams, ISetWorksheetRowIsAutoHeightMutationParams, ISheetDrawing, ISheetDrawingPosition } from '@univerjs/sheets';
+import { DeleteRangeMoveLeftCommand, DeleteRangeMoveUpCommand, DeltaColumnWidthCommand, DeltaRowHeightCommand, DrawingApplyType, getSheetCommandTarget, InsertColCommand, InsertRangeMoveDownCommand, InsertRangeMoveRightCommand, InsertRowCommand, ISheetDrawingService, RemoveColCommand, RemoveRowCommand, SetColHiddenCommand, SetColHiddenMutation, SetColVisibleMutation, SetColWidthCommand, SetDrawingApplyMutation, SetRowHeightCommand, SetRowHiddenCommand, SetRowHiddenMutation, SetRowVisibleMutation, SetSpecificColsVisibleCommand, SetSpecificRowsVisibleCommand, SetWorksheetActiveOperation, SetWorksheetColWidthMutation, SetWorksheetRowHeightMutation, SheetDrawingAnchorType, SheetInterceptorService } from '@univerjs/sheets';
+import { ISelectionRenderService } from '@univerjs/sheets-ui';
+import type { IDrawingJsonUndo1 } from '@univerjs/drawing';
+import { ClearSheetDrawingTransformerOperation } from '../commands/operations/clear-drawing-transformer.operation';
+import { drawingPositionToTransform, transformToDrawingPosition } from '../basics/transform-position';
+
+enum RangeMoveUndoType {
+ deleteLeft,
+ deleteUp,
+ insertDown,
+ insertRight,
+}
+
+const UPDATE_COMMANDS = [
+ InsertRowCommand.id, InsertColCommand.id, RemoveRowCommand.id, RemoveColCommand.id,
+
+ DeleteRangeMoveLeftCommand.id,
+ DeleteRangeMoveUpCommand.id,
+ InsertRangeMoveDownCommand.id,
+ InsertRangeMoveRightCommand.id,
+
+ DeltaRowHeightCommand.id,
+ SetRowHeightCommand.id,
+ DeltaColumnWidthCommand.id,
+ SetColWidthCommand.id,
+
+ SetRowHiddenCommand.id,
+ SetSpecificRowsVisibleCommand.id,
+ SetSpecificColsVisibleCommand.id,
+ SetColHiddenCommand.id,
+];
+
+const REFRESH_MUTATIONS = [
+ SetRowVisibleMutation.id,
+ SetRowHiddenMutation.id,
+ SetColVisibleMutation.id,
+ SetColHiddenMutation.id,
+ SetWorksheetRowHeightMutation.id,
+ SetWorksheetColWidthMutation.id,
+];
+
+@OnLifecycle(LifecycleStages.Rendered, SheetDrawingTransformAffectedController)
+export class SheetDrawingTransformAffectedController extends Disposable {
+ constructor(
+ @ICommandService private readonly _commandService: ICommandService,
+ @Inject(SheetInterceptorService) private readonly _sheetInterceptorService: SheetInterceptorService,
+ @ISheetDrawingService private readonly _sheetDrawingService: ISheetDrawingService,
+ @IDrawingManagerService private readonly _drawingManagerService: IDrawingManagerService,
+ @ISelectionRenderService private readonly _selectionRenderService: ISelectionRenderService,
+ @IUniverInstanceService private readonly _univerInstanceService: IUniverInstanceService
+ ) {
+ super();
+
+ this._init();
+ }
+
+ private _init(): void {
+ this._sheetInterceptorListener();
+
+ this._commandListener();
+
+ this._sheetRefreshListener();
+ }
+
+ private _sheetInterceptorListener() {
+ this.disposeWithMe(
+ this._sheetInterceptorService.interceptCommand({
+
+ getMutations: (commandInfo) => {
+ if (!UPDATE_COMMANDS.includes(commandInfo.id)) {
+ return { redos: [], undos: [] };
+ }
+ if (commandInfo.params == null) {
+ return { redos: [], undos: [] };
+ }
+ const cId = commandInfo.id;
+ if (cId === InsertRowCommand.id) {
+ return this._moveRowInterceptor(commandInfo.params as IInsertRowCommandParams, 'insert');
+ } else if (cId === InsertColCommand.id) {
+ return this._moveColInterceptor(commandInfo.params as IInsertColCommandParams, 'insert');
+ } else if (cId === RemoveRowCommand.id) {
+ return this._moveRowInterceptor(commandInfo.params as IRemoveRowColCommandParams, 'remove');
+ } else if (cId === RemoveColCommand.id) {
+ return this._moveColInterceptor(commandInfo.params as IRemoveRowColCommandParams, 'remove');
+ } else if (cId === DeleteRangeMoveLeftCommand.id) {
+ const { range } = commandInfo.params as IRemoveRowColCommandParams;
+ return this._getRangeMoveUndo(range, RangeMoveUndoType.deleteLeft);
+ } else if (cId === DeleteRangeMoveUpCommand.id) {
+ const { range } = commandInfo.params as IRemoveRowColCommandParams;
+ return this._getRangeMoveUndo(range, RangeMoveUndoType.deleteUp);
+ } else if (cId === InsertRangeMoveDownCommand.id) {
+ const { range } = commandInfo.params as IRemoveRowColCommandParams;
+ return this._getRangeMoveUndo(range, RangeMoveUndoType.insertDown);
+ } else if (cId === InsertRangeMoveRightCommand.id) {
+ const { range } = commandInfo.params as IRemoveRowColCommandParams;
+ return this._getRangeMoveUndo(range, RangeMoveUndoType.insertRight);
+ } else if (cId === SetRowHiddenCommand.id || cId === SetSpecificRowsVisibleCommand.id) {
+ const params = commandInfo.params as ISetRowHiddenMutationParams | ISetSpecificRowsVisibleCommandParams;
+ const { unitId, subUnitId, ranges } = params;
+ return this._getDrawingUndoForRowVisible(unitId, subUnitId, ranges);
+ } else if (cId === SetSpecificColsVisibleCommand.id || cId === SetColHiddenCommand.id) {
+ const params = commandInfo.params as ISetSpecificColsVisibleCommandParams | ISetColHiddenMutationParams;
+ const { unitId, subUnitId, ranges } = params;
+ return this._getDrawingUndoForColVisible(unitId, subUnitId, ranges);
+ } else if (cId === DeltaRowHeightCommand.id || cId === SetRowHeightCommand.id || cId === DeltaColumnWidthCommand.id || cId === SetColWidthCommand.id) {
+ const params = commandInfo.params as ISetWorksheetRowHeightMutationParams | ISetWorksheetColWidthMutationParams;
+ const { unitId, subUnitId, ranges } = params;
+ const isRow = cId === DeltaRowHeightCommand.id || cId === SetRowHeightCommand.id;
+ return this._getDrawingUndoForRowAndColSize(unitId, subUnitId, ranges, isRow);
+ }
+
+ return { redos: [], undos: [] };
+ },
+ })
+ );
+ }
+
+ private _getRangeMoveUndo(range: IRange, type: RangeMoveUndoType) {
+ const newParams = getSheetCommandTarget(this._univerInstanceService);
+
+ if (newParams == null) {
+ return { redos: [], undos: [] };
+ }
+ const unitId = newParams.unitId;
+ const subUnitId = newParams.subUnitId;
+
+ const redos: IMutationInfo[] = [];
+ const undos: IMutationInfo[] = [];
+
+ const drawingData = this._sheetDrawingService.getDrawingData(unitId, subUnitId);
+
+ const updateDrawings: Partial<ISheetDrawing>[] = [];
+ const deleteDrawings: Partial<ISheetDrawing>[] = [];
+
+ Object.keys(drawingData).forEach((drawingId) => {
+ const drawing = drawingData[drawingId];
+
+ const { updateDrawings: updateDrawingsPart, deleteDrawings: deleteDrawingsPart } = this._getUpdateOrDeleteDrawings(range, type, drawing);
+
+ updateDrawings.push(...updateDrawingsPart);
+ deleteDrawings.push(...deleteDrawingsPart);
+ });
+
+ if (updateDrawings.length === 0 && deleteDrawings.length === 0) {
+ return { redos: [], undos: [] };
+ }
+
+ if (updateDrawings.length > 0) {
+ const updateJsonOp = this._sheetDrawingService.getBatchUpdateOp(updateDrawings as ISheetDrawing[]) as IDrawingJsonUndo1;
+ const { undo, redo, objects } = updateJsonOp;
+ redos.push({ id: SetDrawingApplyMutation.id, params: { unitId, subUnitId, op: redo, objects, type: DrawingApplyType.UPDATE } });
+ undos.push({ id: SetDrawingApplyMutation.id, params: { unitId, subUnitId, op: undo, objects, type: DrawingApplyType.UPDATE } });
+ }
+
+ if (deleteDrawings.length > 0) {
+ const deleteJsonOp = this._sheetDrawingService.getBatchRemoveOp(deleteDrawings as ISheetDrawing[]) as IDrawingJsonUndo1;
+ const deleteUndo = deleteJsonOp.undo;
+ const deleteRedo = deleteJsonOp.redo;
+ const deleteObjects = deleteJsonOp.objects;
+ redos.push({ id: SetDrawingApplyMutation.id, params: { unitId, subUnitId, op: deleteRedo, objects: deleteObjects, type: DrawingApplyType.REMOVE } });
+ undos.push({ id: SetDrawingApplyMutation.id, params: { unitId, subUnitId, op: deleteUndo, objects: deleteObjects, type: DrawingApplyType.INSERT } });
+ }
+
+ redos.push({ id: ClearSheetDrawingTransformerOperation.id, params: [unitId] });
+ undos.push({ id: ClearSheetDrawingTransformerOperation.id, params: [unitId] });
+
+ return {
+ redos,
+ undos,
+ };
+ }
+
+ private _getUpdateOrDeleteDrawings(range: IRange, type: RangeMoveUndoType, drawing: ISheetDrawing) {
+ const updateDrawings: Partial<ISheetDrawing>[] = [];
+ const deleteDrawings: Partial<ISheetDrawing>[] = [];
+
+ const { sheetTransform, anchorType = SheetDrawingAnchorType.Position, transform, unitId, subUnitId, drawingId } = drawing;
+ const { from, to } = sheetTransform;
+ const { row: fromRow, column: fromColumn } = from;
+ const { row: toRow, column: toColumn } = to;
+
+ if (sheetTransform == null || transform == null) {
+ return {
+ updateDrawings,
+ deleteDrawings,
+ };
+ }
+
+ const { startRow, endRow, startColumn, endColumn } = range;
+ let newSheetTransform: Nullable<ISheetDrawingPosition> = null;
+ let newTransform: Nullable<ITransformState> = null;
+
+ if (type === RangeMoveUndoType.deleteLeft && fromRow >= startRow && toRow <= endRow) {
+ if (fromColumn >= startColumn && toColumn <= endColumn) {
+ // delete drawing
+ deleteDrawings.push({ unitId, subUnitId, drawingId });
+ } else {
+ // move drawing left
+ const param = this._shrinkCol(sheetTransform, transform, startColumn, endColumn, anchorType);
+ newSheetTransform = param?.newSheetTransform;
+ newTransform = param?.newTransform;
+ }
+ } else if (type === RangeMoveUndoType.deleteUp && fromColumn >= startColumn && toColumn <= endColumn) {
+ if (fromRow >= startRow && toRow <= endRow) {
+ // delete drawing
+ deleteDrawings.push({ unitId, subUnitId, drawingId });
+ } else {
+ // move drawing up
+ const param = this._shrinkRow(sheetTransform, transform, startRow, endRow, anchorType);
+ newSheetTransform = param?.newSheetTransform;
+ newTransform = param?.newTransform;
+ }
+ } else if (type === RangeMoveUndoType.insertDown) {
+ const param = this._expandRow(sheetTransform, transform, startRow, endRow, anchorType);
+ newSheetTransform = param?.newSheetTransform;
+ newTransform = param?.newTransform;
+ } else if (type === RangeMoveUndoType.insertRight) {
+ const param = this._expandCol(sheetTransform, transform, startColumn, endColumn, anchorType);
+ newSheetTransform = param?.newSheetTransform;
+ newTransform = param?.newTransform;
+ }
+
+ if (newSheetTransform != null && newTransform != null) {
+ const newTransform = drawingPositionToTransform(newSheetTransform, this._selectionRenderService);
+ updateDrawings.push({ ...drawing, sheetTransform: newSheetTransform, transform: newTransform });
+ }
+
+ return { updateDrawings, deleteDrawings };
+ }
+
+ private _remainDrawingSize(transform: Nullable<ITransformState>, updateDrawings: ISheetDrawing[], drawing: ISheetDrawing) {
+ const newSheetTransform = transformToDrawingPosition({ ...transform }, this._selectionRenderService);
+ if (newSheetTransform != null) {
+ updateDrawings.push({
+ ...drawing,
+ sheetTransform: newSheetTransform,
+ });
+ }
+ }
+
+ // eslint-disable-next-line max-lines-per-function
+ private _getDrawingUndoForColVisible(unitId: string, subUnitId: string, ranges: IRange[]) {
+ const drawingData = this._drawingManagerService.getDrawingData(unitId, subUnitId);
+ const updateDrawings: ISheetDrawing[] = [];
+ const preUpdateDrawings: ISheetDrawing[] = [];
+ // eslint-disable-next-line complexity, max-lines-per-function
+ Object.keys(drawingData).forEach((drawingId) => {
+ const drawing = drawingData[drawingId] as ISheetDrawing;
+ const { sheetTransform, transform, anchorType = SheetDrawingAnchorType.Position } = drawing;
+ if (anchorType === SheetDrawingAnchorType.None) {
+ this._remainDrawingSize(transform, updateDrawings, drawing);
+ } else {
+ const { from, to } = sheetTransform;
+ const { row: fromRow, column: fromColumn } = from;
+ const { row: toRow, column: toColumn } = to;
+ for (let i = 0; i < ranges.length; i++) {
+ const range = ranges[i];
+ const { startRow, endRow, startColumn, endColumn } = range;
+ if (toColumn < startColumn) {
+ continue;
+ }
+ if (anchorType === SheetDrawingAnchorType.Position) {
+ let newSheetTransform: Nullable<ISheetDrawingPosition> = null;
+ let newTransform: Nullable<ITransformState> = null;
+ if (fromColumn >= startColumn && fromColumn <= endColumn) {
+ const selectionCell = this._selectionRenderService.attachRangeWithCoord({ startColumn: fromColumn, endColumn, startRow: from.row, endRow: to.row });
+ if (selectionCell == null) {
+ return;
+ }
+ newTransform = { ...transform, left: selectionCell.startX };
+ }
+ if (newTransform != null) {
+ newSheetTransform = transformToDrawingPosition(newTransform, this._selectionRenderService);
+ if (newSheetTransform != null && newTransform != null) {
+ updateDrawings.push({ ...drawing, sheetTransform: newSheetTransform, transform: newTransform });
+ break;
+ }
+ }
+
+ this._remainDrawingSize(transform, updateDrawings, drawing);
+
+ continue;
+ }
+ if (fromColumn >= startColumn && toColumn <= endColumn) {
+ continue;
+ }
+ let newSheetTransform: Nullable<ISheetDrawingPosition> = null;
+ let newTransform: Nullable<ITransformState> = null;
+
+ if (fromColumn >= startColumn && fromColumn <= endColumn) {
+ const selectionCell = this._selectionRenderService.attachRangeWithCoord({ startColumn: fromColumn, endColumn, startRow: from.row, endRow: to.row });
+ if (selectionCell == null) {
+ return;
+ }
+ newTransform = {
+ ...transform,
+ left: (selectionCell?.startX || 0),
+ width: (transform?.width || 0) - selectionCell.endX + selectionCell.startX,
+ };
+ } else if (toColumn >= startColumn && toColumn <= endColumn) {
+ const selectionCell = this._selectionRenderService.attachRangeWithCoord({ startColumn, endColumn: toColumn, startRow: from.row, endRow: to.row });
+ if (selectionCell == null) {
+ return;
+ }
+ newTransform = {
+ ...transform,
+ left: selectionCell.startX - (transform?.width || 0),
+ };
+ } else {
+ const selectionCell = this._selectionRenderService.attachRangeWithCoord({ startColumn, endColumn, startRow: from.row, endRow: to.row });
+ if (selectionCell == null) {
+ return;
+ }
+ newTransform = {
+ ...transform,
+ width: (transform?.width || 0) - selectionCell.endX + selectionCell.startX,
+ };
+ newSheetTransform = transformToDrawingPosition(newTransform, this._selectionRenderService);
+ if (newSheetTransform != null && newTransform != null) {
+ preUpdateDrawings.push({ ...drawing, sheetTransform: newSheetTransform, transform: newTransform });
+ break;
+ }
+ }
+
+ if (newTransform != null) {
+ newSheetTransform = transformToDrawingPosition(newTransform, this._selectionRenderService);
+ }
+ if (newTransform != null && newSheetTransform != null) {
+ updateDrawings.push({ ...drawing, sheetTransform: newSheetTransform, transform: newTransform });
+ break;
+ } else {
+ this._remainDrawingSize(transform, updateDrawings, drawing);
+ }
+ }
+ }
+ });
+
+ if (updateDrawings.length === 0 && preUpdateDrawings.length === 0) {
+ return { redos: [], undos: [] };
+ }
+
+ const { redos, undos } = this._createUndoAndRedoMutation(unitId, subUnitId, updateDrawings);
+
+ const preRedos: IMutationInfo[] = [];
+ const preUndos: IMutationInfo[] = [];
+
+ if (preUpdateDrawings.length > 0) {
+ const { redos, undos } = this._createUndoAndRedoMutation(unitId, subUnitId, preUpdateDrawings);
+ preRedos.push(...redos);
+ preUndos.push(...undos);
+ }
+
+ return {
+ redos,
+ undos,
+ preRedos,
+ preUndos,
+ };
+ }
+
+ private _createUndoAndRedoMutation(unitId: string, subUnitId: string, updateDrawings: ISheetDrawing[]) {
+ const updateJsonOp = this._sheetDrawingService.getBatchUpdateOp(updateDrawings as ISheetDrawing[]) as IDrawingJsonUndo1;
+ const { undo, redo, objects } = updateJsonOp;
+ const redos: IMutationInfo[] = [
+ { id: SetDrawingApplyMutation.id, params: { unitId, subUnitId, op: redo, objects, type: DrawingApplyType.UPDATE } },
+ { id: ClearSheetDrawingTransformerOperation.id, params: [unitId] },
+ ];
+ const undos: IMutationInfo[] = [
+ { id: SetDrawingApplyMutation.id, params: { unitId, subUnitId, op: undo, objects, type: DrawingApplyType.UPDATE } },
+ { id: ClearSheetDrawingTransformerOperation.id, params: [unitId] },
+ ];
+
+ return {
+ redos,
+ undos,
+ };
+ }
+
+ // eslint-disable-next-line max-lines-per-function
+ private _getDrawingUndoForRowVisible(unitId: string, subUnitId: string, ranges: IRange[]) {
+ const drawingData = this._drawingManagerService.getDrawingData(unitId, subUnitId);
+
+ const updateDrawings: ISheetDrawing[] = [];
+ const preUpdateDrawings: ISheetDrawing[] = [];
+ // eslint-disable-next-line complexity, max-lines-per-function
+ Object.keys(drawingData).forEach((drawingId) => {
+ const drawing = drawingData[drawingId] as ISheetDrawing;
+ const { sheetTransform, transform, anchorType = SheetDrawingAnchorType.Position } = drawing;
+ if (anchorType === SheetDrawingAnchorType.None) {
+ this._remainDrawingSize(transform, updateDrawings, drawing);
+ } else {
+ const { from, to } = sheetTransform;
+ const { row: fromRow, column: fromColumn } = from;
+ const { row: toRow, column: toColumn } = to;
+ for (let i = 0; i < ranges.length; i++) {
+ const range = ranges[i];
+ const { startRow, endRow, startColumn, endColumn } = range;
+ if (toRow < startRow) {
+ continue;
+ }
+ if (anchorType === SheetDrawingAnchorType.Position) {
+ let newSheetTransform: Nullable<ISheetDrawingPosition> = null;
+ let newTransform: Nullable<ITransformState> = null;
+ if (fromRow >= startRow && fromRow <= endRow) {
+ const selectionCell = this._selectionRenderService.attachRangeWithCoord({ startColumn: from.column, endColumn: to.column, startRow: fromRow, endRow });
+ if (selectionCell == null) {
+ return;
+ }
+ newTransform = { ...transform, top: selectionCell.startY };
+ }
+ if (newTransform != null) {
+ newSheetTransform = transformToDrawingPosition(newTransform, this._selectionRenderService);
+ if (newSheetTransform != null && newTransform != null) {
+ updateDrawings.push({ ...drawing, sheetTransform: newSheetTransform, transform: newTransform });
+ break;
+ }
+ }
+
+ this._remainDrawingSize(transform, updateDrawings, drawing);
+
+ continue;
+ }
+ if (fromRow >= startRow && toRow <= endRow) {
+ continue;
+ }
+ let newSheetTransform: Nullable<ISheetDrawingPosition> = null;
+ let newTransform: Nullable<ITransformState> = null;
+
+ if (fromRow >= startRow && fromRow <= endRow) {
+ const selectionCell = this._selectionRenderService.attachRangeWithCoord({ startColumn: from.column, endColumn: to.column, startRow: fromRow, endRow });
+ if (selectionCell == null) {
+ return;
+ }
+ newTransform = {
+ ...transform,
+ top: (selectionCell?.startY || 0),
+ height: (transform?.height || 0) - selectionCell.endY + selectionCell.startY,
+ };
+ } else if (toRow >= startRow && toRow <= endRow) {
+ const selectionCell = this._selectionRenderService.attachRangeWithCoord({ startColumn: from.column, endColumn: to.column, startRow, endRow: toRow });
+ if (selectionCell == null) {
+ return;
+ }
+ newTransform = {
+ ...transform,
+ top: selectionCell.startY - (transform?.height || 0),
+ };
+ } else {
+ const selectionCell = this._selectionRenderService.attachRangeWithCoord({ startColumn: from.column, endColumn: to.column, startRow, endRow });
+ if (selectionCell == null) {
+ return;
+ }
+ newTransform = {
+ ...transform,
+ height: (transform?.height || 0) - selectionCell.endY + selectionCell.startY,
+ };
+ newSheetTransform = transformToDrawingPosition(newTransform, this._selectionRenderService);
+ if (newSheetTransform != null && newTransform != null) {
+ preUpdateDrawings.push({ ...drawing, sheetTransform: newSheetTransform, transform: newTransform });
+ break;
+ }
+ }
+
+ if (newTransform != null) {
+ newSheetTransform = transformToDrawingPosition(newTransform, this._selectionRenderService);
+ }
+ if (newTransform != null && newSheetTransform != null) {
+ updateDrawings.push({ ...drawing, sheetTransform: newSheetTransform, transform: newTransform });
+ break;
+ } else {
+ this._remainDrawingSize(transform, updateDrawings, drawing);
+ }
+ }
+ }
+ });
+
+ if (updateDrawings.length === 0 && preUpdateDrawings.length === 0) {
+ return { redos: [], undos: [] };
+ }
+
+ const { redos, undos } = this._createUndoAndRedoMutation(unitId, subUnitId, updateDrawings);
+
+ const preRedos: IMutationInfo[] = [];
+ const preUndos: IMutationInfo[] = [];
+
+ if (preUpdateDrawings.length > 0) {
+ const { redos, undos } = this._createUndoAndRedoMutation(unitId, subUnitId, preUpdateDrawings);
+ preRedos.push(...redos);
+ preUndos.push(...undos);
+ }
+
+ return {
+ redos,
+ undos,
+ preRedos,
+ preUndos,
+ };
+ }
+
+ private _getDrawingUndoForRowAndColSize(unitId: string, subUnitId: string, ranges: IRange[], isRow: boolean) {
+ const drawingData = this._drawingManagerService.getDrawingData(unitId, subUnitId);
+
+ const updateDrawings: ISheetDrawing[] = [];
+
+ Object.keys(drawingData).forEach((drawingId) => {
+ const drawing = drawingData[drawingId] as ISheetDrawing;
+ const { sheetTransform, transform, anchorType = SheetDrawingAnchorType.Position } = drawing;
+ if (anchorType === SheetDrawingAnchorType.None) {
+ this._remainDrawingSize(transform, updateDrawings, drawing);
+ } else {
+ const { from, to } = sheetTransform;
+ const { row: fromRow, column: fromColumn } = from;
+ const { row: toRow, column: toColumn } = to;
+ for (let i = 0; i < ranges.length; i++) {
+ const range = ranges[i];
+ const { startRow, endRow, startColumn, endColumn } = range;
+
+ if (toRow < startRow || toColumn < startColumn) {
+ continue;
+ }
+
+ if (anchorType === SheetDrawingAnchorType.Position) {
+ if ((fromRow <= startRow && toRow >= endRow) || (fromColumn <= startColumn && toColumn >= endColumn)) {
+ this._remainDrawingSize(transform, updateDrawings, drawing);
+ continue;
+ }
+ }
+
+ const newTransform = drawingPositionToTransform({ ...sheetTransform }, this._selectionRenderService);
+ if (newTransform != null) {
+ updateDrawings.push({
+ ...drawing,
+ transform: newTransform,
+ });
+ break;
+ }
+ }
+ }
+ });
+
+ if (updateDrawings.length === 0) {
+ return { redos: [], undos: [] };
+ }
+
+ return this._createUndoAndRedoMutation(unitId, subUnitId, updateDrawings);
+ }
+
+ private _getUnitIdAndSubUnitId(params: IInsertRowCommandParams | IRemoveRowColCommandParams, type: 'insert' | 'remove') {
+ let unitId: string;
+ let subUnitId: string;
+ if (type === 'insert') {
+ unitId = (params as IInsertRowCommandParams).unitId;
+ subUnitId = (params as IInsertRowCommandParams).subUnitId;
+ } else {
+ const newParams = getSheetCommandTarget(this._univerInstanceService);
+ if (newParams == null) {
+ return;
+ }
+ unitId = newParams.unitId;
+ subUnitId = newParams.subUnitId;
+ }
+
+ return { unitId, subUnitId };
+ }
+
+ private _moveRowInterceptor(params: IInsertRowCommandParams | IRemoveRowColCommandParams, type: 'insert' | 'remove') {
+ const ids = this._getUnitIdAndSubUnitId(params, type);
+ if (ids == null) {
+ return { redos: [], undos: [] };
+ }
+ const { unitId, subUnitId } = ids;
+ const { range } = params;
+
+ const rowStartIndex = range.startRow;
+ const rowEndIndex = range.endRow;
+
+ const redos: IMutationInfo[] = [];
+ const undos: IMutationInfo[] = [];
+
+ const data = this._sheetDrawingService.getDrawingData(unitId, subUnitId);
+ const updateDrawings: Partial<ISheetDrawing>[] = [];
+ const deleteDrawings: Partial<ISheetDrawing>[] = [];
+
+ Object.keys(data).forEach((drawingId) => {
+ const drawing = data[drawingId];
+ const { sheetTransform, transform, anchorType = SheetDrawingAnchorType.Position } = drawing;
+
+ if (sheetTransform == null || transform == null) {
+ return;
+ }
+ let newSheetTransform: Nullable<ISheetDrawingPosition>;
+ let newTransform: Nullable<ITransformState>;
+ if (type === 'insert') {
+ const param = this._expandRow(sheetTransform, transform, rowStartIndex, rowEndIndex, anchorType);
+ newSheetTransform = param?.newSheetTransform;
+ newTransform = param?.newTransform;
+ } else {
+ const { from, to } = sheetTransform;
+ const { row: fromRow } = from;
+ const { row: toRow } = to;
+ if (fromRow >= rowStartIndex && toRow <= rowEndIndex) {
+ // delete drawing
+ deleteDrawings.push({ unitId, subUnitId, drawingId });
+ } else {
+ const param = this._shrinkRow(sheetTransform, transform, rowStartIndex, rowEndIndex, anchorType);
+ newSheetTransform = param?.newSheetTransform;
+ newTransform = param?.newTransform;
+ }
+ }
+ if (!newSheetTransform || !newTransform) {
+ return;
+ }
+ const params = { unitId, subUnitId, drawingId, transform: newTransform, sheetTransform: newSheetTransform };
+ updateDrawings.push(params);
+ });
+
+ if (updateDrawings.length === 0 && deleteDrawings.length === 0) {
+ return { redos: [], undos: [] };
+ }
+
+ if (updateDrawings.length > 0) {
+ const updateJsonOp = this._sheetDrawingService.getBatchUpdateOp(updateDrawings as ISheetDrawing[]) as IDrawingJsonUndo1;
+ const { undo, redo, objects } = updateJsonOp;
+ redos.push({ id: SetDrawingApplyMutation.id, params: { unitId, subUnitId, op: redo, objects, type: DrawingApplyType.UPDATE } });
+ undos.push({ id: SetDrawingApplyMutation.id, params: { unitId, subUnitId, op: undo, objects, type: DrawingApplyType.UPDATE } });
+ }
+
+ if (deleteDrawings.length > 0) {
+ const deleteJsonOp = this._sheetDrawingService.getBatchRemoveOp(deleteDrawings as ISheetDrawing[]) as IDrawingJsonUndo1;
+ const deleteUndo = deleteJsonOp.undo;
+ const deleteRedo = deleteJsonOp.redo;
+ const deleteObjects = deleteJsonOp.objects;
+ redos.push({ id: SetDrawingApplyMutation.id, params: { unitId, subUnitId, op: deleteRedo, objects: deleteObjects, type: DrawingApplyType.REMOVE } });
+ undos.push({ id: SetDrawingApplyMutation.id, params: { unitId, subUnitId, op: deleteUndo, objects: deleteObjects, type: DrawingApplyType.INSERT } });
+ }
+
+ redos.push({ id: ClearSheetDrawingTransformerOperation.id, params: [unitId] });
+ undos.push({ id: ClearSheetDrawingTransformerOperation.id, params: [unitId] });
+
+ return {
+ redos,
+ undos,
+ };
+ }
+
+ private _moveColInterceptor(params: IInsertColCommandParams | IRemoveRowColCommandParams, type: 'insert' | 'remove') {
+ const ids = this._getUnitIdAndSubUnitId(params, type);
+ if (ids == null) {
+ return { redos: [], undos: [] };
+ }
+ const { unitId, subUnitId } = ids;
+ const { range } = params;
+
+ const colStartIndex = range.startColumn;
+ const colEndIndex = range.endColumn;
+
+ const redos: IMutationInfo[] = [];
+ const undos: IMutationInfo[] = [];
+
+ const data = this._sheetDrawingService.getDrawingData(unitId, subUnitId);
+ const updateDrawings: Partial<ISheetDrawing>[] = [];
+ const deleteDrawings: Partial<ISheetDrawing>[] = [];
+
+ Object.keys(data).forEach((drawingId) => {
+ const drawing = data[drawingId];
+ const { sheetTransform, transform, anchorType = SheetDrawingAnchorType.Position } = drawing;
+
+ if (sheetTransform == null || transform == null) {
+ return;
+ }
+ let newSheetTransform: Nullable<ISheetDrawingPosition>;
+ let newTransform: Nullable<ITransformState>;
+ if (type === 'insert') {
+ const param = this._expandCol(sheetTransform, transform, colStartIndex, colEndIndex, anchorType);
+ newSheetTransform = param?.newSheetTransform;
+ newTransform = param?.newTransform;
+ } else {
+ const { from, to } = sheetTransform;
+ const { column: fromColumn } = from;
+ const { column: toColumn } = to;
+ if (fromColumn >= colStartIndex && toColumn <= colEndIndex) {
+ // delete drawing
+ deleteDrawings.push({ unitId, subUnitId, drawingId });
+ } else {
+ const param = this._shrinkCol(sheetTransform, transform, colStartIndex, colEndIndex, anchorType);
+ newSheetTransform = param?.newSheetTransform;
+ newTransform = param?.newTransform;
+ }
+ }
+
+ if (!newSheetTransform || !newTransform) {
+ return;
+ }
+
+ const params = { unitId, subUnitId, drawingId, transform: newTransform, sheetTransform: newSheetTransform };
+ updateDrawings.push(params);
+ });
+
+ if (updateDrawings.length === 0 && deleteDrawings.length === 0) {
+ return { redos: [], undos: [] };
+ }
+
+ if (updateDrawings.length > 0) {
+ const updateJsonOp = this._sheetDrawingService.getBatchUpdateOp(updateDrawings as ISheetDrawing[]) as IDrawingJsonUndo1;
+ const { undo, redo, objects } = updateJsonOp;
+ redos.push({ id: SetDrawingApplyMutation.id, params: { unitId, subUnitId, op: redo, objects, type: DrawingApplyType.UPDATE } });
+ undos.push({ id: SetDrawingApplyMutation.id, params: { unitId, subUnitId, op: undo, objects, type: DrawingApplyType.UPDATE } });
+ }
+
+ if (deleteDrawings.length > 0) {
+ const deleteJsonOp = this._sheetDrawingService.getBatchRemoveOp(deleteDrawings as ISheetDrawing[]) as IDrawingJsonUndo1;
+ const deleteUndo = deleteJsonOp.undo;
+ const deleteRedo = deleteJsonOp.redo;
+ const deleteObjects = deleteJsonOp.objects;
+ redos.push({ id: SetDrawingApplyMutation.id, params: { unitId, subUnitId, op: deleteRedo, objects: deleteObjects, type: DrawingApplyType.REMOVE } });
+ undos.push({ id: SetDrawingApplyMutation.id, params: { unitId, subUnitId, op: deleteUndo, objects: deleteObjects, type: DrawingApplyType.INSERT } });
+ }
+
+ redos.push({ id: ClearSheetDrawingTransformerOperation.id, params: [unitId] });
+ undos.push({ id: ClearSheetDrawingTransformerOperation.id, params: [unitId] });
+
+ return { redos, undos };
+ }
+
+ private _expandCol(sheetTransform: ISheetDrawingPosition, transform: ITransformState, colStartIndex: number, colEndIndex: number, anchorType = SheetDrawingAnchorType.Position) {
+ const colCount = colEndIndex - colStartIndex + 1;
+
+ const { from, to } = sheetTransform;
+
+ const { column: fromColumn } = from;
+ const { column: toColumn } = to;
+
+ if (anchorType === SheetDrawingAnchorType.None) {
+ return {
+ newSheetTransform: transformToDrawingPosition({ ...transform }, this._selectionRenderService),
+ newTransform: transform,
+ };
+ }
+
+ let newSheetTransform: Nullable<ISheetDrawingPosition> = null;
+ let newTransform: Nullable<ITransformState> = null;
+
+ if (fromColumn >= colStartIndex) {
+ // move start and end col right
+ // newSheetTransform = {
+ // from: { ...from, column: fromColumn + colCount },
+ // to: { ...to, column: toColumn + colCount },
+ // };
+ // newTransform = drawingPositionToTransform(newSheetTransform, this._selectionRenderService);
+
+ const selectionCell = this._selectionRenderService.attachRangeWithCoord({ startColumn: colStartIndex, endColumn: colEndIndex, startRow: from.row, endRow: to.row });
+ if (selectionCell == null) {
+ return;
+ }
+ newTransform = { ...transform, left: (transform.left || 0) + selectionCell.endX - selectionCell.startX };
+ newSheetTransform = transformToDrawingPosition(newTransform, this._selectionRenderService);
+ } else if (toColumn >= colEndIndex) {
+ // move end right only
+ if (anchorType === SheetDrawingAnchorType.Both) {
+ newSheetTransform = {
+ from: { ...from },
+ to: { ...to, column: toColumn + colCount },
+ };
+ newTransform = drawingPositionToTransform(newSheetTransform, this._selectionRenderService);
+ } else {
+ return {
+ newSheetTransform: transformToDrawingPosition({ ...transform }, this._selectionRenderService),
+ newTransform: transform,
+ };
+ }
+ }
+
+ if (newSheetTransform != null && newTransform != null) {
+ return {
+ newSheetTransform,
+ newTransform,
+ };
+ }
+
+ return null;
+ }
+
+ private _shrinkCol(sheetTransform: ISheetDrawingPosition, transform: ITransformState, colStartIndex: number, colEndIndex: number, anchorType = SheetDrawingAnchorType.Position) {
+ const colCount = colEndIndex - colStartIndex + 1;
+ const { from, to } = sheetTransform;
+ const { column: fromColumn } = from;
+ const { column: toColumn } = to;
+ if (anchorType === SheetDrawingAnchorType.None) {
+ return {
+ newSheetTransform: transformToDrawingPosition({ ...transform }, this._selectionRenderService),
+ newTransform: transform,
+ };
+ }
+ let newSheetTransform: Nullable<ISheetDrawingPosition> = null;
+ let newTransform: Nullable<ITransformState> = null;
+
+ if (fromColumn > colEndIndex) {
+ // shrink start and end col left only
+ newSheetTransform = {
+ from: { ...from, column: fromColumn - colCount },
+ to: { ...to, column: toColumn - colCount },
+ };
+ newTransform = drawingPositionToTransform(newSheetTransform, this._selectionRenderService);
+ } else if (fromColumn >= colStartIndex && toColumn <= colEndIndex) {
+ // delete drawing
+ return null;
+ } else if (fromColumn < colStartIndex && toColumn > colEndIndex) {
+ // shrink end left only
+ if (anchorType === SheetDrawingAnchorType.Both) {
+ newSheetTransform = {
+ from: { ...from },
+ to: { ...to, column: toColumn - colCount },
+ };
+ newTransform = drawingPositionToTransform(newSheetTransform, this._selectionRenderService);
+ } else {
+ return {
+ newSheetTransform: transformToDrawingPosition({ ...transform }, this._selectionRenderService),
+ newTransform: transform,
+ };
+ }
+ } else if (fromColumn >= colStartIndex && fromColumn <= colEndIndex) {
+ if (fromColumn === colStartIndex) {
+ newTransform = { ...transform, left: (transform.left || 0) - sheetTransform.from.columnOffset };
+ } else {
+ const selectionCell = this._selectionRenderService.attachRangeWithCoord({ startColumn: colStartIndex, endColumn: fromColumn - 1, startRow: from.row, endRow: to.row });
+ if (selectionCell == null) {
+ return;
+ }
+ newTransform = { ...transform, left: (transform.left || 0) - selectionCell.endX + selectionCell.startX - sheetTransform.from.columnOffset };
+ }
+ newSheetTransform = transformToDrawingPosition(newTransform, this._selectionRenderService);
+ } else if (toColumn >= colStartIndex && toColumn <= colEndIndex && anchorType === SheetDrawingAnchorType.Both) {
+ // shrink end col left, then set toColOffset to full cell width
+ const selectionCell = this._selectionRenderService.attachRangeWithCoord({
+ startColumn: colStartIndex - 1,
+ endColumn: colStartIndex - 1,
+ startRow: from.row,
+ endRow: to.row,
+ });
+
+ if (selectionCell == null) {
+ return;
+ }
+ newSheetTransform = {
+ from: { ...from },
+ to: { ...to, column: colStartIndex - 1, columnOffset: selectionCell.endX - selectionCell.startX },
+ };
+ newTransform = drawingPositionToTransform(newSheetTransform, this._selectionRenderService);
+ }
+
+ if (newSheetTransform != null && newTransform != null) {
+ return {
+ newSheetTransform,
+ newTransform,
+ };
+ }
+
+ return null;
+ }
+
+ private _expandRow(sheetTransform: ISheetDrawingPosition, transform: ITransformState, rowStartIndex: number, rowEndIndex: number, anchorType = SheetDrawingAnchorType.Position) {
+ const rowCount = rowEndIndex - rowStartIndex + 1;
+
+ const { from, to } = sheetTransform;
+
+ const { row: fromRow } = from;
+ const { row: toRow } = to;
+
+ if (anchorType === SheetDrawingAnchorType.None) {
+ return {
+ newSheetTransform: transformToDrawingPosition({ ...transform }, this._selectionRenderService),
+ newTransform: transform,
+ };
+ }
+
+ let newSheetTransform: Nullable<ISheetDrawingPosition> = null;
+ let newTransform: Nullable<ITransformState> = null;
+
+ if (fromRow >= rowStartIndex) {
+ // move start and end row down
+ const selectionCell = this._selectionRenderService.attachRangeWithCoord({ startRow: rowStartIndex, endRow: rowEndIndex, startColumn: from.column, endColumn: to.column });
+ if (selectionCell == null) {
+ return;
+ }
+ newTransform = { ...transform, top: (transform.top || 0) + selectionCell.endY - selectionCell.startY };
+ newSheetTransform = transformToDrawingPosition(newTransform, this._selectionRenderService);
+ } else if (toRow >= rowEndIndex) {
+ // move end down only
+ if (anchorType === SheetDrawingAnchorType.Both) {
+ newSheetTransform = {
+ from: { ...from },
+ to: {
+ ...to,
+ row: toRow + rowCount,
+ },
+ };
+ newTransform = drawingPositionToTransform(newSheetTransform, this._selectionRenderService);
+ } else {
+ return {
+ newSheetTransform: transformToDrawingPosition({ ...transform }, this._selectionRenderService),
+ newTransform: transform,
+ };
+ }
+ }
+
+ if (newSheetTransform != null && newTransform != null) {
+ return {
+ newSheetTransform,
+ newTransform,
+ };
+ }
+
+ return null;
+ }
+
+ private _shrinkRow(sheetTransform: ISheetDrawingPosition, transform: ITransformState, rowStartIndex: number, rowEndIndex: number, anchorType = SheetDrawingAnchorType.Position) {
+ const rowCount = rowEndIndex - rowStartIndex + 1;
+
+ const { from, to } = sheetTransform;
+
+ const { row: fromRow } = from;
+ const { row: toRow } = to;
+
+ if (anchorType === SheetDrawingAnchorType.None) {
+ return {
+ newSheetTransform: transformToDrawingPosition({ ...transform }, this._selectionRenderService),
+ newTransform: transform,
+ };
+ }
+
+ let newSheetTransform: Nullable<ISheetDrawingPosition> = null;
+ let newTransform: Nullable<ITransformState> = null;
+
+ if (fromRow > rowEndIndex) {
+ // shrink start and end up only
+ newSheetTransform = {
+ from: { ...from, row: fromRow - rowCount },
+ to: { ...to, row: toRow - rowCount },
+ };
+ newTransform = drawingPositionToTransform(newSheetTransform, this._selectionRenderService);
+ } else if (fromRow >= rowStartIndex && toRow <= rowEndIndex) {
+ // delete drawing
+ return null;
+ } else if (fromRow < rowStartIndex && toRow > rowEndIndex) {
+ // shrink end up only
+ if (anchorType === SheetDrawingAnchorType.Both) {
+ newSheetTransform = {
+ from: { ...from },
+ to: { ...to, row: toRow - rowCount },
+ };
+ newTransform = drawingPositionToTransform(newSheetTransform, this._selectionRenderService);
+ } else {
+ return {
+ newSheetTransform: transformToDrawingPosition({ ...transform }, this._selectionRenderService),
+ newTransform: transform,
+ };
+ }
+ } else if (fromRow >= rowStartIndex && fromRow <= rowEndIndex) {
+ // shrink start and end row up, then set fromRowOffset to 0
+ if (fromRow === rowStartIndex) {
+ newTransform = { ...transform, top: (transform.top || 0) - sheetTransform.from.rowOffset };
+ } else {
+ const selectionCell = this._selectionRenderService.attachRangeWithCoord({ startRow: rowStartIndex, endRow: fromRow - 1, startColumn: from.column, endColumn: to.column });
+ if (selectionCell == null) {
+ return;
+ }
+ newTransform = { ...transform, top: (transform.top || 0) - selectionCell.endY + selectionCell.startY - sheetTransform.from.rowOffset };
+ }
+ newSheetTransform = transformToDrawingPosition(newTransform, this._selectionRenderService);
+ } else if (toRow >= rowStartIndex && toRow <= rowEndIndex && anchorType === SheetDrawingAnchorType.Both) {
+ // shrink end row up, then set toRowOffset to full cell height
+ const selectionCell = this._selectionRenderService.attachRangeWithCoord({ startColumn: from.column, endColumn: from.column, startRow: rowStartIndex - 1, endRow: rowStartIndex - 1 });
+
+ if (selectionCell == null) {
+ return;
+ }
+ newSheetTransform = {
+ from: { ...from },
+ to: { ...to, row: rowStartIndex - 1, rowOffset: selectionCell.endY - selectionCell.startY },
+ };
+ newTransform = drawingPositionToTransform(newSheetTransform, this._selectionRenderService);
+ }
+
+ if (newSheetTransform != null && newTransform != null) {
+ return {
+ newSheetTransform,
+ newTransform,
+ };
+ }
+
+ return null;
+ }
+
+ private _commandListener() {
+ this.disposeWithMe(
+ this._commandService.onCommandExecuted((command: ICommandInfo) => {
+ if (command.id === SetWorksheetActiveOperation.id) {
+ const params = command.params as ISetWorksheetActiveOperationParams;
+ const { unitId: showUnitId, subUnitId: showSubunitId } = params;
+
+ const drawingMap = this._drawingManagerService.drawingManagerData;
+
+ const insertDrawings: IDrawingParam[] = [];
+
+ const removeDrawings: IDrawingParam[] = [];
+
+ Object.keys(drawingMap).forEach((unitId) => {
+ const subUnitMap = drawingMap[unitId];
+ Object.keys(subUnitMap).forEach((subUnitId) => {
+ const drawingData = subUnitMap[subUnitId].data;
+ if (drawingData == null) {
+ return;
+ }
+ Object.keys(drawingData).forEach((drawingId) => {
+ if (unitId === showUnitId && subUnitId === showSubunitId) {
+ insertDrawings.push(drawingData[drawingId]);
+ } else {
+ removeDrawings.push(drawingData[drawingId]);
+ }
+ });
+ });
+ });
+
+ this._drawingManagerService.removeNotification(removeDrawings);
+ this._drawingManagerService.addNotification(insertDrawings);
+ }
+ })
+ );
+ }
+
+ private _sheetRefreshListener() {
+ this.disposeWithMe(
+ this._commandService.onCommandExecuted((command: ICommandInfo) => {
+ if (!REFRESH_MUTATIONS.includes(command.id)) {
+ return;
+ }
+
+ requestIdleCallback(() => {
+ const params = command.params as ISetRowVisibleMutationParams | ISetColHiddenMutationParams | ISetWorksheetRowHeightMutationParams | ISetWorksheetColWidthMutationParams | ISetWorksheetRowIsAutoHeightMutationParams | ISetRowHiddenMutationParams | ISetColVisibleMutationParams | ISetWorksheetColWidthMutationParams;
+ const { unitId, subUnitId, ranges } = params;
+ this._refreshDrawingTransform(unitId, subUnitId, ranges);
+ });
+ })
+ );
+ }
+
+ private _refreshDrawingTransform(unitId: string, subUnitId: string, ranges: IRange[]) {
+ const drawingData = this._drawingManagerService.getDrawingData(unitId, subUnitId);
+
+ const updateDrawings: ISheetDrawing[] = [];
+
+ Object.keys(drawingData).forEach((drawingId) => {
+ const drawing = drawingData[drawingId] as ISheetDrawing;
+ const { sheetTransform, anchorType = SheetDrawingAnchorType.Position } = drawing;
+ if (anchorType === SheetDrawingAnchorType.None) {
+ return true;
+ }
+
+ const { from, to } = sheetTransform;
+ const { row: fromRow, column: fromColumn } = from;
+ const { row: toRow, column: toColumn } = to;
+ for (let i = 0; i < ranges.length; i++) {
+ const range = ranges[i];
+ const { startRow, endRow, startColumn, endColumn } = range;
+ if (Rectangle.intersects(
+ {
+ startRow, endRow, startColumn, endColumn,
+ },
+ {
+ startRow: fromRow, endRow: toRow, startColumn: fromColumn, endColumn: toColumn,
+ }
+ ) || fromRow > endRow || fromColumn > endColumn) {
+ updateDrawings.push({
+ ...drawing,
+ transform: drawingPositionToTransform(sheetTransform, this._selectionRenderService),
+ });
+ break;
+ }
+ }
+ });
+
+ if (updateDrawings.length === 0) {
+ return;
+ }
+
+ this._drawingManagerService.refreshTransform(updateDrawings);
+
+ this._commandService.syncExecuteCommand(ClearSheetDrawingTransformerOperation.id, [unitId]);
+ }
+}
diff --git a/packages/sheets-drawing-ui/src/controllers/sheet-drawing-update.controller.ts b/packages/sheets-drawing-ui/src/controllers/sheet-drawing-update.controller.ts
new file mode 100644
index 0000000000..8e7f1187d6
--- /dev/null
+++ b/packages/sheets-drawing-ui/src/controllers/sheet-drawing-update.controller.ts
@@ -0,0 +1,378 @@
+/**
+ * Copyright 2023-present DreamNum Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { ICommandInfo, IImageIoServiceParam, IRange, Nullable, Workbook } from '@univerjs/core';
+import { Disposable, DrawingTypeEnum, FOCUSING_COMMON_DRAWINGS, ICommandService, IContextService, IDrawingManagerService, IImageIoService, ImageUploadStatusType, IUniverInstanceService, LifecycleStages, LocaleService, OnLifecycle, UniverInstanceType } from '@univerjs/core';
+import { Inject } from '@wendellhu/redi';
+import type { IImageData } from '@univerjs/drawing';
+import { DRAWING_IMAGE_ALLOW_SIZE, DRAWING_IMAGE_COUNT_LIMIT, DRAWING_IMAGE_HEIGHT_LIMIT, DRAWING_IMAGE_WIDTH_LIMIT, getImageSize } from '@univerjs/drawing';
+import type { ISheetDrawing, ISheetDrawingPosition } from '@univerjs/sheets';
+import { ISheetDrawingService, SelectionManagerService } from '@univerjs/sheets';
+import { ISelectionRenderService } from '@univerjs/sheets-ui';
+import { IMessageService } from '@univerjs/ui';
+import { MessageType } from '@univerjs/design';
+import { IRenderManagerService } from '@univerjs/engine-render';
+import type { IInsertImageOperationParams } from '../commands/operations/insert-image.operation';
+import { InsertCellImageOperation, InsertFloatImageOperation } from '../commands/operations/insert-image.operation';
+import { InsertSheetDrawingCommand } from '../commands/commands/insert-sheet-drawing.command';
+import type { IInsertDrawingCommandParams, ISetDrawingCommandParams } from '../commands/commands/interfaces';
+import { SetSheetDrawingCommand } from '../commands/commands/set-sheet-drawing.command';
+import type { ISetDrawingArrangeCommandParams } from '../commands/commands/set-drawing-arrange.command';
+import { SetDrawingArrangeCommand } from '../commands/commands/set-drawing-arrange.command';
+import { GroupSheetDrawingCommand } from '../commands/commands/group-sheet-drawing.command';
+import { UngroupSheetDrawingCommand } from '../commands/commands/ungroup-sheet-drawing.command';
+import { drawingPositionToTransform, transformToDrawingPosition } from '../basics/transform-position';
+
+@OnLifecycle(LifecycleStages.Rendered, SheetDrawingUpdateController)
+export class SheetDrawingUpdateController extends Disposable {
+ constructor(
+ @ICommandService private readonly _commandService: ICommandService,
+ @IUniverInstanceService private readonly _univerInstanceService: IUniverInstanceService,
+ @Inject(SelectionManagerService) private readonly _selectionManagerService: SelectionManagerService,
+ @ISelectionRenderService private readonly _selectionRenderService: ISelectionRenderService,
+ @IImageIoService private readonly _imageIoService: IImageIoService,
+ @ISheetDrawingService private readonly _sheetDrawingService: ISheetDrawingService,
+ @IDrawingManagerService private readonly _drawingManagerService: IDrawingManagerService,
+ @IContextService private readonly _contextService: IContextService,
+ @IMessageService private readonly _messageService: IMessageService,
+ @Inject(LocaleService) private readonly _localeService: LocaleService,
+ @IRenderManagerService private readonly _renderManagerService: IRenderManagerService
+ ) {
+ super();
+
+ this._init();
+ }
+
+ private _init(): void {
+ this._initCommandListeners();
+
+ this._updateImageListener();
+
+ this._updateOrderListener();
+
+ this._groupDrawingListener();
+
+ this._focusDrawingListener();
+ }
+
+ /**
+ * Upload image to cell or float image
+ */
+ private _initCommandListeners() {
+ this.disposeWithMe(
+ this._commandService.onCommandExecuted(async (command: ICommandInfo) => {
+ if (command.id === InsertCellImageOperation.id || command.id === InsertFloatImageOperation.id) {
+ const params = command.params as IInsertImageOperationParams;
+ if (params.files == null) {
+ return;
+ }
+
+ const fileLength = params.files.length;
+
+ if (fileLength > DRAWING_IMAGE_COUNT_LIMIT) {
+ this._messageService.show({
+ type: MessageType.Error,
+ content: this._localeService.t('update-status.exceedMaxCount', String(DRAWING_IMAGE_COUNT_LIMIT)),
+ });
+ return;
+ }
+
+ this._imageIoService.setWaitCount(fileLength);
+ if (command.id === InsertCellImageOperation.id) {
+ params.files.forEach(async (file) => {
+ await this._insertCellImage(file);
+ });
+ } else {
+ params.files.forEach(async (file) => {
+ await this._insertFloatImage(file);
+ });
+ }
+ }
+ })
+ );
+ }
+
+ private async _insertCellImage(file: File) {
+
+ }
+
+ private async _insertFloatImage(file: File) {
+ let imageParam: Nullable<IImageIoServiceParam>;
+
+ try {
+ imageParam = await this._imageIoService.saveImage(file);
+ } catch (error) {
+ const type = (error as Error).message;
+ if (type === ImageUploadStatusType.ERROR_EXCEED_SIZE) {
+ this._messageService.show({
+ type: MessageType.Error,
+ content: this._localeService.t('update-status.exceedMaxSize', String(DRAWING_IMAGE_ALLOW_SIZE / (1024 * 1024))),
+ });
+ } else if (type === ImageUploadStatusType.ERROR_IMAGE_TYPE) {
+ this._messageService.show({
+ type: MessageType.Error,
+ content: this._localeService.t('update-status.invalidImageType'),
+ });
+ } else if (type === ImageUploadStatusType.ERROR_IMAGE) {
+ this._messageService.show({
+ type: MessageType.Error,
+ content: this._localeService.t('update-status.invalidImage'),
+ });
+ }
+ }
+
+ if (imageParam == null) {
+ return;
+ }
+
+ const info = this._getUnitInfo();
+ if (info == null) {
+ return;
+ }
+ const { unitId, subUnitId } = info;
+
+ const { imageId, imageSourceType, source, base64Cache } = imageParam;
+
+ const { width, height, image } = await getImageSize(base64Cache || '');
+
+ const renderObject = this._renderManagerService.getRenderById(unitId);
+
+ if (renderObject == null) {
+ return;
+ }
+
+ const { width: sceneWidth, height: sceneHeight } = renderObject.scene;
+
+ this._imageIoService.addImageSourceCache(source, imageSourceType, image);
+
+ let scale = 1;
+ if (width > DRAWING_IMAGE_WIDTH_LIMIT || height > DRAWING_IMAGE_HEIGHT_LIMIT) {
+ const scaleWidth = DRAWING_IMAGE_WIDTH_LIMIT / width;
+ const scaleHeight = DRAWING_IMAGE_HEIGHT_LIMIT / height;
+ scale = Math.max(scaleWidth, scaleHeight);
+ }
+
+ const sheetTransform = this._getImagePosition(width * scale, height * scale, sceneWidth, sceneHeight);
+
+ if (sheetTransform == null) {
+ return;
+ }
+
+ const sheetDrawingParam: ISheetDrawing = {
+ unitId,
+ subUnitId,
+ drawingId: imageId,
+ drawingType: DrawingTypeEnum.DRAWING_IMAGE,
+ imageSourceType,
+ source,
+ transform: drawingPositionToTransform(sheetTransform, this._selectionRenderService),
+ sheetTransform,
+ };
+
+ this._commandService.executeCommand(InsertSheetDrawingCommand.id, {
+ unitId,
+ drawings: [sheetDrawingParam],
+ } as IInsertDrawingCommandParams);
+ }
+
+ private _getUnitInfo() {
+ const universheet = this._univerInstanceService.getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET);
+ if (universheet == null) {
+ return;
+ }
+
+ const worksheet = universheet.getActiveSheet();
+ if (worksheet == null) {
+ return;
+ }
+
+ const unitId = universheet.getUnitId();
+ const subUnitId = worksheet.getSheetId();
+
+ return {
+ unitId,
+ subUnitId,
+ };
+ }
+
+ private _getImagePosition(imageWidth: number, imageHeight: number, sceneWidth: number, sceneHeight: number): Nullable<ISheetDrawingPosition> {
+ const selections = this._selectionManagerService.getSelections();
+ let range: IRange = {
+ startRow: 0,
+ endRow: 0,
+ startColumn: 0,
+ endColumn: 0,
+ };
+ if (selections && selections.length > 0) {
+ range = selections[selections.length - 1].range;
+ }
+
+ const rangeWithCoord = this._selectionRenderService.attachRangeWithCoord(range);
+ if (rangeWithCoord == null) {
+ return;
+ }
+
+ let { startColumn, startRow, startX, startY } = rangeWithCoord;
+
+ let isChangeStart = false;
+ if (startX + imageWidth > sceneWidth) {
+ startX = sceneWidth - imageWidth;
+
+ if (startX < 0) {
+ startX = 0;
+ imageWidth = sceneWidth;
+ }
+
+ isChangeStart = true;
+ }
+
+ if (startY + imageHeight > sceneHeight) {
+ startY = sceneHeight - imageHeight;
+
+ if (startY < 0) {
+ startY = 0;
+ imageHeight = sceneHeight;
+ }
+
+ isChangeStart = true;
+ }
+
+ if (isChangeStart) {
+ const newCoord = this._selectionRenderService.getSelectionCellByPosition(startX, startY);
+ if (newCoord == null) {
+ return;
+ }
+ startX = newCoord.startX;
+ startY = newCoord.startY;
+ startColumn = newCoord.actualColumn;
+ startRow = newCoord.actualRow;
+ }
+
+ const from = {
+ column: startColumn,
+ columnOffset: 0,
+ row: startRow,
+ rowOffset: 0,
+ };
+
+ const endSelectionCell = this._selectionRenderService.getSelectionCellByPosition(startX + imageWidth, startY + imageHeight);
+
+ if (endSelectionCell == null) {
+ return;
+ }
+
+ const to = {
+ column: endSelectionCell.actualColumn,
+ columnOffset: startX + imageWidth - endSelectionCell.startX,
+ row: endSelectionCell.actualRow,
+ rowOffset: startY + imageHeight - endSelectionCell.startY,
+ };
+
+ return {
+ from,
+ to,
+ };
+ }
+
+ private _updateOrderListener() {
+ this._drawingManagerService.featurePluginOrderUpdate$.subscribe((params) => {
+ const { unitId, subUnitId, drawingIds, arrangeType } = params;
+
+ this._commandService.executeCommand(SetDrawingArrangeCommand.id, {
+ unitId,
+ subUnitId,
+ drawingIds,
+ arrangeType,
+ } as ISetDrawingArrangeCommandParams);
+ });
+ }
+
+ private _updateImageListener() {
+ this._drawingManagerService.featurePluginUpdate$.subscribe((params) => {
+ const drawings: Partial<ISheetDrawing>[] = [];
+
+ if (params.length === 0) {
+ return;
+ }
+
+ (params as IImageData[]).forEach((param) => {
+ const { unitId, subUnitId, drawingId, drawingType, transform } = param;
+ if (transform == null) {
+ return;
+ }
+
+ const sheetDrawing = this._sheetDrawingService.getDrawingByParam({ unitId, subUnitId, drawingId });
+
+ // const imageDrawing = this._drawingManagerService.getDrawingByParam({ unitId, subUnitId, drawingId });
+
+ if (sheetDrawing == null) {
+ return;
+ }
+
+ const sheetTransform = transformToDrawingPosition({ ...sheetDrawing.transform, ...transform }, this._selectionRenderService);
+
+ if (sheetTransform == null) {
+ return;
+ }
+
+ // const oldDrawing: Partial<ISheetDrawing> = {
+ // ...sheetDrawing,
+ // };
+
+ const newDrawing: Partial<ISheetDrawing> = {
+ ...param,
+ transform: { ...transform, ...drawingPositionToTransform(sheetTransform, this._selectionRenderService) },
+ sheetTransform: { ...sheetTransform },
+ };
+
+ drawings.push(newDrawing);
+ });
+
+ if (drawings.length > 0) {
+ this._commandService.executeCommand(SetSheetDrawingCommand.id, {
+ unitId: params[0].unitId,
+ drawings,
+ } as ISetDrawingCommandParams);
+ }
+ });
+ }
+
+ private _groupDrawingListener() {
+ this._drawingManagerService.featurePluginGroupUpdate$.subscribe((params) => {
+ this._commandService.executeCommand(GroupSheetDrawingCommand.id, params);
+ const { unitId, subUnitId, drawingId } = params[0].parent;
+ this._drawingManagerService.focusDrawing([{ unitId, subUnitId, drawingId }]);
+ });
+
+ this._drawingManagerService.featurePluginUngroupUpdate$.subscribe((params) => {
+ this._commandService.executeCommand(UngroupSheetDrawingCommand.id, params);
+ });
+ }
+
+ private _focusDrawingListener() {
+ this.disposeWithMe(
+ this._drawingManagerService.focus$.subscribe((params) => {
+ if (params == null || params.length === 0) {
+ this._contextService.setContextValue(FOCUSING_COMMON_DRAWINGS, false);
+ this._sheetDrawingService.focusDrawing([]);
+ } else {
+ this._contextService.setContextValue(FOCUSING_COMMON_DRAWINGS, true);
+ this._sheetDrawingService.focusDrawing(params);
+ }
+ })
+ );
+ }
+}
diff --git a/packages/sheets-drawing-ui/src/controllers/sheet-drawing.controller.ts b/packages/sheets-drawing-ui/src/controllers/sheet-drawing.controller.ts
new file mode 100644
index 0000000000..ec50d0a2e6
--- /dev/null
+++ b/packages/sheets-drawing-ui/src/controllers/sheet-drawing.controller.ts
@@ -0,0 +1,124 @@
+/**
+ * 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 { DependencyOverride } from '@univerjs/core';
+import { Disposable, ICommandService, LifecycleStages, OnLifecycle } from '@univerjs/core';
+import type { MenuConfig } from '@univerjs/ui';
+import { ComponentManager, IMenuService, IShortcutService } from '@univerjs/ui';
+import { Inject, Injector } from '@wendellhu/redi';
+
+import { AddImageSingle } from '@univerjs/icons';
+import { UploadFileMenu } from '../views/upload-component/UploadFile';
+import { COMPONENT_UPLOAD_FILE_MENU } from '../views/upload-component/component-name';
+import { IMAGE_UPLOAD_ICON, ImageMenuFactory, UploadFloatImageMenuFactory } from '../views/menu/image.menu';
+import { InsertCellImageOperation, InsertFloatImageOperation } from '../commands/operations/insert-image.operation';
+import { InsertSheetDrawingCommand } from '../commands/commands/insert-sheet-drawing.command';
+import { RemoveSheetDrawingCommand } from '../commands/commands/remove-sheet-drawing.command';
+import { SetSheetDrawingCommand } from '../commands/commands/set-sheet-drawing.command';
+import { COMPONENT_SHEET_DRAWING_PANEL } from '../views/sheet-image-panel/component-name';
+import { SheetDrawingPanel } from '../views/sheet-image-panel/SheetDrawingPanel';
+
+import { ClearSheetDrawingTransformerOperation } from '../commands/operations/clear-drawing-transformer.operation';
+import { EditSheetDrawingOperation } from '../commands/operations/edit-sheet-drawing.operation';
+import { GroupSheetDrawingCommand } from '../commands/commands/group-sheet-drawing.command';
+import { UngroupSheetDrawingCommand } from '../commands/commands/ungroup-sheet-drawing.command';
+import { SidebarSheetDrawingOperation } from '../commands/operations/open-drawing-panel.operation';
+import { MoveDrawingsCommand } from '../commands/commands/move-drawings.command';
+import { DeleteDrawingsCommand } from '../commands/commands/delete-drawings.command';
+import { SetDrawingArrangeCommand } from '../commands/commands/set-drawing-arrange.command';
+import { DeleteDrawingsShortcutItem, MoveDrawingDownShortcutItem, MoveDrawingLeftShortcutItem, MoveDrawingRightShortcutItem, MoveDrawingUpShortcutItem } from './shortcuts/drawing.shortcut';
+
+export interface IUniverSheetsDrawingConfig {
+ menu?: MenuConfig;
+ overrides?: DependencyOverride;
+}
+
+export const DefaultSheetsDrawingConfig: IUniverSheetsDrawingConfig = {
+
+};
+
+@OnLifecycle(LifecycleStages.Rendered, SheetDrawingUIController)
+export class SheetDrawingUIController extends Disposable {
+ constructor(
+ private readonly _config: Partial<IUniverSheetsDrawingConfig>,
+ @Inject(Injector) private readonly _injector: Injector,
+ @Inject(ComponentManager) private readonly _componentManager: ComponentManager,
+ @IMenuService private readonly _menuService: IMenuService,
+ @ICommandService private readonly _commandService: ICommandService,
+ @IShortcutService private readonly _shortcutService: IShortcutService
+ ) {
+ super();
+
+ this._init();
+ }
+
+ private _initCustomComponents(): void {
+ const componentManager = this._componentManager;
+ this.disposeWithMe(componentManager.register(IMAGE_UPLOAD_ICON, AddImageSingle));
+ this.disposeWithMe(componentManager.register(COMPONENT_UPLOAD_FILE_MENU, UploadFileMenu));
+ this.disposeWithMe(componentManager.register(COMPONENT_SHEET_DRAWING_PANEL, SheetDrawingPanel));
+ }
+
+ private _initMenus(): void {
+ const { menu = {} } = this._config;
+ // init menus
+ [
+ ImageMenuFactory,
+ UploadFloatImageMenuFactory,
+ // UploadCellImageMenuFactory,
+ ].forEach((menuFactory) => {
+ this._menuService.addMenuItem(menuFactory(this._injector), menu);
+ });
+ }
+
+ private _initCommands() {
+ [
+ InsertFloatImageOperation,
+ InsertCellImageOperation,
+ InsertSheetDrawingCommand,
+ RemoveSheetDrawingCommand,
+ SetSheetDrawingCommand,
+ SidebarSheetDrawingOperation,
+ ClearSheetDrawingTransformerOperation,
+ EditSheetDrawingOperation,
+ GroupSheetDrawingCommand,
+ UngroupSheetDrawingCommand,
+ MoveDrawingsCommand,
+ DeleteDrawingsCommand,
+ SetDrawingArrangeCommand,
+ ].forEach((command) => this.disposeWithMe(this._commandService.registerCommand(command)));
+ }
+
+ private _initShortcuts(): void {
+ [
+ // sheet drawing shortcuts
+ MoveDrawingDownShortcutItem,
+ MoveDrawingUpShortcutItem,
+ MoveDrawingLeftShortcutItem,
+ MoveDrawingRightShortcutItem,
+ DeleteDrawingsShortcutItem,
+ ].forEach((item) => {
+ this.disposeWithMe(this._shortcutService.registerShortcut(item));
+ });
+ }
+
+ private _init(): void {
+ this._initCommands();
+ this._initCustomComponents();
+ this._initMenus();
+ this._initShortcuts();
+ }
+}
diff --git a/packages/sheets-drawing-ui/src/controllers/shortcuts/drawing.shortcut.ts b/packages/sheets-drawing-ui/src/controllers/shortcuts/drawing.shortcut.ts
new file mode 100644
index 0000000000..870c19fcfd
--- /dev/null
+++ b/packages/sheets-drawing-ui/src/controllers/shortcuts/drawing.shortcut.ts
@@ -0,0 +1,87 @@
+/**
+ * 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 { IContextService } from '@univerjs/core';
+import { Direction, EDITOR_ACTIVATED, FOCUSING_COMMON_DRAWINGS, FOCUSING_FORMULA_EDITOR } from '@univerjs/core';
+import type { IShortcutItem } from '@univerjs/ui';
+import { KeyCode } from '@univerjs/ui';
+import { type IMoveDrawingsCommandParams, MoveDrawingsCommand } from '../../commands/commands/move-drawings.command';
+import { DeleteDrawingsCommand } from '../../commands/commands/delete-drawings.command';
+
+export function whenSheetDrawingFocused(contextService: IContextService): boolean {
+ return (
+ !contextService.getContextValue(FOCUSING_FORMULA_EDITOR) &&
+ !contextService.getContextValue(EDITOR_ACTIVATED) &&
+ contextService.getContextValue(FOCUSING_COMMON_DRAWINGS)
+ );
+}
+
+export const MoveDrawingDownShortcutItem: IShortcutItem<IMoveDrawingsCommandParams> = {
+ id: MoveDrawingsCommand.id,
+ description: 'shortcut.sheet.drawing-move-down',
+ group: '4_sheet-drawing-view',
+ binding: KeyCode.ARROW_DOWN,
+ priority: 100,
+ preconditions: whenSheetDrawingFocused,
+ staticParameters: {
+ direction: Direction.DOWN,
+ },
+};
+
+export const MoveDrawingUpShortcutItem: IShortcutItem<IMoveDrawingsCommandParams> = {
+ id: MoveDrawingsCommand.id,
+ description: 'shortcut.sheet.drawing-move-up',
+ group: '4_sheet-drawing-view',
+ binding: KeyCode.ARROW_UP,
+ priority: 100,
+ preconditions: whenSheetDrawingFocused,
+ staticParameters: {
+ direction: Direction.UP,
+ },
+};
+
+export const MoveDrawingLeftShortcutItem: IShortcutItem<IMoveDrawingsCommandParams> = {
+ id: MoveDrawingsCommand.id,
+ description: 'shortcut.sheet.drawing-move-left',
+ group: '4_sheet-drawing-view',
+ binding: KeyCode.ARROW_LEFT,
+ priority: 100,
+ preconditions: whenSheetDrawingFocused,
+ staticParameters: {
+ direction: Direction.LEFT,
+ },
+};
+
+export const MoveDrawingRightShortcutItem: IShortcutItem<IMoveDrawingsCommandParams> = {
+ id: MoveDrawingsCommand.id,
+ description: 'shortcut.sheet.drawing-move-right',
+ group: '4_sheet-drawing-view',
+ binding: KeyCode.ARROW_RIGHT,
+ priority: 100,
+ preconditions: whenSheetDrawingFocused,
+ staticParameters: {
+ direction: Direction.RIGHT,
+ },
+};
+export const DeleteDrawingsShortcutItem: IShortcutItem = {
+ id: DeleteDrawingsCommand.id,
+ description: 'shortcut.sheet.drawing-delete',
+ group: '4_sheet-drawing-view',
+ // when focusing on any other input tag do not trigger this shortcut
+ preconditions: whenSheetDrawingFocused,
+ binding: KeyCode.DELETE,
+ mac: KeyCode.BACKSPACE,
+};
diff --git a/packages/sheets-drawing-ui/src/index.ts b/packages/sheets-drawing-ui/src/index.ts
new file mode 100644
index 0000000000..b5a0215d86
--- /dev/null
+++ b/packages/sheets-drawing-ui/src/index.ts
@@ -0,0 +1,17 @@
+/**
+ * Copyright 2023-present DreamNum Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+export { UniverSheetsDrawingUIPlugin } from './plugin';
diff --git a/packages/sheets-drawing-ui/src/locale/en-US.ts b/packages/sheets-drawing-ui/src/locale/en-US.ts
new file mode 100644
index 0000000000..e3db2a43d0
--- /dev/null
+++ b/packages/sheets-drawing-ui/src/locale/en-US.ts
@@ -0,0 +1,51 @@
+/**
+ * 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.
+ */
+
+const locale = {
+ sheetImage: {
+ title: 'Image',
+
+ upload: {
+ float: 'Float Image',
+ cell: 'Cell Image',
+ },
+
+ panel: {
+ title: 'Edit Image',
+ },
+ },
+ 'image-popup': {
+ replace: 'Replace',
+ delete: 'Delete',
+ edit: 'Edit',
+ crop: 'Crop',
+ reset: 'Reset Size',
+ },
+ 'drawing-anchor': {
+ title: 'Anchor Properties',
+ both: 'Move and size with cells',
+ position: "Move but don't size with cells",
+ none: "Don't move or size with cells",
+ },
+ 'update-status': {
+ exceedMaxSize: 'Image size exceeds limit, limit is {0}M',
+ invalidImageType: 'Invalid image type',
+ exceedMaxCount: 'Only {0} images can be uploaded at a time',
+ invalidImage: 'Invalid image',
+ },
+};
+
+export default locale;
diff --git a/packages/sheets-drawing-ui/src/locale/index.ts b/packages/sheets-drawing-ui/src/locale/index.ts
new file mode 100644
index 0000000000..1eff5fc204
--- /dev/null
+++ b/packages/sheets-drawing-ui/src/locale/index.ts
@@ -0,0 +1,18 @@
+/**
+ * Copyright 2023-present DreamNum Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+export { default as enUS } from './en-US';
+export { default as zhCN } from './zh-CN';
diff --git a/packages/sheets-drawing-ui/src/locale/ru-RU.ts b/packages/sheets-drawing-ui/src/locale/ru-RU.ts
new file mode 100644
index 0000000000..8378543689
--- /dev/null
+++ b/packages/sheets-drawing-ui/src/locale/ru-RU.ts
@@ -0,0 +1,53 @@
+/**
+ * Copyright 2023-present DreamNum Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type enUS from './en-US';
+
+const locale: typeof enUS = {
+ sheetImage: {
+ title: 'Изображение',
+
+ upload: {
+ float: 'Плавающее изображение',
+ cell: 'Изображение в ячейке',
+ },
+
+ panel: {
+ title: 'Редактировать изображение',
+ },
+ },
+ 'image-popup': {
+ replace: 'Заменить',
+ delete: 'Удалить',
+ edit: 'Редактировать',
+ crop: 'Обрезать',
+ reset: 'Сбросить размер',
+ },
+ 'drawing-anchor': {
+ title: 'Свойства привязки',
+ both: 'Перемещать и изменять размер с ячейками',
+ position: 'Перемещать, но не изменять размер с ячейками',
+ none: 'Не перемещать и не изменять размер с ячейками',
+ },
+ 'update-status': {
+ exceedMaxSize: 'Размер изображения превышает лимит, лимит составляет {0}М',
+ invalidImageType: 'Недопустимый тип изображения',
+ exceedMaxCount: 'За один раз можно загрузить только {0} изображений',
+ invalidImage: 'Недопустимое изображение',
+ },
+};
+
+export default locale;
diff --git a/packages/sheets-drawing-ui/src/locale/zh-CN.ts b/packages/sheets-drawing-ui/src/locale/zh-CN.ts
new file mode 100644
index 0000000000..f1b9cf0cec
--- /dev/null
+++ b/packages/sheets-drawing-ui/src/locale/zh-CN.ts
@@ -0,0 +1,53 @@
+/**
+ * Copyright 2023-present DreamNum Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type enUS from './en-US';
+
+const locale: typeof enUS = {
+ sheetImage: {
+ title: '图片',
+
+ upload: {
+ float: '浮动图片',
+ cell: '单元格图片',
+ },
+
+ panel: {
+ title: '编辑图片',
+ },
+ },
+ 'image-popup': {
+ replace: '替换',
+ delete: '删除',
+ edit: '编辑',
+ crop: '裁剪',
+ reset: '重置大小',
+ },
+ 'drawing-anchor': {
+ title: '锚点属性',
+ both: '与单元格一起移动和调整大小',
+ position: '移动但不调整大小与单元格',
+ none: '不要移动或调整大小与单元格',
+ },
+ 'update-status': {
+ exceedMaxSize: '图片大小超过限制, 限制为{0}M',
+ invalidImageType: '图片类型错误',
+ exceedMaxCount: '图片只能一次上传{0}张',
+ invalidImage: '无效图片',
+ },
+};
+
+export default locale;
diff --git a/packages/sheets-drawing-ui/src/plugin.ts b/packages/sheets-drawing-ui/src/plugin.ts
new file mode 100644
index 0000000000..bc54e12dad
--- /dev/null
+++ b/packages/sheets-drawing-ui/src/plugin.ts
@@ -0,0 +1,75 @@
+/**
+ * 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 { LocaleService, Plugin, Tools, UniverInstanceType } from '@univerjs/core';
+import type { Dependency } from '@wendellhu/redi';
+import { Inject, Injector } from '@wendellhu/redi';
+import { enUS, zhCN } from './locale';
+import { DrawingPopupMenuController } from './controllers/drawing-popup-menu.controller';
+import { SheetDrawingUpdateController } from './controllers/sheet-drawing-update.controller';
+import type { IUniverSheetsDrawingConfig } from './controllers/sheet-drawing.controller';
+import { DefaultSheetsDrawingConfig, SheetDrawingUIController } from './controllers/sheet-drawing.controller';
+import { SheetDrawingTransformAffectedController } from './controllers/sheet-drawing-transform-affected.controller';
+
+const PLUGIN_NAME = 'SHEETS_IMAGE_UI_PLUGIN';
+
+export class UniverSheetsDrawingUIPlugin extends Plugin {
+ static override type = UniverInstanceType.UNIVER_SHEET;
+ static override pluginName = PLUGIN_NAME;
+
+ private _pluginConfig: IUniverSheetsDrawingConfig;
+
+ constructor(
+ config: Partial<IUniverSheetsDrawingConfig> = {},
+ @Inject(Injector) protected _injector: Injector,
+ @Inject(LocaleService) private readonly _localeService: LocaleService
+ ) {
+ super();
+
+ this._pluginConfig = Tools.deepMerge({}, DefaultSheetsDrawingConfig, config);
+
+ this._localeService.load({
+ zhCN,
+ enUS,
+ });
+ }
+
+ override onStarting(_injector: Injector): void {
+ super.onStarting(_injector);
+ this._initDependencies(_injector);
+ }
+
+ private _initDependencies(injector: Injector): void {
+ const dependencies: Dependency[] = [
+
+ // services
+
+ // controllers
+ [
+ SheetDrawingUIController,
+ {
+ useFactory: () => this._injector.createInstance(SheetDrawingUIController, this._pluginConfig),
+ },
+ ],
+ [SheetDrawingUpdateController],
+ [DrawingPopupMenuController],
+ [SheetDrawingTransformAffectedController],
+
+ ];
+
+ dependencies.forEach((dependency) => injector.add(dependency));
+ }
+}
diff --git a/packages/sheets-drawing-ui/src/views/menu/image.menu.ts b/packages/sheets-drawing-ui/src/views/menu/image.menu.ts
new file mode 100644
index 0000000000..2be62e0c11
--- /dev/null
+++ b/packages/sheets-drawing-ui/src/views/menu/image.menu.ts
@@ -0,0 +1,70 @@
+/**
+ * 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 { getMenuHiddenObservable, type IMenuItem, MenuGroup, MenuItemType, MenuPosition } from '@univerjs/ui';
+import type { IAccessor } from '@wendellhu/redi';
+import { UniverInstanceType } from '@univerjs/core';
+import { COMPONENT_UPLOAD_FILE_MENU, UploadFileType } from '../upload-component/component-name';
+import { InsertCellImageOperation, InsertFloatImageOperation } from '../../commands/operations/insert-image.operation';
+
+export const IMAGE_UPLOAD_ICON = 'addition-and-subtraction-single';
+const IMAGE_MENU_ID = 'sheet.menu.image';
+
+export function ImageMenuFactory(accessor: IAccessor): IMenuItem {
+ return {
+ id: IMAGE_MENU_ID,
+ type: MenuItemType.SUBITEMS,
+ positions: [MenuPosition.TOOLBAR_START],
+ group: MenuGroup.TOOLBAR_FORMULAS_INSERT,
+ icon: IMAGE_UPLOAD_ICON,
+ tooltip: 'sheetImage.title',
+ hidden$: getMenuHiddenObservable(accessor, UniverInstanceType.UNIVER_SHEET),
+ };
+}
+
+export function UploadFloatImageMenuFactory(_accessor: IAccessor): IMenuItem {
+ return {
+ id: InsertFloatImageOperation.id,
+ title: 'sheetImage.upload.float',
+ type: MenuItemType.SELECTOR,
+ label: {
+ name: COMPONENT_UPLOAD_FILE_MENU,
+ props: {
+ type: UploadFileType.floatImage,
+ },
+ },
+ positions: [IMAGE_MENU_ID],
+ // disabled$: getCurrentSheetDisabled$(_accessor),
+ hidden$: getMenuHiddenObservable(_accessor, UniverInstanceType.UNIVER_SHEET),
+ };
+}
+
+export function UploadCellImageMenuFactory(_accessor: IAccessor): IMenuItem {
+ return {
+ id: InsertCellImageOperation.id,
+ title: 'sheetImage.upload.cell',
+ type: MenuItemType.SELECTOR,
+ label: {
+ name: COMPONENT_UPLOAD_FILE_MENU,
+ props: {
+ type: UploadFileType.cellImage,
+ },
+ },
+ positions: [IMAGE_MENU_ID],
+ // disabled$: getCurrentSheetDisabled$(_accessor),
+ hidden$: getMenuHiddenObservable(_accessor, UniverInstanceType.UNIVER_SHEET),
+ };
+}
diff --git a/packages/sheets-drawing-ui/src/views/sheet-image-panel/SheetDrawingAnchor.tsx b/packages/sheets-drawing-ui/src/views/sheet-image-panel/SheetDrawingAnchor.tsx
new file mode 100644
index 0000000000..d0e16eebea
--- /dev/null
+++ b/packages/sheets-drawing-ui/src/views/sheet-image-panel/SheetDrawingAnchor.tsx
@@ -0,0 +1,160 @@
+/**
+ * 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 { IDrawingParam, Nullable } from '@univerjs/core';
+import { ICommandService, IDrawingManagerService, LocaleService } from '@univerjs/core';
+import { useDependency } from '@wendellhu/redi/react-bindings';
+import React, { useEffect, useState } from 'react';
+import { Radio, RadioGroup } from '@univerjs/design';
+import clsx from 'clsx';
+import styles from '@univerjs/drawing-ui/views/panel/index.module.less';
+import type { ISheetDrawing } from '@univerjs/sheets';
+import { SheetDrawingAnchorType } from '@univerjs/sheets';
+import type { BaseObject } from '@univerjs/engine-render';
+import { IRenderManagerService } from '@univerjs/engine-render';
+import { SetSheetDrawingCommand } from '../../commands/commands/set-sheet-drawing.command';
+
+export interface ISheetDrawingAnchorProps {
+ drawings: IDrawingParam[];
+}
+
+export const SheetDrawingAnchor = (props: ISheetDrawingAnchorProps) => {
+ const commandService = useDependency(ICommandService);
+ const localeService = useDependency(LocaleService);
+ const drawingManagerService = useDependency(IDrawingManagerService);
+ const renderManagerService = useDependency(IRenderManagerService);
+
+ const { drawings } = props;
+
+ const drawingParam = drawings[0] as ISheetDrawing;
+
+ if (drawingParam == null) {
+ return;
+ }
+
+ const { unitId } = drawingParam;
+
+ const renderObject = renderManagerService.getRenderById(unitId);
+ const scene = renderObject?.scene;
+ if (scene == null) {
+ return;
+ }
+ const transformer = scene.getTransformerByCreate();
+
+ const [anchorShow, setAnchorShow] = useState(true);
+
+ const type = drawingParam.anchorType ?? SheetDrawingAnchorType.Position;
+ const [value, setValue] = useState(type);
+
+ function getUpdateParams(objects: Map<string, BaseObject>, drawingManagerService: IDrawingManagerService): Nullable<ISheetDrawing>[] {
+ const params: Nullable<ISheetDrawing>[] = [];
+ objects.forEach((object) => {
+ const { oKey } = object;
+
+ const searchParam = drawingManagerService.getDrawingOKey(oKey);
+
+ if (searchParam == null) {
+ params.push(null);
+ return true;
+ }
+
+ const { unitId, subUnitId, drawingId, drawingType, anchorType, sheetTransform } = searchParam as ISheetDrawing;
+
+ params.push({
+ unitId,
+ subUnitId,
+ drawingId,
+ anchorType,
+ sheetTransform,
+ drawingType,
+ });
+ });
+
+ return params;
+ }
+
+ useEffect(() => {
+ const onClearControlObserver = transformer.onClearControlObservable.add((changeSelf) => {
+ if (changeSelf === true) {
+ setAnchorShow(false);
+ }
+ });
+
+ const onChangeStartObserver = transformer.onChangeStartObservable.add((state) => {
+ const { objects } = state;
+ const params = getUpdateParams(objects, drawingManagerService);
+
+ if (params.length === 0) {
+ setAnchorShow(false);
+ } else if (params.length >= 1) {
+ setAnchorShow(true);
+ const anchorType = params[0]?.anchorType || SheetDrawingAnchorType.Position;
+ setValue(anchorType);
+ }
+ });
+
+ return () => {
+ onChangeStartObserver?.dispose();
+ onClearControlObserver?.dispose();
+ };
+ }, []);
+
+ function handleChange(value: string | number | boolean) {
+ setValue((value as SheetDrawingAnchorType));
+
+ const focusDrawings = drawingManagerService.getFocusDrawings();
+ if (focusDrawings.length === 0) {
+ return;
+ }
+
+ const updateParams = focusDrawings.map((drawing) => {
+ return {
+ unitId: drawing.unitId,
+ subUnitId: drawing.subUnitId,
+ drawingId: drawing.drawingId,
+ anchorType: value,
+ };
+ });
+
+ commandService.executeCommand(SetSheetDrawingCommand.id, {
+ unitId: focusDrawings[0].unitId,
+ drawings: updateParams,
+ });
+ }
+
+ const gridDisplay = (isShow: boolean) => {
+ return isShow ? 'block' : 'none';
+ };
+
+ return (
+ <div className={clsx(styles.imageCommonPanelGrid, styles.imageCommonPanelBorder)} style={{ display: gridDisplay(anchorShow) }}>
+ <div className={styles.imageCommonPanelRow}>
+ <div className={clsx(styles.imageCommonPanelColumn, styles.imageCommonPanelTitle)}>
+ <div>{localeService.t('drawing-anchor.title')}</div>
+ </div>
+ </div>
+ <div className={clsx(styles.imageCommonPanelRow)}>
+ <div className={clsx(styles.imageCommonPanelColumn)}>
+ <RadioGroup value={value} onChange={handleChange} direction="vertical">
+ <Radio value={SheetDrawingAnchorType.Both}>{localeService.t('drawing-anchor.both')}</Radio>
+ <Radio value={SheetDrawingAnchorType.Position}>{localeService.t('drawing-anchor.position')}</Radio>
+ <Radio value={SheetDrawingAnchorType.None}>{localeService.t('drawing-anchor.none')}</Radio>
+ </RadioGroup>
+ </div>
+ </div>
+ </div>
+ );
+};
diff --git a/packages/sheets-drawing-ui/src/views/sheet-image-panel/SheetDrawingPanel.tsx b/packages/sheets-drawing-ui/src/views/sheet-image-panel/SheetDrawingPanel.tsx
new file mode 100644
index 0000000000..eb6a0d78d5
--- /dev/null
+++ b/packages/sheets-drawing-ui/src/views/sheet-image-panel/SheetDrawingPanel.tsx
@@ -0,0 +1,52 @@
+/**
+ * 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 { IDrawingParam } from '@univerjs/core';
+import { IDrawingManagerService } from '@univerjs/core';
+import { useDependency } from '@wendellhu/redi/react-bindings';
+import React, { useEffect, useState } from 'react';
+import { DrawingCommonPanel } from '@univerjs/drawing-ui';
+import styles from '@univerjs/drawing-ui/views/panel/index.module.less';
+import { SheetDrawingAnchor } from './SheetDrawingAnchor';
+
+export const SheetDrawingPanel = () => {
+ const drawingManagerService = useDependency(IDrawingManagerService);
+ const focusDrawings = drawingManagerService.getFocusDrawings();
+
+ if (focusDrawings == null || focusDrawings.length === 0) {
+ return;
+ }
+
+ const [drawings, setDrawings] = useState<IDrawingParam[]>(focusDrawings);
+
+ useEffect(() => {
+ const focusDispose = drawingManagerService.focus$.subscribe((drawings) => {
+ setDrawings(drawings);
+ });
+
+ return () => {
+ focusDispose.unsubscribe();
+ };
+ }, []);
+
+ return (
+ <div className={styles.imageCommonPanel}>
+ <DrawingCommonPanel drawings={drawings} />
+ <SheetDrawingAnchor drawings={drawings} />
+ </div>
+ );
+};
+
diff --git a/packages/sheets-drawing-ui/src/views/sheet-image-panel/component-name.ts b/packages/sheets-drawing-ui/src/views/sheet-image-panel/component-name.ts
new file mode 100644
index 0000000000..ddb28492ec
--- /dev/null
+++ b/packages/sheets-drawing-ui/src/views/sheet-image-panel/component-name.ts
@@ -0,0 +1,17 @@
+/**
+ * Copyright 2023-present DreamNum Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+export const COMPONENT_SHEET_DRAWING_PANEL = 'COMPONENT_SHEET_DRAWING_PANEL';
diff --git a/packages/sheets-drawing-ui/src/views/sheet-image-panel/index.module.less b/packages/sheets-drawing-ui/src/views/sheet-image-panel/index.module.less
new file mode 100644
index 0000000000..703b56678d
--- /dev/null
+++ b/packages/sheets-drawing-ui/src/views/sheet-image-panel/index.module.less
@@ -0,0 +1,12 @@
+.sheet-image {
+ &-menu {
+ position: absolute;
+ height: 100%;
+ width: 100%;
+ text-align: center;
+
+ &-input {
+ display: none;
+ }
+ }
+}
diff --git a/packages/sheets-drawing-ui/src/views/upload-component/UploadFile.tsx b/packages/sheets-drawing-ui/src/views/upload-component/UploadFile.tsx
new file mode 100644
index 0000000000..9e2df793f0
--- /dev/null
+++ b/packages/sheets-drawing-ui/src/views/upload-component/UploadFile.tsx
@@ -0,0 +1,76 @@
+/**
+ * Copyright 2023-present DreamNum Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { Nullable } from '@univerjs/core';
+import { ICommandService } from '@univerjs/core';
+import { useDependency } from '@wendellhu/redi/react-bindings';
+import React, { useRef } from 'react';
+import type { ICustomComponentProps } from '@univerjs/ui';
+import { DRAWING_IMAGE_ALLOW_IMAGE_LIST } from '@univerjs/drawing';
+import { InsertCellImageOperation, InsertFloatImageOperation } from '../../commands/operations/insert-image.operation';
+import styles from './index.module.less';
+import { UploadFileType } from './component-name';
+
+export interface IUploadFileProps extends ICustomComponentProps<Nullable<File>> {
+ type: UploadFileType;
+}
+
+export const UploadFileMenu = (props: IUploadFileProps) => {
+ const { type } = props;
+
+ const commandService = useDependency(ICommandService);
+
+ const fileInputRef = useRef<HTMLInputElement>(null);
+
+ const handleButtonClick = () => {
+ fileInputRef.current?.click();
+ };
+
+ const imageAccept = DRAWING_IMAGE_ALLOW_IMAGE_LIST.map((image) => `.${image.replace('image/', '')}`).join(',');
+
+ const handleFileChange = (event: React.ChangeEvent<HTMLInputElement>) => {
+ const fileList = event.target.files;
+
+ if (fileList == null) {
+ return;
+ }
+
+ const files: File[] = Array.from(fileList);
+
+ if (type === UploadFileType.floatImage) {
+ commandService.executeCommand(InsertFloatImageOperation.id, { files });
+ } else if (type === UploadFileType.cellImage) {
+ commandService.executeCommand(InsertCellImageOperation.id, { files });
+ }
+
+ if (fileInputRef.current) {
+ fileInputRef.current.value = '';
+ }
+ };
+
+ return (
+ <div onClick={handleButtonClick} className={styles.uploadFileMenu}>
+ <input
+ type="file"
+ className={styles.uploadFileMenuInput}
+ ref={fileInputRef}
+ onChange={handleFileChange}
+ accept={imageAccept}
+ multiple
+ />
+ </div>
+ );
+};
diff --git a/packages/sheets-drawing-ui/src/views/upload-component/component-name.ts b/packages/sheets-drawing-ui/src/views/upload-component/component-name.ts
new file mode 100644
index 0000000000..5cd1cb4841
--- /dev/null
+++ b/packages/sheets-drawing-ui/src/views/upload-component/component-name.ts
@@ -0,0 +1,22 @@
+/**
+ * Copyright 2023-present DreamNum Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+export const COMPONENT_UPLOAD_FILE_MENU = 'COMPONENT_UPLOAD_FILE_MENU';
+
+export enum UploadFileType {
+ cellImage,
+ floatImage,
+}
diff --git a/packages/sheets-drawing-ui/src/views/upload-component/index.module.less b/packages/sheets-drawing-ui/src/views/upload-component/index.module.less
new file mode 100644
index 0000000000..963abf12ee
--- /dev/null
+++ b/packages/sheets-drawing-ui/src/views/upload-component/index.module.less
@@ -0,0 +1,12 @@
+.upload-file {
+ &-menu {
+ position: absolute;
+ height: 100%;
+ width: 100%;
+ text-align: center;
+
+ &-input {
+ display: none;
+ }
+ }
+}
diff --git a/packages/sheets-drawing-ui/src/vite-env.d.ts b/packages/sheets-drawing-ui/src/vite-env.d.ts
new file mode 100644
index 0000000000..11f02fe2a0
--- /dev/null
+++ b/packages/sheets-drawing-ui/src/vite-env.d.ts
@@ -0,0 +1 @@
+/// <reference types="vite/client" />
diff --git a/packages/sheets-drawing-ui/tsconfig.json b/packages/sheets-drawing-ui/tsconfig.json
new file mode 100644
index 0000000000..d676ad2a20
--- /dev/null
+++ b/packages/sheets-drawing-ui/tsconfig.json
@@ -0,0 +1,9 @@
+{
+ "extends": "@univerjs/shared/tsconfigs/base",
+ "compilerOptions": {
+ "rootDir": "src",
+ "outDir": "lib/types"
+ },
+ "references": [{ "path": "./tsconfig.node.json" }],
+ "include": ["src"]
+}
diff --git a/packages/sheets-drawing-ui/tsconfig.node.json b/packages/sheets-drawing-ui/tsconfig.node.json
new file mode 100644
index 0000000000..e53dac8868
--- /dev/null
+++ b/packages/sheets-drawing-ui/tsconfig.node.json
@@ -0,0 +1,4 @@
+{
+ "extends": "@univerjs/shared/tsconfigs/node",
+ "include": ["vite.config.ts"]
+}
diff --git a/packages/sheets-drawing-ui/vite.config.ts b/packages/sheets-drawing-ui/vite.config.ts
new file mode 100644
index 0000000000..925b530b4d
--- /dev/null
+++ b/packages/sheets-drawing-ui/vite.config.ts
@@ -0,0 +1,12 @@
+import createViteConfig from '@univerjs/shared/vite';
+import pkg from './package.json';
+
+export default ({ mode }) => createViteConfig({}, {
+ mode,
+ pkg,
+ features: {
+ react: false,
+ css: true,
+ dom: true,
+ },
+});
diff --git a/packages/sheets-filter-ui/package.json b/packages/sheets-filter-ui/package.json
index 7011d53405..1914881bc1 100644
--- a/packages/sheets-filter-ui/package.json
+++ b/packages/sheets-filter-ui/package.json
@@ -81,6 +81,7 @@
"devDependencies": {
"@univerjs/core": "workspace:*",
"@univerjs/design": "workspace:*",
+ "@univerjs/drawing": "workspace:*",
"@univerjs/engine-render": "workspace:*",
"@univerjs/shared": "workspace:*",
"@univerjs/sheets": "workspace:*",
diff --git a/packages/sheets-filter-ui/src/controllers/__tests__/sheets-filter.menu.spec.ts b/packages/sheets-filter-ui/src/controllers/__tests__/sheets-filter.menu.spec.ts
index 7c0395bb80..a43edd6f83 100644
--- a/packages/sheets-filter-ui/src/controllers/__tests__/sheets-filter.menu.spec.ts
+++ b/packages/sheets-filter-ui/src/controllers/__tests__/sheets-filter.menu.spec.ts
@@ -15,13 +15,14 @@
*/
import type { IRange, IWorkbookData } from '@univerjs/core';
-import { AuthzIoLocalService, DisposableCollection, IAuthzIoService, ICommandService, LocaleType, Plugin, RANGE_TYPE, Univer, UniverInstanceType } from '@univerjs/core';
+import { AuthzIoLocalService, DisposableCollection, IAuthzIoService, ICommandService, IDrawingManagerService, LocaleType, Plugin, RANGE_TYPE, Univer, UniverInstanceType } from '@univerjs/core';
import { NORMAL_SELECTION_PLUGIN_NAME, RangeProtectionRuleModel, RefRangeService, SelectionManagerService, SetWorksheetActiveOperation, SheetInterceptorService, WorkbookPermissionService, WorksheetPermissionService, WorksheetProtectionPointModel, WorksheetProtectionRuleModel } from '@univerjs/sheets';
import type { ISetSheetsFilterCriteriaMutationParams, ISetSheetsFilterRangeMutationParams } from '@univerjs/sheets-filter';
import { RemoveSheetsFilterMutation, SetSheetsFilterCriteriaMutation, SetSheetsFilterRangeMutation, UniverSheetsFilterPlugin } from '@univerjs/sheets-filter';
import { DesktopMenuService, DesktopPlatformService, DesktopShortcutService, IMenuService, IPlatformService, IShortcutService } from '@univerjs/ui';
import { Injector } from '@wendellhu/redi';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+import { DrawingManagerService } from '@univerjs/drawing';
import { ClearSheetsFilterCriteriaCommand, ReCalcSheetsFilterCommand, SmartToggleSheetsFilterCommand } from '../../commands/sheets-filter.command';
import { CloseFilterPanelOperation, OpenFilterPanelOperation } from '../../commands/sheets-filter.operation';
import { ClearFilterCriteriaMenuItemFactory, ReCalcFilterMenuItemFactory, SmartToggleFilterMenuItemFactory } from '../sheets-filter.menu';
@@ -73,6 +74,7 @@ function createSheetsFilterMenuTestBed() {
injector.add([WorksheetProtectionRuleModel]);
injector.add([SheetInterceptorService]);
injector.add([RangeProtectionRuleModel]);
+ injector.add([IDrawingManagerService, { useClass: DrawingManagerService }]);
const commandService = injector.get(ICommandService);
[
diff --git a/packages/sheets-filter-ui/src/controllers/sheets-filter-render.controller.ts b/packages/sheets-filter-ui/src/controllers/sheets-filter-render.controller.ts
index 56f8f3193e..22fa495a4e 100644
--- a/packages/sheets-filter-ui/src/controllers/sheets-filter-render.controller.ts
+++ b/packages/sheets-filter-ui/src/controllers/sheets-filter-render.controller.ts
@@ -128,7 +128,7 @@ export class SheetsFilterRenderController extends RxDisposable implements IRende
}
const { scene } = renderer;
- const { rangeWithCoord, style } = this._selectionRenderService.convertSelectionToCoord({
+ const { rangeWithCoord, style } = this._selectionRenderService.attachSelectionWithCoord({
range,
primary: null,
style: null,
@@ -181,6 +181,7 @@ export class SheetsFilterRenderController extends RxDisposable implements IRende
top: iconStartY,
height: FILTER_ICON_SIZE,
width: FILTER_ICON_SIZE,
+ zIndex: SHEETS_FILTER_BUTTON_Z_INDEX,
cellHeight,
cellWidth,
filterParams: { unitId, subUnitId: worksheetId, col, hasCriteria },
@@ -190,7 +191,7 @@ export class SheetsFilterRenderController extends RxDisposable implements IRende
this._filterButtonShapes.push(buttonShape);
}
- scene.addObjects(this._filterButtonShapes, SHEETS_FILTER_BUTTON_Z_INDEX);
+ scene.addObjects(this._filterButtonShapes);
scene.makeDirty();
}
diff --git a/packages/sheets-find-replace/src/controllers/sheet-find-replace.controller.ts b/packages/sheets-find-replace/src/controllers/sheet-find-replace.controller.ts
index e43fe1c4dd..87001fa663 100644
--- a/packages/sheets-find-replace/src/controllers/sheet-find-replace.controller.ts
+++ b/packages/sheets-find-replace/src/controllers/sheet-find-replace.controller.ts
@@ -509,12 +509,13 @@ export class SheetFindModel extends FindModel {
height,
evented: false,
inHiddenRange,
+ zIndex: FIND_REPLACE_Z_INDEX,
};
return new SheetFindReplaceHighlightShape(`find-highlight-${index}`, props);
});
- scene.addObjects(highlightShapes, FIND_REPLACE_Z_INDEX);
+ scene.addObjects(highlightShapes);
this._highlightShapes = highlightShapes;
scene.makeDirty();
diff --git a/packages/sheets-formula/src/controllers/formula-editor-show.controller.ts b/packages/sheets-formula/src/controllers/formula-editor-show.controller.ts
index e1fc74f2da..36539d058c 100644
--- a/packages/sheets-formula/src/controllers/formula-editor-show.controller.ts
+++ b/packages/sheets-formula/src/controllers/formula-editor-show.controller.ts
@@ -216,7 +216,7 @@ export class FormulaEditorShowController extends Disposable implements IRenderCo
};
const { scene } = this._renderManagerService.getRenderById(unitId) || {};
- const { rangeWithCoord, primaryWithCoord } = this._selectionRenderService.convertSelectionToCoord({
+ const { rangeWithCoord, primaryWithCoord } = this._selectionRenderService.attachSelectionWithCoord({
range: arrayRange,
primary: null,
style,
diff --git a/packages/sheets-formula/src/controllers/prompt.controller.ts b/packages/sheets-formula/src/controllers/prompt.controller.ts
index 4339360575..d34d562819 100644
--- a/packages/sheets-formula/src/controllers/prompt.controller.ts
+++ b/packages/sheets-formula/src/controllers/prompt.controller.ts
@@ -1660,7 +1660,7 @@ export class PromptController extends Disposable {
this._syncToEditor(sequenceNodes, node.endIndex + 1);
- controlSelection.update(toRange, undefined, undefined, undefined, this._selectionRenderService.convertCellRangeToInfo(primary));
+ controlSelection.update(toRange, undefined, undefined, undefined, this._selectionRenderService.attachPrimaryWithCoord(primary));
}
private _refreshFormulaAndCellEditor(unitIds: string[]) {
diff --git a/packages/sheets-ui/package.json b/packages/sheets-ui/package.json
index fbca237dbb..09d9cd9b49 100644
--- a/packages/sheets-ui/package.json
+++ b/packages/sheets-ui/package.json
@@ -92,6 +92,7 @@
"@univerjs/core": "workspace:*",
"@univerjs/design": "workspace:*",
"@univerjs/docs": "workspace:*",
+ "@univerjs/drawing": "workspace:*",
"@univerjs/engine-formula": "workspace:*",
"@univerjs/engine-numfmt": "workspace:*",
"@univerjs/engine-render": "workspace:*",
diff --git a/packages/sheets-ui/src/commands/commands/auto-fill.command.ts b/packages/sheets-ui/src/commands/commands/auto-fill.command.ts
index be23a34c16..ae59087b8a 100644
--- a/packages/sheets-ui/src/commands/commands/auto-fill.command.ts
+++ b/packages/sheets-ui/src/commands/commands/auto-fill.command.ts
@@ -34,7 +34,7 @@ export const AutoFillCommand: ICommand = {
handler: async (accessor: IAccessor, params: IAutoFillCommandParams) => {
const autoFillService = accessor.get(IAutoFillService);
- return autoFillService.fillData(params.unitId, params.subUnitId); ;
+ return autoFillService.fillData(params.unitId, params.subUnitId);
},
};
diff --git a/packages/sheets-ui/src/common/keys.ts b/packages/sheets-ui/src/common/keys.ts
index e3666b48c2..f68be99234 100644
--- a/packages/sheets-ui/src/common/keys.ts
+++ b/packages/sheets-ui/src/common/keys.ts
@@ -36,12 +36,14 @@ export enum VIEWPORT_KEY {
export const SHEET_COMPONENT_MAIN_LAYER_INDEX = 0;
-export const SHEET_COMPONENT_HEADER_LAYER_INDEX = 2;
+export const SHEET_COMPONENT_SELECTION_LAYER_INDEX = 1;
-export const SHEET_COMPONENT_SELECTION_LAYER_INDEX = 3;
+export const SHEET_COMPONENT_HEADER_LAYER_INDEX = 10;
export const SHEET_ZOOM_RANGE = [10, 400];
-export const SHEET_COMPONENT_UNHIDE_LAYER_INDEX = 1001;
+export const SHEET_COMPONENT_HEADER_SELECTION_LAYER_INDEX = 11;
+
+export const SHEET_COMPONENT_UNHIDE_LAYER_INDEX = 12;
// TODO@wzhudev: there should be a global zIndex layer fo sheet selections
diff --git a/packages/sheets-ui/src/controllers/editor/__tests__/end-edit.controller.spec.ts b/packages/sheets-ui/src/controllers/editor/__tests__/end-edit.controller.spec.ts
index 49f1296bf1..2d51322a88 100644
--- a/packages/sheets-ui/src/controllers/editor/__tests__/end-edit.controller.spec.ts
+++ b/packages/sheets-ui/src/controllers/editor/__tests__/end-edit.controller.spec.ts
@@ -20,7 +20,6 @@ import { LexerTreeBuilder } from '@univerjs/engine-formula';
import { SpreadsheetSkeleton } from '@univerjs/engine-render';
import type { Injector } from '@wendellhu/redi';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
-
import { getCellDataByInput } from '../end-edit.controller';
import { createTestBed } from './create-test-bed';
diff --git a/packages/sheets-ui/src/controllers/hover-render.controller.ts b/packages/sheets-ui/src/controllers/hover-render.controller.ts
index 84bdbeac6f..bf8e1fad38 100644
--- a/packages/sheets-ui/src/controllers/hover-render.controller.ts
+++ b/packages/sheets-ui/src/controllers/hover-render.controller.ts
@@ -50,14 +50,14 @@ export class HoverRenderController extends Disposable implements IRenderControll
return;
}
- const { scene } = currentRender;
- const observer = scene.onPointerMoveObserver.add((evt) => {
+ const { mainComponent } = currentRender;
+ const observer = mainComponent?.onPointerMoveObserver.add((evt) => {
this._hoverManagerService.onMouseMove(evt.offsetX, evt.offsetY);
});
disposeSet.add({
dispose() {
- scene.onPointerMoveObserver.remove(observer);
+ observer?.dispose();
},
});
};
diff --git a/packages/sheets-ui/src/controllers/menu/__tests__/create-menu-test-bed.ts b/packages/sheets-ui/src/controllers/menu/__tests__/create-menu-test-bed.ts
index 1e5aac9fb0..eb1073e7fe 100644
--- a/packages/sheets-ui/src/controllers/menu/__tests__/create-menu-test-bed.ts
+++ b/packages/sheets-ui/src/controllers/menu/__tests__/create-menu-test-bed.ts
@@ -15,7 +15,7 @@
*/
import type { IWorkbookData } from '@univerjs/core';
-import { LocaleType, Plugin, Univer, UniverInstanceType } from '@univerjs/core';
+import { IDrawingManagerService, LocaleType, Plugin, Univer, UniverInstanceType } from '@univerjs/core';
import { RangeProtectionRefRangeService, RangeProtectionRenderModel, RangeProtectionRuleModel, RangeProtectionService, RefRangeService, SelectionManagerService,
SheetInterceptorService,
WorkbookPermissionService,
@@ -26,6 +26,7 @@ import { RangeProtectionRefRangeService, RangeProtectionRenderModel, RangeProtec
import { DesktopMenuService, DesktopPlatformService, DesktopShortcutService, IMenuService, IPlatformService, IShortcutService } from '@univerjs/ui';
import { Inject, Injector } from '@wendellhu/redi';
import { IRenderManagerService, RenderManagerService } from '@univerjs/engine-render';
+import { DrawingManagerService } from '@univerjs/drawing';
const TEST_WORKBOOK_DATA_DEMO: IWorkbookData = {
id: 'test',
@@ -78,6 +79,7 @@ export function createMenuTestBed() {
injector.add([WorksheetProtectionRuleModel]);
injector.add([IRenderManagerService, { useClass: RenderManagerService }]);
injector.add([RefRangeService]);
+ injector.add([IDrawingManagerService, { useClass: DrawingManagerService }]);
injector.add([RangeProtectionRefRangeService]);
injector.add([RangeProtectionRenderModel]);
diff --git a/packages/sheets-ui/src/controllers/menu/menu-util.ts b/packages/sheets-ui/src/controllers/menu/menu-util.ts
index f8d7a58584..1b4baedbc3 100644
--- a/packages/sheets-ui/src/controllers/menu/menu-util.ts
+++ b/packages/sheets-ui/src/controllers/menu/menu-util.ts
@@ -15,7 +15,7 @@
*/
import type { ICellDataForSheetInterceptor, IPermissionTypes, IRange, Nullable, Workbook, Worksheet } from '@univerjs/core';
-import { IPermissionService, IUniverInstanceService, Rectangle, Tools, UniverInstanceType, UserManagerService } from '@univerjs/core';
+import { IDrawingManagerService, IPermissionService, IUniverInstanceService, Rectangle, Tools, UniverInstanceType, UserManagerService } from '@univerjs/core';
import { UnitAction } from '@univerjs/protocol';
import type { ICellPermission } from '@univerjs/sheets';
@@ -53,11 +53,16 @@ export function getCurrentRangeDisable$(accessor: IAccessor, permissionTypes: IP
const worksheetRuleModel = accessor.get(WorksheetProtectionRuleModel);
const workbook = univerInstanceService.getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET)!;
const userManagerService = accessor.get(UserManagerService);
+ const drawingManagerService = accessor.get(IDrawingManagerService);
if (!workbook) {
return of(true);
}
- return combineLatest([userManagerService.currentUser$, workbook.activeSheet$, selectionManagerService.selectionMoveEnd$]).pipe(
- switchMap(() => {
+ return combineLatest([userManagerService.currentUser$, workbook.activeSheet$, selectionManagerService.selectionMoveEnd$, drawingManagerService.focus$]).pipe(
+ switchMap(([user, sheet, selection, drawings]) => {
+ if (drawings.length > 0) {
+ return of(true);
+ }
+
const worksheet = workbook.getActiveSheet();
const unitId = workbook.getUnitId();
const subUnitId = worksheet.getSheetId();
diff --git a/packages/sheets-ui/src/controllers/render-controllers/contextmenu.render-controller.ts b/packages/sheets-ui/src/controllers/render-controllers/contextmenu.render-controller.ts
index 2864ddb9ca..eb4f1fd0f6 100644
--- a/packages/sheets-ui/src/controllers/render-controllers/contextmenu.render-controller.ts
+++ b/packages/sheets-ui/src/controllers/render-controllers/contextmenu.render-controller.ts
@@ -59,7 +59,7 @@ export class SheetContextMenuRenderController extends Disposable implements IRen
return;
}
const rangeType = currentSelection.range.rangeType;
- const range = this._selectionRenderService.convertSelectionToCoord(currentSelection).rangeWithCoord;
+ const range = this._selectionRenderService.attachSelectionWithCoord(currentSelection).rangeWithCoord;
const isPointerInRange = () => {
if (!range) {
return false;
diff --git a/packages/sheets-ui/src/controllers/render-controllers/freeze.render-controller.ts b/packages/sheets-ui/src/controllers/render-controllers/freeze.render-controller.ts
index 50b1fced30..8adcf14d19 100644
--- a/packages/sheets-ui/src/controllers/render-controllers/freeze.render-controller.ts
+++ b/packages/sheets-ui/src/controllers/render-controllers/freeze.render-controller.ts
@@ -191,11 +191,11 @@ export class HeaderFreezeRenderController extends Disposable implements IRenderC
const config = freezeConfig ?? this._getFreeze();
if (config == null) return null;
- const skeleton = this._sheetSkeletonManagerService.getCurrent()?.skeleton!;
+ const skeleton = this._sheetSkeletonManagerService.getCurrent()?.skeleton;
const { startRow: freezeRow, startColumn: freezeColumn } = config;
const position = this._getPositionByIndex(freezeRow, freezeColumn);
- if (position == null) return null;
+ if (position == null || skeleton == null) return null;
const sheetObject = this._getSheetObject()!;
const engine = sheetObject.engine;
@@ -230,13 +230,8 @@ export class HeaderFreezeRenderController extends Disposable implements IRenderC
const FREEZE_OFFSET = FREEZE_SIZE;
this._rowFreezeHeaderRect = new Rect(FREEZE_ROW_HEADER_NAME, {
- fill: this._freezeNormalHeaderColor,
- width: rowHeaderWidthAndMarginLeft,
- height: FREEZE_SIZE,
- left: 0,
- top: startY - FREEZE_OFFSET,
- zIndex: 3,
- });
+ fill: this._freezeNormalHeaderColor, width: rowHeaderWidthAndMarginLeft,
+ height: FREEZE_SIZE, left: 0, top: startY - FREEZE_OFFSET, zIndex: 3 });
let fill = this._freezeNormalHeaderColor;
if (freezeRow === -1 || freezeRow === 0) {
@@ -261,13 +256,8 @@ export class HeaderFreezeRenderController extends Disposable implements IRenderC
const FREEZE_OFFSET = FREEZE_SIZE;
this._columnFreezeHeaderRect = new Rect(FREEZE_COLUMN_HEADER_NAME, {
- fill: this._freezeNormalHeaderColor,
- width: FREEZE_SIZE,
- height: columnHeaderHeightAndMarginTop,
- left: startX - FREEZE_OFFSET,
- top: 0,
- zIndex: 3,
- });
+ fill: this._freezeNormalHeaderColor, width: FREEZE_SIZE, height: columnHeaderHeightAndMarginTop,
+ left: startX - FREEZE_OFFSET, top: 0, zIndex: 3 });
let fill = this._freezeNormalHeaderColor;
if (freezeColumn === -1 || freezeColumn === 0) {
@@ -283,10 +273,7 @@ export class HeaderFreezeRenderController extends Disposable implements IRenderC
zIndex: 3,
});
- scene.addObjects(
- [this._columnFreezeHeaderRect, this._columnFreezeMainRect],
- SHEET_COMPONENT_HEADER_LAYER_INDEX
- );
+ scene.addObjects([this._columnFreezeHeaderRect, this._columnFreezeMainRect], SHEET_COMPONENT_HEADER_LAYER_INDEX);
}
this._eventBinding(freezeDirectionType);
@@ -737,6 +724,7 @@ export class HeaderFreezeRenderController extends Disposable implements IRenderC
);
}
+ // eslint-disable-next-line max-lines-per-function
private _updateViewport(
row: number = -1,
column: number = -1,
@@ -1113,9 +1101,11 @@ export class HeaderFreezeRenderController extends Disposable implements IRenderC
this._freezeHoverColor = style.grey500;
}
+ // eslint-disable-next-line max-lines-per-function
private _interceptorCommands() {
this.disposeWithMe(
this._sheetInterceptorService.interceptCommand({
+ // eslint-disable-next-line complexity, max-lines-per-function
getMutations: (command) => {
const empty = {
redos: [],
@@ -1354,12 +1344,12 @@ export class HeaderFreezeRenderController extends Disposable implements IRenderC
const updateCommandList = [SetFrozenMutation.id, SetZoomRatioOperation.id];
this.disposeWithMe(
+ // eslint-disable-next-line complexity
this._commandService.onCommandExecuted((command: ICommandInfo) => {
if (updateCommandList.includes(command.id)) {
const lastFreeze = this._lastFreeze;
const workbook = this._context.unit;
const worksheet = workbook.getActiveSheet();
-
const params = command.params as ISetFrozenMutationParams;
const { unitId, subUnitId } = params;
if (!(unitId === workbook.getUnitId() && subUnitId === worksheet.getSheetId())) {
@@ -1368,7 +1358,6 @@ export class HeaderFreezeRenderController extends Disposable implements IRenderC
const freeze = worksheet.getConfig().freeze;
this._lastFreeze = freeze;
-
if (freeze == null) {
return;
}
@@ -1376,51 +1365,34 @@ export class HeaderFreezeRenderController extends Disposable implements IRenderC
let resetScroll = ResetScrollType.NONE;
const { startRow = -1, startColumn = -1, ySplit = 0, xSplit = 0 } = freeze;
-
if (!lastFreeze || lastFreeze.startRow !== startRow || lastFreeze.ySplit !== ySplit) {
resetScroll |= ResetScrollType.Y;
}
-
if (!lastFreeze || lastFreeze.startColumn !== startColumn || lastFreeze.xSplit !== xSplit) {
resetScroll |= ResetScrollType.X;
}
-
if (params.resetScroll === false) {
resetScroll = ResetScrollType.NONE;
}
-
this._refreshFreeze(startRow, startColumn, ySplit, xSplit, resetScroll);
} else if (command.id === SetWorksheetRowHeightMutation.id) {
const freeze = this._getFreeze();
- if (
- command.params &&
- freeze &&
- (command.params as ISetWorksheetRowHeightMutationParams).ranges.some(
- (i) => i.startRow < freeze.startRow
- )
- ) {
+ const isRefresh = freeze && (command.params as ISetWorksheetRowHeightMutationParams).ranges.some((i) => i.startRow < freeze.startRow);
+ if (command.params && isRefresh) {
this._refreshCurrent();
}
} else if (command.id === SetWorksheetColWidthMutation.id) {
const freeze = this._getFreeze();
- if (
- command.params &&
- freeze &&
- (command.params as ISetWorksheetColWidthMutationParams).ranges.some(
- (i) => i.startColumn < freeze.startColumn
- )
- ) {
+ if (command.params && freeze && (command.params as ISetWorksheetColWidthMutationParams).ranges.some(
+ (i) => i.startColumn < freeze.startColumn
+ )) {
this._refreshCurrent();
}
} else if (command.id === SetWorksheetRowAutoHeightMutation.id) {
const params = command.params as ISetWorksheetRowAutoHeightMutationParams;
const freeze = this._getFreeze();
- if (
- freeze &&
- freeze.startRow > -1 &&
- params.rowsAutoHeightInfo.some((info) => info.row < freeze.startRow)
- ) {
+ if (freeze && freeze.startRow > -1 && params.rowsAutoHeightInfo.some((info) => info.row < freeze.startRow)) {
const subscription = this._sheetSkeletonManagerService.currentSkeleton$.subscribe(() => {
this._refreshCurrent();
setTimeout(() => {
@@ -1432,11 +1404,7 @@ export class HeaderFreezeRenderController extends Disposable implements IRenderC
const params = command.params as ISetColHiddenMutationParams;
const freeze = this._getFreeze();
const ranges = params.ranges;
- if (
- freeze &&
- freeze.startColumn > -1 &&
- ranges.some((range) => range.startColumn < freeze.startColumn)
- ) {
+ if (freeze && freeze.startColumn > -1 && ranges.some((range) => range.startColumn < freeze.startColumn)) {
this._refreshCurrent();
}
} else if (command.id === SetRowHiddenMutation.id || command.id === SetRowVisibleMutation.id) {
diff --git a/packages/sheets-ui/src/controllers/render-controllers/header-move.render-controller.ts b/packages/sheets-ui/src/controllers/render-controllers/header-move.render-controller.ts
index 8ef4539e97..d8039ce8dc 100644
--- a/packages/sheets-ui/src/controllers/render-controllers/header-move.render-controller.ts
+++ b/packages/sheets-ui/src/controllers/render-controllers/header-move.render-controller.ts
@@ -390,7 +390,7 @@ export class HeaderMoveRenderController extends Disposable implements IRenderCon
const { startX: cellStartX, startY: cellStartY, endX: cellEndX, endY: cellEndY } = startCell;
- const selectionWithCoord = this._selectionRenderService.convertRangeDataToSelection(matchSelectionData.range);
+ const selectionWithCoord = this._selectionRenderService.attachRangeWithCoord(matchSelectionData.range);
if (selectionWithCoord == null) {
return;
diff --git a/packages/sheets-ui/src/controllers/render-controllers/selection.render-controller.ts b/packages/sheets-ui/src/controllers/render-controllers/selection.render-controller.ts
index c12d931687..a8c3652fe1 100644
--- a/packages/sheets-ui/src/controllers/render-controllers/selection.render-controller.ts
+++ b/packages/sheets-ui/src/controllers/render-controllers/selection.render-controller.ts
@@ -231,7 +231,7 @@ export class SelectionRenderController extends Disposable implements IRenderCont
private _refreshSelection(params: readonly ISelectionWithStyle[]) {
const selections = params.map((selectionWithStyle) => {
- const selectionData = this._selectionRenderService.convertSelectionToCoord(selectionWithStyle);
+ const selectionData = this._selectionRenderService.attachSelectionWithCoord(selectionWithStyle);
selectionData.style = getNormalSelectionStyle(this._themeService);
return selectionData;
});
@@ -297,7 +297,7 @@ export class SelectionRenderController extends Disposable implements IRenderCont
const selectionWithStyle = this._getAllRange(skeleton);
- const selectionData = this._selectionRenderService.convertSelectionToCoord(selectionWithStyle);
+ const selectionData = this._selectionRenderService.attachSelectionWithCoord(selectionWithStyle);
this._selectionRenderService.addControlToCurrentByRangeData(selectionData);
this._selectionRenderService.refreshSelectionMoveStart();
@@ -325,7 +325,7 @@ export class SelectionRenderController extends Disposable implements IRenderCont
continue;
}
const selectionData =
- this._selectionRenderService.convertSelectionToCoord(selectionWithStyle);
+ this._selectionRenderService.attachSelectionWithCoord(selectionWithStyle);
this._selectionRenderService.addControlToCurrentByRangeData(selectionData);
}
diff --git a/packages/sheets-ui/src/controllers/shortcuts/utils.ts b/packages/sheets-ui/src/controllers/shortcuts/utils.ts
index 89aaa13450..d0a535644b 100644
--- a/packages/sheets-ui/src/controllers/shortcuts/utils.ts
+++ b/packages/sheets-ui/src/controllers/shortcuts/utils.ts
@@ -17,6 +17,7 @@
import type { IContextService } from '@univerjs/core';
import {
EDITOR_ACTIVATED,
+ FOCUSING_COMMON_DRAWINGS,
FOCUSING_EDITOR_INPUT_FORMULA,
FOCUSING_EDITOR_STANDALONE,
FOCUSING_FORMULA_EDITOR,
@@ -37,7 +38,8 @@ export function whenSheetEditorFocused(contextService: IContextService): boolean
return (
contextService.getContextValue(FOCUSING_SHEET) &&
contextService.getContextValue(FOCUSING_UNIVER_EDITOR) &&
- !contextService.getContextValue(EDITOR_ACTIVATED)
+ !contextService.getContextValue(EDITOR_ACTIVATED) &&
+ !contextService.getContextValue(FOCUSING_COMMON_DRAWINGS)
);
}
@@ -46,7 +48,8 @@ export function whenSheetEditorFocusedAndFxNotFocused(contextService: IContextSe
contextService.getContextValue(FOCUSING_SHEET) &&
contextService.getContextValue(FOCUSING_UNIVER_EDITOR) &&
!contextService.getContextValue(EDITOR_ACTIVATED) &&
- !contextService.getContextValue(FOCUSING_FORMULA_EDITOR)
+ !contextService.getContextValue(FOCUSING_FORMULA_EDITOR) &&
+ !contextService.getContextValue(FOCUSING_COMMON_DRAWINGS)
);
}
diff --git a/packages/sheets-ui/src/locale/en-US.ts b/packages/sheets-ui/src/locale/en-US.ts
index 8aa0afd221..cbda39bbc6 100644
--- a/packages/sheets-ui/src/locale/en-US.ts
+++ b/packages/sheets-ui/src/locale/en-US.ts
@@ -538,6 +538,10 @@ const locale: typeof zhCN = {
nameInvalid: 'The name is invalid',
nameSheetConflict: 'The name conflicts with the sheet name',
},
+ uploadLoading: {
+ loading: 'Loading..., remaining', // 正在上传,当前剩余
+ error: 'Error', // 加载失败
+ },
};
export default locale;
diff --git a/packages/sheets-ui/src/locale/ru-RU.ts b/packages/sheets-ui/src/locale/ru-RU.ts
index 8fec864062..d9b43edbb4 100644
--- a/packages/sheets-ui/src/locale/ru-RU.ts
+++ b/packages/sheets-ui/src/locale/ru-RU.ts
@@ -538,6 +538,10 @@ const locale: typeof zhCN = {
nameInvalid: 'Имя недействительно',
nameSheetConflict: 'Имя конфликтует с именем листа',
},
+ uploadLoading: {
+ loading: 'Загрузка...',
+ error: 'Ошибка',
+ },
};
export default locale;
diff --git a/packages/sheets-ui/src/locale/zh-CN.ts b/packages/sheets-ui/src/locale/zh-CN.ts
index 0edfa61510..b970375ba3 100644
--- a/packages/sheets-ui/src/locale/zh-CN.ts
+++ b/packages/sheets-ui/src/locale/zh-CN.ts
@@ -533,6 +533,10 @@ const locale = {
nameInvalid: '名称不包含空格或不允许的字符',
nameSheetConflict: '名称与工作表名称冲突',
},
+ uploadLoading: {
+ loading: '正在上传,当前剩余',
+ error: '加载失败',
+ },
};
export default locale;
diff --git a/packages/sheets-ui/src/services/clipboard/__tests__/clipboard-test-bed.ts b/packages/sheets-ui/src/services/clipboard/__tests__/clipboard-test-bed.ts
index cb78145edb..4001d912f8 100644
--- a/packages/sheets-ui/src/services/clipboard/__tests__/clipboard-test-bed.ts
+++ b/packages/sheets-ui/src/services/clipboard/__tests__/clipboard-test-bed.ts
@@ -550,7 +550,7 @@ export function clipboardTestBed(workbookData?: IWorkbookData, dependencies?: De
]);
injector.add([IRenderManagerService, { useClass: RenderManagerService }]);
injector.add([ISelectionRenderService, { useClass: SelectionRenderService }]);
- injector.add([INotificationService, { useClass: testNotificationService }]); ;
+ injector.add([INotificationService, { useClass: testNotificationService }]);
injector.add([IPlatformService, { useClass: testPlatformService }]);
// Because SheetClipboardController is initialized in the rendered life cycle, here we need to initialize it manually
const sheetClipboardController = injector.createInstance(SheetClipboardController);
diff --git a/packages/sheets-ui/src/services/editor-bridge.service.ts b/packages/sheets-ui/src/services/editor-bridge.service.ts
index 1c885ea76b..a4d50becbc 100644
--- a/packages/sheets-ui/src/services/editor-bridge.service.ts
+++ b/packages/sheets-ui/src/services/editor-bridge.service.ts
@@ -192,7 +192,7 @@ export class EditorBridgeService extends Disposable implements IEditorBridgeServ
const { primary, unitId, sheetId, scene, engine } = currentEditCell;
const { startRow, startColumn } = primary;
- const primaryWithCoord = this._selectionRenderService.convertCellRangeToInfo(primary);
+ const primaryWithCoord = this._selectionRenderService.attachPrimaryWithCoord(primary);
if (primaryWithCoord == null) {
return;
}
diff --git a/packages/sheets-ui/src/services/mark-selection/mark-selection.service.ts b/packages/sheets-ui/src/services/mark-selection/mark-selection.service.ts
index bbd9932f9a..6a193f6c9b 100644
--- a/packages/sheets-ui/src/services/mark-selection/mark-selection.service.ts
+++ b/packages/sheets-ui/src/services/mark-selection/mark-selection.service.ts
@@ -88,7 +88,7 @@ export class MarkSelectionService extends Disposable implements IMarkSelectionSe
const { style } = selection;
const { scene } = this._renderManagerService.getRenderById(unitId) || {};
const { rangeWithCoord, primaryWithCoord } =
- this._selectionRenderService.convertSelectionToCoord(selection);
+ this._selectionRenderService.attachSelectionWithCoord(selection);
const skeleton = this._sheetSkeletonManagerService.getCurrent()?.skeleton;
if (!scene || !skeleton) return;
const { rowHeaderWidth, columnHeaderHeight } = skeleton;
diff --git a/packages/sheets-ui/src/services/selection/selection-render.service.ts b/packages/sheets-ui/src/services/selection/selection-render.service.ts
index 75f7650878..0cf003c939 100644
--- a/packages/sheets-ui/src/services/selection/selection-render.service.ts
+++ b/packages/sheets-ui/src/services/selection/selection-render.service.ts
@@ -84,9 +84,10 @@ export interface ISelectionRenderService {
getActiveRange(): Nullable<IRange>;
getActiveSelection(): Nullable<SelectionShape>;
getSelectionDataWithStyle(): ISelectionWithCoordAndStyle[];
- convertSelectionToCoord(selectionWithStyle: ISelectionWithStyle): ISelectionWithCoordAndStyle;
- convertRangeDataToSelection(range: IRange): Nullable<IRangeWithCoord>;
- convertCellRangeToInfo(primary: Nullable<ISelectionCell>): Nullable<ISelectionCellWithCoord>;
+ attachSelectionWithCoord(selectionWithStyle: ISelectionWithStyle): ISelectionWithCoordAndStyle;
+ attachRangeWithCoord(range: IRange): Nullable<IRangeWithCoord>;
+ attachPrimaryWithCoord(primary: Nullable<ISelectionCell>): Nullable<ISelectionCellWithCoord>;
+ getSelectionCellByPosition(x: number, y: number): Nullable<ISelectionCellWithCoord>;
eventTrigger(
evt: IPointerEvent | IMouseEvent,
zIndex: number,
@@ -536,8 +537,8 @@ export class SelectionRenderService implements ISelectionRenderService {
* @param style selection style, Styles for user-customized selectors
* @param zIndex Stacking order of the selection object
* @param rangeType Determines whether the selection is made normally according to the range or by rows and columns
- * @returns
*/
+ // eslint-disable-next-line max-lines-per-function, complexity
eventTrigger(
evt: IPointerEvent | IMouseEvent,
zIndex = 0,
@@ -774,6 +775,8 @@ export class SelectionRenderService implements ISelectionRenderService {
this._addCancelObserver();
+ scene.getTransformer()?.clearSelectedObjects();
+
if (rangeType === RANGE_TYPE.ROW || rangeType === RANGE_TYPE.COLUMN) {
this._moving(newEvtOffsetX, newEvtOffsetY, selectionControl, rangeType);
}
@@ -783,6 +786,7 @@ export class SelectionRenderService implements ISelectionRenderService {
let lastX = newEvtOffsetX;
let lastY = newEvtOffsetY;
+ // eslint-disable-next-line max-lines-per-function, complexity
this._moveObserver = scene.onPointerMoveObserver.add((moveEvt: IPointerEvent | IMouseEvent) => {
const { offsetX: moveOffsetX, offsetY: moveOffsetY } = moveEvt;
@@ -926,9 +930,9 @@ export class SelectionRenderService implements ISelectionRenderService {
this._shortcutService.setDisable(true);
}
- convertSelectionToCoord(selectionWithStyle: ISelectionWithStyle): ISelectionWithCoordAndStyle {
+ attachSelectionWithCoord(selectionWithStyle: ISelectionWithStyle): ISelectionWithCoordAndStyle {
const { range, primary, style } = selectionWithStyle;
- let rangeWithCoord = this.convertRangeDataToSelection(range);
+ let rangeWithCoord = this.attachRangeWithCoord(range);
if (rangeWithCoord == null) {
rangeWithCoord = {
startRow: -1,
@@ -944,12 +948,12 @@ export class SelectionRenderService implements ISelectionRenderService {
}
return {
rangeWithCoord,
- primaryWithCoord: this.convertCellRangeToInfo(primary),
+ primaryWithCoord: this.attachPrimaryWithCoord(primary),
style,
};
}
- convertRangeDataToSelection(range: IRange): Nullable<IRangeWithCoord> {
+ attachRangeWithCoord(range: IRange): Nullable<IRangeWithCoord> {
const { startRow, startColumn, endRow, endColumn, rangeType } = range;
const scene = this._scene;
const skeleton = this._skeleton;
@@ -973,7 +977,7 @@ export class SelectionRenderService implements ISelectionRenderService {
};
}
- convertCellRangeToInfo(primary: Nullable<ISelectionCell>): Nullable<ISelectionCellWithCoord> {
+ attachPrimaryWithCoord(primary: Nullable<ISelectionCell>): Nullable<ISelectionCellWithCoord> {
if (primary == null) {
return;
}
@@ -1013,9 +1017,36 @@ export class SelectionRenderService implements ISelectionRenderService {
};
}
+ getSelectionCellByPosition(x: number, y: number) {
+ const scene = this._scene;
+
+ if (scene == null) {
+ return;
+ }
+
+ const skeleton = this._sheetSkeletonManagerService.getCurrent()?.skeleton;
+ if (skeleton == null) {
+ return;
+ }
+
+ // const scrollXY = scene.getScrollXYByRelativeCoords(Vector2.FromArray([this._startOffsetX, this._startOffsetY]));
+ const scrollXY = scene.getScrollXY(scene.getViewport(VIEWPORT_KEY.VIEW_MAIN)!);
+ const { scaleX, scaleY } = scene.getAncestorScale();
+
+ return skeleton.calculateCellIndexByPosition(
+ x,
+ y,
+ scaleX,
+ scaleY,
+ scrollXY
+ );
+ }
+
/**
* When mousedown and mouseup need to go to the coordination and undo stack, when mousemove does not need to go to the coordination and undo stack
*/
+
+ // eslint-disable-next-line max-lines-per-function
private _moving(
moveOffsetX: number,
moveOffsetY: number,
@@ -1240,5 +1271,5 @@ export class SelectionRenderService implements ISelectionRenderService {
* @deprecated Should be refactored to RenderUnit.
*/
export const ISelectionRenderService = createIdentifier<SelectionRenderService>(
- 'deprecated.univer.sheet.selection-render-service'
+ 'univer.sheet.selection-render-service'
);
diff --git a/packages/sheets-ui/src/services/selection/selection-shape.ts b/packages/sheets-ui/src/services/selection/selection-shape.ts
index cf096e16e8..efc5f78175 100644
--- a/packages/sheets-ui/src/services/selection/selection-shape.ts
+++ b/packages/sheets-ui/src/services/selection/selection-shape.ts
@@ -17,7 +17,7 @@
import type { IRangeWithCoord, ISelectionCellWithCoord, Nullable, ThemeService } from '@univerjs/core';
import { ColorKit, Disposable, RANGE_TYPE, toDisposable } from '@univerjs/core';
import type { Scene } from '@univerjs/engine-render';
-import { cancelRequestFrame, DEFAULT_SELECTION_LAYER_INDEX, FIX_ONE_PIXEL_BLUR_OFFSET, Group, Rect, requestNewFrame, TRANSFORM_CHANGE_OBSERVABLE_TYPE } from '@univerjs/engine-render';
+import { cancelRequestFrame, FIX_ONE_PIXEL_BLUR_OFFSET, Group, Rect, requestNewFrame, TRANSFORM_CHANGE_OBSERVABLE_TYPE } from '@univerjs/engine-render';
import type { ISelectionStyle, ISelectionWidgetConfig, ISelectionWithCoordAndStyle } from '@univerjs/sheets';
import {
getNormalSelectionStyle,
@@ -26,7 +26,7 @@ import {
} from '@univerjs/sheets';
import { BehaviorSubject, Subject } from 'rxjs';
-import { SHEET_COMPONENT_SELECTION_LAYER_INDEX } from '../../common/keys';
+import { SHEET_COMPONENT_HEADER_SELECTION_LAYER_INDEX, SHEET_COMPONENT_SELECTION_LAYER_INDEX } from '../../common/keys';
import { SelectionRenderModel } from './selection-render-model';
enum SELECTION_MANAGER_KEY {
@@ -385,6 +385,7 @@ export class SelectionShape extends Disposable {
*
* inner update
*/
+ // eslint-disable-next-line max-lines-per-function
private _updateControl(style: Nullable<ISelectionStyle>, rowHeaderWidth: number, columnHeaderHeight: number) {
const { startX, startY, endX, endY } = this._selectionModel;
const defaultStyle = this._defaultStyle;
@@ -590,27 +591,15 @@ export class SelectionShape extends Disposable {
stroke: '#fff',
});
- const shapes = [
- this._fillControl,
- this._leftControl,
- this._rightControl,
- this._topControl,
- this._bottomControl,
- this._backgroundControlTop,
- this._backgroundControlMiddleLeft,
- this._backgroundControlMiddleRight,
- this._backgroundControlBottom,
- this._dashRect,
+ const shapes = [this._fillControl, this._leftControl, this._rightControl, this._topControl,
+ this._bottomControl, this._backgroundControlTop, this._backgroundControlMiddleLeft,
+ this._backgroundControlMiddleRight, this._backgroundControlBottom, this._dashRect,
];
this._widgetRects = this._initialWidget();
-
this._selectionShape = new Group(SELECTION_MANAGER_KEY.Selection + zIndex, ...shapes, ...this._widgetRects);
-
this._selectionShape.hide();
-
this._selectionShape.evented = false;
-
this._selectionShape.zIndex = zIndex;
const scene = this.getScene();
@@ -679,7 +668,7 @@ export class SelectionShape extends Disposable {
this._columnHeaderGroup.zIndex = zIndex;
const scene = this.getScene();
- scene.addObjects([this._rowHeaderGroup, this._columnHeaderGroup], DEFAULT_SELECTION_LAYER_INDEX);
+ scene.addObjects([this._rowHeaderGroup, this._columnHeaderGroup], SHEET_COMPONENT_HEADER_SELECTION_LAYER_INDEX);
}
private _initialWidget() {
@@ -728,13 +717,8 @@ export class SelectionShape extends Disposable {
];
}
- private _updateBackgroundTitle(
- style: Nullable<ISelectionStyle>,
- rowHeaderWidth: number,
- columnHeaderHeight: number
- ) {
+ private _updateBackgroundTitle(style: Nullable<ISelectionStyle>, rowHeaderWidth: number, columnHeaderHeight: number) {
const { startX, startY, endX, endY, rangeType } = this._selectionModel;
-
const defaultStyle = this._defaultStyle;
if (style == null) {
@@ -744,14 +728,8 @@ export class SelectionShape extends Disposable {
const scale = this._getScale();
const {
- stroke,
- hasRowHeader,
- rowHeaderFill = defaultStyle.rowHeaderFill!,
- rowHeaderStroke = defaultStyle.rowHeaderStroke!,
-
- hasColumnHeader,
- columnHeaderFill = defaultStyle.columnHeaderFill!,
- columnHeaderStroke = defaultStyle.columnHeaderStroke!,
+ stroke, hasRowHeader, rowHeaderFill = defaultStyle.rowHeaderFill!, rowHeaderStroke = defaultStyle.rowHeaderStroke!,
+ hasColumnHeader, columnHeaderFill = defaultStyle.columnHeaderFill!, columnHeaderStroke = defaultStyle.columnHeaderStroke!,
} = style;
let {
@@ -829,13 +807,9 @@ export class SelectionShape extends Disposable {
}
const scale = this._getScale();
-
const { fill = defaultStyle.fill! } = style;
-
let { strokeWidth = defaultStyle.strokeWidth! } = style;
-
strokeWidth /= scale;
-
const highlightSelection = this._selectionModel.highlightToSelection();
if (!highlightSelection) {
@@ -848,7 +822,6 @@ export class SelectionShape extends Disposable {
}
const { startX: h_startX, startY: h_startY, endX: h_endX, endY: h_endY } = highlightSelection;
-
const strokeOffset = strokeWidth / 2;
const topConfig = {
@@ -907,152 +880,77 @@ export class SelectionShape extends Disposable {
private _updateWidgets(style: Nullable<ISelectionStyle>) {
const { startX, startY, endX, endY } = this._selectionModel;
-
const defaultStyle = this._defaultStyle;
if (style == null) {
style = defaultStyle;
}
- const {
- stroke = defaultStyle.stroke!,
- widgets = defaultStyle.widgets!,
- widgetStroke = defaultStyle.widgetStroke!,
- } = style;
-
+ const { stroke = defaultStyle.stroke!, widgets = defaultStyle.widgets!, widgetStroke = defaultStyle.widgetStroke! } = style;
const scale = this._getScale();
-
let { widgetSize = defaultStyle.widgetSize!, widgetStrokeWidth = defaultStyle.widgetStrokeWidth! } = style;
widgetSize /= scale;
-
widgetStrokeWidth /= scale;
- const position = {
- left: -widgetSize / 2 + widgetStrokeWidth / 2,
- center: (endX - startX) / 2 - widgetSize / 2 + widgetStrokeWidth / 2,
- right: endX - startX - widgetSize / 2 + widgetStrokeWidth / 2,
- top: -widgetSize / 2,
- middle: (endY - startY) / 2 - widgetSize / 2,
- bottom: endY - startY - widgetSize / 2 + widgetStrokeWidth / 2,
- };
-
+ const position = { left: -widgetSize / 2 + widgetStrokeWidth / 2, center: (endX - startX) / 2 - widgetSize / 2 + widgetStrokeWidth / 2, right: endX - startX - widgetSize / 2 + widgetStrokeWidth / 2, top: -widgetSize / 2, middle: (endY - startY) / 2 - widgetSize / 2, bottom: endY - startY - widgetSize / 2 + widgetStrokeWidth / 2 };
const size = widgetSize - widgetStrokeWidth;
this._widgetRects.forEach((widget) => {
- widget.setProps({
- fill: stroke,
- stroke: widgetStroke,
- });
+ widget.setProps({ fill: stroke, stroke: widgetStroke });
});
if (widgets.tl === true) {
- this._topLeftWidget.transformByState({
- height: size,
- width: size,
- left: position.left,
- top: position.top,
- strokeWidth: widgetStrokeWidth,
- });
-
+ this._topLeftWidget.transformByState({ height: size, width: size, left: position.left, top: position.top, strokeWidth: widgetStrokeWidth });
this._topLeftWidget.show();
} else {
this._topLeftWidget.hide();
}
if (widgets.tc === true) {
- this._topCenterWidget.transformByState({
- height: size,
- width: size,
- left: position.center,
- top: position.top,
- strokeWidth: widgetStrokeWidth,
- });
-
+ this._topCenterWidget.transformByState({ height: size, width: size, left: position.center, top: position.top, strokeWidth: widgetStrokeWidth });
this._topCenterWidget.show();
} else {
this._topCenterWidget.hide();
}
if (widgets.tr === true) {
- this._topRightWidget.transformByState({
- height: size,
- width: size,
- left: position.right,
- top: position.top,
- strokeWidth: widgetStrokeWidth,
- });
-
+ this._topRightWidget.transformByState({ height: size, width: size, left: position.right, top: position.top, strokeWidth: widgetStrokeWidth });
this._topRightWidget.show();
} else {
this._topRightWidget.hide();
}
if (widgets.ml === true) {
- this._middleLeftWidget.transformByState({
- height: size,
- width: size,
- left: position.left,
- top: position.middle,
- strokeWidth: widgetStrokeWidth,
- });
-
+ this._middleLeftWidget.transformByState({ height: size, width: size, left: position.left, top: position.middle, strokeWidth: widgetStrokeWidth });
this._middleLeftWidget.show();
} else {
this._middleLeftWidget.hide();
}
if (widgets.mr === true) {
- this._middleRightWidget.transformByState({
- height: size,
- width: size,
- left: position.right,
- top: position.middle,
- strokeWidth: widgetStrokeWidth,
- });
-
+ this._middleRightWidget.transformByState({ height: size, width: size, left: position.right, top: position.middle, strokeWidth: widgetStrokeWidth });
this._middleRightWidget.show();
} else {
this._middleRightWidget.hide();
}
if (widgets.bl === true) {
- this._bottomLeftWidget.transformByState({
- height: size,
- width: size,
- left: position.left,
- top: position.bottom,
- strokeWidth: widgetStrokeWidth,
- });
-
+ this._bottomLeftWidget.transformByState({ height: size, width: size, left: position.left, top: position.bottom, strokeWidth: widgetStrokeWidth });
this._bottomLeftWidget.show();
} else {
this._bottomLeftWidget.hide();
}
if (widgets.bc === true) {
- this._bottomCenterWidget.transformByState({
- height: size,
- width: size,
- left: position.center,
- top: position.bottom,
- strokeWidth: widgetStrokeWidth,
- });
-
+ this._bottomCenterWidget.transformByState({ height: size, width: size, left: position.center, top: position.bottom, strokeWidth: widgetStrokeWidth });
this._bottomCenterWidget.show();
} else {
this._bottomCenterWidget.hide();
}
if (widgets.br === true) {
- this._bottomRightWidget.transformByState({
- height: size,
- width: size,
- left: position.right,
- top: position.bottom,
- strokeWidth: widgetStrokeWidth,
- });
-
+ this._bottomRightWidget.transformByState({ height: size, width: size, left: position.right, top: position.bottom, strokeWidth: widgetStrokeWidth });
this._bottomRightWidget.show();
} else {
this._bottomRightWidget.hide();
diff --git a/packages/sheets-ui/src/views/sheet-canvas-view.ts b/packages/sheets-ui/src/views/sheet-canvas-view.ts
index cc5575c60a..6d7cac245a 100644
--- a/packages/sheets-ui/src/views/sheet-canvas-view.ts
+++ b/packages/sheets-ui/src/views/sheet-canvas-view.ts
@@ -63,7 +63,6 @@ export class SheetCanvasView extends RxDisposable implements IRenderController {
private _addNewRender(workbook: Workbook) {
const { scene, engine } = this._context;
- scene.openTransformer();
scene.addLayer(new Layer(scene, [], 0), new Layer(scene, [], 2));
this._addComponent(workbook);
@@ -230,7 +229,7 @@ export class SheetCanvasView extends RxDisposable implements IRenderController {
* | VIEW_ROW_BOTTOM | VIEW_MAIN_LEFT | VIEW_MAIN |
* +-----------------+--------------------+-------------------+
*/
- // eslint-disable-next-line max-lines-per-function
+
private _addViewport(worksheet: Worksheet) {
const scene = this._context.scene;
if (scene == null) {
@@ -239,7 +238,18 @@ export class SheetCanvasView extends RxDisposable implements IRenderController {
const { rowHeader, columnHeader } = worksheet.getConfig();
const { viewMain } = this._initViewports(scene, rowHeader, columnHeader);
- // mouse scroll
+ this._initMouseWheel(scene, viewMain);
+
+ // create a scroll bar
+ const scrollBar = new ScrollBar(viewMain);
+
+ scene.attachControl();
+
+ return viewMain;
+ }
+
+ // mouse scroll
+ private _initMouseWheel(scene: Scene, viewMain: Viewport) {
this.disposeWithMe(
toDisposable(
scene.onMouseWheelObserver.add((evt: IWheelEvent, state) => {
@@ -323,10 +333,5 @@ export class SheetCanvasView extends RxDisposable implements IRenderController {
})
)
);
-
- // create a scroll bar
- new ScrollBar(viewMain);
- scene.attachControl();
- return viewMain;
}
}
diff --git a/packages/sheets-ui/src/views/sheet-container/SheetContainer.tsx b/packages/sheets-ui/src/views/sheet-container/SheetContainer.tsx
index a5985f0020..bab7818058 100644
--- a/packages/sheets-ui/src/views/sheet-container/SheetContainer.tsx
+++ b/packages/sheets-ui/src/views/sheet-container/SheetContainer.tsx
@@ -26,6 +26,7 @@ import { FormulaBar } from '../formula-bar/FormulaBar';
import { OperateContainer } from '../operate-container/OperateContainer';
import { SheetBar } from '../sheet-bar/SheetBar';
import { StatusBar } from '../status-bar/StatusBar';
+import { UploadLoading } from '../upload-loading/UploadLoading';
import styles from './index.module.less';
export function RenderSheetFooter() {
@@ -61,6 +62,7 @@ export function RenderSheetContent() {
<>
<EditorContainer />
<OperateContainer />
+ <UploadLoading />
</>
);
}
diff --git a/packages/sheets-ui/src/views/upload-loading/UploadLoading.tsx b/packages/sheets-ui/src/views/upload-loading/UploadLoading.tsx
new file mode 100644
index 0000000000..c3844d51f9
--- /dev/null
+++ b/packages/sheets-ui/src/views/upload-loading/UploadLoading.tsx
@@ -0,0 +1,46 @@
+/**
+ * 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 { IImageIoService, LocaleService } from '@univerjs/core';
+import { useDependency } from '@wendellhu/redi/react-bindings';
+import React, { useEffect } from 'react';
+import styles from './index.module.less';
+
+export const UploadLoading = () => {
+ const imageIoService = useDependency(IImageIoService);
+ const localeService = useDependency(LocaleService);
+
+ const [remain, setRemain] = React.useState(0);
+
+ useEffect(() => {
+ const sub = imageIoService.change$.subscribe((count) => {
+ setRemain(count);
+ });
+
+ return () => {
+ sub.unsubscribe();
+ };
+ }, [imageIoService]);
+
+ return (
+ <div style={{ display: remain > 0 ? 'block' : 'none' }} className={styles.uploadLoading}>
+ <div className={styles.uploadLoadingBody}>
+ <div className={styles.uploadLoadingBodyAnimation}></div>
+ <div className={styles.uploadLoadingBodyText}>{`${localeService.t('uploadLoading.loading')}: ${remain}` }</div>
+ </div>
+ </div>
+ );
+};
diff --git a/packages/sheets-ui/src/views/upload-loading/index.module.less b/packages/sheets-ui/src/views/upload-loading/index.module.less
new file mode 100644
index 0000000000..e615b3663d
--- /dev/null
+++ b/packages/sheets-ui/src/views/upload-loading/index.module.less
@@ -0,0 +1,47 @@
+.upload-loading {
+ position: absolute;
+ height: 100%;
+ width: 100%;
+ text-align: center;
+ background-color: rgba(var(--color-black), 0.5);
+ z-index: 1000;
+ user-select: none;
+
+ &-body {
+ position: absolute;
+ top: 50%;
+ left: 50%;
+ transform: translate(-50%, -50%);
+ background-color: rgb(var(--color-white));
+ padding: 20px 40px;
+ display: flex;
+ align-items: center;
+ justify-items: center;
+ border-radius: var(--border-radius-lg);
+
+ &-animation {
+ width: 30px;
+ height: 30px;
+ border: 2px solid rgb(var(--color-black));
+ border-top-color: transparent;
+ border-radius: 100%;
+
+ animation: UniverCircleAnimation infinite 0.75s linear;
+ }
+
+ &-text {
+ font-size: var(--font-size-xs);
+ color: var(--color-black);
+ padding: 10px;
+ }
+ }
+}
+
+@keyframes UniverCircleAnimation {
+ 0% {
+ transform: rotate(0);
+ }
+ 100% {
+ transform: rotate(360deg);
+ }
+}
diff --git a/packages/sheets/package.json b/packages/sheets/package.json
index e2a24be7d2..9d06b5ddbe 100644
--- a/packages/sheets/package.json
+++ b/packages/sheets/package.json
@@ -76,6 +76,7 @@
},
"devDependencies": {
"@univerjs/core": "workspace:*",
+ "@univerjs/drawing": "workspace:*",
"@univerjs/engine-formula": "workspace:*",
"@univerjs/engine-numfmt": "workspace:*",
"@univerjs/engine-render": "workspace:*",
diff --git a/packages/sheets/src/commands/commands/insert-range-move-down.command.ts b/packages/sheets/src/commands/commands/insert-range-move-down.command.ts
index 773ca923f4..7498faf486 100644
--- a/packages/sheets/src/commands/commands/insert-range-move-down.command.ts
+++ b/packages/sheets/src/commands/commands/insert-range-move-down.command.ts
@@ -54,6 +54,7 @@ export const InsertRangeMoveDownCommand: ICommand = {
type: CommandType.COMMAND,
id: 'sheet.command.insert-range-move-down',
+ // eslint-disable-next-line max-lines-per-function
handler: async (accessor: IAccessor, params?: InsertRangeMoveDownCommandParams) => {
const commandService = accessor.get(ICommandService);
const undoRedoService = accessor.get(IUndoRedoService);
diff --git a/packages/sheets/src/commands/commands/insert-range-move-right.command.ts b/packages/sheets/src/commands/commands/insert-range-move-right.command.ts
index ecebad9240..3060380f57 100644
--- a/packages/sheets/src/commands/commands/insert-range-move-right.command.ts
+++ b/packages/sheets/src/commands/commands/insert-range-move-right.command.ts
@@ -53,6 +53,7 @@ export const InsertRangeMoveRightCommand: ICommand = {
type: CommandType.COMMAND,
id: InsertRangeMoveRightCommandId,
+ // eslint-disable-next-line max-lines-per-function
handler: async (accessor: IAccessor, params?: InsertRangeMoveRightCommandParams) => {
const commandService = accessor.get(ICommandService);
const undoRedoService = accessor.get(IUndoRedoService);
diff --git a/packages/sheets/src/commands/commands/set-col-visible.command.ts b/packages/sheets/src/commands/commands/set-col-visible.command.ts
index 5955e991c1..1ee13072b8 100644
--- a/packages/sheets/src/commands/commands/set-col-visible.command.ts
+++ b/packages/sheets/src/commands/commands/set-col-visible.command.ts
@@ -36,6 +36,7 @@ import {
} from '../mutations/set-col-visible.mutation';
import type { ISetSelectionsOperationParams } from '../operations/selection.operation';
import { SetSelectionsOperation } from '../operations/selection.operation';
+import { SheetInterceptorService } from '../../services/sheet-interceptor/sheet-interceptor.service';
import { getPrimaryForRange } from './utils/selection-utils';
export interface ISetSpecificColsVisibleCommandParams {
@@ -48,6 +49,7 @@ export const SetSpecificColsVisibleCommand: ICommand<ISetSpecificColsVisibleComm
type: CommandType.COMMAND,
id: 'sheet.command.set-col-visible-on-cols',
handler: async (accessor, params: ISetSpecificColsVisibleCommandParams) => {
+ const sheetInterceptorService = accessor.get(SheetInterceptorService);
const { unitId, subUnitId, ranges } = params;
const worksheet = accessor
@@ -79,25 +81,33 @@ export const SetSpecificColsVisibleCommand: ICommand<ISetSpecificColsVisibleComm
};
const commandService = accessor.get(ICommandService);
- const result = sequenceExecute(
- [
- { id: SetColVisibleMutation.id, params: redoMutationParams },
- { id: SetSelectionsOperation.id, params: setSelectionOperationParams },
- ],
- commandService
- );
- if (result.result) {
+ const result = sequenceExecute([
+ { id: SetColVisibleMutation.id, params: redoMutationParams },
+ { id: SetSelectionsOperation.id, params: setSelectionOperationParams },
+ ], commandService);
+
+ const intercepted = sheetInterceptorService.onCommandExecute({
+ id: SetSpecificColsVisibleCommand.id,
+ params,
+ });
+
+ const interceptedResult = sequenceExecute([...intercepted.redos], commandService);
+
+ if (result.result && interceptedResult.result) {
const undoRedoService = accessor.get(IUndoRedoService);
undoRedoService.pushUndoRedo({
unitID: unitId,
undoMutations: [
{ id: SetColHiddenMutation.id, params: undoMutationParams },
{ id: SetSelectionsOperation.id, params: undoSetSelectionsOperationParams },
+ ...(intercepted.undos ?? []),
],
redoMutations: [
+ ...(intercepted.preRedos ?? []),
{ id: SetColVisibleMutation.id, params: redoMutationParams },
{ id: SetSelectionsOperation.id, params: setSelectionOperationParams },
+ ...intercepted.redos,
],
});
@@ -146,10 +156,9 @@ export const SetColHiddenCommand: ICommand = {
id: 'sheet.command.set-col-hidden',
handler: async (accessor: IAccessor) => {
const selectionManagerService = accessor.get(SelectionManagerService);
- const ranges = selectionManagerService
- .getSelections()
- ?.map((s) => s.range)
- .filter((r) => r.rangeType === RANGE_TYPE.COLUMN);
+ const sheetInterceptorService = accessor.get(SheetInterceptorService);
+
+ const ranges = selectionManagerService.getSelections()?.map((s) => s.range).filter((r) => r.rangeType === RANGE_TYPE.COLUMN);
if (!ranges?.length) {
return false;
}
@@ -163,14 +172,10 @@ export const SetColHiddenCommand: ICommand = {
const unitId = workbook.getUnitId();
const subUnitId = worksheet.getSheetId();
const redoMutationParams: ISetColHiddenMutationParams = {
- unitId,
- subUnitId,
- ranges,
+ unitId, subUnitId, ranges,
};
const setSelectionOperationParams: ISetSelectionsOperationParams = {
- unitId,
- subUnitId,
- pluginName: NORMAL_SELECTION_PLUGIN_NAME,
+ unitId, subUnitId, pluginName: NORMAL_SELECTION_PLUGIN_NAME,
selections: getSelectionsAfterHiding(ranges).map((range) => ({
range,
primary: getPrimaryForRange(range, worksheet),
@@ -178,9 +183,7 @@ export const SetColHiddenCommand: ICommand = {
})),
};
const undoSetSelectionsOperationParams: ISetSelectionsOperationParams = {
- unitId,
- subUnitId,
- pluginName: NORMAL_SELECTION_PLUGIN_NAME,
+ unitId, subUnitId, pluginName: NORMAL_SELECTION_PLUGIN_NAME,
selections: ranges.map((range) => ({
range,
primary: getPrimaryForRange(range, worksheet),
@@ -189,14 +192,20 @@ export const SetColHiddenCommand: ICommand = {
};
const commandService = accessor.get(ICommandService);
- const result = sequenceExecute(
- [
- { id: SetColHiddenMutation.id, params: redoMutationParams },
- { id: SetSelectionsOperation.id, params: setSelectionOperationParams },
- ],
- commandService
- );
- if (result.result) {
+
+ const result = sequenceExecute([
+ { id: SetColHiddenMutation.id, params: redoMutationParams },
+ { id: SetSelectionsOperation.id, params: setSelectionOperationParams },
+ ], commandService);
+
+ const intercepted = sheetInterceptorService.onCommandExecute({
+ id: SetColHiddenCommand.id,
+ params: redoMutationParams,
+ });
+
+ const interceptedResult = sequenceExecute([...intercepted.redos], commandService);
+
+ if (result.result && interceptedResult.result) {
const undoRedoService = accessor.get(IUndoRedoService);
const undoMutationParams = SetColHiddenUndoMutationFactory(accessor, redoMutationParams);
undoRedoService.pushUndoRedo({
@@ -204,10 +213,13 @@ export const SetColHiddenCommand: ICommand = {
undoMutations: [
{ id: SetColVisibleMutation.id, params: undoMutationParams },
{ id: SetSelectionsOperation.id, params: undoSetSelectionsOperationParams },
+ ...(intercepted.undos ?? []),
],
redoMutations: [
+ ...(intercepted.preRedos ?? []),
{ id: SetColHiddenMutation.id, params: redoMutationParams },
{ id: SetSelectionsOperation.id, params: setSelectionOperationParams },
+ ...intercepted.redos,
],
});
return true;
@@ -219,7 +231,6 @@ export const SetColHiddenCommand: ICommand = {
/**
* Get the selections after hiding cols.
- *
* @param worksheet the worksheet the command invoked on
* @param ranges cols to be hidden
*/
diff --git a/packages/sheets/src/commands/commands/set-row-visible.command.ts b/packages/sheets/src/commands/commands/set-row-visible.command.ts
index 1ac4c603c5..3f4c0a074e 100644
--- a/packages/sheets/src/commands/commands/set-row-visible.command.ts
+++ b/packages/sheets/src/commands/commands/set-row-visible.command.ts
@@ -36,6 +36,7 @@ import {
} from '../mutations/set-row-visible.mutation';
import type { ISetSelectionsOperationParams } from '../operations/selection.operation';
import { SetSelectionsOperation } from '../operations/selection.operation';
+import { SheetInterceptorService } from '../../services/sheet-interceptor/sheet-interceptor.service';
import { getPrimaryForRange } from './utils/selection-utils';
import { getSheetCommandTarget } from './utils/target-util';
@@ -52,6 +53,7 @@ export const SetSpecificRowsVisibleCommand: ICommand<ISetSpecificRowsVisibleComm
const { unitId, subUnitId, ranges } = params;
const commandService = accessor.get(ICommandService);
const undoRedoService = accessor.get(IUndoRedoService);
+ const sheetInterceptorService = accessor.get(SheetInterceptorService);
const worksheet = accessor
.get(IUniverInstanceService)
@@ -89,20 +91,29 @@ export const SetSpecificRowsVisibleCommand: ICommand<ISetSpecificRowsVisibleComm
[
{ id: SetRowVisibleMutation.id, params: redoMutationParams },
{ id: SetSelectionsOperation.id, params: setSelectionOperationParams },
- ],
- commandService
- );
+ ], commandService);
- if (result.result) {
+ const intercepted = sheetInterceptorService.onCommandExecute({
+ id: SetSpecificRowsVisibleCommand.id,
+ params,
+ });
+
+ const interceptedResult = sequenceExecute([...intercepted.redos], commandService);
+
+ if (result.result && interceptedResult.result) {
undoRedoService.pushUndoRedo({
unitID: unitId,
undoMutations: [
+ ...(intercepted.preUndos ?? []),
{ id: SetRowHiddenMutation.id, params: undoMutationParams },
{ id: SetSelectionsOperation.id, params: undoSetSelectionsOperationParams },
+ ...(intercepted.undos ?? []),
],
redoMutations: [
+ ...(intercepted.preRedos ?? []),
{ id: SetRowVisibleMutation.id, params: redoMutationParams },
{ id: SetSelectionsOperation.id, params: setSelectionOperationParams },
+ ...intercepted.redos,
],
});
@@ -153,11 +164,10 @@ export const SetRowHiddenCommand: ICommand = {
const commandService = accessor.get(ICommandService);
const undoRedoService = accessor.get(IUndoRedoService);
const univerInstanceService = accessor.get(IUniverInstanceService);
+ const sheetInterceptorService = accessor.get(SheetInterceptorService);
+
+ const ranges = selectionManagerService.getSelections()?.map((s) => s.range).filter((r) => r.rangeType === RANGE_TYPE.ROW);
- const ranges = selectionManagerService
- .getSelections()
- ?.map((s) => s.range)
- .filter((r) => r.rangeType === RANGE_TYPE.ROW);
if (!ranges?.length) {
return false;
}
@@ -173,9 +183,7 @@ export const SetRowHiddenCommand: ICommand = {
ranges,
};
const setSelectionOperationParams: ISetSelectionsOperationParams = {
- unitId,
- subUnitId,
- pluginName: NORMAL_SELECTION_PLUGIN_NAME,
+ unitId, subUnitId, pluginName: NORMAL_SELECTION_PLUGIN_NAME,
selections: getSelectionsAfterHiding(ranges).map((range) => ({
range,
primary: getPrimaryForRange(range, worksheet),
@@ -183,9 +191,7 @@ export const SetRowHiddenCommand: ICommand = {
})),
};
const undoSetSelectionsOperationParams: ISetSelectionsOperationParams = {
- unitId,
- subUnitId,
- pluginName: NORMAL_SELECTION_PLUGIN_NAME,
+ unitId, subUnitId, pluginName: NORMAL_SELECTION_PLUGIN_NAME,
selections: ranges.map((range) => ({
range,
primary: getPrimaryForRange(range, worksheet),
@@ -194,23 +200,37 @@ export const SetRowHiddenCommand: ICommand = {
};
const undoMutationParams = SetRowHiddenUndoMutationFactory(accessor, redoMutationParams);
- const result = sequenceExecute(
- [
- { id: SetRowHiddenMutation.id, params: redoMutationParams },
- { id: SetSelectionsOperation.id, params: setSelectionOperationParams },
- ],
- commandService
- );
- if (result.result) {
+
+ const intercepted = sheetInterceptorService.onCommandExecute({
+ id: SetRowHiddenCommand.id,
+ params: redoMutationParams,
+ });
+
+ if (intercepted.preRedos && intercepted.preRedos.length > 0) {
+ sequenceExecute([...intercepted.preRedos], commandService);
+ }
+
+ const result = sequenceExecute([
+ { id: SetRowHiddenMutation.id, params: redoMutationParams },
+ { id: SetSelectionsOperation.id, params: setSelectionOperationParams },
+ ], commandService);
+
+ const interceptedResult = sequenceExecute([...intercepted.redos], commandService);
+
+ if (result.result && interceptedResult.result) {
undoRedoService.pushUndoRedo({
unitID: unitId,
undoMutations: [
+ ...(intercepted.preUndos ?? []),
{ id: SetRowVisibleMutation.id, params: undoMutationParams },
{ id: SetSelectionsOperation.id, params: undoSetSelectionsOperationParams },
+ ...(intercepted.undos ?? []),
],
redoMutations: [
+ ...(intercepted.preRedos ?? []),
{ id: SetRowHiddenMutation.id, params: redoMutationParams },
{ id: SetSelectionsOperation.id, params: setSelectionOperationParams },
+ ...intercepted.redos,
],
});
return true;
diff --git a/packages/sheets/src/commands/commands/set-worksheet-col-width.command.ts b/packages/sheets/src/commands/commands/set-worksheet-col-width.command.ts
index f8191477a0..1f1e512893 100644
--- a/packages/sheets/src/commands/commands/set-worksheet-col-width.command.ts
+++ b/packages/sheets/src/commands/commands/set-worksheet-col-width.command.ts
@@ -43,9 +43,11 @@ export interface IDeltaColumnWidthCommandParams {
export const DeltaColumnWidthCommand: ICommand<IDeltaColumnWidthCommandParams> = {
type: CommandType.COMMAND,
id: 'sheet.command.delta-column-width',
+ // eslint-disable-next-line max-lines-per-function
handler: async (accessor: IAccessor, params: IDeltaColumnWidthCommandParams) => {
const selectionManagerService = accessor.get(SelectionManagerService);
const selections = selectionManagerService.getSelections();
+ const sheetInterceptorService = accessor.get(SheetInterceptorService);
if (!selections?.length) {
return false;
@@ -113,6 +115,11 @@ export const DeltaColumnWidthCommand: ICommand<IDeltaColumnWidthCommandParams> =
};
}
+ const { undos, redos } = accessor.get(SheetInterceptorService).onCommandExecute({
+ id: DeltaColumnWidthCommand.id,
+ params: redoMutationParams,
+ });
+
const undoMutationParams: ISetWorksheetColWidthMutationParams = SetWorksheetColWidthMutationFactory(
accessor,
redoMutationParams
@@ -123,11 +130,6 @@ export const DeltaColumnWidthCommand: ICommand<IDeltaColumnWidthCommandParams> =
redoMutationParams
);
- const { undos, redos } = accessor.get(SheetInterceptorService).onCommandExecute({
- id: DeltaColumnWidthCommand.id,
- params: redoMutationParams,
- });
-
const result = sequenceExecute([...redos], commandService);
if (setColWidthResult && result.result) {
@@ -155,6 +157,7 @@ export const SetColWidthCommand: ICommand = {
const selectionManagerService = accessor.get(SelectionManagerService);
const commandService = accessor.get(ICommandService);
const undoRedoService = accessor.get(IUndoRedoService);
+ const sheetInterceptorService = accessor.get(SheetInterceptorService);
const selections = selectionManagerService.getSelectionRanges();
if (!selections?.length) return false;
@@ -183,13 +186,18 @@ export const SetColWidthCommand: ICommand = {
params: redoMutationParams,
});
- const result = sequenceExecute([...redos], commandService);
+ const intercepted = sheetInterceptorService.onCommandExecute({
+ id: SetColWidthCommand.id,
+ params: redoMutationParams,
+ });
+
+ const result = sequenceExecute([...redos, ...intercepted.redos], commandService);
if (setColWidthResult && result.result) {
undoRedoService.pushUndoRedo({
unitID: unitId,
- undoMutations: [{ id: SetWorksheetColWidthMutation.id, params: undoMutationParams }, ...undos],
- redoMutations: [{ id: SetWorksheetColWidthMutation.id, params: redoMutationParams }, ...redos],
+ undoMutations: [...(intercepted.preUndos ?? []), { id: SetWorksheetColWidthMutation.id, params: undoMutationParams }, ...undos],
+ redoMutations: [...(intercepted.preRedos ?? []), { id: SetWorksheetColWidthMutation.id, params: redoMutationParams }, ...redos],
});
return true;
diff --git a/packages/sheets/src/commands/commands/set-worksheet-row-height.command.ts b/packages/sheets/src/commands/commands/set-worksheet-row-height.command.ts
index a149089a96..accd9ddfaf 100644
--- a/packages/sheets/src/commands/commands/set-worksheet-row-height.command.ts
+++ b/packages/sheets/src/commands/commands/set-worksheet-row-height.command.ts
@@ -49,9 +49,12 @@ export interface IDeltaRowHeightCommand {
export const DeltaRowHeightCommand: ICommand = {
type: CommandType.COMMAND,
id: 'sheet.command.delta-row-height',
+ // eslint-disable-next-line max-lines-per-function
handler: async (accessor: IAccessor, params: IDeltaRowHeightCommand) => {
const selectionManagerService = accessor.get(SelectionManagerService);
const selections = selectionManagerService.getSelections();
+ const sheetInterceptorService = accessor.get(SheetInterceptorService);
+
if (!selections?.length) {
return false;
}
@@ -133,24 +136,29 @@ export const DeltaRowHeightCommand: ICommand = {
const commandService = accessor.get(ICommandService);
const undoRedoService = accessor.get(IUndoRedoService);
- const result = sequenceExecute(
- [
- {
- id: SetWorksheetRowHeightMutation.id,
- params: redoMutationParams,
- },
- {
- id: SetWorksheetRowIsAutoHeightMutation.id,
- params: redoSetIsAutoHeightParams,
- },
- ],
- commandService
- );
+ const intercepted = sheetInterceptorService.onCommandExecute({
+ id: DeltaRowHeightCommand.id,
+ params: redoMutationParams,
+ });
+
+ const result = sequenceExecute([
+ {
+ id: SetWorksheetRowHeightMutation.id,
+ params: redoMutationParams,
+ },
+ {
+ id: SetWorksheetRowIsAutoHeightMutation.id,
+ params: redoSetIsAutoHeightParams,
+ },
+ ], commandService);
- if (result.result) {
+ const interceptedResult = sequenceExecute([...intercepted.redos], commandService);
+
+ if (result.result && interceptedResult.result) {
undoRedoService.pushUndoRedo({
unitID: unitId,
undoMutations: [
+ ...(intercepted.preUndos ?? []),
{
id: SetWorksheetRowHeightMutation.id,
params: undoMutationParams,
@@ -159,8 +167,10 @@ export const DeltaRowHeightCommand: ICommand = {
id: SetWorksheetRowIsAutoHeightMutation.id,
params: undoSetIsAutoHeightParams,
},
+ ...intercepted.undos,
],
redoMutations: [
+ ...(intercepted.preRedos ?? []),
{
id: SetWorksheetRowHeightMutation.id,
params: redoMutationParams,
@@ -169,6 +179,7 @@ export const DeltaRowHeightCommand: ICommand = {
id: SetWorksheetRowIsAutoHeightMutation.id,
params: redoSetIsAutoHeightParams,
},
+ ...intercepted.redos,
],
});
return true;
@@ -184,11 +195,13 @@ export interface ISetRowHeightCommandParams {
export const SetRowHeightCommand: ICommand = {
type: CommandType.COMMAND,
id: 'sheet.command.set-row-height',
+ // eslint-disable-next-line max-lines-per-function
handler: (accessor: IAccessor, params: ISetRowHeightCommandParams) => {
const selectionManagerService = accessor.get(SelectionManagerService);
const commandService = accessor.get(ICommandService);
const undoRedoService = accessor.get(IUndoRedoService);
const univerInstanceService = accessor.get(IUniverInstanceService);
+ const sheetInterceptorService = accessor.get(SheetInterceptorService);
const selections = selectionManagerService.getSelectionRanges();
if (!selections?.length) {
@@ -222,24 +235,29 @@ export const SetRowHeightCommand: ICommand = {
const undoSetIsAutoHeightParams: ISetWorksheetRowIsAutoHeightMutationParams =
SetWorksheetRowIsAutoHeightMutationFactory(accessor, redoSetIsAutoHeightParams);
- const result = sequenceExecute(
- [
- {
- id: SetWorksheetRowHeightMutation.id,
- params: redoMutationParams,
- },
- {
- id: SetWorksheetRowIsAutoHeightMutation.id,
- params: redoSetIsAutoHeightParams,
- },
- ],
- commandService
- );
+ const result = sequenceExecute([
+ {
+ id: SetWorksheetRowHeightMutation.id,
+ params: redoMutationParams,
+ },
+ {
+ id: SetWorksheetRowIsAutoHeightMutation.id,
+ params: redoSetIsAutoHeightParams,
+ },
+ ], commandService);
+
+ const intercepted = sheetInterceptorService.onCommandExecute({
+ id: SetRowHeightCommand.id,
+ params: redoMutationParams,
+ });
+
+ const sheetInterceptorResult = sequenceExecute([...intercepted.redos], commandService);
- if (result.result) {
+ if (result.result && sheetInterceptorResult.result) {
undoRedoService.pushUndoRedo({
unitID: unitId,
undoMutations: [
+ ...intercepted.preRedos ?? [],
{
id: SetWorksheetRowHeightMutation.id,
params: undoMutationParams,
@@ -248,8 +266,10 @@ export const SetRowHeightCommand: ICommand = {
id: SetWorksheetRowIsAutoHeightMutation.id,
params: undoSetIsAutoHeightParams,
},
+ ...intercepted.undos,
],
redoMutations: [
+ ...intercepted.preRedos ?? [],
{
id: SetWorksheetRowHeightMutation.id,
params: redoMutationParams,
@@ -258,6 +278,7 @@ export const SetRowHeightCommand: ICommand = {
id: SetWorksheetRowIsAutoHeightMutation.id,
params: redoSetIsAutoHeightParams,
},
+ ...intercepted.redos,
],
});
return true;
diff --git a/packages/sheets/src/commands/mutations/set-drawing-apply.mutation.ts b/packages/sheets/src/commands/mutations/set-drawing-apply.mutation.ts
new file mode 100644
index 0000000000..41fa690703
--- /dev/null
+++ b/packages/sheets/src/commands/mutations/set-drawing-apply.mutation.ts
@@ -0,0 +1,74 @@
+/**
+ * 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 { IDrawingGroupUpdateParam, IDrawingOrderMapParam, IDrawingSearch, IMutation } from '@univerjs/core';
+import { CommandType, IDrawingManagerService } from '@univerjs/core';
+import type { IDrawingJson1Type } from '@univerjs/drawing';
+import { ISheetDrawingService } from '../../services/sheet-drawing.service';
+
+export enum DrawingApplyType {
+ INSERT,
+ REMOVE,
+ UPDATE,
+ ARRANGE,
+ GROUP,
+ UNGROUP,
+}
+
+export interface ISetDrawingApplyMutationParams extends IDrawingJson1Type {
+ type: DrawingApplyType;
+}
+
+export const SetDrawingApplyMutation: IMutation<ISetDrawingApplyMutationParams> = {
+ id: 'sheet.mutation.set-drawing-json-apply',
+ type: CommandType.MUTATION,
+ handler: (accessor, params) => {
+ const drawingManagerService = accessor.get(IDrawingManagerService);
+ const sheetDrawingService = accessor.get(ISheetDrawingService);
+
+ const { op, unitId, subUnitId, type, objects } = params;
+
+ drawingManagerService.applyJson1(unitId, subUnitId, op);
+ sheetDrawingService.applyJson1(unitId, subUnitId, op);
+
+ switch (type) {
+ case DrawingApplyType.INSERT:
+ drawingManagerService.addNotification(objects as IDrawingSearch[]);
+ sheetDrawingService.addNotification(objects as IDrawingSearch[]);
+ break;
+ case DrawingApplyType.REMOVE:
+ drawingManagerService.removeNotification(objects as IDrawingSearch[]);
+ sheetDrawingService.removeNotification(objects as IDrawingSearch[]);
+ break;
+ case DrawingApplyType.UPDATE:
+ drawingManagerService.updateNotification(objects as IDrawingSearch[]);
+ sheetDrawingService.updateNotification(objects as IDrawingSearch[]);
+ break;
+ case DrawingApplyType.ARRANGE:
+ drawingManagerService.orderNotification(objects as IDrawingOrderMapParam);
+ sheetDrawingService.orderNotification(objects as IDrawingOrderMapParam);
+ break;
+ case DrawingApplyType.GROUP:
+ drawingManagerService.groupUpdateNotification(objects as IDrawingGroupUpdateParam[]);
+ break;
+ case DrawingApplyType.UNGROUP:
+ drawingManagerService.ungroupUpdateNotification(objects as IDrawingGroupUpdateParam[]);
+ break;
+ }
+
+ return true;
+ },
+};
diff --git a/packages/sheets/src/controllers/basic-worksheet.controller.ts b/packages/sheets/src/controllers/basic-worksheet.controller.ts
index d2d51fafa9..faa1b23000 100644
--- a/packages/sheets/src/controllers/basic-worksheet.controller.ts
+++ b/packages/sheets/src/controllers/basic-worksheet.controller.ts
@@ -83,7 +83,6 @@ import {
SetWorksheetRowIsAutoHeightCommand,
} from '../commands/commands/set-worksheet-row-height.command';
import { SetWorksheetShowCommand } from '../commands/commands/set-worksheet-show.command';
-import { AddWorksheetMergeMutation } from '../commands/mutations/add-worksheet-merge.mutation';
import { InsertColMutation, InsertRowMutation } from '../commands/mutations/insert-row-col.mutation';
import { InsertSheetMutation } from '../commands/mutations/insert-sheet.mutation';
import { MoveRangeMutation } from '../commands/mutations/move-range.mutation';
@@ -128,7 +127,10 @@ import { SetRangeProtectionCommand } from '../commands/commands/set-range-protec
import { AddRangeProtectionMutation } from '../commands/mutations/add-range-protection.mutation';
import { DeleteRangeProtectionMutation } from '../commands/mutations/delete-range-protection.mutation';
import { SetRangeProtectionMutation } from '../commands/mutations/set-range-protection.mutation';
+import { SetDrawingApplyMutation } from '../commands/mutations/set-drawing-apply.mutation';
+import { AddWorksheetMergeMutation } from '../commands/mutations/add-worksheet-merge.mutation';
import { MAX_CELL_PER_SHEET_DEFAULT, MAX_CELL_PER_SHEET_KEY } from './config/config';
+import { ONLY_REGISTER_FORMULA_RELATED_MUTATIONS_KEY } from './config';
export interface IStyleTypeValue<T> {
type: keyof IStyleData;
@@ -231,15 +233,14 @@ export class BasicWorksheetController extends Disposable implements IDisposable
SetWorksheetRowHeightMutation,
SetWorksheetRowIsAutoHeightCommand,
SetWorksheetRowIsAutoHeightMutation,
- SetWorksheetShowCommand,
SetNumfmtMutation,
SetSelectionsOperation,
RemoveNumfmtMutation,
EmptyMutation,
+ ScrollToCellOperation,
InsertDefinedNameCommand,
RemoveDefinedNameCommand,
SetDefinedNameCommand,
- ScrollToCellOperation,
SetWorksheetPermissionPointsCommand,
AddWorksheetProtectionMutation,
@@ -256,6 +257,15 @@ export class BasicWorksheetController extends Disposable implements IDisposable
SetRangeProtectionMutation,
].forEach((command) => this.disposeWithMe(this._commandService.registerCommand(command)));
+ const onlyRegisterFormulaRelatedMutations = this._configService.getConfig(ONLY_REGISTER_FORMULA_RELATED_MUTATIONS_KEY) ?? false;
+ if (!onlyRegisterFormulaRelatedMutations) {
+ // TODO: more commands should be moved into this array
+ [
+ SetWorksheetShowCommand,
+ SetDrawingApplyMutation,
+ ].forEach((command) => this.disposeWithMe(this._commandService.registerCommand(command)));
+ }
+
this._configService.setConfig(MAX_CELL_PER_SHEET_KEY, MAX_CELL_PER_SHEET_DEFAULT);
}
}
diff --git a/packages/sheets/src/controllers/config.ts b/packages/sheets/src/controllers/config.ts
new file mode 100644
index 0000000000..ace0a2c22c
--- /dev/null
+++ b/packages/sheets/src/controllers/config.ts
@@ -0,0 +1,17 @@
+/**
+ * Copyright 2023-present DreamNum Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+export const ONLY_REGISTER_FORMULA_RELATED_MUTATIONS_KEY = 'ONLY_REGISTER_FORMULA_RELATED_MUTATIONS_KEY';
diff --git a/packages/sheets/src/controllers/defined-name-data.controller.ts b/packages/sheets/src/controllers/defined-name-data.controller.ts
index 20668558de..b61c9144af 100644
--- a/packages/sheets/src/controllers/defined-name-data.controller.ts
+++ b/packages/sheets/src/controllers/defined-name-data.controller.ts
@@ -46,8 +46,8 @@ export class DefinedNameDataController extends Disposable {
}
private _initSnapshot() {
- const toJson = (unitID: string) => {
- const map = this._definedNamesService.getDefinedNameMap(unitID);
+ const toJson = (unitId: string) => {
+ const map = this._definedNamesService.getDefinedNameMap(unitId);
if (map) {
return JSON.stringify(map);
}
@@ -67,13 +67,13 @@ export class DefinedNameDataController extends Disposable {
this._resourceManagerService.registerPluginResource<IDefinedNameMapItem>({
pluginName: SHEET_DEFINED_NAME_PLUGIN,
businesses: [UniverInstanceType.UNIVER_SHEET],
- toJson: (unitID) => toJson(unitID),
+ toJson: (unitId) => toJson(unitId),
parseJson: (json) => parseJson(json),
- onUnLoad: (unitID) => {
- this._definedNamesService.removeUnitDefinedName(unitID);
+ onUnLoad: (unitId) => {
+ this._definedNamesService.removeUnitDefinedName(unitId);
},
- onLoad: (unitID, value) => {
- this._definedNamesService.registerDefinedNames(unitID, value);
+ onLoad: (unitId, value) => {
+ this._definedNamesService.registerDefinedNames(unitId, value);
},
})
);
diff --git a/packages/sheets/src/controllers/sheet-drawing-data.controller.ts b/packages/sheets/src/controllers/sheet-drawing-data.controller.ts
new file mode 100644
index 0000000000..0454409397
--- /dev/null
+++ b/packages/sheets/src/controllers/sheet-drawing-data.controller.ts
@@ -0,0 +1,73 @@
+/**
+ * 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 { IDrawingSubunitMap } from '@univerjs/core';
+import { Disposable, IDrawingManagerService, IResourceManagerService, LifecycleStages, OnLifecycle, UniverInstanceType } from '@univerjs/core';
+import { type ISheetDrawing, ISheetDrawingService } from '../services/sheet-drawing.service';
+
+export const SHEET_DRAWING_PLUGIN = 'SHEET_DRAWING_PLUGIN';
+@OnLifecycle(LifecycleStages.Ready, SheetDrawingDataController)
+export class SheetDrawingDataController extends Disposable {
+ constructor(
+ @ISheetDrawingService private readonly _sheetDrawingService: ISheetDrawingService,
+ @IDrawingManagerService private readonly _drawingManagerService: IDrawingManagerService,
+ @IResourceManagerService private _resourceManagerService: IResourceManagerService
+ ) {
+ super();
+
+ this._init();
+ }
+
+ private _init(): void {
+ this._initSnapshot();
+ }
+
+ private _initSnapshot() {
+ const toJson = (unitId: string) => {
+ const map = this._sheetDrawingService.getDrawingDataForUnit(unitId);
+ if (map) {
+ return JSON.stringify(map);
+ }
+ return '';
+ };
+ const parseJson = (json: string): IDrawingSubunitMap<ISheetDrawing> => {
+ if (!json) {
+ return {};
+ }
+ try {
+ return JSON.parse(json);
+ } catch (err) {
+ return {};
+ }
+ };
+ this.disposeWithMe(
+ this._resourceManagerService.registerPluginResource<IDrawingSubunitMap<ISheetDrawing>>({
+ pluginName: SHEET_DRAWING_PLUGIN,
+ businesses: [UniverInstanceType.UNIVER_SHEET],
+ toJson: (unitId) => toJson(unitId),
+ parseJson: (json) => parseJson(json),
+ onUnLoad: (unitId) => {
+ this._sheetDrawingService.removeDrawingDataForUnit(unitId);
+ this._drawingManagerService.removeDrawingDataForUnit(unitId);
+ },
+ onLoad: (unitId, value) => {
+ this._sheetDrawingService.registerDrawingData(unitId, value);
+ this._drawingManagerService.registerDrawingData(unitId, value);
+ },
+ })
+ );
+ }
+}
diff --git a/packages/sheets/src/index.ts b/packages/sheets/src/index.ts
index 175efe1d7c..7a4261b682 100644
--- a/packages/sheets/src/index.ts
+++ b/packages/sheets/src/index.ts
@@ -376,3 +376,5 @@ export {
export { RangeProtectionPermissionEditPoint } from './services/permission/permission-point/range/edit';
export { RangeProtectionPermissionViewPoint } from './services/permission/permission-point/range/view';
+export { type ISheetDrawing, type ISheetUpdateDrawing, type ISheetDrawingPosition, ISheetDrawingService, SheetDrawingAnchorType, type ISheetDrawingBase } from './services/sheet-drawing.service';
+export { SetDrawingApplyMutation, type ISetDrawingApplyMutationParams, DrawingApplyType } from './commands/mutations/set-drawing-apply.mutation';
diff --git a/packages/sheets/src/services/sheet-drawing.service.ts b/packages/sheets/src/services/sheet-drawing.service.ts
new file mode 100644
index 0000000000..835bdba83f
--- /dev/null
+++ b/packages/sheets/src/services/sheet-drawing.service.ts
@@ -0,0 +1,64 @@
+/**
+ * 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 { IDrawingParam, IRotationSkewFlipTransform, IUnitDrawingService } from '@univerjs/core';
+import { createIdentifier } from '@wendellhu/redi';
+import { type IImageData, UnitDrawingService } from '@univerjs/drawing';
+
+interface ICellPosition {
+ column: number; // column number
+ columnOffset: number; // column offset, unit is EMUs
+ row: number; // row number
+ rowOffset: number; // row offset, unit is EMUs
+}
+
+export enum SheetDrawingAnchorType {
+ Position = '0',
+ Both = '1',
+ None = '2',
+}
+
+export interface ISheetDrawingPosition extends IRotationSkewFlipTransform {
+ from: ICellPosition;
+ to: ICellPosition;
+}
+
+export interface ISheetDrawingBase {
+ sheetTransform: ISheetDrawingPosition;
+ anchorType?: SheetDrawingAnchorType;
+}
+
+export interface ISheetImage extends IImageData, ISheetDrawingBase {
+
+}
+
+/**
+ * test type
+ */
+export interface ISheetShape extends IDrawingParam, ISheetDrawingBase {
+
+}
+
+export type ISheetDrawing = ISheetImage | ISheetShape;
+
+type OptionalField<T, K extends keyof T> = Omit<T, K> & Partial<Pick<T, K>>;
+export type ISheetUpdateDrawing = OptionalField<ISheetImage | ISheetShape, 'sheetTransform'>;
+
+export class SheetDrawingService extends UnitDrawingService<ISheetDrawing> {}
+
+export interface ISheetDrawingService extends IUnitDrawingService<ISheetDrawing> {}
+
+export const ISheetDrawingService = createIdentifier<ISheetDrawingService>('univer.sheet.plugin.sheet-drawing.service');
diff --git a/packages/sheets/src/sheets-plugin.ts b/packages/sheets/src/sheets-plugin.ts
index 9d6c535f93..119ed7b165 100644
--- a/packages/sheets/src/sheets-plugin.ts
+++ b/packages/sheets/src/sheets-plugin.ts
@@ -15,7 +15,7 @@
*/
import type { DependencyOverride } from '@univerjs/core';
-import { ICommandService, LocaleService, mergeOverrideWithDependencies, Plugin, UniverInstanceType } from '@univerjs/core';
+import { ICommandService, IConfigService, LocaleService, mergeOverrideWithDependencies, Plugin, UniverInstanceType } from '@univerjs/core';
import type { Dependency } from '@wendellhu/redi';
import { Inject, Injector } from '@wendellhu/redi';
@@ -38,12 +38,21 @@ import { RangeProtectionRuleModel } from './model/range-protection-rule.model';
import { RangeProtectionRefRangeService } from './services/permission/range-permission/range-protection.ref-range';
import { RangeProtectionService } from './services/permission/range-permission/range-protection.service';
+import { ISheetDrawingService, SheetDrawingService } from './services/sheet-drawing.service';
+import { ONLY_REGISTER_FORMULA_RELATED_MUTATIONS_KEY } from './controllers/config';
+import { SheetDrawingDataController } from './controllers/sheet-drawing-data.controller';
const PLUGIN_NAME = 'SHEET_PLUGIN';
export interface IUniverSheetsConfig {
notExecuteFormula?: boolean;
override?: DependencyOverride;
+
+ /**
+ * Only register the mutations related to the formula calculation. Especially useful for the
+ * web worker environment or server-side-calculation.
+ */
+ onlyRegisterFormulaRelatedMutations?: true;
}
/**
@@ -54,20 +63,28 @@ export class UniverSheetsPlugin extends Plugin {
static override type = UniverInstanceType.UNIVER_SHEET;
constructor(
- private _config: IUniverSheetsConfig,
+ private _config: IUniverSheetsConfig | undefined,
@ICommandService private readonly _commandService: ICommandService,
+ @IConfigService private readonly _configService: IConfigService,
@Inject(LocaleService) private readonly _localeService: LocaleService,
@Inject(Injector) override readonly _injector: Injector
) {
super();
- this._initializeDependencies(_injector);
+ this._initConfig();
+ this._initDependencies(_injector);
}
override onRendered(): void {
}
- private _initializeDependencies(sheetInjector: Injector) {
+ private _initConfig(): void {
+ if (this._config?.onlyRegisterFormulaRelatedMutations) {
+ this._configService.setConfig(ONLY_REGISTER_FORMULA_RELATED_MUTATIONS_KEY, true);
+ }
+ }
+
+ private _initDependencies(sheetInjector: Injector) {
const dependencies: Dependency[] = [
// services
[BorderStyleManagerService],
@@ -99,6 +116,11 @@ export class UniverSheetsPlugin extends Plugin {
[CalculateResultApplyController],
[FeatureCalculationController]
);
+ } else {
+ dependencies.push(
+ [ISheetDrawingService, { useClass: SheetDrawingService }],
+ [SheetDrawingDataController]
+ );
}
mergeOverrideWithDependencies(dependencies, this._config?.override).forEach((d) => {
diff --git a/packages/slides/src/basics/demo-data.ts b/packages/slides/src/basics/demo-data.ts
index 636ce0d117..9f85a66fd2 100644
--- a/packages/slides/src/basics/demo-data.ts
+++ b/packages/slides/src/basics/demo-data.ts
@@ -19,6 +19,7 @@ import {
BaselineOffset,
BooleanNumber,
ColumnSeparatorType,
+ DrawingTypeEnum,
ObjectRelativeFromH,
ObjectRelativeFromV,
PositionedObjectLayoutType,
@@ -31,10 +32,13 @@ export const docsDemoData: IDocumentData = {
id: 'd',
drawings: {
shapeTest1: {
- objectId: 'shapeTest1',
+ unitId: 'd',
+ subUnitId: 'd',
+ drawingType: DrawingTypeEnum.DRAWING_SHAPE,
+ drawingId: 'shapeTest1',
title: 'test shape',
description: 'test shape',
- objectTransform: {
+ docTransform: {
size: {
width: 100,
height: 400,
diff --git a/packages/slides/src/views/render/adaptors/docs-adaptor.ts b/packages/slides/src/views/render/adaptors/docs-adaptor.ts
index 27d9964164..7ea87b7cf6 100644
--- a/packages/slides/src/views/render/adaptors/docs-adaptor.ts
+++ b/packages/slides/src/views/render/adaptors/docs-adaptor.ts
@@ -22,9 +22,9 @@ import {
DocumentSkeleton,
DocumentViewModel,
EVENT_TYPE,
+ Image,
Liquid,
PageLayoutType,
- Picture,
Rect,
Scene,
SceneViewer,
@@ -106,7 +106,6 @@ export class DocsAdaptor extends ObjectAdaptor {
skewY,
flipX,
flipY,
- isTransformer: true,
});
const scene = new Scene(DOCS_VIEW_KEY.SCENE + id, sv);
@@ -205,19 +204,18 @@ export class DocsAdaptor extends ObjectAdaptor {
skeDrawings.forEach((drawing: IDocumentSkeletonDrawing) => {
const { aLeft, aTop, height, width, drawingOrigin } = drawing;
- const { objectTransform } = drawingOrigin;
+ const { docTransform } = drawingOrigin;
- const rect = new Picture(drawing.objectId, {
- // url: objectTransform.imageProperties?.contentUrl || '',
+ const rect = new Image(drawing.drawingId, {
+ // url: docTransform.imageProperties?.contentUrl || '',
left: aLeft + docsLeft + this._liquid.x,
top: aTop + docsTop + this._liquid.y,
width,
height,
zIndex: 11,
- isTransformer: true,
});
- pageMarginCache.set(drawing.objectId, {
+ pageMarginCache.set(drawing.drawingId, {
marginLeft: this._liquid.x,
marginTop: this._liquid.y,
});
@@ -232,8 +230,12 @@ export class DocsAdaptor extends ObjectAdaptor {
documents.pageMarginTop
);
}
- scene.openTransformer();
+
scene.addObjects(objectList);
+ objectList.forEach((object) => {
+ scene.attachTransformerTo(object);
+ });
+
scene.getTransformer()?.onChangingObservable.add((state) => {
const { objects } = state;
@@ -258,8 +260,6 @@ export class DocsAdaptor extends ObjectAdaptor {
documentSkeleton?.calculate();
});
- scene.closeTransformer();
-
this._calculatePagePosition(documents, scene, viewMain);
return sv;
diff --git a/packages/slides/src/views/render/adaptors/image-adaptor.ts b/packages/slides/src/views/render/adaptors/image-adaptor.ts
index 1f36461335..7f1e83d6c0 100644
--- a/packages/slides/src/views/render/adaptors/image-adaptor.ts
+++ b/packages/slides/src/views/render/adaptors/image-adaptor.ts
@@ -16,7 +16,7 @@
import type { IPageElement } from '@univerjs/core';
import { PageElementType } from '@univerjs/core';
-import { Picture } from '@univerjs/engine-render';
+import { Image } from '@univerjs/engine-render';
import type { Injector } from '@wendellhu/redi';
import { CanvasObjectProviderRegistry, ObjectAdaptor } from '../adaptor';
@@ -56,7 +56,7 @@ export class ImageAdaptor extends ObjectAdaptor {
const contentUrl = imageProperties?.contentUrl || '';
- return new Picture(id, {
+ return new Image(id, {
url: contentUrl,
top,
left,
@@ -70,7 +70,6 @@ export class ImageAdaptor extends ObjectAdaptor {
skewY,
flipX,
flipY,
- isTransformer: true,
forceRender: true,
});
}
diff --git a/packages/slides/src/views/render/adaptors/rich-text-adaptor.ts b/packages/slides/src/views/render/adaptors/rich-text-adaptor.ts
index d2ff651bd9..f39dc21201 100644
--- a/packages/slides/src/views/render/adaptors/rich-text-adaptor.ts
+++ b/packages/slides/src/views/render/adaptors/rich-text-adaptor.ts
@@ -72,7 +72,6 @@ export class RichTextAdaptor extends ObjectAdaptor {
skewY,
flipX,
flipY,
- isTransformer: true,
forceRender: true,
};
let isNotNull = false;
diff --git a/packages/slides/src/views/render/adaptors/shape-adaptor.ts b/packages/slides/src/views/render/adaptors/shape-adaptor.ts
index c9ecb616a1..a7768e7ffa 100644
--- a/packages/slides/src/views/render/adaptors/shape-adaptor.ts
+++ b/packages/slides/src/views/render/adaptors/shape-adaptor.ts
@@ -15,7 +15,7 @@
*/
import type { IPageElement } from '@univerjs/core';
-import { getColorStyle, PageElementType, ShapeType } from '@univerjs/core';
+import { BasicShapes, getColorStyle, PageElementType } from '@univerjs/core';
import { Rect } from '@univerjs/engine-render';
import type { Injector } from '@wendellhu/redi';
@@ -65,7 +65,7 @@ export class ShapeAdaptor extends ObjectAdaptor {
strokeStyle.stroke = getColorStyle(outlineFill) || 'rgba(0,0,0,1)';
}
- if (shapeType === ShapeType.RECTANGLE) {
+ if (shapeType === BasicShapes.Rect) {
return new Rect(id, {
fill,
top,
@@ -80,12 +80,11 @@ export class ShapeAdaptor extends ObjectAdaptor {
skewY,
flipX,
flipY,
- isTransformer: true,
forceRender: true,
...strokeStyle,
});
}
- if (shapeType === ShapeType.ROUND_RECTANGLE) {
+ if (shapeType === BasicShapes.RoundRect) {
const radius = shapeProperties?.radius || 0;
return new Rect(id, {
fill,
@@ -101,7 +100,6 @@ export class ShapeAdaptor extends ObjectAdaptor {
skewY,
flipX,
flipY,
- isTransformer: true,
forceRender: true,
radius,
...strokeStyle,
diff --git a/packages/slides/src/views/render/adaptors/slide-adaptor.ts b/packages/slides/src/views/render/adaptors/slide-adaptor.ts
index 7235c5ea31..ccd9d3837d 100644
--- a/packages/slides/src/views/render/adaptors/slide-adaptor.ts
+++ b/packages/slides/src/views/render/adaptors/slide-adaptor.ts
@@ -88,7 +88,6 @@ export class SlideAdaptor extends ObjectAdaptor {
skewY,
flipX,
flipY,
- isTransformer: false,
forceRender: true,
});
@@ -140,12 +139,14 @@ export class SlideAdaptor extends ObjectAdaptor {
const objects = this._ObjectProvider?.convertToRenderObjects(pageElements, mainScene);
- scene.openTransformer();
-
this._addBackgroundRect(scene, pageBackgroundFill, model);
scene.addObjects(objects!);
+ objects?.forEach((object) => {
+ scene.attachTransformerTo(object);
+ });
+
return scene;
}
diff --git a/packages/slides/src/views/render/adaptors/spreadsheet-adaptor.ts b/packages/slides/src/views/render/adaptors/spreadsheet-adaptor.ts
index 5c0b6e8c74..31b911c36a 100644
--- a/packages/slides/src/views/render/adaptors/spreadsheet-adaptor.ts
+++ b/packages/slides/src/views/render/adaptors/spreadsheet-adaptor.ts
@@ -67,6 +67,7 @@ export class SpreadsheetAdaptor extends ObjectAdaptor {
return this;
}
+ // eslint-disable-next-line max-lines-per-function
override convert(pageElement: IPageElement, mainScene: Scene) {
const {
id,
@@ -123,7 +124,6 @@ export class SpreadsheetAdaptor extends ObjectAdaptor {
skewY,
flipX,
flipY,
- isTransformer: true,
forceRender: true,
});
const scene = new Scene(SHEET_VIEW_KEY.SCENE + id, sv, {
@@ -154,6 +154,7 @@ export class SpreadsheetAdaptor extends ObjectAdaptor {
return sv;
}
+ // eslint-disable-next-line max-lines-per-function
private _updateViewport(
id: string,
rowHeaderWidth: number,
@@ -193,7 +194,7 @@ export class SpreadsheetAdaptor extends ObjectAdaptor {
isWheelPreventDefaultX: true,
});
- new Viewport(SHEET_VIEW_KEY.VIEW_LEFT_TOP + id, scene, {
+ const VIEW_LEFT_TOP = new Viewport(SHEET_VIEW_KEY.VIEW_LEFT_TOP + id, scene, {
left: 0,
top: 0,
width: rowHeaderWidthScale,
diff --git a/packages/slides/src/views/render/canvas-view.ts b/packages/slides/src/views/render/canvas-view.ts
index 23f90e3e54..a172ff8c28 100644
--- a/packages/slides/src/views/render/canvas-view.ts
+++ b/packages/slides/src/views/render/canvas-view.ts
@@ -428,11 +428,15 @@ export class CanvasView extends RxDisposable {
// SceneViewers
const objects = this._objectProvider.convertToRenderObjects(pageElements, mainScene);
if (!objects || !slide) return;
- scene.openTransformer();
+
this._addBackgroundRect(scene, pageBackgroundFill);
// So finally SceneViewers are added to the scene as objects. How can we do optimizations on this?
scene.addObjects(objects);
+ objects.forEach((object) => {
+ scene.attachTransformerTo(object);
+ });
+
const transformer = scene.getTransformer();
transformer?.onChangeEndObservable.add(() => {
diff --git a/packages/ui/src/components/editor/TextEditor.tsx b/packages/ui/src/components/editor/TextEditor.tsx
index 492b8f0aa3..40e69a618d 100644
--- a/packages/ui/src/components/editor/TextEditor.tsx
+++ b/packages/ui/src/components/editor/TextEditor.tsx
@@ -14,7 +14,8 @@
* limitations under the License.
*/
-import { debounce, type IDocumentData, isInternalEditorID, LocaleService, type Nullable } from '@univerjs/core';
+import type { IDocumentData, Nullable } from '@univerjs/core';
+import { debounce, isInternalEditorID, LocaleService } from '@univerjs/core';
import { useDependency } from '@wendellhu/redi/react-bindings';
import React, { useEffect, useRef, useState } from 'react';
import { Popup } from '@univerjs/design';
diff --git a/packages/ui/src/views/components/doc-bars/hook.ts b/packages/ui/src/views/components/doc-bars/hook.ts
index d98e4f1b77..5ad82860cd 100644
--- a/packages/ui/src/views/components/doc-bars/hook.ts
+++ b/packages/ui/src/views/components/doc-bars/hook.ts
@@ -138,7 +138,7 @@ export function useToolbarItemStatus(menuItem: IDisplayMenuItem<IMenuItem>): ITo
activated$ && subscriptions.push(activated$.subscribe((activated) => setActivated(activated)));
value$ && subscriptions.push(value$.subscribe((value) => setValue(value)));
- return () => subscriptions.forEach((subscription) => subscription.unsubscribe()); ;
+ return () => subscriptions.forEach((subscription) => subscription.unsubscribe());
}, [activated$, disabled$, hidden$, value$]);
return { disabled, value, activated, hidden };
diff --git a/packages/umd/package.json b/packages/umd/package.json
index 2ae59a1bb8..99d62065b7 100644
--- a/packages/umd/package.json
+++ b/packages/umd/package.json
@@ -46,12 +46,12 @@
"@univerjs/design": "workspace:*",
"@univerjs/docs": "workspace:*",
"@univerjs/docs-ui": "workspace:*",
+ "@univerjs/drawing": "workspace:*",
"@univerjs/engine-formula": "workspace:*",
"@univerjs/engine-numfmt": "workspace:*",
"@univerjs/engine-render": "workspace:*",
"@univerjs/facade": "workspace:*",
"@univerjs/find-replace": "workspace:*",
- "@univerjs/image": "workspace:*",
"@univerjs/network": "workspace:*",
"@univerjs/protocol": "^0.1.34",
"@univerjs/rpc": "workspace:*",
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 2dab57ef05..d5c7b2d25e 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -213,9 +213,18 @@ importers:
'@univerjs/docs':
specifier: workspace:*
version: link:../packages/docs
+ '@univerjs/docs-drawing-ui':
+ specifier: workspace:*
+ version: link:../packages/docs-drawing-ui
'@univerjs/docs-ui':
specifier: workspace:*
version: link:../packages/docs-ui
+ '@univerjs/drawing':
+ specifier: workspace:*
+ version: link:../packages/drawing
+ '@univerjs/drawing-ui':
+ specifier: workspace:*
+ version: link:../packages/drawing-ui
'@univerjs/engine-formula':
specifier: workspace:*
version: link:../packages/engine-formula
@@ -231,9 +240,6 @@ importers:
'@univerjs/icons':
specifier: ^0.1.52
- '@univerjs/image':
- specifier: workspace:*
- version: link:../packages/image
'@univerjs/rpc':
specifier: workspace:*
version: link:../packages/rpc
@@ -249,6 +255,9 @@ importers:
'@univerjs/sheets-data-validation':
specifier: workspace:*
version: link:../packages/sheets-data-validation
+ '@univerjs/sheets-drawing-ui':
+ specifier: workspace:*
+ version: link:../packages/sheets-drawing-ui
'@univerjs/sheets-filter':
specifier: workspace:*
version: link:../packages/sheets-filter
@@ -576,6 +585,9 @@ importers:
'@univerjs/core':
specifier: workspace:*
version: link:../core
+ '@univerjs/drawing':
+ specifier: workspace:*
+ version: link:../drawing
'@univerjs/engine-render':
specifier: workspace:*
version: link:../engine-render
@@ -598,6 +610,64 @@ importers:
specifier: ^1.6.0
+ packages/docs-drawing-ui:
+ dependencies:
+ '@univerjs/icons':
+ specifier: ^0.1.46
+ devDependencies:
+ '@univerjs/core':
+ specifier: workspace:*
+ version: link:../core
+ '@univerjs/design':
+ specifier: workspace:*
+ version: link:../design
+ '@univerjs/docs':
+ specifier: workspace:*
+ version: link:../docs
+ '@univerjs/docs-ui':
+ specifier: workspace:*
+ version: link:../docs-ui
+ '@univerjs/drawing':
+ specifier: workspace:*
+ version: link:../drawing
+ '@univerjs/drawing-ui':
+ specifier: workspace:*
+ version: link:../drawing-ui
+ '@univerjs/engine-render':
+ specifier: workspace:*
+ version: link:../engine-render
+ '@univerjs/shared':
+ specifier: workspace:*
+ version: link:../../common/shared
+ '@univerjs/ui':
+ specifier: workspace:*
+ version: link:../ui
+ '@wendellhu/redi':
+ specifier: 0.15.2
+ version: 0.15.2
+ clsx:
+ specifier: ^2.1.0
+ version: 2.1.1
+ less:
+ specifier: ^4.2.0
+ version: 4.2.0
+ react:
+ specifier: ^18.2.0
+ version: 18.2.0
+ rxjs:
+ specifier: ^7.8.1
+ version: 7.8.1
+ typescript:
+ specifier: ^5.3.3
+ version: 5.4.5
+ vite:
+ specifier: ^5.1.4
+ vitest:
+ specifier: ^1.3.1
+
packages/docs-ui:
devDependencies:
'@types/react':
@@ -643,6 +713,98 @@ importers:
specifier: ^1.6.0
+ packages/drawing:
+ dependencies:
+ '@univerjs/engine-render':
+ specifier: workspace:*
+ version: link:../engine-render
+ '@univerjs/icons':
+ specifier: ^0.1.52
+ ot-json1:
+ specifier: ^1.0.2
+ version: 1.0.2
+ devDependencies:
+ '@univerjs/core':
+ specifier: workspace:*
+ version: link:../core
+ '@univerjs/shared':
+ specifier: workspace:*
+ version: link:../../common/shared
+ '@univerjs/ui':
+ specifier: workspace:*
+ version: link:../ui
+ '@wendellhu/redi':
+ specifier: 0.15.2
+ version: 0.15.2
+ less:
+ specifier: ^4.2.0
+ version: 4.2.0
+ react:
+ specifier: 18.2.0
+ version: 18.2.0
+ rxjs:
+ specifier: ^7.8.1
+ version: 7.8.1
+ typescript:
+ specifier: ^5.4.5
+ version: 5.4.5
+ vite:
+ specifier: ^5.2.11
+ vitest:
+ specifier: ^1.6.0
+
+ packages/drawing-ui:
+ dependencies:
+ '@univerjs/icons':
+ specifier: ^0.1.52
+ devDependencies:
+ '@univerjs/core':
+ specifier: workspace:*
+ version: link:../core
+ '@univerjs/design':
+ specifier: workspace:*
+ version: link:../design
+ '@univerjs/drawing':
+ specifier: workspace:*
+ version: link:../drawing
+ '@univerjs/engine-render':
+ specifier: workspace:*
+ version: link:../engine-render
+ '@univerjs/shared':
+ specifier: workspace:*
+ version: link:../../common/shared
+ '@univerjs/ui':
+ specifier: workspace:*
+ version: link:../ui
+ '@wendellhu/redi':
+ specifier: 0.15.2
+ version: 0.15.2
+ clsx:
+ specifier: ^2.1.0
+ version: 2.1.1
+ less:
+ specifier: ^4.2.0
+ version: 4.2.0
+ react:
+ specifier: ^18.2.0
+ version: 18.2.0
+ rxjs:
+ specifier: ^7.8.1
+ version: 7.8.1
+ typescript:
+ specifier: ^5.3.3
+ version: 5.4.5
+ vite:
+ specifier: ^5.1.4
+ vitest:
+ specifier: ^1.3.1
+
packages/engine-formula:
dependencies:
big.js:
@@ -842,52 +1004,6 @@ importers:
specifier: ^1.6.0
- packages/image:
- dependencies:
- '@univerjs/icons':
- specifier: ^0.1.52
- devDependencies:
- '@univerjs/core':
- specifier: workspace:*
- version: link:../core
- '@univerjs/design':
- specifier: workspace:*
- version: link:../design
- '@univerjs/engine-render':
- specifier: workspace:*
- version: link:../engine-render
- '@univerjs/shared':
- specifier: workspace:*
- version: link:../../common/shared
- '@univerjs/sheets':
- specifier: workspace:*
- version: link:../sheets
- '@univerjs/ui':
- specifier: workspace:*
- version: link:../ui
- '@wendellhu/redi':
- specifier: 0.15.2
- version: 0.15.2
- less:
- specifier: ^4.2.0
- version: 4.2.0
- react:
- specifier: 18.2.0
- version: 18.2.0
- rxjs:
- specifier: ^7.8.1
- version: 7.8.1
- typescript:
- specifier: ^5.4.5
- version: 5.4.5
- vite:
- specifier: ^5.2.11
- vitest:
- specifier: ^1.6.0
-
packages/network:
devDependencies:
'@univerjs/core':
@@ -945,6 +1061,9 @@ importers:
'@univerjs/core':
specifier: workspace:*
version: link:../core
+ '@univerjs/drawing':
+ specifier: workspace:*
+ version: link:../drawing
'@univerjs/engine-formula':
specifier: workspace:*
version: link:../engine-formula
@@ -1171,6 +1290,64 @@ importers:
specifier: ^1.6.0
+ packages/sheets-drawing-ui:
+ dependencies:
+ '@univerjs/icons':
+ specifier: ^0.1.29
+ devDependencies:
+ '@univerjs/core':
+ specifier: workspace:*
+ version: link:../core
+ '@univerjs/design':
+ specifier: workspace:*
+ version: link:../design
+ '@univerjs/drawing':
+ specifier: workspace:*
+ version: link:../drawing
+ '@univerjs/drawing-ui':
+ specifier: workspace:*
+ version: link:../drawing-ui
+ '@univerjs/engine-render':
+ specifier: workspace:*
+ version: link:../engine-render
+ '@univerjs/shared':
+ specifier: workspace:*
+ version: link:../../common/shared
+ '@univerjs/sheets':
+ specifier: workspace:*
+ version: link:../sheets
+ '@univerjs/sheets-ui':
+ specifier: workspace:*
+ version: link:../sheets-ui
+ '@univerjs/ui':
+ specifier: workspace:*
+ version: link:../ui
+ '@wendellhu/redi':
+ specifier: 0.15.2
+ version: 0.15.2
+ clsx:
+ specifier: ^2.1.0
+ version: 2.1.1
+ less:
+ specifier: ^4.2.0
+ version: 4.2.0
+ react:
+ specifier: ^18.2.0
+ version: 18.2.0
+ rxjs:
+ specifier: ^7.8.1
+ version: 7.8.1
+ typescript:
+ specifier: ^5.3.3
+ version: 5.4.5
+ vite:
+ specifier: ^5.1.4
+ vitest:
+ specifier: ^1.3.1
+
packages/sheets-filter:
devDependencies:
'@univerjs/core':
@@ -1216,6 +1393,9 @@ importers:
'@univerjs/design':
specifier: workspace:*
version: link:../design
+ '@univerjs/drawing':
+ specifier: workspace:*
+ version: link:../drawing
'@univerjs/engine-render':
specifier: workspace:*
version: link:../engine-render
@@ -1584,6 +1764,9 @@ importers:
'@univerjs/docs':
specifier: workspace:*
version: link:../docs
+ '@univerjs/drawing':
+ specifier: workspace:*
+ version: link:../drawing
'@univerjs/engine-formula':
specifier: workspace:*
version: link:../engine-formula
@@ -1937,6 +2120,9 @@ importers:
'@univerjs/docs-ui':
specifier: workspace:*
version: link:../docs-ui
+ '@univerjs/drawing':
+ specifier: workspace:*
+ version: link:../drawing
'@univerjs/engine-formula':
specifier: workspace:*
version: link:../engine-formula
@@ -1952,9 +2138,6 @@ importers:
'@univerjs/find-replace':
specifier: workspace:*
version: link:../find-replace
- '@univerjs/image':
- specifier: workspace:*
- version: link:../image
'@univerjs/network':
specifier: workspace:*
version: link:../network