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.

refactor(editor): component editor (#1419)

Univer8db5c064e331
diff --git a/examples/src/data/docs/default-document-data-cn.ts b/examples/src/data/docs/default-document-data-cn.ts
index d39ff0746f..4a8ee4ca2a 100644
--- a/examples/src/data/docs/default-document-data-cn.ts
+++ b/examples/src/data/docs/default-document-data-cn.ts
@@ -16,12 +16,13 @@
import type { IDocumentData } from '@univerjs/core';
import { BooleanNumber } from '@univerjs/core';
+import { ptToPixel } from '@univerjs/engine-render';
export const DEFAULT_DOCUMENT_DATA_CN: IDocumentData = {
id: 'default-document-id',
body: {
dataStream:
- '荷塘月色\r\r作者:朱自清\r\r这几天心里颇不宁静。今晚在院子里坐着乘凉,忽然想起日日走过的荷塘,在这满月的光里,总该另有一番样子吧。月亮渐渐地升高了,墙外马路上孩子们的欢笑,已经听不见了;妻在屋里拍着闰儿,迷迷糊糊地哼着眠歌。我悄悄地披了大衫,带上门出去。\r\r沿着荷塘,是一条曲折的小煤屑路。这是一条幽僻的路;白天也少人走,夜晚更加寂寞。荷塘四面,长着许多树,蓊蓊郁郁的。路的一旁,是些杨柳,和一些不知道名字的树。没有月光的晚上,这路上阴森森的,有些怕人。今晚却很好,虽然月光也还是淡淡的。\r\r路上只我一个人,背着手踱着。这一片天地好像是我的;我也像超出了平常的自己,到了另一个世界里。我爱热闹,也爱冷静;爱群居,也爱独处。像今晚上,一个人在这苍茫的月下,什么都可以想,什么都可以不想,便觉是个自由的人。白天里一定要做的事,一定要说的话,现在都可不理。这是独处的妙处,我且受用这无边的荷香月色好了。\r\r曲曲折折的荷塘上面,弥望的是田田的叶子。叶子出水很高,像亭亭的舞女的裙。层层的叶子中间,零星地点缀着些白花,有袅娜地开着的,有羞涩地打着朵儿的;正如一粒粒的明珠,又如碧天里的星星,又如刚出浴的美人。微风过处,送来缕缕清香,仿佛远处高楼上渺茫的歌声似的。这时候叶子与花也有一丝的颤动,像闪电般,霎时传过荷塘的那边去了。叶子本是肩并肩密密地挨着,这便宛然有了一道凝碧的波痕。叶子底下是脉脉的流水,遮住了,不能见一些颜色;而叶子却更见风致了。\r\r月光如流水一般,静静地泻在这一片叶子和花上。薄薄的青雾浮起在荷塘里。叶子和花仿佛在牛乳中洗过一样;又像笼着轻纱的梦。虽然是满月,天上却有一层淡淡的云,所以不能朗照;但我以为这恰是到了好处——酣眠固不可少,小睡也别有风味的。月光是隔了树照过来的,高处丛生的灌木,落下参差的斑驳的黑影,峭楞楞如鬼一般;弯弯的杨柳的稀疏的倩影,却又像是画在荷叶上。塘中的月色并不均匀;但光与影有着和谐的旋律,如梵婀玲上奏着的名曲。\r\r荷塘的四面,远远近近,高高低低都是树,而杨柳最多。这些树将一片荷塘重重围住;只在小路一旁,漏着几段空隙,像是特为月光留下的。树色一例是阴阴的,乍看像一团烟雾;但杨柳的丰姿,便在烟雾里也辨得出。树梢上隐隐约约的是一带远山,只有些大意罢了。树缝里也漏着一两点路灯光,没精打采的,是渴睡人的眼。这时候最热闹的,要数树上的蝉声与水里的蛙声;但热闹是它们的,我什么也没有。\r\r忽然想起采莲的事情来了。采莲是江南的旧俗,似乎很早就有,而六朝时为盛;从诗歌里可以约略知道。采莲的是少年的女子,她们是荡着小船,唱着艳歌去的。采莲人不用说很多,还有看采莲的人。那是一个热闹的季节,也是一个风流的季节。梁元帝《采莲赋》里说得好:\r\r于是妖童女,荡舟心许;鷁首徐回,兼传羽杯;櫂将移而藻挂,船欲动而萍开。尔其纤腰束素,迁延顾步;夏始春余,叶嫩花初,恐沾裳而浅笑,畏倾船而敛裾。\r\r可见当时嬉游的光景了。这真是有趣的事,可惜我们现在早已无福消受了。\r\r于是又记起,《西洲曲》里的句子:\r\r采莲南塘秋,莲花过人头;低头弄莲子,莲子清如水。\r\r今晚若有采莲人,这儿的莲花也算得“过人头”了;只不见一些流水的影子,是不行的。这令我到底惦着江南了。——这样想着,猛一抬头,不觉已是自己的门前;轻轻地推门进去,什么声息也没有,妻已睡熟好久了。\r\r一九二七年七月,北京清华园。\r\r\r\r《荷塘月色》语言朴素典雅,准确生动,贮满诗意,满溢着朱自清的散文语言一贯有朴素的美,不用浓墨重彩,画的是淡墨水彩。\r\r朱自清先生一笔写景一笔说情,看起来松散不知所云,可仔细体会下,就能感受到先生在字里行间表述出的苦闷,而随之读者也被先生的文字所感染,被带进了他当时那苦闷而无法明喻的心情。这就是优异散文的必须品质之一。\r\r扩展资料:\r一首长诗《毁灭》奠定了朱自清在文坛新诗人的地位,而《桨声灯影里的秦淮河》则被公认为白话美文的典范。朱自清用白话美文向复古派宣战,有力地回击了复古派“白话不能作美文”之说,他是“五四”新文学运动的开拓者之一。\r\r朱自清的美文影响了一代又一代人。作家贾平凹说:来到扬州,第一个想到的人是朱自清,他是知识分子中最最了不起的人物。\r\r实际上,朱自清的写作路程是非常曲折的,他早期的时候大多数作品都是诗歌,但是他的诗歌和我国古代诗人的诗有很大区别,他的诗是用白话文写的,这其实也是他写作的惯用风格。\r\r后来,朱自清开始写一些关于社会的文章,因为那个时候社会比较混乱,这时候的作品大多抨击社会的黑暗面,文体风格大多硬朗,基调伉俪。到了后期,大多是写关于山水的文章,这类文章的写作格调大多以清丽雅致为主。\r\r朱自清的写作风格虽然在不同的时期随着他的人生阅历和社会形态的不同而发生着变化,但是他文章的主基调是没有变的,他这一生,所写的所有文章风格上都有一个非常显著的特点,那就是简约平淡,他不是类似古代花间词派的诗人们,不管是他的诗词还是他的文章从来都不用过于华丽的辞藻,他崇尚的是平淡。\r\r英国友人戴立克试过英译朱自清几篇散文,译完一读显得单薄,远远不如原文流利。他不服气,改用稍微古奥的英文重译,好多了:“那是说,朱先生外圆内方,文字尽管浅白,心思却很深沉,译笔只好朝深处经营。”朱自清的很多文章,譬如《背影》《祭亡妇》,读来自有一番只可意会不可言传的东西。\r\r平淡就是朱自清的写作风格。他不是豪放派的作家,他在创作的时候钟情于清新的风格,给人耳目一新的感觉。在他的文章中包含了他对生活的向往,由此可见他的写作风格和他待人处事的态度也是有几分相似的。他的文章非常优美,但又不会让人觉得狭隘,给人一种豁达渊博的感觉,这就是朱自清的写作风格,更是朱自清的为人品质。\r\r写有《荷塘月色》《背影》等名篇的著名散文家朱自清先生,不仅自己一生风骨正气,还用无形的家风涵养子孙。良好的家风家规意蕴深远,催人向善,是凝聚情感、涵养德行、砥砺成才的人生信条。“北有朱自清,南有朱物华,一文一武,一南一北,双星闪耀”,这是中国知识界、教育界对朱家两兄弟的赞誉。\r\r朱自清性格温和,为人和善,对待年轻人平易近人,是个平和的人。他取字“佩弦”,意思要像弓弦那样将自己绷紧,给人的感觉是自我要求高,偶尔有呆气。朱自清教学负责,对学生要求严格,修他的课的学生都受益不少。\r\r1948年6月,患胃病多年的朱自清,在《抗议美国扶日政策并拒绝领取美援面粉宣言》上,一丝不苟地签下了自己的名字。随后,朱自清还将面粉配购证以及面粉票退了回去。1948年8月12日,朱自清因不堪胃病折磨,离开人世。在新的时代即将到来时,朱自清却匆匆地离人们远去。他为人们留下了无数经典的诗歌和文字,还有永不屈服的精神。\r\r朱自清没有豪言壮语,他只是用坚定的行动、朴实的语言,向世人展示了中国知识分子在祖国危难之际坚定的革命性,体现了中国人的骨气,表现了无比高贵的民族气节,呈现了人生最有价值的一面,谱就了生命中最华丽的乐章。\r\r他以“自清”为名,自勉在困境中不丧志;他身患重病,至死拒领美援面粉,其气节令世人感佩;他的《背影》《荷塘月色》《匆匆》脍炙人口;他的文字追求“真”,没有半点矫饰,却蕴藏着动人心弦的力量。\r\r朱自清不但在文学创作方面有很高的造诣,也是一名革命民主主义战士,在反饥饿、反内战的斗争中,他始终保持着一个正直的爱国知识分子的气节和情操。毛泽东对朱自清宁肯饿死不领美国“救济粉”的精神给予称赞,赞扬他“表现了我们民族的英雄气概”。\r\n',
+ '荷塘月色\r\r作者:朱自清\r\r这几天心里颇不宁静。今晚在院子里坐着乘凉,忽然想起日日走过的荷塘,在这满月的光里,总该另有一番样子吧。月亮渐渐地升高了,墙外马路上孩子们的欢笑,已经听不见了;妻在屋里拍着闰儿,迷迷糊糊地哼着眠歌。我悄悄地披了大衫,带上门出去。\r\r沿着荷塘,是一条曲折的小煤屑路。这是一条幽僻的路;白天也少人走,夜晚更加寂寞。荷塘四面,长着许多树,蓊蓊郁郁的。路的一旁,是些杨柳,和一些不知道名字的树。没有月光的晚上,这路上阴森森的,有些怕人。今晚却很好,虽然月光也还是淡淡的。\r\r路上只我一个人,背着手踱着。这一片天地好像是我的;我也像超出了平常的自己,到了另一个世界里。我爱热闹,也爱冷静;爱群居,也爱独处。像今晚上,一个人在这苍茫的月下,什么都可以想,什么都可以不想,便觉是个自由的人。白天里一定要做的事,一定要说的话,现在都可不理。这是独处的妙处,我且受用这无边的荷香月色好了。\r\r曲曲折折的荷塘上面,弥望的是田田的叶子。叶子出水很高,像亭亭的舞女的裙。层层的叶子中间,零星地点缀着些白花,有袅娜地开着的,有羞涩地打着朵儿的;正如一粒粒的明珠,又如碧天里的星星,又如刚出浴的美人。微风过处,送来缕缕清香,仿佛远处高楼上渺茫的歌声似的。这时候叶子与花也有一丝的颤动,像闪电般,霎时传过荷塘的那边去了。叶子本是肩并肩密密地挨着,这便宛然有了一道凝碧的波痕。叶子底下是脉脉的流水,遮住了,不能见一些颜色;而叶子却更见风致了。\r\r月光如流水一般,静静地泻在这一片叶子和花上。薄薄的青雾浮起在荷塘里。叶子和花仿佛在牛乳中洗过一样;又像笼着轻纱的梦。虽然是满月,天上却有一层淡淡的云,所以不能朗照;但我以为这恰是到了好处——酣眠固不可少,小睡也别有风味的。月光是隔了树照过来的,高处丛生的灌木,落下参差的斑驳的黑影,峭楞楞如鬼一般;弯弯的杨柳的稀疏的倩影,却又像是画在荷叶上。塘中的月色并不均匀;但光与影有着和谐的旋律,如梵婀玲上奏着的名曲。\r\r荷塘的四面,远远近近,高高低低都是树,而杨柳最多。这些树将一片荷塘重重围住;只在小路一旁,漏着几段空隙,像是特为月光留下的。树色一例是阴阴的,乍看像一团烟雾;但杨柳的丰姿,便在烟雾里也辨得出。树梢上隐隐约约的是一带远山,只有些大意罢了。树缝里也漏着一两点路灯光,没精打采的,是渴睡人的眼。这时候最热闹的,要数树上的蝉声与水里的蛙声;但热闹是它们的,我什么也没有。\r\r忽然想起采莲的事情来了。采莲是江南的旧俗,似乎很早就有,而六朝时为盛;从诗歌里可以约略知道。采莲的是少年的女子,她们是荡着小船,唱着艳歌去的。采莲人不用说很多,还有看采莲的人。那是一个热闹的季节,也是一个风流的季节。梁元帝《采莲赋》里说得好:\r\r于是妖童女,荡舟心许;鷁首徐回,兼传羽杯;櫂将移而藻挂,船欲动而萍开。尔其纤腰束素,迁延顾步;夏始春余,叶嫩花初,恐沾裳而浅笑,畏倾船而敛裾。\r\r可见当时嬉游的光景了。这真是有趣的事,可惜我们现在早已无福消受了。\r\r于是又记起,《西洲曲》里的句子:\r\r采莲南塘秋,莲花过人头;低头弄莲子,莲子清如水。\r\r今晚若有采莲人,这儿的莲花也算得“过人头”了;只不见一些流水的影子,是不行的。这令我到底惦着江南了。——这样想着,猛一抬头,不觉已是自己的门前;轻轻地推门进去,什么声息也没有,妻已睡熟好久了。\r\r一九二七年七月,北京清华园。\r\r\r\r《荷塘月色》语言朴素典雅,准确生动,贮满诗意,满溢着朱自清的散文语言一贯有朴素的美,不用浓墨重彩,画的是淡墨水彩。\r\r朱自清先生一笔写景一笔说情,看起来松散不知所云,可仔细体会下,就能感受到先生在字里行间表述出的苦闷,而随之读者也被先生的文字所感染,被带进了他当时那苦闷而无法明喻的心情。这就是优异散文的必须品质之一。\r\r扩展资料:\r一首长诗《毁灭》奠定了朱自清在文坛新诗人的地位,而《桨声灯影里的秦淮河》则被公认为白话美文的典范。朱自清用白话美文向复古派宣战,有力地回击了复古派“白话不能作美文”之说,他是“五四”新文学运动的开拓者之一。\r\r朱自清的美文影响了一代又一代人。作家贾平凹说:来到扬州,第一个想到的人是朱自清,他是知识分子中最最了不起的人物。\r\r实际上,朱自清的写作路程是非常曲折的,他早期的时候大多数作品都是诗歌,但是他的诗歌和我国古代诗人的诗有很大区别,他的诗是用白话文写的,这其实也是他写作的惯用风格。\r\r后来,朱自清开始写一些关于社会的文章,因为那个时候社会比较混乱,这时候的作品大多抨击社会的黑暗面,文体风格大多硬朗,基调伉俪。到了后期,大多是写关于山水的文章,这类文章的写作格调大多以清丽雅致为主。\r\r朱自清的写作风格虽然在不同的时期随着他的人生阅历和社会形态的不同而发生着变化,但是他文章的主基调是没有变的,他这一生,所写的所有文章风格上都有一个非常显著的特点,那就是简约平淡,他不是类似古代花间词派的诗人们,不管是他的诗词还是他的文章从来都不用过于华丽的辞藻,他崇尚的是平淡。\r\r英国友人戴立克试过英译朱自清几篇散文,译完一读显得单薄,远远不如原文流利。他不服气,改用稍微古奥的英文重译,好多了:“那是说,朱先生外圆内方,文字尽管浅白,心思却很深沉,译笔只好朝深处经营。”朱自清的很多文章,譬如《背影》《祭亡妇》,读来自有一番只可意会不可言传的东西。\r\r平淡就是朱自清的写作风格。他不是豪放派的作家,他在创作的时候钟情于清新的风格,给人耳目一新的感觉。在他的文章中包含了他对生活的向往,由此可见他的写作风格和他待人处事的态度也是有几分相似的。他的文章非常优美,但又不会让人觉得狭隘,给人一种豁达渊博的感觉,这就是朱自清的写作风格,更是朱自清的为人品质。\r\r写有《荷塘月色》《背影》等名篇的著名散文家朱自清先生,不仅自己一生风骨正气,还用无形的家风涵养子孙。良好的家风家规意蕴深远,催人向善,是凝聚情感、涵养德行、砥砺成才的人生信条。“北有朱自清,南有朱物华,一文一武,一南一北,双星闪耀”,这是中国知识界、教育界对朱家两兄弟的赞誉。\r\r朱自清性格温和,为人和善,对待年轻人平易近人,是个平和的人。他取字“佩弦”,意思要像弓弦那样将自己绷紧,给人的感觉是自我要求高,偶尔有呆气。朱自清教学负责,对学生要求严格,修他的课的学生都受益不少。\r\r1948 年 6 月,患胃病多年的朱自清,在《抗议美国扶日政策并拒绝领取美援面粉宣言》上,一丝不苟地签下了自己的名字。随后,朱自清还将面粉配购证以及面粉票退了回去。1948 年 8 月 12 日,朱自清因不堪胃病折磨,离开人世。在新的时代即将到来时,朱自清却匆匆地离人们远去。他为人们留下了无数经典的诗歌和文字,还有永不屈服的精神。\r\r朱自清没有豪言壮语,他只是用坚定的行动、朴实的语言,向世人展示了中国知识分子在祖国危难之际坚定的革命性,体现了中国人的骨气,表现了无比高贵的民族气节,呈现了人生最有价值的一面,谱就了生命中最华丽的乐章。\r\r他以“自清”为名,自勉在困境中不丧志;他身患重病,至死拒领美援面粉,其气节令世人感佩;他的《背影》《荷塘月色》《匆匆》脍炙人口;他的文字追求“真”,没有半点矫饰,却蕴藏着动人心弦的力量。\r\r朱自清不但在文学创作方面有很高的造诣,也是一名革命民主主义战士,在反饥饿、反内战的斗争中,他始终保持着一个正直的爱国知识分子的气节和情操。毛泽东对朱自清宁肯饿死不领美国“救济粉”的精神给予称赞,赞扬他“表现了我们民族的英雄气概”。\r\n',
textRuns: [
{
st: 0,
@@ -591,13 +592,13 @@ export const DEFAULT_DOCUMENT_DATA_CN: IDocumentData = {
},
documentStyle: {
pageSize: {
- width: 595,
- height: 842,
+ width: ptToPixel(595),
+ height: ptToPixel(842),
},
- marginTop: 50,
- marginBottom: 50,
- marginRight: 40,
- marginLeft: 40,
+ marginTop: ptToPixel(50),
+ marginBottom: ptToPixel(50),
+ marginRight: ptToPixel(40),
+ marginLeft: ptToPixel(40),
renderConfig: {
vertexAngle: 0,
centerAngle: 0,
diff --git a/examples/src/plugins/debugger/commands/operations/sidebar.operation.ts b/examples/src/plugins/debugger/commands/operations/sidebar.operation.ts
index 35d506b950..9a5bad77da 100644
--- a/examples/src/plugins/debugger/commands/operations/sidebar.operation.ts
+++ b/examples/src/plugins/debugger/commands/operations/sidebar.operation.ts
@@ -15,9 +15,10 @@
*/
import type { ICommand } from '@univerjs/core';
-import { CommandType } from '@univerjs/core';
-import { ISidebarService } from '@univerjs/ui';
+import { CommandType, IUniverInstanceService } from '@univerjs/core';
+import { IEditorService, ISidebarService } from '@univerjs/ui';
import type { IAccessor } from '@wendellhu/redi';
+import { TEST_EDITOR_CONTAINER_COMPONENT } from '../../views/test-editor/component-name';
export interface IUIComponentCommandParams {
value: string;
@@ -28,18 +29,30 @@ export const SidebarOperation: ICommand = {
type: CommandType.COMMAND,
handler: async (accessor: IAccessor, params: IUIComponentCommandParams) => {
const sidebarService = accessor.get(ISidebarService);
-
+ const editorService = accessor.get(IEditorService);
+ const univerInstanceService = accessor.get(IUniverInstanceService);
+ const unit = univerInstanceService.getCurrentUniverSheetInstance();
switch (params.value) {
case 'open':
+ editorService.setOperationSheetUnitId(unit.getUnitId());
+ editorService.setOperationSheetSubUnitId(unit.getActiveSheet().getSheetId());
sidebarService.open({
header: { title: 'debugger.sidebar.title' },
- children: { title: 'Sidebar Content' },
+ children: { title: 'Sidebar Content', label: TEST_EDITOR_CONTAINER_COMPONENT },
footer: { title: 'Sidebar Footer' },
+ onClose: () => {
+ editorService.setOperationSheetUnitId(null);
+ editorService.setOperationSheetSubUnitId(null);
+ editorService.changeEditorFocus();
+ },
});
break;
case 'close':
default:
+ editorService.setOperationSheetUnitId(null);
+ editorService.setOperationSheetSubUnitId(null);
+ editorService.changeEditorFocus();
sidebarService.close();
break;
}
diff --git a/examples/src/plugins/debugger/controllers/debugger.controller.ts b/examples/src/plugins/debugger/controllers/debugger.controller.ts
index 54eeb8b0c7..39ae54c6fb 100644
--- a/examples/src/plugins/debugger/controllers/debugger.controller.ts
+++ b/examples/src/plugins/debugger/controllers/debugger.controller.ts
@@ -15,7 +15,7 @@
*/
import { Disposable, ICommandService, ISnapshotPersistenceService, IUniverInstanceService } from '@univerjs/core';
-import { IMenuService } from '@univerjs/ui';
+import { ComponentManager, IMenuService } from '@univerjs/ui';
import { Inject, Injector } from '@wendellhu/redi';
import { ExportController, LocalSnapshotService, RecordController } from '../../local-save';
@@ -28,6 +28,8 @@ import { SaveSnapshotOptions } from '../commands/operations/save-snapshot.operat
import { SetEditable } from '../commands/operations/set.editable.operation';
import { SidebarOperation } from '../commands/operations/sidebar.operation';
import { ThemeOperation } from '../commands/operations/theme.operation';
+import { TestEditorContainer } from '../views/test-editor/TestTextEditor';
+import { TEST_EDITOR_CONTAINER_COMPONENT } from '../views/test-editor/component-name';
import {
ConfirmMenuItemFactory,
DialogMenuItemFactory,
@@ -45,11 +47,14 @@ export class DebuggerController extends Disposable {
@Inject(Injector) private readonly _injector: Injector,
@IMenuService private readonly _menuService: IMenuService,
@ICommandService private readonly _commandService: ICommandService,
- @Inject(IUniverInstanceService) private _univerInstanceService: IUniverInstanceService
+ @Inject(IUniverInstanceService) private _univerInstanceService: IUniverInstanceService,
+ @Inject(ComponentManager) private readonly _componentManager: ComponentManager
) {
super();
this._initializeContextMenu();
+ this._initCustomComponents();
+
[
LocaleOperation,
ThemeOperation,
@@ -82,4 +87,9 @@ export class DebuggerController extends Disposable {
this.disposeWithMe(this._menuService.addMenuItem(this._injector.invoke(factory)));
});
}
+
+ private _initCustomComponents(): void {
+ const componentManager = this._componentManager;
+ this.disposeWithMe(componentManager.register(TEST_EDITOR_CONTAINER_COMPONENT, TestEditorContainer));
+ }
}
diff --git a/examples/src/plugins/debugger/controllers/performance-monitor.controller.ts b/examples/src/plugins/debugger/controllers/performance-monitor.controller.ts
index c2505fa69c..22e72da777 100644
--- a/examples/src/plugins/debugger/controllers/performance-monitor.controller.ts
+++ b/examples/src/plugins/debugger/controllers/performance-monitor.controller.ts
@@ -15,7 +15,7 @@
*/
import { IUniverInstanceService, LifecycleStages, OnLifecycle, RxDisposable, UniverInstanceType } from '@univerjs/core';
-import { DocCanvasView } from '@univerjs/docs';
+import { DocCanvasView } from '@univerjs/docs-ui';
import { SheetCanvasView } from '@univerjs/sheets-ui';
import { Inject, Injector } from '@wendellhu/redi';
import { interval, takeUntil, throttle } from 'rxjs';
diff --git a/examples/src/plugins/debugger/views/test-editor/TestTextEditor.tsx b/examples/src/plugins/debugger/views/test-editor/TestTextEditor.tsx
new file mode 100644
index 0000000000..b0791340b4
--- /dev/null
+++ b/examples/src/plugins/debugger/views/test-editor/TestTextEditor.tsx
@@ -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 React from 'react';
+
+import { TextEditor } from '@univerjs/ui';
+
+const containerStyle: React.CSSProperties = {
+ position: 'absolute',
+ left: '10px',
+ top: '300px',
+ width: 'calc(100% - 20px)',
+ height: 'calc(100% - 300px)',
+};
+
+const editorStyle: React.CSSProperties = {
+ position: 'relative',
+ width: '100%',
+ height: '40px',
+ border: '1px solid #000',
+};
+
+/**
+ * Floating editor's container.
+ * @returns
+ */
+export const TestEditorContainer = () => {
+ return (
+ <div
+ style={containerStyle}
+ >
+ <TextEditor id="test-editor-1" style={editorStyle} canvasStyle={{ fontSize: 10 }} value="I found one cent on the roadside." />
+ <br></br>
+ <TextEditor id="test-editor-2" style={editorStyle} canvasStyle={{ fontSize: 12 }} />
+ <br></br>
+ <TextEditor id="test-editor-3" style={editorStyle} canvasStyle={{ fontSize: 14 }} />
+ <br></br>
+ <TextEditor id="test-editor-4" style={editorStyle} canvasStyle={{ fontSize: 18 }} />
+ </div>
+ );
+};
diff --git a/examples/src/plugins/debugger/views/test-editor/component-name.ts b/examples/src/plugins/debugger/views/test-editor/component-name.ts
new file mode 100644
index 0000000000..e44baea550
--- /dev/null
+++ b/examples/src/plugins/debugger/views/test-editor/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 TEST_EDITOR_CONTAINER_COMPONENT = 'TestEditorContainer';
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 99584f163c..9d3b21b080 100644
--- a/packages/core/src/docs/data-model/document-data-model.ts
+++ b/packages/core/src/docs/data-model/document-data-model.ts
@@ -23,6 +23,7 @@ import type {
IDocumentBody,
IDocumentData,
IDocumentRenderConfig,
+ IDocumentStyle,
} from '../../types/interfaces/i-document-data';
import type { IPaddingData } from '../../types/interfaces/i-style-data';
import { updateAttributeByDelete } from './apply-utils/delete-apply';
@@ -112,6 +113,17 @@ class DocumentDataModelSimple {
}
}
+ updateDocumentStyle(config: IDocumentStyle) {
+ if (this.snapshot.documentStyle == null) {
+ this.snapshot.documentStyle = config;
+ } else {
+ this.snapshot.documentStyle = {
+ ...this.snapshot.documentStyle,
+ ...config,
+ };
+ }
+ }
+
updateDocumentDataMargin(data: IPaddingData) {
const { t, l, b, r } = data;
const { documentStyle } = this.snapshot;
diff --git a/packages/core/src/services/lifecycle/lifecycle.ts b/packages/core/src/services/lifecycle/lifecycle.ts
index a7ce30da07..103173d301 100644
--- a/packages/core/src/services/lifecycle/lifecycle.ts
+++ b/packages/core/src/services/lifecycle/lifecycle.ts
@@ -19,7 +19,7 @@ import type { Ctor, DependencyIdentifier } from '@wendellhu/redi';
/**
* This enum defines multiple lifecycle stages in Univer SDK.
*/
-export const enum LifecycleStages {
+export enum LifecycleStages {
/**
* Register plugins to Univer.
*/
diff --git a/packages/docs-ui/src/controllers/doc-editor-bridge.controller.ts b/packages/docs-ui/src/controllers/doc-editor-bridge.controller.ts
new file mode 100644
index 0000000000..c4e27e605e
--- /dev/null
+++ b/packages/docs-ui/src/controllers/doc-editor-bridge.controller.ts
@@ -0,0 +1,184 @@
+/**
+ * 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, Nullable } from '@univerjs/core';
+import { Disposable, ICommandService, IUniverInstanceService, LifecycleStages, OnLifecycle } from '@univerjs/core';
+import { Inject } from '@wendellhu/redi';
+
+import { ITextSelectionRenderManager, ScrollBar } from '@univerjs/engine-render';
+import type { IRichTextEditingMutationParams } from '@univerjs/docs';
+import { CoverContentCommand, DocSkeletonManagerService, RichTextEditingMutation, VIEWPORT_KEY } from '@univerjs/docs';
+import { IEditorService, SetEditorResizeOperation } from '@univerjs/ui';
+
+@OnLifecycle(LifecycleStages.Rendered, DocEditorBridgeController)
+export class DocEditorBridgeController extends Disposable {
+ private _initialEditors = new Set<string>();
+
+ constructor(
+ @IUniverInstanceService private readonly _currentUniverService: IUniverInstanceService,
+ @Inject(DocSkeletonManagerService) private readonly _docSkeletonManagerService: DocSkeletonManagerService,
+ @IEditorService private readonly _editorService: IEditorService,
+ @ICommandService private readonly _commandService: ICommandService,
+ @ITextSelectionRenderManager private readonly _textSelectionRenderManager: ITextSelectionRenderManager
+
+ ) {
+ super();
+ this._initialize();
+ }
+
+ private _initialize() {
+ this._editorService.resize$.subscribe((unitId: string) => {
+ this._resize(unitId);
+ });
+
+ this._editorService.getAllEditor().forEach((editor) => {
+ const unitId = editor.editorUnitId;
+ if (this._initialEditors.has(unitId)) {
+ return;
+ }
+ this._initialEditors.add(unitId);
+ this._resize(unitId);
+ });
+
+ this._commandExecutedListener();
+
+ this._initialSetValue();
+
+ this._initialBlur();
+
+ this._initialFocus();
+ }
+
+ private _resize(unitId: Nullable<string>) {
+ if (unitId == null) {
+ return;
+ }
+
+ const editor = this._editorService.getEditor(unitId);
+
+ if (editor?.cancelDefaultResizeListener === true) {
+ return;
+ }
+
+ const skeleton = this._docSkeletonManagerService.getSkeletonByUnitId(unitId)?.skeleton;
+
+ const editorDataModel = this._currentUniverService.getUniverDocInstance(unitId);
+
+ if (editor == null || editor.render == null || skeleton == null || editorDataModel == null) {
+ return;
+ }
+
+ const { marginTop = 0, marginBottom = 0, marginLeft = 0, marginRight = 0 } = editorDataModel.getSnapshot().documentStyle;
+
+ const { scene, mainComponent } = editor.render;
+
+ let { actualHeight, actualWidth } = skeleton.getActualSize();
+
+ actualHeight += marginTop + marginBottom;
+
+ actualWidth += marginLeft + marginRight;
+
+ const { width, height } = editor.getBoundingClientRect();
+
+ const viewportMain = scene.getViewport(VIEWPORT_KEY.VIEW_MAIN);
+
+ let scrollBar = viewportMain?.getScrollBar() as Nullable<ScrollBar>;
+
+ const contentWidth = Math.max(actualWidth, width);
+
+ const contentHeight = Math.max(actualHeight, height);
+
+ scene.transformByState({
+ width: contentWidth,
+ height: contentHeight,
+ });
+
+ mainComponent?.resize(contentWidth, contentHeight);
+
+ if (editor.isSingle === false) {
+ if (actualHeight > height) {
+ if (scrollBar == null) {
+ viewportMain && new ScrollBar(viewportMain, { enableHorizontal: false, barSize: 8 });
+ } else {
+ viewportMain?.resetSizeAndScrollBar();
+ }
+ } else {
+ scrollBar = null;
+ viewportMain?.scrollTo({ x: 0, y: 0 });
+ viewportMain?.getScrollBar()?.dispose();
+ }
+ } else {
+ if (actualWidth > width) {
+ if (scrollBar == null) {
+ viewportMain && new ScrollBar(viewportMain, { barSize: 8, enableVertical: false });
+ } else {
+ viewportMain?.resetSizeAndScrollBar();
+ }
+ } else {
+ scrollBar = null;
+ viewportMain?.scrollTo({ x: 0, y: 0 });
+ viewportMain?.getScrollBar()?.dispose();
+ }
+ }
+ }
+
+ private _initialSetValue() {
+ this._editorService.setValue$.subscribe((param) => {
+ this._commandService.executeCommand(CoverContentCommand.id, {
+ unitId: param.editorUnitId,
+ body: param.body,
+ segmentId: null,
+ });
+ });
+ }
+
+ private _initialBlur() {
+ this._editorService.blur$.subscribe(() => {
+ this._textSelectionRenderManager.removeAllTextRanges();
+
+ this._textSelectionRenderManager.blur();
+ });
+ }
+
+ private _initialFocus() {
+ this._editorService.focus$.subscribe((textRange) => {
+ this._textSelectionRenderManager.removeAllTextRanges();
+ this._textSelectionRenderManager.addTextRanges([textRange]);
+ });
+ }
+
+ /**
+ * Listen to document edits to refresh the size of the normula editor.
+ */
+ private _commandExecutedListener() {
+ const updateCommandList = [RichTextEditingMutation.id, SetEditorResizeOperation.id];
+
+ this.disposeWithMe(
+ this._commandService.onCommandExecuted((command: ICommandInfo) => {
+ if (updateCommandList.includes(command.id)) {
+ const params = command.params as IRichTextEditingMutationParams;
+ const { unitId } = params;
+
+ if (this._editorService.isSheetEditor(unitId)) {
+ return;
+ }
+
+ this._resize(unitId);
+ }
+ })
+ );
+ }
+}
diff --git a/packages/docs/src/controllers/doc-render.controller.ts b/packages/docs-ui/src/controllers/doc-render.controller.ts
similarity index 74%
rename from packages/docs/src/controllers/doc-render.controller.ts
rename to packages/docs-ui/src/controllers/doc-render.controller.ts
index 17634d2bb7..2b6ba0b9ae 100644
--- a/packages/docs/src/controllers/doc-render.controller.ts
+++ b/packages/docs-ui/src/controllers/doc-render.controller.ts
@@ -14,30 +14,30 @@
* limitations under the License.
*/
-import type { ICommandInfo } from '@univerjs/core';
+import type { ICommandInfo, Nullable } from '@univerjs/core';
import {
- DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY,
- DOCS_NORMAL_EDITOR_UNIT_ID_KEY,
ICommandService,
LifecycleStages,
OnLifecycle,
- RxDisposable,
-} from '@univerjs/core';
+ RxDisposable } from '@univerjs/core';
import type { Documents, DocumentSkeleton, IRender } from '@univerjs/engine-render';
import { IRenderManagerService, PageLayoutType } from '@univerjs/engine-render';
import { Inject } from '@wendellhu/redi';
import { takeUntil } from 'rxjs';
-import type { IRichTextEditingMutationParams } from '../commands/mutations/core-editing.mutation';
-import { RichTextEditingMutation } from '../commands/mutations/core-editing.mutation';
-import { DocSkeletonManagerService } from '../services/doc-skeleton-manager.service';
+import { IEditorService } from '@univerjs/ui';
+import type { IDocSkeletonManagerParam, IRichTextEditingMutationParams } from '@univerjs/docs';
+import { DocSkeletonManagerService, RichTextEditingMutation } from '@univerjs/docs';
@OnLifecycle(LifecycleStages.Rendered, DocRenderController)
export class DocRenderController extends RxDisposable {
+ private _docRenderMap = new Set<string>();
+
constructor(
@Inject(DocSkeletonManagerService) private readonly _docSkeletonManagerService: DocSkeletonManagerService,
@IRenderManagerService private readonly _renderManagerService: IRenderManagerService,
- @ICommandService private readonly _commandService: ICommandService
+ @ICommandService private readonly _commandService: ICommandService,
+ @IEditorService private readonly _editorService: IEditorService
) {
super();
@@ -48,30 +48,35 @@ export class DocRenderController extends RxDisposable {
private _initialRenderRefresh() {
this._docSkeletonManagerService.currentSkeletonBefore$.pipe(takeUntil(this.dispose$)).subscribe((param) => {
- if (param == null) {
- return;
- }
+ this._create(param);
+ });
+ }
- const { skeleton: documentSkeleton, unitId } = param;
+ private _create(param: Nullable<IDocSkeletonManagerParam>) {
+ if (param == null) {
+ return;
+ }
- const currentRender = this._renderManagerService.getRenderById(unitId);
+ const { skeleton: documentSkeleton, unitId } = param;
- if (currentRender == null) {
- return;
- }
+ let currentRender = this._renderManagerService.getRenderById(unitId);
- const { mainComponent } = currentRender;
+ if (currentRender == null) {
+ this._renderManagerService.create(unitId);
+ currentRender = this._renderManagerService.getRenderById(unitId)!;
+ }
- const docsComponent = mainComponent as Documents;
+ const { mainComponent } = currentRender;
- docsComponent.changeSkeleton(documentSkeleton);
+ const docsComponent = mainComponent as Documents;
- this._recalculateSizeBySkeleton(currentRender, documentSkeleton);
- });
+ docsComponent.changeSkeleton(documentSkeleton);
+
+ this._recalculateSizeBySkeleton(currentRender, documentSkeleton);
}
private _recalculateSizeBySkeleton(currentRender: IRender, skeleton: DocumentSkeleton) {
- const { mainComponent, scene } = currentRender;
+ const { mainComponent, scene, unitId } = currentRender;
const docsComponent = mainComponent as Documents;
@@ -110,9 +115,7 @@ export class DocRenderController extends RxDisposable {
docsComponent.resize(width, height);
- const excludeUnitList = [DOCS_NORMAL_EDITOR_UNIT_ID_KEY, DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY];
-
- if (!excludeUnitList.includes(currentRender.unitId)) {
+ if (!this._editorService.isEditor(unitId)) {
scene.resize(width, height);
}
}
@@ -120,8 +123,6 @@ export class DocRenderController extends RxDisposable {
private _commandExecutedListener() {
const updateCommandList = [RichTextEditingMutation.id];
- const excludeUnitList = [DOCS_NORMAL_EDITOR_UNIT_ID_KEY, DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY];
-
this.disposeWithMe(
this._commandService.onCommandExecuted((command: ICommandInfo) => {
if (updateCommandList.includes(command.id)) {
@@ -144,7 +145,7 @@ export class DocRenderController extends RxDisposable {
skeleton.calculate();
- if (excludeUnitList.includes(unitId)) {
+ if (this._editorService.isEditor(unitId)) {
currentRender.mainComponent?.makeDirty();
return;
diff --git a/packages/docs-ui/src/controllers/doc-ui.controller.ts b/packages/docs-ui/src/controllers/doc-ui.controller.ts
index 78b35b7f09..5e862675b6 100644
--- a/packages/docs-ui/src/controllers/doc-ui.controller.ts
+++ b/packages/docs-ui/src/controllers/doc-ui.controller.ts
@@ -14,11 +14,12 @@
* limitations under the License.
*/
-import { Disposable, ICommandService, LifecycleStages, OnLifecycle } from '@univerjs/core';
+import { Disposable, IUniverInstanceService, LifecycleStages, OnLifecycle } from '@univerjs/core';
import type { IDesktopUIController, IMenuItemFactory } from '@univerjs/ui';
-import { ComponentManager, IMenuService, IShortcutService, IUIController } from '@univerjs/ui';
+import { ComponentManager, IEditorService, IMenuService, IUIController } from '@univerjs/ui';
import { Inject, Injector } from '@wendellhu/redi';
+import { connectInjector } from '@wendellhu/redi/react-bindings';
import { COLOR_PICKER_COMPONENT, ColorPicker } from '../components/color-picker';
import {
FONT_FAMILY_COMPONENT,
@@ -27,6 +28,7 @@ import {
FontFamilyItem,
} from '../components/font-family';
import { FONT_SIZE_COMPONENT, FontSize } from '../components/font-size';
+import { DocBackground } from '../views/doc-background/DocBackground';
import {
BoldMenuItemFactory,
BulletListMenuItemFactory,
@@ -47,10 +49,10 @@ export class DocUIController extends Disposable {
constructor(
@Inject(Injector) private readonly _injector: Injector,
@Inject(ComponentManager) private readonly _componentManager: ComponentManager,
- @ICommandService private readonly _commandService: ICommandService,
- @IShortcutService private readonly _shortcutService: IShortcutService,
+ @IEditorService private readonly _editorService: IEditorService,
@IMenuService private readonly _menuService: IMenuService,
- @IUIController private readonly _uiController: IDesktopUIController
+ @IUIController private readonly _uiController: IDesktopUIController,
+ @IUniverInstanceService private readonly _currentUniverService: IUniverInstanceService
) {
super();
@@ -89,5 +91,19 @@ export class DocUIController extends Disposable {
private _init(): void {
this._initCustomComponents();
this._initMenus();
+ this._initDocBackground();
+ }
+
+ private _initDocBackground() {
+ const firstDocUnitId = this._currentUniverService.getAllUniverDocsInstance()[0].getUnitId();
+ if (firstDocUnitId == null) {
+ return;
+ }
+ const embedded = this._editorService.isEditor(firstDocUnitId);
+ if (!embedded) {
+ this.disposeWithMe(
+ this._uiController.registerContentComponent(() => connectInjector(DocBackground, this._injector))
+ );
+ }
}
}
diff --git a/packages/docs/src/controllers/floating-object.controller.ts b/packages/docs-ui/src/controllers/floating-object.controller.ts
similarity index 92%
rename from packages/docs/src/controllers/floating-object.controller.ts
rename to packages/docs-ui/src/controllers/floating-object.controller.ts
index e24f2067e4..1e1bd639b0 100644
--- a/packages/docs/src/controllers/floating-object.controller.ts
+++ b/packages/docs-ui/src/controllers/floating-object.controller.ts
@@ -18,23 +18,19 @@ import type { ICommandInfo, IFloatingObjectManagerParam } from '@univerjs/core';
import {
DEFAULT_DOCUMENT_SUB_COMPONENT_ID,
Disposable,
- DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY,
- DOCS_NORMAL_EDITOR_UNIT_ID_KEY,
ICommandService,
IFloatingObjectManagerService,
IUniverInstanceService,
LifecycleStages,
OnLifecycle,
} 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';
-import type { IRichTextEditingMutationParams } from '../commands/mutations/core-editing.mutation';
-import { RichTextEditingMutation } from '../commands/mutations/core-editing.mutation';
-import { SetDocZoomRatioOperation } from '../commands/operations/set-doc-zoom-ratio.operation';
-import { DocSkeletonManagerService } from '../services/doc-skeleton-manager.service';
-
@OnLifecycle(LifecycleStages.Steady, FloatingObjectController)
export class FloatingObjectController extends Disposable {
private _liquid = new Liquid();
@@ -46,7 +42,8 @@ export class FloatingObjectController extends Disposable {
@IUniverInstanceService private readonly _currentUniverService: IUniverInstanceService,
@IRenderManagerService private readonly _renderManagerService: IRenderManagerService,
@ICommandService private readonly _commandService: ICommandService,
- @IFloatingObjectManagerService private readonly _floatingObjectManagerService: IFloatingObjectManagerService
+ @IFloatingObjectManagerService private readonly _floatingObjectManagerService: IFloatingObjectManagerService,
+ @IEditorService private readonly _editorService: IEditorService
) {
super();
@@ -136,8 +133,6 @@ export class FloatingObjectController extends Disposable {
private _commandExecutedListener() {
const updateCommandList = [RichTextEditingMutation.id, SetDocZoomRatioOperation.id];
- const excludeUnitList = [DOCS_NORMAL_EDITOR_UNIT_ID_KEY, DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY];
-
this.disposeWithMe(
this._commandService.onCommandExecuted((command: ICommandInfo) => {
if (updateCommandList.includes(command.id)) {
@@ -162,7 +157,7 @@ export class FloatingObjectController extends Disposable {
return;
}
- if (excludeUnitList.includes(unitId)) {
+ if (this._editorService.isEditor(unitId)) {
currentRender.mainComponent?.makeDirty();
return;
}
diff --git a/packages/docs/src/controllers/page-render.controller.ts b/packages/docs-ui/src/controllers/page-render.controller.ts
similarity index 87%
rename from packages/docs/src/controllers/page-render.controller.ts
rename to packages/docs-ui/src/controllers/page-render.controller.ts
index 74982d2743..ede70b92e3 100644
--- a/packages/docs/src/controllers/page-render.controller.ts
+++ b/packages/docs-ui/src/controllers/page-render.controller.ts
@@ -16,15 +16,13 @@
import {
Disposable,
- DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY,
- DOCS_NORMAL_EDITOR_UNIT_ID_KEY,
IUniverInstanceService,
LifecycleStages,
OnLifecycle,
} from '@univerjs/core';
import type { Documents, IPageRenderConfig } from '@univerjs/engine-render';
import { IRenderManagerService, Rect } from '@univerjs/engine-render';
-import { Inject } from '@wendellhu/redi';
+import { IEditorService } from '@univerjs/ui';
const PAGE_STROKE_COLOR = 'rgba(198, 198, 198, 1)';
@@ -34,7 +32,8 @@ const PAGE_FILL_COLOR = 'rgba(255, 255, 255, 1)';
export class PageRenderController extends Disposable {
constructor(
@IRenderManagerService private readonly _renderManagerService: IRenderManagerService,
- @Inject(IUniverInstanceService) private readonly _currentUniverService: IUniverInstanceService
+ @IEditorService private readonly _editorService: IEditorService,
+ @IUniverInstanceService private readonly _currentUniverService: IUniverInstanceService
) {
super();
@@ -53,12 +52,12 @@ export class PageRenderController extends Disposable {
return;
}
- if (this._currentUniverService.getUniverDocInstance(unitId) == null) {
+ const currentRender = this._renderManagerService.getRenderById(unitId);
+
+ if (this._editorService.isEditor(unitId) || this._currentUniverService.getUniverDocInstance(unitId) == null) {
return;
}
- const currentRender = this._renderManagerService.getRenderById(unitId);
-
if (currentRender == null) {
return;
}
@@ -70,7 +69,7 @@ export class PageRenderController extends Disposable {
const pageSize = docsComponent.getSkeleton()?.getPageSize();
docsComponent.onPageRenderObservable.add((config: IPageRenderConfig) => {
- if ([DOCS_NORMAL_EDITOR_UNIT_ID_KEY, DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY].includes(unitId)) {
+ if (this._editorService.isEditor(unitId)) {
return;
}
diff --git a/packages/docs/src/controllers/zoom.controller.ts b/packages/docs-ui/src/controllers/zoom.controller.ts
similarity index 89%
rename from packages/docs/src/controllers/zoom.controller.ts
rename to packages/docs-ui/src/controllers/zoom.controller.ts
index 6aff5fbfc2..79c1b62cb6 100644
--- a/packages/docs/src/controllers/zoom.controller.ts
+++ b/packages/docs-ui/src/controllers/zoom.controller.ts
@@ -17,26 +17,19 @@
import type { ICommandInfo } from '@univerjs/core';
import {
Disposable,
- DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY,
- DOCS_NORMAL_EDITOR_UNIT_ID_KEY,
ICommandService,
IUniverInstanceService,
LifecycleStages,
OnLifecycle,
toDisposable,
} from '@univerjs/core';
+import type { IDocObjectParam } from '@univerjs/docs';
+import { DocSkeletonManagerService, getDocObject, SetDocZoomRatioCommand, SetDocZoomRatioOperation, TextSelectionManagerService, VIEWPORT_KEY } from '@univerjs/docs';
import type { IWheelEvent } from '@univerjs/engine-render';
import { IRenderManagerService } from '@univerjs/engine-render';
+import { IEditorService } from '@univerjs/ui';
import { Inject } from '@wendellhu/redi';
-import type { IDocObjectParam } from '../basics/component-tools';
-import { getDocObject } from '../basics/component-tools';
-import { VIEWPORT_KEY } from '../basics/docs-view-key';
-import { SetDocZoomRatioCommand } from '../commands/commands/set-doc-zoom-ratio.command';
-import { SetDocZoomRatioOperation } from '../commands/operations/set-doc-zoom-ratio.operation';
-import { DocSkeletonManagerService } from '../services/doc-skeleton-manager.service';
-import { TextSelectionManagerService } from '../services/text-selection-manager.service';
-
interface ISetDocMutationParams {
unitId: string;
}
@@ -50,7 +43,8 @@ export class ZoomController extends Disposable {
@IUniverInstanceService private readonly _currentUniverService: IUniverInstanceService,
@ICommandService private readonly _commandService: ICommandService,
@IRenderManagerService private readonly _renderManagerService: IRenderManagerService,
- @Inject(TextSelectionManagerService) private readonly _textSelectionManagerService: TextSelectionManagerService
+ @Inject(TextSelectionManagerService) private readonly _textSelectionManagerService: TextSelectionManagerService,
+ @IEditorService private readonly _editorService: IEditorService
) {
super();
@@ -82,8 +76,7 @@ export class ZoomController extends Disposable {
}
if (
- this._initializedRender.has(unitId) ||
- [DOCS_NORMAL_EDITOR_UNIT_ID_KEY, DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY].includes(unitId)
+ this._initializedRender.has(unitId) || this._editorService.isEditor(unitId)
) {
return;
}
@@ -137,7 +130,7 @@ export class ZoomController extends Disposable {
private _skeletonListener() {
this.disposeWithMe(
toDisposable(
- this._docSkeletonManagerService.currentSkeletonBefore$.subscribe((param) => {
+ this._docSkeletonManagerService.currentSkeleton$.subscribe((param) => {
if (param == null) {
return;
}
diff --git a/packages/docs-ui/src/docs-ui-plugin.ts b/packages/docs-ui/src/docs-ui-plugin.ts
index adf629b23a..b0be093ca0 100644
--- a/packages/docs-ui/src/docs-ui-plugin.ts
+++ b/packages/docs-ui/src/docs-ui-plugin.ts
@@ -15,8 +15,6 @@
*/
import {
- DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY,
- DOCS_NORMAL_EDITOR_UNIT_ID_KEY,
ILogService,
IUniverInstanceService,
LocaleService,
@@ -27,7 +25,8 @@ import {
import type { Dependency } from '@wendellhu/redi';
import { Inject, Injector } from '@wendellhu/redi';
-import { IShortcutService } from '@univerjs/ui';
+import { IEditorService, IShortcutService } from '@univerjs/ui';
+
import {
MoveCursorDownShortcut,
MoveCursorLeftShortcut,
@@ -49,6 +48,12 @@ import { zhCN } from './locale';
import { BreakLineShortcut, DeleteLeftShortcut, DeleteRightShortcut } from './shortcuts/core-editing.shortcut';
import { DocClipboardService, IDocClipboardService } from './services/clipboard/clipboard.service';
import { DocClipboardController } from './controllers/clipboard.controller';
+import { DocEditorBridgeController } from './controllers/doc-editor-bridge.controller';
+import { DocRenderController } from './controllers/doc-render.controller';
+import { DocCanvasView } from './views/doc-canvas-view';
+import { FloatingObjectController } from './controllers/floating-object.controller';
+import { PageRenderController } from './controllers/page-render.controller';
+import { ZoomController } from './controllers/zoom.controller';
export class UniverDocsUIPlugin extends Plugin {
static override type = PluginType.Doc;
@@ -98,8 +103,14 @@ export class UniverDocsUIPlugin extends Plugin {
private _initDependencies(injector: Injector) {
const dependencies: Dependency[] = [
+ // Controller
[DocUIController],
[DocClipboardController],
+ [DocEditorBridgeController],
+ [DocRenderController],
+ [FloatingObjectController],
+ [PageRenderController],
+ [ZoomController],
[
// controllers
AppUIController,
@@ -113,6 +124,9 @@ export class UniverDocsUIPlugin extends Plugin {
useClass: DocClipboardService,
},
],
+
+ // Render views
+ [DocCanvasView],
];
dependencies.forEach((d) => {
@@ -122,12 +136,11 @@ export class UniverDocsUIPlugin extends Plugin {
private _markDocAsFocused() {
const currentService = this._injector.get(IUniverInstanceService);
-
+ const editorService = this._injector.get(IEditorService);
try {
const doc = currentService.getCurrentUniverDocInstance();
const id = doc.getUnitId();
-
- if (id !== DOCS_NORMAL_EDITOR_UNIT_ID_KEY && id !== DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY) {
+ if (!editorService.isEditor(id)) {
currentService.focusUniverInstance(doc.getUnitId());
}
} catch (err) {
diff --git a/packages/docs-ui/src/index.ts b/packages/docs-ui/src/index.ts
index d0bc47ad25..42e13a5401 100644
--- a/packages/docs-ui/src/index.ts
+++ b/packages/docs-ui/src/index.ts
@@ -17,3 +17,4 @@
export * from './basics';
export * from './docs-ui-plugin';
export { enUS, zhCN } from './locale';
+export { DocCanvasView } from './views/doc-canvas-view';
diff --git a/packages/docs-ui/src/services/clipboard/html-to-udm/utils.ts b/packages/docs-ui/src/services/clipboard/html-to-udm/utils.ts
index e5a2410154..853998a072 100644
--- a/packages/docs-ui/src/services/clipboard/html-to-udm/utils.ts
+++ b/packages/docs-ui/src/services/clipboard/html-to-udm/utils.ts
@@ -15,6 +15,7 @@
*/
import type { IParagraphStyle, Nullable } from '@univerjs/core';
+import { ptToPixel } from '@univerjs/engine-render';
// TODO: @JOCS, Complete other missing attributes that exist in IParagraphStyle
export function getParagraphStyle(el: HTMLElement): Nullable<IParagraphStyle> {
@@ -48,10 +49,3 @@ export function getParagraphStyle(el: HTMLElement): Nullable<IParagraphStyle> {
return Object.getOwnPropertyNames(paragraphStyle).length ? paragraphStyle : null;
}
-
-export function ptToPixel(pt: number) {
- // 1 pixel * 0.75 = 1 pt
- const PX_TO_PT_RATIO = 0.75;
-
- return pt / PX_TO_PT_RATIO;
-}
diff --git a/packages/docs-ui/src/views/doc-background/DocBackground.tsx b/packages/docs-ui/src/views/doc-background/DocBackground.tsx
new file mode 100644
index 0000000000..411817dd76
--- /dev/null
+++ b/packages/docs-ui/src/views/doc-background/DocBackground.tsx
@@ -0,0 +1,28 @@
+/**
+ * Copyright 2023-present DreamNum Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import React from 'react';
+
+import styles from './index.module.less';
+
+/**
+ * Doc standalone background
+ */
+export const DocBackground = () => {
+ return (
+ <div className={styles.docsUiCanvasBackground}></div>
+ );
+};
diff --git a/packages/docs-ui/src/views/doc-background/index.module.less b/packages/docs-ui/src/views/doc-background/index.module.less
new file mode 100644
index 0000000000..f9d6c50294
--- /dev/null
+++ b/packages/docs-ui/src/views/doc-background/index.module.less
@@ -0,0 +1,11 @@
+@size: 100%;
+
+.docs-ui-canvas-background {
+ position: relative;
+ width: @size;
+ height: @size;
+ background: rgb(var(--grey-50)); //rgb(233,238,242)
+ z-index: 1;
+ user-select: none;
+ pointer-events: none;
+}
diff --git a/packages/docs/src/views/doc-canvas-view.ts b/packages/docs-ui/src/views/doc-canvas-view.ts
similarity index 83%
rename from packages/docs/src/views/doc-canvas-view.ts
rename to packages/docs-ui/src/views/doc-canvas-view.ts
index 32911011c8..62b44ccc38 100644
--- a/packages/docs/src/views/doc-canvas-view.ts
+++ b/packages/docs-ui/src/views/doc-canvas-view.ts
@@ -16,28 +16,18 @@
import type { DocumentDataModel, EventState, Nullable } from '@univerjs/core';
import {
- DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY,
IConfigService,
IUniverInstanceService,
LifecycleStages,
OnLifecycle,
RxDisposable,
} from '@univerjs/core';
+import { DOCS_COMPONENT_DEFAULT_Z_INDEX, DOCS_COMPONENT_HEADER_LAYER_INDEX, DOCS_COMPONENT_MAIN_LAYER_INDEX, DOCS_VIEW_KEY, VIEWPORT_KEY } from '@univerjs/docs';
import type { IRender, IWheelEvent, RenderManagerService, Scene } from '@univerjs/engine-render';
import { Documents, EVENT_TYPE, IRenderManagerService, Layer, ScrollBar, Viewport } from '@univerjs/engine-render';
-import { Inject } from '@wendellhu/redi';
import { BehaviorSubject, takeUntil } from 'rxjs';
-import {
- DOCS_COMPONENT_DEFAULT_Z_INDEX,
- DOCS_COMPONENT_HEADER_LAYER_INDEX,
- DOCS_COMPONENT_MAIN_LAYER_INDEX,
- DOCS_VIEW_KEY,
- VIEWPORT_KEY,
-} from '../basics/docs-view-key';
-import { DocViewModelManagerService } from '../services/doc-view-model-manager.service';
-
-@OnLifecycle(LifecycleStages.Ready, DocCanvasView)
+@OnLifecycle(LifecycleStages.Starting, DocCanvasView)
export class DocCanvasView extends RxDisposable {
private _scene!: Scene;
@@ -52,27 +42,23 @@ export class DocCanvasView extends RxDisposable {
constructor(
@IRenderManagerService private readonly _renderManagerService: RenderManagerService,
@IConfigService private readonly _configService: IConfigService,
- @IUniverInstanceService private readonly _currentUniverService: IUniverInstanceService,
- @Inject(DocViewModelManagerService) private readonly _docViewModelManagerService: DocViewModelManagerService
+ @IUniverInstanceService private readonly _currentUniverService: IUniverInstanceService
) {
super();
this._initialize();
}
private _initialize() {
- this._currentUniverService.currentDoc$.pipe(takeUntil(this.dispose$)).subscribe((documentModel) => {
- if (documentModel == null) {
- return;
- }
-
- this._currentDocumentModel = documentModel;
+ this._renderManagerService.createRender$.pipe(takeUntil(this.dispose$)).subscribe((unitId) => {
+ this._create(unitId);
+ });
- const unitId = documentModel.getUnitId();
+ this._currentUniverService.currentDoc$.pipe(takeUntil(this.dispose$)).subscribe((documentModel) => {
+ this._create(documentModel?.getUnitId());
+ });
- if (!this._loadedMap.has(unitId)) {
- this._addNewRender();
- this._loadedMap.add(unitId);
- }
+ this._currentUniverService.getAllUniverDocsInstance().forEach((documentModel) => {
+ this._create(documentModel.getUnitId());
});
}
@@ -80,6 +66,25 @@ export class DocCanvasView extends RxDisposable {
this._fps$.complete();
}
+ private _create(unitId: Nullable<string>) {
+ if (unitId == null) {
+ return;
+ }
+
+ const model = this._currentUniverService.getUniverDocInstance(unitId);
+
+ if (model == null) {
+ return;
+ }
+
+ this._currentDocumentModel = model;
+
+ if (!this._loadedMap.has(unitId)) {
+ this._addNewRender();
+ this._loadedMap.add(unitId);
+ }
+ }
+
private _addNewRender() {
const documentModel = this._currentDocumentModel;
@@ -147,8 +152,8 @@ export class DocCanvasView extends RxDisposable {
});
const hasScroll = this._configService.getConfig('hasScroll') as Nullable<boolean>;
- // TODO: @JOCS, do not show scroll bar when initialize formula editor, any better way?
- if (hasScroll !== false && unitId !== DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY) {
+
+ if (hasScroll !== false) {
new ScrollBar(viewMain);
}
diff --git a/packages/docs/src/controllers/text-selection.controller.ts b/packages/docs/src/controllers/text-selection.controller.ts
index 4ae3db9860..b731b43198 100644
--- a/packages/docs/src/controllers/text-selection.controller.ts
+++ b/packages/docs/src/controllers/text-selection.controller.ts
@@ -14,8 +14,8 @@
* limitations under the License.
*/
-import type { ICommandInfo, Nullable, Observer } from '@univerjs/core';
-import { Disposable, ICommandService, IUniverInstanceService, LifecycleStages, OnLifecycle } from '@univerjs/core';
+import type { ICommandInfo, Nullable } from '@univerjs/core';
+import { Disposable, ICommandService, IUniverInstanceService, LifecycleStages, OnLifecycle, toDisposable } from '@univerjs/core';
import type { Documents, IMouseEvent, IPointerEvent } from '@univerjs/engine-render';
import { CURSOR_TYPE, IRenderManagerService, ITextSelectionRenderManager } from '@univerjs/engine-render';
import { Inject } from '@wendellhu/redi';
@@ -28,16 +28,6 @@ import { TextSelectionManagerService } from '../services/text-selection-manager.
@OnLifecycle(LifecycleStages.Rendered, TextSelectionController)
export class TextSelectionController extends Disposable {
- private _moveInObserver: Nullable<Observer<IPointerEvent | IMouseEvent>>;
-
- private _moveOutObserver: Nullable<Observer<IPointerEvent | IMouseEvent>>;
-
- private _downObserver: Nullable<Observer<IPointerEvent | IMouseEvent>>;
-
- private _dblClickObserver: Nullable<Observer<IPointerEvent | IMouseEvent>>;
-
- private _tripleClickObserver: Nullable<Observer<IPointerEvent | IMouseEvent>>;
-
private _loadedMap = new Set();
constructor(
@@ -51,44 +41,42 @@ export class TextSelectionController extends Disposable {
) {
super();
- this._renderManagerService.currentRender$.subscribe((unitId) => {
- if (unitId == null) {
- return;
- }
-
- if (this._currentUniverService.getUniverDocInstance(unitId) == null) {
- return;
- }
-
- if (!this._loadedMap.has(unitId)) {
- this._initialMain(unitId);
- this._loadedMap.add(unitId);
- }
- });
-
this._initialize();
}
private _initialize() {
+ this._init();
this._skeletonListener();
this._commandExecutedListener();
}
- override dispose(): void {
- this._renderManagerService.getRenderAll().forEach((docObject) => {
- const { mainComponent } = docObject;
- if (mainComponent == null) {
- return;
- }
-
- mainComponent.onPointerEnterObserver.remove(this._moveInObserver);
- mainComponent.onPointerLeaveObserver.remove(this._moveOutObserver);
- mainComponent.onPointerDownObserver.remove(this._downObserver);
- mainComponent.onDblclickObserver.remove(this._dblClickObserver);
- mainComponent.onTripleClickObserver.remove(this._tripleClickObserver);
+ private _init() {
+ this.disposeWithMe(
+ this._renderManagerService.currentRender$.subscribe((unitId) => {
+ this._create(unitId);
+ })
+ );
+
+ this._renderManagerService.getRenderAll().forEach((_, unitId) => {
+ this._create(unitId);
});
}
+ private _create(unitId: Nullable<string>) {
+ if (unitId == null) {
+ return;
+ }
+
+ if (this._currentUniverService.getUniverDocInstance(unitId) == null) {
+ return;
+ }
+
+ if (!this._loadedMap.has(unitId)) {
+ this._initialMain(unitId);
+ this._loadedMap.add(unitId);
+ }
+ }
+
private _initialMain(unitId: string) {
const docObject = this._getDocObjectById(unitId);
if (docObject == null) {
@@ -96,37 +84,56 @@ export class TextSelectionController extends Disposable {
}
const { document, scene } = docObject;
+ this.disposeWithMe(
+ toDisposable(
+ document.onPointerEnterObserver.add(() => {
+ document.cursor = CURSOR_TYPE.TEXT;
+ })
+ )
+ );
- this._moveInObserver = document.onPointerEnterObserver.add(() => {
- document.cursor = CURSOR_TYPE.TEXT;
- });
-
- this._moveOutObserver = document.onPointerLeaveObserver.add(() => {
- document.cursor = CURSOR_TYPE.DEFAULT;
- scene.resetCursor();
- });
+ this.disposeWithMe(
+ toDisposable(
+ document.onPointerLeaveObserver.add(() => {
+ document.cursor = CURSOR_TYPE.DEFAULT;
+ scene.resetCursor();
+ })
+ )
+ );
- this._downObserver = document?.onPointerDownObserver.add((evt: IPointerEvent | IMouseEvent, state) => {
- const currentDocInstance = this._currentUniverService.getCurrentUniverDocInstance();
+ this.disposeWithMe(
+ toDisposable(
+ document?.onPointerDownObserver.add((evt: IPointerEvent | IMouseEvent, state) => {
+ const currentDocInstance = this._currentUniverService.getCurrentUniverDocInstance();
- if (currentDocInstance.getUnitId() !== unitId) {
- this._currentUniverService.setCurrentUniverDocInstance(unitId);
- }
+ if (currentDocInstance.getUnitId() !== unitId) {
+ this._currentUniverService.setCurrentUniverDocInstance(unitId);
+ }
- this._textSelectionRenderManager.eventTrigger(evt);
+ this._textSelectionRenderManager.eventTrigger(evt);
- if (evt.button !== 2) {
- state.stopPropagation();
- }
- });
+ if (evt.button !== 2) {
+ state.stopPropagation();
+ }
+ })
+ )
+ );
- this._dblClickObserver = document?.onDblclickObserver.add((evt: IPointerEvent | IMouseEvent) => {
- this._textSelectionRenderManager.handleDblClick(evt);
- });
+ this.disposeWithMe(
+ toDisposable(
+ document?.onDblclickObserver.add((evt: IPointerEvent | IMouseEvent) => {
+ this._textSelectionRenderManager.handleDblClick(evt);
+ })
+ )
+ );
- this._tripleClickObserver = document?.onTripleClickObserver.add((evt: IPointerEvent | IMouseEvent) => {
- this._textSelectionRenderManager.handleTripleClick(evt);
- });
+ this.disposeWithMe(
+ toDisposable(
+ document?.onTripleClickObserver.add((evt: IPointerEvent | IMouseEvent) => {
+ this._textSelectionRenderManager.handleTripleClick(evt);
+ })
+ )
+ );
}
private _commandExecutedListener() {
@@ -152,27 +159,29 @@ export class TextSelectionController extends Disposable {
private _skeletonListener() {
// Change text selection runtime(skeleton, scene) and update text selection manager current selection.
- this._docSkeletonManagerService.currentSkeleton$.subscribe((param) => {
- if (param == null) {
- return;
- }
- const { unitId, skeleton } = param;
+ this.disposeWithMe(
+ this._docSkeletonManagerService.currentSkeleton$.subscribe((param) => {
+ if (param == null) {
+ return;
+ }
+ const { unitId, skeleton } = param;
- const currentRender = this._renderManagerService.getRenderById(unitId);
+ const currentRender = this._renderManagerService.getRenderById(unitId);
- if (currentRender == null) {
- return;
- }
+ if (currentRender == null) {
+ return;
+ }
- const { scene, mainComponent } = currentRender;
+ const { scene, mainComponent } = currentRender;
- this._textSelectionRenderManager.changeRuntime(skeleton, scene, mainComponent as Documents);
+ this._textSelectionRenderManager.changeRuntime(skeleton, scene, mainComponent as Documents);
- this._textSelectionManagerService.setCurrentSelectionNotRefresh({
- unitId,
- subUnitId: '',
- });
- });
+ this._textSelectionManagerService.setCurrentSelectionNotRefresh({
+ unitId,
+ subUnitId: '',
+ });
+ })
+ );
}
private _getDocObjectById(unitId: string) {
diff --git a/packages/docs/src/doc-plugin.ts b/packages/docs/src/doc-plugin.ts
index 70e43ca431..2088195692 100644
--- a/packages/docs/src/doc-plugin.ts
+++ b/packages/docs/src/doc-plugin.ts
@@ -50,20 +50,15 @@ import { MoveCursorOperation, MoveSelectionOperation } from './commands/operatio
import { SelectAllOperation } from './commands/operations/select-all.operation';
import { SetDocZoomRatioOperation } from './commands/operations/set-doc-zoom-ratio.operation';
import { SetTextSelectionsOperation } from './commands/operations/text-selection.operation';
-import { DocRenderController } from './controllers/doc-render.controller';
-import { FloatingObjectController } from './controllers/floating-object.controller';
import { IMEInputController } from './controllers/ime-input.controller';
import { InlineFormatController } from './controllers/inline-format.controller';
import { MoveCursorController } from './controllers/move-cursor.controller';
import { NormalInputController } from './controllers/normal-input.controller';
-import { PageRenderController } from './controllers/page-render.controller';
import { TextSelectionController } from './controllers/text-selection.controller';
-import { ZoomController } from './controllers/zoom.controller';
import { DocSkeletonManagerService } from './services/doc-skeleton-manager.service';
import { DocViewModelManagerService } from './services/doc-view-model-manager.service';
import { IMEInputManagerService } from './services/ime-input-manager.service';
import { TextSelectionManagerService } from './services/text-selection-manager.service';
-import { DocCanvasView } from './views/doc-canvas-view';
import { DocStateChangeManagerService } from './services/doc-state-change-manager.service';
export interface IUniverDocsConfig {
@@ -145,13 +140,6 @@ export class UniverDocsPlugin extends Plugin {
private _initializeDependencies(docInjector: Injector) {
(
[
- // [
- // CanvasView,
- // { useFactory: () => docInjector.createInstance(CanvasView, this._config.standalone ?? true) },
- // ], // FIXME: CanvasView shouldn't be a dependency of UniverDocs. Because it maybe created dynamically.
- //views
- [DocCanvasView],
-
// services
[DocSkeletonManagerService],
[DocViewModelManagerService],
@@ -166,15 +154,11 @@ export class UniverDocsPlugin extends Plugin {
[TextSelectionManagerService],
// controllers
- [DocRenderController],
- [PageRenderController],
[TextSelectionController],
[NormalInputController],
[IMEInputController],
[InlineFormatController],
[MoveCursorController],
- [ZoomController],
- [FloatingObjectController],
] as Dependency[]
).forEach((d) => docInjector.add(d));
}
diff --git a/packages/docs/src/index.ts b/packages/docs/src/index.ts
index 30a365c9bc..ceb0d5d151 100644
--- a/packages/docs/src/index.ts
+++ b/packages/docs/src/index.ts
@@ -53,11 +53,12 @@ export {
SetTextSelectionsOperation,
} from './commands/operations/text-selection.operation';
export { type IUniverDocsConfig, UniverDocsPlugin } from './doc-plugin';
-export { DocSkeletonManagerService } from './services/doc-skeleton-manager.service';
+export { DocSkeletonManagerService, type IDocSkeletonManagerParam } from './services/doc-skeleton-manager.service';
export { DocViewModelManagerService } from './services/doc-view-model-manager.service';
export { TextSelectionManagerService, serializeTextRange } from './services/text-selection-manager.service';
export { DocStateChangeManagerService, type IDocStateChangeParams } from './services/doc-state-change-manager.service';
export { IMEInputManagerService } from './services/ime-input-manager.service';
-export { DocCanvasView } from './views/doc-canvas-view';
export { SelectAllOperation } from './commands/operations/select-all.operation';
export { CutContentCommand, InnerPasteCommand } from './commands/commands/clipboard.inner.command';
+export { SetDocZoomRatioOperation } from './commands/operations/set-doc-zoom-ratio.operation';
+export { SetDocZoomRatioCommand } from './commands/commands/set-doc-zoom-ratio.command';
diff --git a/packages/docs/src/services/doc-skeleton-manager.service.ts b/packages/docs/src/services/doc-skeleton-manager.service.ts
index 2273753b32..189fd747e0 100644
--- a/packages/docs/src/services/doc-skeleton-manager.service.ts
+++ b/packages/docs/src/services/doc-skeleton-manager.service.ts
@@ -55,6 +55,16 @@ export class DocSkeletonManagerService extends RxDisposable {
}
private _initialize() {
+ this._init();
+ }
+
+ override dispose(): void {
+ this._currentSkeletonBefore$.complete();
+ this._currentSkeleton$.complete();
+ this._docSkeletonMap.clear();
+ }
+
+ private _init() {
this._docViewModelManagerService.currentDocViewModel$
.pipe(takeUntil(this.dispose$))
.subscribe((docViewModel) => {
@@ -64,18 +74,24 @@ export class DocSkeletonManagerService extends RxDisposable {
this._setCurrent(docViewModel);
});
- }
- override dispose(): void {
- this._currentSkeletonBefore$.complete();
- this._currentSkeleton$.complete();
- this._docSkeletonMap.clear();
+ this._docViewModelManagerService.getAllModel().forEach((docViewModel) => {
+ if (docViewModel == null) {
+ return;
+ }
+
+ this._setCurrent(docViewModel);
+ });
}
getCurrent(): Nullable<IDocSkeletonManagerParam> {
return this.getSkeletonByUnitId(this._currentSkeletonUnitId);
}
+ getAllSkeleton(): Map<string, IDocSkeletonManagerParam> {
+ return this._docSkeletonMap;
+ }
+
makeDirtyCurrent(state: boolean = true) {
this.makeDirty(this._currentSkeletonUnitId, state);
}
diff --git a/packages/docs/src/services/doc-view-model-manager.service.ts b/packages/docs/src/services/doc-view-model-manager.service.ts
index f74de7c9c4..614c9818f5 100644
--- a/packages/docs/src/services/doc-view-model-manager.service.ts
+++ b/packages/docs/src/services/doc-view-model-manager.service.ts
@@ -40,15 +40,7 @@ export class DocViewModelManagerService extends RxDisposable {
}
private _initialize() {
- this._currentUniverService.currentDoc$.pipe(takeUntil(this.dispose$)).subscribe((documentModel) => {
- if (documentModel == null) {
- return;
- }
-
- const unitId = documentModel.getUnitId();
- // Build the view model and notify the skeleton manager to create the skeleton.
- this._setCurrent(unitId);
- });
+ this._init();
}
override dispose(): void {
@@ -56,10 +48,34 @@ export class DocViewModelManagerService extends RxDisposable {
this._docViewModelMap.clear();
}
+ private _init() {
+ this._currentUniverService.currentDoc$.pipe(takeUntil(this.dispose$)).subscribe((documentModel) => {
+ this._create(documentModel);
+ });
+
+ this._currentUniverService.getAllUniverDocsInstance().forEach((documentModel) => {
+ this._create(documentModel);
+ });
+ }
+
+ private _create(documentModel: Nullable<DocumentDataModel>) {
+ if (documentModel == null) {
+ return;
+ }
+
+ const unitId = documentModel.getUnitId();
+ // Build the view model and notify the skeleton manager to create the skeleton.
+ this._setCurrent(unitId);
+ }
+
getCurrent() {
return this._docViewModelMap.get(this._currentViewModelUnitId);
}
+ getAllModel() {
+ return this._docViewModelMap;
+ }
+
getViewModel(unitId: string) {
return this._docViewModelMap.get(unitId)?.docViewModel;
}
diff --git a/packages/engine-render/src/basics/tools.ts b/packages/engine-render/src/basics/tools.ts
index c9cf94e5e8..f6188bf308 100644
--- a/packages/engine-render/src/basics/tools.ts
+++ b/packages/engine-render/src/basics/tools.ts
@@ -252,13 +252,17 @@ export function fixLineWidthByScale(num: number, scale: number) {
return Math.round(num * scale) / scale;
}
+export const UNIVER_GLOBAL_DEFAULT_FONT_SIZE = 11;
+
+export const UNIVER_GLOBAL_DEFAULT_FONT_FAMILY = 'Arial';
+
export function getFontStyleString(textStyle?: IStyleBase, localeService?: LocaleService) {
// 获取字体配置
// TODO: @jikkai @DR-Univer should read default font from configuration, not from locale service
- const defaultFont = 'Arial';
+ const defaultFont = UNIVER_GLOBAL_DEFAULT_FONT_FAMILY;
- const defaultFontSize = 11;
+ const defaultFontSize = UNIVER_GLOBAL_DEFAULT_FONT_SIZE;
if (!textStyle) {
const fontString = `${defaultFontSize}pt ${defaultFont}`;
@@ -707,3 +711,16 @@ export function getSizeForDom(dom: HTMLElement) {
height: pxToNum(height),
};
}
+
+/**
+ *1 pixel * 0.75 = 1 pt
+ */
+const PX_TO_PT_RATIO = 0.75;
+
+export function ptToPixel(pt: number) {
+ return pt / PX_TO_PT_RATIO;
+}
+
+export function pixelToPt(px: number) {
+ return px * PX_TO_PT_RATIO;
+}
diff --git a/packages/engine-render/src/canvas.ts b/packages/engine-render/src/canvas.ts
index 253d06ef7d..4d91bf5f44 100644
--- a/packages/engine-render/src/canvas.ts
+++ b/packages/engine-render/src/canvas.ts
@@ -76,16 +76,23 @@ export class Canvas {
this._canvasEle.style.position = 'absolute';
this._canvasEle.style.top = '0';
this._canvasEle.style.left = '0';
+ this._canvasEle.style.zIndex = '8';
// support focus
this._canvasEle.tabIndex = 1;
this._canvasEle.style.touchAction = 'none';
this._canvasEle.style.outline = '0';
+ const context = this._canvasEle.getContext('2d');
+
+ if (context == null) {
+ throw new Error('context is not support');
+ }
+
if (props.mode === CanvasRenderMode.Printing) {
- this._context = new UniverPrintingContext(this._canvasEle?.getContext('2d')!);
+ this._context = new UniverPrintingContext(context);
} else {
- this._context = new UniverRenderingContext(this._canvasEle?.getContext('2d')!);
+ this._context = new UniverRenderingContext(context);
}
this.setSize(props.width, props.height, props.pixelRatio);
diff --git a/packages/engine-render/src/components/docs/common/tools.ts b/packages/engine-render/src/components/docs/common/tools.ts
index 5afe22495f..9eb385361a 100644
--- a/packages/engine-render/src/components/docs/common/tools.ts
+++ b/packages/engine-render/src/components/docs/common/tools.ts
@@ -133,7 +133,7 @@ export function getNextDivide(curLine: IDocumentSkeletonLine, curDivide: IDocume
}
export function getLastRemainingDivide(curLine: IDocumentSkeletonLine) {
- // 除了divide之外,其他元素不会提前create
+ // Except for divide, the other elements will not be created in advance.
if (!curLine) {
return;
}
@@ -219,9 +219,6 @@ function isLineBlank(line?: IDocumentSkeletonLine) {
return true;
}
-// 重新计算图文混排的布局,每一个TR或者同层级处理函数都要调用这个方法
-export function reCalculateLineDivide() {}
-
export function getNumberUnitValue(unitValue: number | INumberUnit, benchMark: number) {
if (unitValue instanceof Object) {
const { v: value, u: unit } = unitValue;
@@ -235,7 +232,7 @@ export function getNumberUnitValue(unitValue: number | INumberUnit, benchMark: n
return unitValue;
}
-// 返回charSpaceApply,选择网格还是字体来计算一个tab的长度,一个tab代表1字符长度
+// Return charSpaceApply, choose between grid or font to calculate the length of a tab, where one tab represents a length of 1 character.
export function getCharSpaceApply(
charSpace: number = 0,
defaultTabStop: number,
@@ -245,10 +242,10 @@ export function getCharSpaceApply(
let charSpaceApply = 1;
if (validationGrid(gridType, snapToGrid)) {
- // 启用了char网格的情况下,defaultTabStop的参照物是charSpace
+ // When the character grid is enabled, the reference for defaultTabStop is charSpace.
charSpaceApply = charSpace;
}
- charSpaceApply *= defaultTabStop; // 乘以defaultTabStop设置的数值
+ charSpaceApply *= defaultTabStop; // Multiply it by the value set for defaultTabStop.
return charSpaceApply;
}
@@ -347,7 +344,7 @@ export function updateBlockIndex(pages: IDocumentSkeletonPage[], start: number =
maxLineAsc = Math.max(maxLineAsc, ba);
if (i === divideLength - 1) {
- // 宽度为Infinity时,最后一个divide也是Infinity,需要计算一个实际宽度。
+ // When the width is set to Infinity, the last divide should also be Infinity, and an actual width needs to be calculated.
actualWidth += span.width;
}
}
@@ -697,7 +694,8 @@ export function getFontCreateConfig(
) {
const { startIndex } = paragraphNode;
const textRun = bodyModel.getTextRun(index + startIndex) || { ts: {}, st: 0, ed: 0 };
- const { ts: textStyle = {}, st, ed } = textRun;
+ const { st, ed } = textRun;
+ let { ts: textStyle = {} } = textRun;
const cache = fontCreateConfigCache.getValue(st, ed);
if (cache) {
return cache;
@@ -719,6 +717,8 @@ export function getFontCreateConfig(
const { snapToGrid = BooleanNumber.TRUE } = paragraphStyle;
+ textStyle = { ...documentTextStyle, ...textStyle };
+
const fontStyle = getFontStyleString(textStyle, localeService);
const mixTextStyle: ITextStyle = {
diff --git a/packages/engine-render/src/components/docs/doc-skeleton.ts b/packages/engine-render/src/components/docs/doc-skeleton.ts
index e321c9ee73..dcf4373c66 100644
--- a/packages/engine-render/src/components/docs/doc-skeleton.ts
+++ b/packages/engine-render/src/components/docs/doc-skeleton.ts
@@ -504,9 +504,7 @@ export class DocumentSkeleton extends Skeleton {
gridType = GridType.LINES, // gridType
paragraphLineGapDefault = 0,
defaultTabStop = 10.5,
- textStyle = {
- fs: 14,
- },
+ textStyle = {},
renderConfig: global_renderConfig = {
horizontalAlign: HorizontalAlign.UNSPECIFIED,
verticalAlign: VerticalAlign.UNSPECIFIED,
@@ -680,7 +678,7 @@ export class DocumentSkeleton extends Skeleton {
}
}
- // 一页存在多个section的情况,仅在SectionType.CONTINUOUS的情况下出现
+ // 一页存在多个 section 的情况,仅在 SectionType.CONTINUOUS 的情况下出现
private _addNewSectionByContinuous(
curSkeletonPage: IDocumentSkeletonPage,
columnProperties: ISectionColumnProperties[],
diff --git a/packages/engine-render/src/components/docs/document.ts b/packages/engine-render/src/components/docs/document.ts
index 1ed6b6610c..768dabb4f9 100644
--- a/packages/engine-render/src/components/docs/document.ts
+++ b/packages/engine-render/src/components/docs/document.ts
@@ -102,11 +102,23 @@ export class Documents extends DocComponent {
}
setConfig(config?: IDocumentsConfig) {
- this.pageMarginLeft = config?.pageMarginLeft || 17;
+ if (config?.pageMarginLeft != null) {
+ this.pageMarginLeft = config?.pageMarginLeft;
+ } else {
+ this.pageMarginLeft = 17;
+ }
- this.pageMarginTop = config?.pageMarginTop || 14;
+ if (config?.pageMarginTop != null) {
+ this.pageMarginTop = config?.pageMarginTop;
+ } else {
+ this.pageMarginTop = 14;
+ }
- this.pageLayoutType = config?.pageLayoutType || PageLayoutType.VERTICAL;
+ if (config?.pageLayoutType != null) {
+ this.pageLayoutType = config?.pageLayoutType;
+ } else {
+ this.pageLayoutType = PageLayoutType.VERTICAL;
+ }
}
getOffsetConfig(): IDocumentOffsetConfig {
diff --git a/packages/engine-render/src/components/docs/text-selection-render-manager.ts b/packages/engine-render/src/components/docs/text-selection-render-manager.ts
index f9a959b2bb..d885ba0ebd 100644
--- a/packages/engine-render/src/components/docs/text-selection-render-manager.ts
+++ b/packages/engine-render/src/components/docs/text-selection-render-manager.ts
@@ -18,7 +18,7 @@ import type { Nullable, Observer } from '@univerjs/core';
import { DataStreamTreeTokenType, ILogService, RxDisposable } from '@univerjs/core';
import { createIdentifier } from '@wendellhu/redi';
import type { Observable } from 'rxjs';
-import { BehaviorSubject, Subject } from 'rxjs';
+import { BehaviorSubject, fromEvent, Subject } from 'rxjs';
import { CURSOR_TYPE } from '../../basics/const';
import type { IDocumentSkeletonSpan } from '../../basics/i-document-skeleton-cached';
@@ -131,6 +131,8 @@ export interface ITextSelectionRenderManager {
readonly onCompositionend$: Observable<Nullable<IEditorInputConfig>>;
readonly onSelectionStart$: Observable<Nullable<INodePosition>>;
readonly onPaste$: Observable<Nullable<IEditorInputConfig>>;
+ readonly onFocus$: Observable<Nullable<IEditorInputConfig>>;
+ readonly onBlur$: Observable<Nullable<IEditorInputConfig>>;
readonly textSelectionInner$: Observable<Nullable<ITextSelectionInnerParam>>;
__getEditorContainer(): HTMLElement;
@@ -206,6 +208,12 @@ export class TextSelectionRenderManager extends RxDisposable implements ITextSel
private readonly _textSelectionInner$ = new BehaviorSubject<Nullable<ITextSelectionInnerParam>>(null);
readonly textSelectionInner$ = this._textSelectionInner$.asObservable();
+ private readonly _onFocus$ = new Subject<Nullable<IEditorInputConfig>>();
+ readonly onFocus$ = this._onFocus$.asObservable();
+
+ private readonly _onBlur$ = new Subject<Nullable<IEditorInputConfig>>();
+ readonly onBlur$ = this._onBlur$.asObservable();
+
private _container!: HTMLDivElement;
private _inputParent!: HTMLDivElement;
@@ -932,6 +940,8 @@ export class TextSelectionRenderManager extends RxDisposable implements ITextSel
this.deactivate();
this._interactTextRange(activeRangeInstance);
+
+ this._scene?.getEngine()?.setRemainCapture();
}
private _attachScrollEvent(viewport: Nullable<Viewport>) {
@@ -998,55 +1008,83 @@ export class TextSelectionRenderManager extends RxDisposable implements ITextSel
// FIXME: listeners here are not correctly disposed
private _initInputEvents() {
- this._input.addEventListener('keydown', (e) => {
- if (this._isIMEInputApply) {
- return;
- }
-
- this._eventHandle(e, (config) => {
- this._onKeydown$.next(config);
- });
- });
-
- this._input.addEventListener('input', (e) => {
- if (this._isIMEInputApply) {
- return;
- }
-
- this._eventHandle(e, (config) => {
- this._onInputBefore$.next(config);
- this._onInput$.next(config);
- });
- });
-
- this._input.addEventListener('compositionstart', (e) => {
- this._isIMEInputApply = true;
-
- this._eventHandle(e, (config) => {
- this._onCompositionstart$.next(config);
- });
- });
-
- this._input.addEventListener('compositionend', (e) => {
- this._isIMEInputApply = false;
+ this.disposeWithMe(
+ fromEvent(this._input, 'keydown').subscribe((e) => {
+ if (this._isIMEInputApply) {
+ return;
+ }
- this._eventHandle(e, (config) => {
- this._onCompositionend$.next(config);
- });
- });
+ this._eventHandle(e, (config) => {
+ this._onKeydown$.next(config);
+ });
+ })
+ );
- this._input.addEventListener('compositionupdate', (e) => {
- this._eventHandle(e, (config) => {
- this._onInputBefore$.next(config);
- this._onCompositionupdate$.next(config);
- });
- });
+ this.disposeWithMe(
+ fromEvent(this._input, 'input').subscribe((e) => {
+ if (this._isIMEInputApply) {
+ return;
+ }
- this._input.addEventListener('paste', (e) => {
- this._eventHandle(e, (config) => {
- this._onPaste$.next(config);
- });
- });
+ this._eventHandle(e, (config) => {
+ this._onInputBefore$.next(config);
+ this._onInput$.next(config);
+ });
+ })
+ );
+
+ this.disposeWithMe(
+ fromEvent(this._input, 'compositionstart').subscribe((e) => {
+ this._isIMEInputApply = true;
+
+ this._eventHandle(e, (config) => {
+ this._onCompositionstart$.next(config);
+ });
+ })
+ );
+
+ this.disposeWithMe(
+ fromEvent(this._input, 'compositionend').subscribe((e) => {
+ this._isIMEInputApply = false;
+
+ this._eventHandle(e, (config) => {
+ this._onCompositionend$.next(config);
+ });
+ })
+ );
+
+ this.disposeWithMe(
+ fromEvent(this._input, 'compositionupdate').subscribe((e) => {
+ this._eventHandle(e, (config) => {
+ this._onInputBefore$.next(config);
+ this._onCompositionupdate$.next(config);
+ });
+ })
+ );
+
+ this.disposeWithMe(
+ fromEvent(this._input, 'paste').subscribe((e) => {
+ this._eventHandle(e, (config) => {
+ this._onPaste$.next(config);
+ });
+ })
+ );
+
+ this.disposeWithMe(
+ fromEvent(this._input, 'focus').subscribe((e) => {
+ this._eventHandle(e, (config) => {
+ this._onFocus$.next(config);
+ });
+ })
+ );
+
+ this.disposeWithMe(
+ fromEvent(this._input, 'blur').subscribe((e) => {
+ this._eventHandle(e, (config) => {
+ this._onBlur$.next(config);
+ });
+ })
+ );
}
private _eventHandle(e: Event | CompositionEvent | KeyboardEvent, func: (config: IEditorInputConfig) => void) {
diff --git a/packages/engine-render/src/render-manager.service.ts b/packages/engine-render/src/render-manager.service.ts
index d5e5732770..77dd7bdbbe 100644
--- a/packages/engine-render/src/render-manager.service.ts
+++ b/packages/engine-render/src/render-manager.service.ts
@@ -29,6 +29,7 @@ import { SceneViewer } from './scene-viewer';
export interface IRenderManagerService {
currentRender$: Observable<Nullable<string>>;
+ createRender$: Observable<Nullable<string>>;
dispose(): void;
// createRenderWithNewEngine(unitId: string): IRenderManagerService;
createRenderWithParent(unitId: string, parentUnitId: string): IRender;
@@ -36,10 +37,12 @@ export interface IRenderManagerService {
addItem(unitId: string, item: IRender): void;
removeItem(unitId: string): void;
setCurrent(unitId: string): void;
- getCurrent(): Nullable<IRender>;
getRenderById(unitId: string): Nullable<IRender>;
getRenderAll(): Map<string, IRender>;
defaultEngine: Engine;
+ create(unitId: Nullable<string>): void;
+ getCurrent(): Nullable<IRender>;
+ getFirst(): Nullable<IRender>;
}
export type RenderComponentType = SheetComponent | DocComponent | Slide | BaseObject;
@@ -58,17 +61,22 @@ const DEFAULT_SCENE_SIZE = { width: 1500, height: 1000 };
const SCENE_NAMESPACE = '_UNIVER_SCENE_';
export class RenderManagerService implements IRenderManagerService {
- private _defaultEngine = new Engine();
+ private _defaultEngine!: Engine;
private _currentUnitId: string = '';
private _renderMap: Map<string, IRender> = new Map();
private readonly _currentRender$ = new BehaviorSubject<Nullable<string>>(this._currentUnitId);
-
readonly currentRender$ = this._currentRender$.asObservable();
+ private readonly _createRender$ = new BehaviorSubject<Nullable<string>>(this._currentUnitId);
+ readonly createRender$ = this._createRender$.asObservable();
+
get defaultEngine() {
+ if (!this._defaultEngine) {
+ this._defaultEngine = new Engine();
+ }
return this._defaultEngine;
}
@@ -102,6 +110,10 @@ export class RenderManagerService implements IRenderManagerService {
return current;
}
+ create(unitId: Nullable<string>) {
+ this._createRender$.next(unitId);
+ }
+
createRender(unitId: string): IRender {
const engine = new Engine();
@@ -160,8 +172,12 @@ export class RenderManagerService implements IRenderManagerService {
this._currentRender$.next(unitId);
}
- getCurrent(): Nullable<IRender> {
- return this.getRenderById(this._currentUnitId);
+ getCurrent() {
+ return this._renderMap.get(this._currentUnitId);
+ }
+
+ getFirst() {
+ return [...this.getRenderAll().values()][0];
}
getRenderById(unitId: string): Nullable<IRender> {
diff --git a/packages/engine-render/src/shape/scroll-bar.ts b/packages/engine-render/src/shape/scroll-bar.ts
index d3606b268a..7b0f5f30fb 100644
--- a/packages/engine-render/src/shape/scroll-bar.ts
+++ b/packages/engine-render/src/shape/scroll-bar.ts
@@ -370,6 +370,7 @@ export class ScrollBar extends BaseScrollBar {
y: e.offsetY - this._lastY,
});
this._lastY = e.offsetY;
+ mainScene.getEngine()?.setRemainCapture();
});
this._verticalPointerUpObserver = mainScene.onPointerUpObserver.add((evt: unknown, state: EventState) => {
const e = evt as IPointerEvent | IMouseEvent;
@@ -449,6 +450,7 @@ export class ScrollBar extends BaseScrollBar {
x: e.offsetX - this._lastX,
});
this._lastX = e.offsetX;
+ mainScene.getEngine()?.setRemainCapture();
});
this._horizonPointerUpObserver = mainScene.onPointerUpObserver.add((evt: unknown, state: EventState) => {
const e = evt as IPointerEvent | IMouseEvent;
diff --git a/packages/sheets-formula/src/commands/operations/__tests__/create-command-test-bed.ts b/packages/sheets-formula/src/commands/operations/__tests__/create-command-test-bed.ts
index f7b36c72ee..921e8bf90a 100644
--- a/packages/sheets-formula/src/commands/operations/__tests__/create-command-test-bed.ts
+++ b/packages/sheets-formula/src/commands/operations/__tests__/create-command-test-bed.ts
@@ -20,8 +20,9 @@ import { LexerTreeBuilder } from '@univerjs/engine-formula';
import { SelectionManagerService } from '@univerjs/sheets';
import type { Dependency } from '@wendellhu/redi';
import { Inject, Injector } from '@wendellhu/redi';
-
-import { FormulaInputService, IFormulaInputService } from '../../../services/formula-input.service';
+import { EditorService, IEditorService } from '@univerjs/ui';
+import { IRenderManagerService, RenderManagerService } from '@univerjs/engine-render';
+import { FormulaPromptService, IFormulaPromptService } from '../../../services/prompt.service';
const TEST_WORKBOOK_DATA_DEMO: IWorkbookData = {
id: 'test',
@@ -68,7 +69,9 @@ export function createCommandTestBed(workbookConfig?: IWorkbookData, dependencie
override onStarting(injector: Injector): void {
injector.add([SelectionManagerService]);
injector.add([LexerTreeBuilder]);
- injector.add([IFormulaInputService, { useClass: FormulaInputService }]);
+ injector.add([IFormulaPromptService, { useClass: FormulaPromptService }]);
+ injector.add([IEditorService, { useClass: EditorService }]);
+ injector.add([IRenderManagerService, { useClass: RenderManagerService }]);
dependencies?.forEach((d) => injector.add(d));
}
diff --git a/packages/sheets-formula/src/commands/operations/__tests__/insert-function.operation.spec.ts b/packages/sheets-formula/src/commands/operations/__tests__/insert-function.operation.spec.ts
index a36fd9d8a1..d29fd8a668 100644
--- a/packages/sheets-formula/src/commands/operations/__tests__/insert-function.operation.spec.ts
+++ b/packages/sheets-formula/src/commands/operations/__tests__/insert-function.operation.spec.ts
@@ -21,6 +21,7 @@ import {
SelectionManagerService,
SetRangeValuesCommand,
SetRangeValuesMutation,
+ SetSelectionsOperation,
} from '@univerjs/sheets';
import type { Injector } from '@wendellhu/redi';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
@@ -50,6 +51,7 @@ describe('Test insert function operation', () => {
commandService.registerCommand(InsertFunctionCommand);
commandService.registerCommand(SetRangeValuesCommand);
commandService.registerCommand(SetRangeValuesMutation);
+ commandService.registerCommand(SetSelectionsOperation);
});
afterEach(() => {
diff --git a/packages/sheets-formula/src/commands/operations/insert-function.operation.ts b/packages/sheets-formula/src/commands/operations/insert-function.operation.ts
index 4020db3cf6..5a146e8c03 100644
--- a/packages/sheets-formula/src/commands/operations/insert-function.operation.ts
+++ b/packages/sheets-formula/src/commands/operations/insert-function.operation.ts
@@ -34,7 +34,7 @@ import {
} from '@univerjs/sheets';
import type { IAccessor } from '@wendellhu/redi';
-import { IFormulaInputService } from '../../services/formula-input.service';
+import { IEditorService } from '@univerjs/ui';
import type { IInsertFunction } from '../commands/insert-function.command';
import { InsertFunctionCommand } from '../commands/insert-function.command';
@@ -50,7 +50,7 @@ export const InsertFunctionOperation: ICommand = {
type: CommandType.OPERATION,
handler: async (accessor: IAccessor, params: IInsertFunctionOperationParams) => {
const selectionManagerService = accessor.get(SelectionManagerService);
- const formulaInputService = accessor.get(IFormulaInputService);
+ const editorService = accessor.get(IEditorService);
const currentSelections = selectionManagerService.getSelections();
if (!currentSelections || !currentSelections.length) {
return false;
@@ -155,7 +155,7 @@ export const InsertFunctionOperation: ICommand = {
// TODO@DR-Univer: Maybe setTimeout can be removed
setTimeout(() => {
// edit cell
- formulaInputService.inputFormula(`=${value}(${editFormulaRangeString}`);
+ editorService.setFormula(`=${value}(${editFormulaRangeString}`);
}, 0);
}
diff --git a/packages/sheets-formula/src/controllers/formula-input.controller.ts b/packages/sheets-formula/src/controllers/formula-input.controller.ts
deleted file mode 100644
index 7b09e5bb6b..0000000000
--- a/packages/sheets-formula/src/controllers/formula-input.controller.ts
+++ /dev/null
@@ -1,242 +0,0 @@
-/**
- * Copyright 2023-present DreamNum Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-import type { ICommandInfo } from '@univerjs/core';
-import {
- AbsoluteRefType,
- Disposable,
- ICommandService,
- LifecycleStages,
- OnLifecycle,
- toDisposable,
-} from '@univerjs/core';
-import { TextSelectionManagerService } from '@univerjs/docs';
-import {
- deserializeRangeWithSheet,
- LexerTreeBuilder,
- matchToken,
- sequenceNodeType,
- serializeRange,
-} from '@univerjs/engine-formula';
-import { DeviceInputEventType, IRenderManagerService, ITextSelectionRenderManager } from '@univerjs/engine-render';
-import type { EditorBridgeService } from '@univerjs/sheets-ui';
-import { getEditorObject, IEditorBridgeService } from '@univerjs/sheets-ui';
-import { KeyCode } from '@univerjs/ui';
-import { Inject } from '@wendellhu/redi';
-
-import { ReferenceAbsoluteOperation } from '../commands/operations/reference-absolute.operation';
-import { IFormulaInputService } from '../services/formula-input.service';
-
-@OnLifecycle(LifecycleStages.Steady, FormulaInputController)
-export class FormulaInputController extends Disposable {
- private _userCursorMove: boolean = false;
-
- constructor(
- @ICommandService private readonly _commandService: ICommandService,
- @ITextSelectionRenderManager private readonly _textSelectionRenderManager: ITextSelectionRenderManager,
- @Inject(IEditorBridgeService) private readonly _editorBridgeService: EditorBridgeService,
- @Inject(LexerTreeBuilder) private readonly _lexerTreeBuilder: LexerTreeBuilder,
- @IRenderManagerService private readonly _renderManagerService: IRenderManagerService,
- @IFormulaInputService private readonly _formulaInputService: IFormulaInputService,
- @Inject(TextSelectionManagerService) private readonly _textSelectionManagerService: TextSelectionManagerService
- ) {
- super();
-
- this._initialize();
- }
-
- private _initialize(): void {
- this._commandExecutedListener();
-
- this._initialEditorInputChange();
-
- this._userMouseListener();
-
- this._inputFormulaListener();
- }
-
- private _initialEditorInputChange() {
- this.disposeWithMe(
- toDisposable(
- this._textSelectionRenderManager.onInputBefore$.subscribe((param) => {
- const e = param?.event as KeyboardEvent;
- if (e == null) {
- return;
- }
- if (e.which !== KeyCode.F4) {
- this._userCursorMove = false;
- }
- })
- )
- );
- }
-
- private _userMouseListener() {
- const editorObject = this._getEditorObject();
-
- if (editorObject == null) {
- return;
- }
-
- const { document: documentComponent } = editorObject;
- this.disposeWithMe(
- toDisposable(
- documentComponent.onPointerDownObserver.add(() => {
- this._userCursorMove = true;
- })
- )
- );
- }
-
- private _inputFormulaListener() {
- this.disposeWithMe(
- toDisposable(
- this._formulaInputService.inputFormula$.subscribe((formulaString) => {
- const visibleState = this._editorBridgeService.isVisible();
- if (visibleState.visible === false) {
- this._editorBridgeService.changeVisible({
- visible: true,
- eventType: DeviceInputEventType.Dblclick,
- });
- }
-
- const lastSequenceNodes = this._lexerTreeBuilder.sequenceNodesBuilder(formulaString) || [];
-
- this._formulaInputService.setSequenceNodes(lastSequenceNodes);
-
- this._formulaInputService.syncToEditor(formulaString.length - 1);
- })
- )
- );
- }
-
- private _changeRefString() {
- const activeRange = this._textSelectionManagerService.getActiveRange();
-
- if (activeRange == null) {
- return;
- }
-
- const { startOffset } = activeRange;
-
- const strIndex = startOffset - 2;
-
- const nodeIndex = this._formulaInputService.getCurrentSequenceNodeIndex(strIndex);
-
- const node = this._formulaInputService.getCurrentSequenceNodeByIndex(nodeIndex);
-
- if (node == null || typeof node === 'string' || node.nodeType !== sequenceNodeType.REFERENCE) {
- return;
- }
-
- const tokenArray = node.token.split('!');
-
- let token = node.token;
-
- if (tokenArray.length > 1) {
- token = tokenArray[tokenArray.length - 1];
- }
-
- let unitIDAndSheetName = '';
-
- for (let i = 0, len = tokenArray.length; i < len - 1; i++) {
- unitIDAndSheetName += tokenArray[i];
- }
-
- let finalToken = token;
- if (token.indexOf(matchToken.COLON) > -1) {
- if (!this._userCursorMove) {
- finalToken = this._changeRangeRef(token);
- } else {
- const refStringSplit = token.split(matchToken.COLON);
- const prefix = refStringSplit[0];
- const suffix = refStringSplit[1];
- const relativeIndex = strIndex - node.startIndex;
-
- if (relativeIndex <= prefix.length) {
- finalToken = this._changeSingleRef(prefix) + matchToken.COLON + suffix;
- } else {
- finalToken = prefix + matchToken.COLON + this._changeSingleRef(suffix);
- }
- }
- } else {
- finalToken = this._changeSingleRef(token);
- }
-
- finalToken = unitIDAndSheetName + finalToken;
-
- const difference = finalToken.length - node.token.length;
-
- this._formulaInputService.updateSequenceRef(nodeIndex, finalToken);
-
- this._formulaInputService.syncToEditor(strIndex + difference + 1);
- }
-
- private _changeRangeRef(token: string) {
- const range = deserializeRangeWithSheet(token).range;
- let resultToken = '';
- if (range.startAbsoluteRefType === AbsoluteRefType.NONE || range.startAbsoluteRefType == null) {
- range.startAbsoluteRefType = AbsoluteRefType.ALL;
- range.endAbsoluteRefType = AbsoluteRefType.ALL;
- } else {
- range.startAbsoluteRefType = AbsoluteRefType.NONE;
- range.endAbsoluteRefType = AbsoluteRefType.NONE;
- }
- resultToken = serializeRange(range);
- return resultToken;
- }
-
- private _changeSingleRef(token: string) {
- const range = deserializeRangeWithSheet(token).range;
- const type = range.startAbsoluteRefType;
- let resultToken = '';
- if (type === AbsoluteRefType.NONE || type == null) {
- range.startAbsoluteRefType = AbsoluteRefType.ALL;
- range.endAbsoluteRefType = AbsoluteRefType.ALL;
- } else if (type === AbsoluteRefType.ALL) {
- range.startAbsoluteRefType = AbsoluteRefType.ROW;
- range.endAbsoluteRefType = AbsoluteRefType.ROW;
- } else if (type === AbsoluteRefType.ROW) {
- range.startAbsoluteRefType = AbsoluteRefType.COLUMN;
- range.endAbsoluteRefType = AbsoluteRefType.COLUMN;
- } else {
- range.startAbsoluteRefType = AbsoluteRefType.NONE;
- range.endAbsoluteRefType = AbsoluteRefType.NONE;
- }
-
- resultToken = serializeRange(range);
- return resultToken;
- }
-
- private _commandExecutedListener() {
- // Listen to document edits to refresh the size of the editor.
- const updateCommandList = [ReferenceAbsoluteOperation.id];
-
- this.disposeWithMe(
- this._commandService.onCommandExecuted((command: ICommandInfo) => {
- if (!updateCommandList.includes(command.id)) {
- return;
- }
-
- this._changeRefString();
- })
- );
- }
-
- private _getEditorObject() {
- return getEditorObject(this._editorBridgeService.getCurrentEditorId(), this._renderManagerService);
- }
-}
diff --git a/packages/sheets-formula/src/controllers/prompt.controller.ts b/packages/sheets-formula/src/controllers/prompt.controller.ts
index 30d509ea31..e1ee991c36 100644
--- a/packages/sheets-formula/src/controllers/prompt.controller.ts
+++ b/packages/sheets-formula/src/controllers/prompt.controller.ts
@@ -49,6 +49,7 @@ import {
} from '@univerjs/docs';
import type { IAbsoluteRefTypeForRange, ISequenceNode } from '@univerjs/engine-formula';
import {
+ compareToken,
deserializeRangeWithSheet,
generateStringWithSequence,
getAbsoluteRefTypeWitString,
@@ -57,6 +58,7 @@ import {
matchToken,
normalizeSheetName,
sequenceNodeType,
+ serializeRange,
serializeRangeToRefString,
} from '@univerjs/engine-formula';
import {
@@ -81,10 +83,9 @@ import {
ISelectionRenderService,
JumpOver,
MoveSelectionCommand,
- SetEditorResizeOperation,
SheetSkeletonManagerService,
} from '@univerjs/sheets-ui';
-import { IContextMenuService, KeyCode, MetaKeys } from '@univerjs/ui';
+import { IContextMenuService, IEditorService, KeyCode, MetaKeys, SetEditorResizeOperation } from '@univerjs/ui';
import { Inject } from '@wendellhu/redi';
import type { ISelectEditorFormulaOperationParam } from '../commands/operations/editor-formula.operation';
@@ -94,8 +95,8 @@ import { SearchFunctionOperation } from '../commands/operations/search-function.
import { META_KEY_CTRL_AND_SHIFT } from '../common/prompt';
import { FORMULA_REF_SELECTION_PLUGIN_NAME, getFormulaRefSelectionStyle } from '../common/selection';
import { IDescriptionService } from '../services/description.service';
-import { IFormulaInputService } from '../services/formula-input.service';
import { IFormulaPromptService } from '../services/prompt.service';
+import { ReferenceAbsoluteOperation } from '../commands/operations/reference-absolute.operation';
interface IRefSelection {
refIndex: number;
@@ -118,6 +119,8 @@ enum InputPanelState {
mouse,
}
+const sheetEditorUnitIds = [DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY, DOCS_NORMAL_EDITOR_UNIT_ID_KEY];
+
@OnLifecycle(LifecycleStages.Steady, PromptController)
export class PromptController extends Disposable {
private _formulaRefColors: string[] = [];
@@ -130,10 +133,6 @@ export class PromptController extends Disposable {
private _currentInsertRefStringIndex: number = -1;
- private _currentUnitId: Nullable<string>;
-
- private _currentSheetId: Nullable<string>;
-
private _arrowMoveActionState: ArrowMoveAction = ArrowMoveAction.InitialState;
private _isSelectionMovingRefSelections: IRefSelection[] = [];
@@ -146,6 +145,12 @@ export class PromptController extends Disposable {
private _inputPanelState: InputPanelState = InputPanelState.InitialState;
+ private _userCursorMove: boolean = false;
+
+ private _previousEditorUnitId: Nullable<string>;
+
+ private _executeBlurSetTimeout: number | NodeJS.Timeout = -1;
+
constructor(
@ICommandService private readonly _commandService: ICommandService,
@IContextService private readonly _contextService: IContextService,
@@ -161,9 +166,9 @@ export class PromptController extends Disposable {
@Inject(ISelectionRenderService) private readonly _selectionRenderService: ISelectionRenderService,
@Inject(IDescriptionService) private readonly _descriptionService: IDescriptionService,
@Inject(TextSelectionManagerService) private readonly _textSelectionManagerService: TextSelectionManagerService,
- @IFormulaInputService private readonly _formulaInputService: IFormulaInputService,
@Inject(DocViewModelManagerService) private readonly _docViewModelManagerService: DocViewModelManagerService,
- @IContextMenuService private readonly _contextMenuService: IContextMenuService
+ @IContextMenuService private readonly _contextMenuService: IContextMenuService,
+ @IEditorService private readonly _editorService: IEditorService
) {
super();
@@ -180,9 +185,13 @@ export class PromptController extends Disposable {
this._previousInsertRefStringIndex = null;
- this._currentUnitId = null;
+ // this._currentUnitId = null;
- this._currentSheetId = null;
+ // this._currentSheetId = null;
+
+ this._editorService.setOperationSheetUnitId(null);
+
+ this._editorService.setOperationSheetSubUnitId(null);
this._isSelectionMovingRefSelections = [];
@@ -210,7 +219,11 @@ export class PromptController extends Disposable {
this._cursorStateListener();
- this._syncEditorListener();
+ this._userMouseListener();
+
+ this._inputFormulaListener();
+
+ this._initialChangeEditor();
}
private _initialFormulaTheme() {
@@ -240,17 +253,19 @@ export class PromptController extends Disposable {
this.disposeWithMe(
toDisposable(
this._textSelectionManagerService.textSelection$.subscribe((params) => {
- if (
- this._editorBridgeService.isVisible().visible === false ||
- this._formulaInputService.isSelectionMoving() ||
- params?.unitId == null
+ if (params?.unitId == null
) {
return;
}
- const INCLUDE_LIST = [DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY, DOCS_NORMAL_EDITOR_UNIT_ID_KEY];
+ if (
+ (this._editorService.isSheetEditor(params.unitId) && this._editorBridgeService.isVisible().visible === false) ||
+ this._formulaPromptService.isSelectionMoving()
+ ) {
+ return;
+ }
- if (!INCLUDE_LIST.includes(params.unitId)) {
+ if (!this._editorService.isEditor(params.unitId)) {
return;
}
@@ -264,7 +279,7 @@ export class PromptController extends Disposable {
this._switchSelectionPlugin();
- if (this._formulaInputService.isLockedSelectionChange()) {
+ if (this._formulaPromptService.isLockedSelectionChange()) {
return;
}
@@ -282,88 +297,130 @@ export class PromptController extends Disposable {
private _initialEditorInputChange() {
this.disposeWithMe(
- toDisposable(
- this._textSelectionRenderManager.onInputBefore$.subscribe((param) => {
- this._previousSequenceNodes = null;
- this._previousInsertRefStringIndex = null;
+ this._textSelectionRenderManager.onInputBefore$.subscribe((param) => {
+ this._previousSequenceNodes = null;
+ this._previousInsertRefStringIndex = null;
- this._selectionRenderService.enableSkipRemainLast();
+ this._selectionRenderService.enableSkipRemainLast();
- const e = param?.event as KeyboardEvent;
- if (e == null) {
- return;
- }
- if (
- ![KeyCode.ARROW_DOWN, KeyCode.ARROW_UP, KeyCode.ARROW_LEFT, KeyCode.ARROW_RIGHT].includes(
- e.which
- )
- ) {
- if (this._arrowMoveActionState !== ArrowMoveAction.moveCursor) {
- this._arrowMoveActionState = ArrowMoveAction.moveRefReady;
- }
- this._inputPanelState = InputPanelState.keyNormal;
- } else {
- this._inputPanelState = InputPanelState.keyArrow;
+ const e = param?.event as KeyboardEvent;
+
+ if (e == null) {
+ return;
+ }
+
+ if (
+ ![KeyCode.ARROW_DOWN, KeyCode.ARROW_UP, KeyCode.ARROW_LEFT, KeyCode.ARROW_RIGHT].includes(
+ e.which
+ )
+ ) {
+ if (this._arrowMoveActionState !== ArrowMoveAction.moveCursor) {
+ this._arrowMoveActionState = ArrowMoveAction.moveRefReady;
}
- })
- )
+
+ this._inputPanelState = InputPanelState.keyNormal;
+ } else {
+ this._inputPanelState = InputPanelState.keyArrow;
+ }
+
+ if (e.which !== KeyCode.F4) {
+ this._userCursorMove = false;
+ }
+ })
);
}
private _initialExitEditor() {
this.disposeWithMe(
- toDisposable(
- this._editorBridgeService.afterVisible$.subscribe((visibleParam) => {
- if (visibleParam.visible === true) {
- const { unitId, sheetId } = this._getCurrentUnitIdAndSheetId();
-
- if (this._currentUnitId == null) {
- this._currentUnitId = unitId;
- }
+ this._editorBridgeService.afterVisible$.subscribe((visibleParam) => {
+ if (visibleParam.visible === true) {
+ const { unitId, sheetId } = this._getCurrentUnitIdAndSheetId();
- if (this._currentSheetId == null) {
- this._currentSheetId = sheetId;
- }
+ if (this._editorService.getOperationSheetUnitId() == null) {
+ this._editorService.setOperationSheetUnitId(unitId);
+ }
- return;
+ if (this._editorService.getOperationSheetSubUnitId() == null) {
+ this._editorService.setOperationSheetSubUnitId(sheetId);
}
- /**
- * Switching the selection of PluginName causes a refresh.
- * Here, a delay is added to prevent the loss of content when pressing enter.
- */
+ return;
+ }
- const current = this._selectionManagerService.getCurrent();
+ this._changeEditor();
+ })
+ );
+ }
- this._insertSelections = [];
+ private _initialChangeEditor() {
+ this.disposeWithMe(
+ this._currentUniverService.currentDoc$.subscribe((documentDataModel) => {
+ if (documentDataModel == null) {
+ return;
+ }
- if (current?.pluginName === NORMAL_SELECTION_PLUGIN_NAME) {
- this._disableForceKeepVisible();
- /**
- * In the standard selection mode, the pivot table and page fields of the formula selection need to be cleared.
- */
- this._currentUnitId = null;
- this._currentSheetId = null;
- return;
- }
+ const editorId = documentDataModel.getUnitId();
- this._selectionManagerService.clear();
- this._selectionManagerService.changePlugin(NORMAL_SELECTION_PLUGIN_NAME);
+ if (!this._editorService.isEditor(editorId) || this._previousEditorUnitId === editorId) {
+ return;
+ }
- this._updateEditorModel('\r\n', []);
+ if (!this._editorService.isSheetEditor(editorId)) {
+ this._changeEditor(editorId);
+ this._previousEditorUnitId = editorId;
+ }
+ })
+ );
- this._contextService.setContextValue(FOCUSING_EDITOR_INPUT_FORMULA, false);
+ this.disposeWithMe(
+ this._editorService.changeEditorFocus$.subscribe(() => {
+ this._changeEditor();
+ })
+ );
+ }
- this._disableForceKeepVisible();
+ private _changeEditor(editorId: Nullable<string>) {
+ /**
+ * Switching the selection of PluginName causes a refresh.
+ * Here, a delay is added to prevent the loss of content when pressing enter.
+ */
+ const current = this._selectionManagerService.getCurrent();
- this._selectionRenderService.resetStyle();
+ this._insertSelections = [];
- this._resetTemp();
+ if (current?.pluginName === NORMAL_SELECTION_PLUGIN_NAME) {
+ this._disableForceKeepVisible();
+ /**
+ * In the standard selection mode, the pivot table and page fields of the formula selection need to be cleared.
+ */
- this._hideFunctionPanel();
- })
- )
- );
+ const { unitId, sheetId } = this._getCurrentUnitIdAndSheetId();
+
+ this._editorService.setOperationSheetUnitId(unitId);
+
+ this._editorService.setOperationSheetSubUnitId(sheetId);
+
+ return;
+ }
+
+ this._selectionManagerService.clear();
+
+ if (editorId && this._editorService.isSheetEditor(editorId)) {
+ this._selectionManagerService.changePlugin(NORMAL_SELECTION_PLUGIN_NAME);
+ this._updateEditorModel('\r\n', []);
+ } else {
+ this._selectionManagerService.changePluginNoRefresh(NORMAL_SELECTION_PLUGIN_NAME);
+ }
+
+ this._contextService.setContextValue(FOCUSING_EDITOR_INPUT_FORMULA, false);
+
+ this._disableForceKeepVisible();
+
+ this._selectionRenderService.resetStyle();
+
+ this._resetTemp();
+
+ this._hideFunctionPanel();
}
private _initialRefSelectionUpdateEvent() {
@@ -377,7 +434,7 @@ export class PromptController extends Disposable {
const current = this._selectionManagerService.getCurrent();
- this._formulaInputService.disableSelectionMoving();
+ this._formulaPromptService.disableSelectionMoving();
if (current?.pluginName !== FORMULA_REF_SELECTION_PLUGIN_NAME) {
return;
@@ -408,7 +465,7 @@ export class PromptController extends Disposable {
disposableCollection.add(
toDisposable(
controlSelection.selectionMoved$.subscribe(() => {
- this._formulaInputService.disableLockedSelectionChange();
+ this._formulaPromptService.disableLockedSelectionChange();
})
)
);
@@ -416,7 +473,7 @@ export class PromptController extends Disposable {
disposableCollection.add(
toDisposable(
controlSelection.selectionScaled$.subscribe(() => {
- this._formulaInputService.disableLockedSelectionChange();
+ this._formulaPromptService.disableLockedSelectionChange();
})
)
);
@@ -426,27 +483,16 @@ export class PromptController extends Disposable {
);
}
- private _syncEditorListener() {
- this.disposeWithMe(
- toDisposable(
- this._formulaInputService.syncToEditor$.subscribe((param) => {
- const { sequences, textSelectionOffset } = param;
- this._syncToEditor(sequences, textSelectionOffset);
- })
- )
- );
- }
-
private _selectionChanging(selectionWithStyles: ISelectionWithStyle[], isSync: boolean = false) {
if (selectionWithStyles.length === 0) {
return;
}
- if (!this._formulaInputService.isLockedSelectionInsert()) {
+ if (!this._formulaPromptService.isLockedSelectionInsert()) {
return;
}
- this._formulaInputService.enableSelectionMoving();
+ this._formulaPromptService.enableSelectionMoving();
this._inertControlSelection(selectionWithStyles);
@@ -497,9 +543,9 @@ export class PromptController extends Disposable {
const { startOffset } = activeRange;
- const lastSequenceNodes = this._formulaInputService.getSequenceNodes();
+ const lastSequenceNodes = this._formulaPromptService.getSequenceNodes();
- const nodeIndex = this._formulaInputService.getCurrentSequenceNodeIndex(startOffset - 2);
+ const nodeIndex = this._formulaPromptService.getCurrentSequenceNodeIndex(startOffset - 2);
const node = lastSequenceNodes[nodeIndex];
@@ -559,7 +605,7 @@ export class PromptController extends Disposable {
const { startOffset } = activeRange;
- const currentSequenceNode = this._formulaInputService.getCurrentSequenceNode(startOffset - 2);
+ const currentSequenceNode = this._formulaPromptService.getCurrentSequenceNode(startOffset - 2);
if (currentSequenceNode == null) {
this._hideFunctionPanel();
@@ -654,7 +700,7 @@ export class PromptController extends Disposable {
this._contextMenuService.disable();
- this._formulaInputService.enableLockedSelectionInsert();
+ this._formulaPromptService.enableLockedSelectionInsert();
this._selectionRenderService.enableRemainLast();
@@ -669,7 +715,6 @@ export class PromptController extends Disposable {
/**
* Determine whether the character is a token keyword for the formula engine.
* @param char
- * @returns
*/
private _matchRefDrawToken(char: string) {
return (
@@ -715,7 +760,7 @@ export class PromptController extends Disposable {
this._contextMenuService.enable();
- this._formulaInputService.disableLockedSelectionInsert();
+ this._formulaPromptService.disableLockedSelectionInsert();
this._currentInsertRefStringIndex = -1;
this._selectionRenderService.disableRemainLast();
@@ -726,17 +771,11 @@ export class PromptController extends Disposable {
}
private _getCurrentBody() {
- const editorUnitId = this._editorBridgeService.getCurrentEditorId();
- if (editorUnitId == null) {
- return;
- }
- const documentModel = this._currentUniverService.getUniverDocInstance(editorUnitId);
+ const documentModel = this._currentUniverService.getCurrentUniverDocInstance();
return documentModel?.snapshot?.body;
}
- private _getFormulaAndCellEditorBody() {
- const unitIds = [DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY, DOCS_NORMAL_EDITOR_UNIT_ID_KEY];
-
+ private _getFormulaAndCellEditorBody(unitIds: string[]) {
return unitIds.map((unitId) => {
const dataModel = this._currentUniverService.getUniverDocInstance(unitId);
@@ -744,12 +783,23 @@ export class PromptController extends Disposable {
});
}
+ private _editorModelUnitIds() {
+ const currentDocumentDataModel = this._currentUniverService.getCurrentUniverDocInstance();
+
+ const unitId = currentDocumentDataModel.getUnitId();
+
+ if (this._editorService.isEditor(unitId) && !this._editorService.isSheetEditor(unitId)) {
+ return [unitId];
+ }
+
+ return sheetEditorUnitIds;
+ }
+
/**
* Detect whether the user's input content is a formula. If it is a formula,
* serialize the current input content into a sequenceNode;
* otherwise, close the formula panel.
* @param currentInputValue The text content entered by the user in the editor.
- * @returns
*/
private _contextSwitch(currentInputValue: string) {
if (isFormulaString(currentInputValue)) {
@@ -759,7 +809,7 @@ export class PromptController extends Disposable {
this._lexerTreeBuilder.sequenceNodesBuilder(currentInputValue.replace(/\r/g, '').replace(/\n/g, '')) ||
[];
- this._formulaInputService.setSequenceNodes(lastSequenceNodes);
+ this._formulaPromptService.setSequenceNodes(lastSequenceNodes);
const activeRange = this._textSelectionManagerService.getActiveRange();
@@ -773,13 +823,13 @@ export class PromptController extends Disposable {
} else {
this._contextService.setContextValue(FOCUSING_EDITOR_INPUT_FORMULA, false);
- this._formulaInputService.disableLockedSelectionChange();
+ this._formulaPromptService.disableLockedSelectionChange();
- this._formulaInputService.disableLockedSelectionInsert();
+ this._formulaPromptService.disableLockedSelectionInsert();
// this._lastSequenceNodes = [];
- this._formulaInputService.clearSequenceNodes();
+ this._formulaPromptService.clearSequenceNodes();
this._hideFunctionPanel();
}
@@ -829,8 +879,11 @@ export class PromptController extends Disposable {
// dataStream.replace(/\r/g, '').replace(/\n/g, '')
// );
- const sequenceNodes = this._formulaInputService.getSequenceNodes();
- const bodyList = this._getFormulaAndCellEditorBody().filter((b) => !!b);
+ const sequenceNodes = this._formulaPromptService.getSequenceNodes();
+
+ const unitIds = this._editorModelUnitIds();
+
+ const bodyList = this._getFormulaAndCellEditorBody(unitIds).filter((b) => !!b);
this._selectionManagerService.clear();
@@ -844,14 +897,13 @@ export class PromptController extends Disposable {
this._refreshSelectionForReference(refSelections);
}
- this._refreshFormulaAndCellEditor();
+ this._refreshFormulaAndCellEditor(unitIds);
}
/**
* :
* #
* Generate styles for formula text, highlighting references, text, numbers, and arrays.
- * @returns
*/
private _buildTextRuns(sequenceNodes: Array<ISequenceNode | string>) {
const textRuns: ITextRun[] = [];
@@ -919,7 +971,6 @@ export class PromptController extends Disposable {
/**
* Draw the referenced selection text based on the style and token.
* @param refSelections
- * @returns
*/
private _refreshSelectionForReference(refSelections: IRefSelection[]) {
const { unitId, sheetId } = this._getCurrentUnitIdAndSheetId();
@@ -1077,8 +1128,7 @@ export class PromptController extends Disposable {
/**
* Convert the selection range to a ref string for the formula engine, such as A1:B1
- * @param range
- * @returns
+ * @param currentSelection
*/
private _getRefString(currentSelection: ISelectionWithStyle) {
const { unitId, sheetId } = this._getCurrentUnitIdAndSheetId();
@@ -1086,13 +1136,13 @@ export class PromptController extends Disposable {
let refUnitId = '';
let refSheetName = '';
- if (unitId === this._currentUnitId) {
+ if (unitId === this._editorService.getOperationSheetUnitId()) {
refUnitId = '';
} else {
refUnitId = unitId;
}
- if (sheetId === this._currentSheetId) {
+ if (sheetId === this._editorService.getOperationSheetSubUnitId()) {
refSheetName = '';
} else {
refSheetName = this._getSheetNameById(unitId, sheetId);
@@ -1147,11 +1197,11 @@ export class PromptController extends Disposable {
* Restore the sequenceNode generated by the lexer to the text in the editor, and set the cursor position.
* @param sequenceNodes
* @param textSelectionOffset
- * @returns
*/
- private async _syncToEditor(
+ private _syncToEditor(
sequenceNodes: Array<string | ISequenceNode>,
textSelectionOffset: number,
+ editorUnitId?: string,
canUndo: boolean = true
) {
const dataStream = generateStringWithSequence(sequenceNodes);
@@ -1170,11 +1220,15 @@ export class PromptController extends Disposable {
this._currentInsertRefStringIndex = textSelectionOffset;
- await this._fitEditorSize();
+ if (editorUnitId == null) {
+ editorUnitId = this._currentUniverService.getCurrentUniverDocInstance().getUnitId();
+ }
+
+ this._fitEditorSize();
if (canUndo) {
this._commandService.executeCommand(ReplaceContentCommand.id, {
- unitId: this._editorBridgeService.getCurrentEditorId(),
+ unitId: editorUnitId,
body: {
dataStream: `=${dataStream}`,
textRuns,
@@ -1211,13 +1265,14 @@ export class PromptController extends Disposable {
this._setRemainCapture();
}
- private async _fitEditorSize() {
- const editorUnitId = this._editorBridgeService.getCurrentEditorId();
- if (editorUnitId == null) {
+ private _fitEditorSize() {
+ const currentDocumentDataModel = this._currentUniverService.getCurrentUniverDocInstance();
+ const editorUnitId = currentDocumentDataModel.getUnitId();
+ if (this._editorService.isEditor(editorUnitId) && !this._editorService.isSheetEditor(editorUnitId)) {
return;
}
- await this._commandService.syncExecuteCommand(SetEditorResizeOperation.id, {
+ this._commandService.executeCommand(SetEditorResizeOperation.id, {
unitId: editorUnitId,
});
}
@@ -1226,15 +1281,18 @@ export class PromptController extends Disposable {
* Update the editor's model value to facilitate formula updates.
* @param dataStream
* @param textRuns
- * @returns
*/
private _updateEditorModel(dataStream: string, textRuns: ITextRun[]) {
- const editorUnitId = this._editorBridgeService.getCurrentEditorId();
- if (editorUnitId == null) {
+ const documentDataModel = this._currentUniverService.getCurrentUniverDocInstance();
+
+ const editorUnitId = documentDataModel.getUnitId();
+
+ if (!this._editorService.isEditor(editorUnitId)) {
return;
}
- const documentDataModel = this._currentUniverService.getUniverDocInstance(editorUnitId);
+
const docViewModel = this._docViewModelManagerService.getViewModel(editorUnitId);
+
if (docViewModel == null || documentDataModel == null) {
return;
}
@@ -1257,7 +1315,7 @@ export class PromptController extends Disposable {
private _inertControlSelectionReplace(currentSelection: ISelectionWithStyle) {
if (this._previousSequenceNodes == null) {
- this._previousSequenceNodes = this._formulaInputService.getSequenceNodes();
+ this._previousSequenceNodes = this._formulaPromptService.getSequenceNodes();
}
if (this._previousInsertRefStringIndex == null) {
@@ -1272,9 +1330,9 @@ export class PromptController extends Disposable {
const refString = this._getRefString(currentSelection);
- this._formulaInputService.setSequenceNodes(insertNodes);
+ this._formulaPromptService.setSequenceNodes(insertNodes);
- this._formulaInputService.insertSequenceRef(this._previousInsertRefStringIndex, refString);
+ this._formulaPromptService.insertSequenceRef(this._previousInsertRefStringIndex, refString);
this._syncToEditor(insertNodes, this._previousInsertRefStringIndex + refString.length);
@@ -1304,7 +1362,7 @@ export class PromptController extends Disposable {
this._inertControlSelectionReplace(currentSelection);
} else {
// Holding down ctrl causes an addition, requiring the ref string to be increased.
- let insertNodes = this._formulaInputService.getSequenceNodes();
+ let insertNodes = this._formulaPromptService.getSequenceNodes();
if (insertNodes == null) {
return;
@@ -1319,9 +1377,9 @@ export class PromptController extends Disposable {
this._previousInsertRefStringIndex = this._currentInsertRefStringIndex;
if (!this._matchRefDrawToken(char)) {
- this._formulaInputService.insertSequenceString(this._currentInsertRefStringIndex, matchToken.COMMA);
+ this._formulaPromptService.insertSequenceString(this._currentInsertRefStringIndex, matchToken.COMMA);
- insertNodes = this._formulaInputService.getSequenceNodes();
+ insertNodes = this._formulaPromptService.getSequenceNodes();
this._previousInsertRefStringIndex += 1;
}
@@ -1330,9 +1388,9 @@ export class PromptController extends Disposable {
const refString = this._getRefString(currentSelection);
- this._formulaInputService.setSequenceNodes(insertNodes);
+ this._formulaPromptService.setSequenceNodes(insertNodes);
- this._formulaInputService.insertSequenceRef(this._previousInsertRefStringIndex, refString);
+ this._formulaPromptService.insertSequenceRef(this._previousInsertRefStringIndex, refString);
// this._lastSequenceNodes = insertNodes;
@@ -1417,9 +1475,9 @@ export class PromptController extends Disposable {
return;
}
- const { unitId, sheetId, skeleton } = this._getCurrentUnitIdAndSheetId();
+ const { skeleton } = this._getCurrentUnitIdAndSheetId();
- this._formulaInputService.enableLockedSelectionChange();
+ this._formulaPromptService.enableLockedSelectionChange();
const id = controlSelection.selectionStyle?.id;
@@ -1457,7 +1515,7 @@ export class PromptController extends Disposable {
const nodeIndex = Number(id);
- const currentNode = this._formulaInputService.getCurrentSequenceNodeByIndex(nodeIndex);
+ const currentNode = this._formulaPromptService.getCurrentSequenceNodeByIndex(nodeIndex);
let refType: IAbsoluteRefTypeForRange = { startAbsoluteRefType: AbsoluteRefType.NONE };
if (typeof currentNode !== 'string') {
@@ -1482,9 +1540,9 @@ export class PromptController extends Disposable {
style: null,
});
- this._formulaInputService.updateSequenceRef(nodeIndex, refString);
+ this._formulaPromptService.updateSequenceRef(nodeIndex, refString);
- const sequenceNodes = this._formulaInputService.getSequenceNodes();
+ const sequenceNodes = this._formulaPromptService.getSequenceNodes();
const node = sequenceNodes[nodeIndex];
@@ -1503,9 +1561,7 @@ export class PromptController extends Disposable {
);
}
- private _refreshFormulaAndCellEditor() {
- const unitIds = [DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY, DOCS_NORMAL_EDITOR_UNIT_ID_KEY];
-
+ private _refreshFormulaAndCellEditor(unitIds: string[]) {
for (const unitId of unitIds) {
const editorObject = getEditorObject(unitId, this._renderManagerService);
@@ -1543,10 +1599,10 @@ export class PromptController extends Disposable {
return;
}
- const { document: documentComponent } = editorObject;
+ const { mainComponent: documentComponent } = editorObject;
this.disposeWithMe(
toDisposable(
- documentComponent.onPointerDownObserver.add(() => {
+ documentComponent?.onPointerDownObserver.add(() => {
this._arrowMoveActionState = ArrowMoveAction.moveCursor;
this._inputPanelState = InputPanelState.mouse;
@@ -1561,7 +1617,9 @@ export class PromptController extends Disposable {
this.disposeWithMe(
this._commandService.onCommandExecuted((command: ICommandInfo) => {
- if (updateCommandList.includes(command.id)) {
+ if (command.id === ReferenceAbsoluteOperation.id) {
+ this._changeRefString();
+ } else if (updateCommandList.includes(command.id)) {
const params = command.params as ISelectEditorFormulaOperationParam;
const { keycode, metaKey } = params;
@@ -1694,7 +1752,153 @@ export class PromptController extends Disposable {
});
}
+ private _userMouseListener() {
+ const editorObject = this._getEditorObject();
+
+ if (editorObject == null) {
+ return;
+ }
+
+ const { mainComponent: documentComponent } = editorObject;
+ this.disposeWithMe(
+ toDisposable(
+ documentComponent?.onPointerDownObserver.add(() => {
+ this._userCursorMove = true;
+ })
+ )
+ );
+ }
+
+ private _inputFormulaListener() {
+ this.disposeWithMe(
+ toDisposable(
+ this._editorService.inputFormula$.subscribe((param) => {
+ const { formulaString, editorUnitId } = param;
+
+ if (formulaString.substring(0, 1) !== compareToken.EQUALS) {
+ return;
+ }
+
+ const visibleState = this._editorBridgeService.isVisible();
+ if (visibleState.visible === false) {
+ this._editorBridgeService.changeVisible({
+ visible: true,
+ eventType: DeviceInputEventType.Dblclick,
+ });
+ }
+
+ const lastSequenceNodes = this._lexerTreeBuilder.sequenceNodesBuilder(formulaString) || [];
+
+ this._formulaPromptService.setSequenceNodes(lastSequenceNodes);
+
+ this._syncToEditor(lastSequenceNodes, formulaString.length - 1, editorUnitId);
+ })
+ )
+ );
+ }
+
+ private _changeRefString() {
+ const activeRange = this._textSelectionManagerService.getActiveRange();
+
+ if (activeRange == null) {
+ return;
+ }
+
+ const { startOffset } = activeRange;
+
+ const strIndex = startOffset - 2;
+
+ const nodeIndex = this._formulaPromptService.getCurrentSequenceNodeIndex(strIndex);
+
+ const node = this._formulaPromptService.getCurrentSequenceNodeByIndex(nodeIndex);
+
+ if (node == null || typeof node === 'string' || node.nodeType !== sequenceNodeType.REFERENCE) {
+ return;
+ }
+
+ const tokenArray = node.token.split('!');
+
+ let token = node.token;
+
+ if (tokenArray.length > 1) {
+ token = tokenArray[tokenArray.length - 1];
+ }
+
+ let unitIDAndSheetName = '';
+
+ for (let i = 0, len = tokenArray.length; i < len - 1; i++) {
+ unitIDAndSheetName += tokenArray[i];
+ }
+
+ let finalToken = token;
+ if (token.indexOf(matchToken.COLON) > -1) {
+ if (!this._userCursorMove) {
+ finalToken = this._changeRangeRef(token);
+ } else {
+ const refStringSplit = token.split(matchToken.COLON);
+ const prefix = refStringSplit[0];
+ const suffix = refStringSplit[1];
+ const relativeIndex = strIndex - node.startIndex;
+
+ if (relativeIndex <= prefix.length) {
+ finalToken = this._changeSingleRef(prefix) + matchToken.COLON + suffix;
+ } else {
+ finalToken = prefix + matchToken.COLON + this._changeSingleRef(suffix);
+ }
+ }
+ } else {
+ finalToken = this._changeSingleRef(token);
+ }
+
+ finalToken = unitIDAndSheetName + finalToken;
+
+ const difference = finalToken.length - node.token.length;
+
+ this._formulaPromptService.updateSequenceRef(nodeIndex, finalToken);
+
+ this._syncToEditor(this._formulaPromptService.getSequenceNodes(), strIndex + difference + 1);
+ }
+
+ private _changeRangeRef(token: string) {
+ const range = deserializeRangeWithSheet(token).range;
+ let resultToken = '';
+ if (range.startAbsoluteRefType === AbsoluteRefType.NONE || range.startAbsoluteRefType == null) {
+ range.startAbsoluteRefType = AbsoluteRefType.ALL;
+ range.endAbsoluteRefType = AbsoluteRefType.ALL;
+ } else {
+ range.startAbsoluteRefType = AbsoluteRefType.NONE;
+ range.endAbsoluteRefType = AbsoluteRefType.NONE;
+ }
+ resultToken = serializeRange(range);
+ return resultToken;
+ }
+
+ private _changeSingleRef(token: string) {
+ const range = deserializeRangeWithSheet(token).range;
+ const type = range.startAbsoluteRefType;
+ let resultToken = '';
+ if (type === AbsoluteRefType.NONE || type == null) {
+ range.startAbsoluteRefType = AbsoluteRefType.ALL;
+ range.endAbsoluteRefType = AbsoluteRefType.ALL;
+ } else if (type === AbsoluteRefType.ALL) {
+ range.startAbsoluteRefType = AbsoluteRefType.ROW;
+ range.endAbsoluteRefType = AbsoluteRefType.ROW;
+ } else if (type === AbsoluteRefType.ROW) {
+ range.startAbsoluteRefType = AbsoluteRefType.COLUMN;
+ range.endAbsoluteRefType = AbsoluteRefType.COLUMN;
+ } else {
+ range.startAbsoluteRefType = AbsoluteRefType.NONE;
+ range.endAbsoluteRefType = AbsoluteRefType.NONE;
+ }
+
+ resultToken = serializeRange(range);
+ return resultToken;
+ }
+
private _getEditorObject() {
- return getEditorObject(this._editorBridgeService.getCurrentEditorId(), this._renderManagerService);
+ const editorUnitId = this._currentUniverService.getCurrentUniverDocInstance().getUnitId();
+ const editor = this._editorService.getEditor(editorUnitId);
+ return editor?.render;
+ // return getEditorObject(this._editorBridgeService.getCurrentEditorId(), this._renderManagerService);
}
}
diff --git a/packages/sheets-formula/src/formula-ui-plugin.ts b/packages/sheets-formula/src/formula-ui-plugin.ts
index 38077a78ea..5fd8703f8b 100644
--- a/packages/sheets-formula/src/formula-ui-plugin.ts
+++ b/packages/sheets-formula/src/formula-ui-plugin.ts
@@ -25,7 +25,6 @@ import { ArrayFormulaDisplayController } from './controllers/array-formula-displ
import { FormulaAutoFillController } from './controllers/formula-auto-fill.controller';
import { FormulaClipboardController } from './controllers/formula-clipboard.controller';
import { FormulaEditorShowController } from './controllers/formula-editor-show.controller';
-import { FormulaInputController } from './controllers/formula-input.controller';
import { FormulaUIController } from './controllers/formula-ui.controller';
import { PromptController } from './controllers/prompt.controller';
import { TriggerCalculationController } from './controllers/trigger-calculation.controller';
@@ -37,7 +36,6 @@ import {
FormulaCustomFunctionService,
IFormulaCustomFunctionService,
} from './services/formula-custom-function.service';
-import { FormulaInputService, IFormulaInputService } from './services/formula-input.service';
import { FormulaPromptService, IFormulaPromptService } from './services/prompt.service';
import { IRegisterFunctionService, RegisterFunctionService } from './services/register-function.service';
import { NumfmtFormulaDisplayController } from './controllers/numfmt-formula-display.controller';
@@ -69,7 +67,6 @@ export class UniverSheetsFormulaPlugin extends Plugin {
const dependencies: Dependency[] = [
// services
[IFormulaPromptService, { useClass: FormulaPromptService }],
- [IFormulaInputService, { useClass: FormulaInputService }],
[
IDescriptionService,
{
@@ -83,7 +80,6 @@ export class UniverSheetsFormulaPlugin extends Plugin {
// controllers
[FormulaUIController],
[PromptController],
- [FormulaInputController],
[FormulaAutoFillController],
[FormulaClipboardController],
[ArrayFormulaDisplayController],
diff --git a/packages/sheets-formula/src/services/formula-input.service.ts b/packages/sheets-formula/src/services/formula-input.service.ts
deleted file mode 100644
index d2ea5e2100..0000000000
--- a/packages/sheets-formula/src/services/formula-input.service.ts
+++ /dev/null
@@ -1,301 +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 { ISequenceNode } from '@univerjs/engine-formula';
-import { sequenceNodeType } from '@univerjs/engine-formula';
-import type { IDisposable } from '@wendellhu/redi';
-import { createIdentifier } from '@wendellhu/redi';
-import type { Observable } from 'rxjs';
-import { Subject } from 'rxjs';
-
-export interface ISyncToEditorParam {
- textSelectionOffset: number;
- sequences: Array<string | ISequenceNode>;
-}
-
-export interface IFormulaInputService {
- syncToEditor$: Observable<ISyncToEditorParam>;
-
- inputFormula$: Observable<string>;
-
- changeRef$: Observable<boolean>;
-
- syncToEditor(textSelectionOffset: number): void;
-
- dispose(): void;
-
- getSequenceNodes(): Array<string | ISequenceNode>;
-
- setSequenceNodes(nodes: Array<string | ISequenceNode>): void;
-
- clearSequenceNodes(): void;
-
- getCurrentSequenceNodeIndex(strIndex: number): number;
-
- getCurrentSequenceNodeByIndex(nodeIndex: number): string | ISequenceNode;
-
- getCurrentSequenceNode(strIndex: number): string | ISequenceNode;
-
- updateSequenceRef(nodeIndex: number, refString: string): void;
-
- insertSequenceRef(index: number, refString: string): void;
-
- insertSequenceString(index: number, content: string): void;
-
- enableSelectionMoving(): void;
-
- disableSelectionMoving(): void;
-
- isSelectionMoving(): boolean;
-
- enableLockedSelectionChange(): void;
-
- disableLockedSelectionChange(): void;
-
- isLockedSelectionChange(): boolean;
-
- enableLockedSelectionInsert(): void;
-
- disableLockedSelectionInsert(): void;
-
- isLockedSelectionInsert(): boolean;
-
- inputFormula(formulaString: string): void;
-}
-
-export class FormulaInputService implements IFormulaInputService, IDisposable {
- private _sequenceNodes: Array<string | ISequenceNode> = [];
-
- private _isSelectionMoving = false;
-
- private _isLockedOnSelectionChangeRefString: boolean = false;
-
- private _isLockedOnSelectionInsertRefString: boolean = false;
-
- private readonly _syncToEditor$ = new Subject<ISyncToEditorParam>();
-
- readonly syncToEditor$ = this._syncToEditor$.asObservable();
-
- private _changeRef$ = new Subject<boolean>();
-
- readonly changeRef$ = this._changeRef$.asObservable();
-
- private readonly _inputFormula$ = new Subject<string>();
-
- readonly inputFormula$ = this._inputFormula$.asObservable();
-
- dispose(): void {
- this._sequenceNodes = [];
- }
-
- inputFormula(formulaString: string) {
- this._inputFormula$.next(formulaString);
- }
-
- syncToEditor(textSelectionOffset: number) {
- this._syncToEditor$.next({ sequences: this.getSequenceNodes(), textSelectionOffset });
- }
-
- getSequenceNodes() {
- return [...this._sequenceNodes];
- }
-
- setSequenceNodes(nodes: Array<string | ISequenceNode>) {
- this._sequenceNodes = nodes;
- }
-
- clearSequenceNodes() {
- this._sequenceNodes = [];
- }
-
- getCurrentSequenceNode(strIndex: number) {
- return this._sequenceNodes[this.getCurrentSequenceNodeIndex(strIndex)];
- }
-
- getCurrentSequenceNodeByIndex(nodeIndex: number) {
- return this._sequenceNodes[nodeIndex];
- }
-
- /**
- * Query the text coordinates in the sequenceNodes and determine the actual insertion index.
- * @param sequenceNodes
- * @param strIndex
- * @returns
- */
- getCurrentSequenceNodeIndex(strIndex: number) {
- let nodeIndex = 0;
- for (let i = 0, len = this._sequenceNodes.length; i < len; i++) {
- const node = this._sequenceNodes[i];
-
- if (typeof node === 'string') {
- nodeIndex++;
- } else {
- const { endIndex } = node;
-
- nodeIndex = endIndex;
- }
-
- if (strIndex <= nodeIndex) {
- return i;
- }
- }
-
- return this._sequenceNodes.length;
- }
-
- /**
- * Synchronize the reference text based on the changes of the selection.
- * @param refIndex
- * @param rangeWithCoord
- * @returns
- */
- updateSequenceRef(nodeIndex: number, refString: string) {
- const node = this._sequenceNodes[nodeIndex];
-
- if (typeof node === 'string' || node.nodeType !== sequenceNodeType.REFERENCE) {
- return;
- }
-
- const difference = refString.length - node.token.length;
-
- const newNode = { ...node };
-
- newNode.token = refString;
-
- newNode.endIndex += difference;
-
- this._sequenceNodes[nodeIndex] = newNode;
-
- for (let i = nodeIndex + 1, len = this._sequenceNodes.length; i < len; i++) {
- const node = this._sequenceNodes[i];
- if (typeof node === 'string') {
- continue;
- }
-
- const newNode = { ...node };
-
- newNode.startIndex += difference;
- newNode.endIndex += difference;
-
- this._sequenceNodes[i] = newNode;
- }
-
- this._changeRef$.next(true);
- }
-
- /**
- * When the cursor is on the right side of a formula token,
- * you can add reference text to the formula by drawing a selection.
- * @param index
- * @param range
- */
- insertSequenceRef(index: number, refString: string) {
- const refStringCount = refString.length;
-
- const nodeIndex = this.getCurrentSequenceNodeIndex(index);
-
- this._sequenceNodes.splice(nodeIndex, 0, {
- token: refString,
- startIndex: index,
- endIndex: index + refStringCount - 1,
- nodeType: sequenceNodeType.REFERENCE,
- });
-
- for (let i = nodeIndex + 1, len = this._sequenceNodes.length; i < len; i++) {
- const node = this._sequenceNodes[i];
- if (typeof node === 'string') {
- continue;
- }
-
- const newNode = { ...node };
-
- newNode.startIndex += refStringCount;
- newNode.endIndex += refStringCount;
-
- this._sequenceNodes[i] = newNode;
- }
-
- this._changeRef$.next(true);
- }
-
- /**
- * Insert a string at the cursor position in the text corresponding to the sequenceNodes.
- * @param sequenceNodes
- * @param index
- * @param content
- */
- insertSequenceString(index: number, content: string) {
- const nodeIndex = this.getCurrentSequenceNodeIndex(index);
- const str = content.split('');
- this._sequenceNodes.splice(nodeIndex, 0, ...str);
-
- const contentCount = str.length;
-
- for (let i = nodeIndex + contentCount, len = this._sequenceNodes.length; i < len; i++) {
- const node = this._sequenceNodes[i];
- if (typeof node === 'string') {
- continue;
- }
-
- const newNode = { ...node };
-
- newNode.startIndex += contentCount;
- newNode.endIndex += contentCount;
-
- this._sequenceNodes[i] = newNode;
- }
-
- this._changeRef$.next(true);
- }
-
- enableSelectionMoving() {
- this._isSelectionMoving = true;
- }
-
- disableSelectionMoving() {
- this._isSelectionMoving = false;
- }
-
- isSelectionMoving() {
- return this._isSelectionMoving;
- }
-
- enableLockedSelectionChange() {
- this._isLockedOnSelectionChangeRefString = true;
- }
-
- disableLockedSelectionChange() {
- this._isLockedOnSelectionChangeRefString = false;
- }
-
- isLockedSelectionChange() {
- return this._isLockedOnSelectionChangeRefString;
- }
-
- enableLockedSelectionInsert() {
- this._isLockedOnSelectionInsertRefString = true;
- }
-
- disableLockedSelectionInsert() {
- this._isLockedOnSelectionInsertRefString = false;
- }
-
- isLockedSelectionInsert() {
- return this._isLockedOnSelectionInsertRefString;
- }
-}
-
-export const IFormulaInputService = createIdentifier<FormulaInputService>('formula-ui.input-service');
diff --git a/packages/sheets-formula/src/services/prompt.service.ts b/packages/sheets-formula/src/services/prompt.service.ts
index f2733353db..060f4ab518 100644
--- a/packages/sheets-formula/src/services/prompt.service.ts
+++ b/packages/sheets-formula/src/services/prompt.service.ts
@@ -15,7 +15,7 @@
*/
import type { Direction } from '@univerjs/core';
-import type { IFunctionInfo } from '@univerjs/engine-formula';
+import { type IFunctionInfo, type ISequenceNode, sequenceNodeType } from '@univerjs/engine-formula';
import type { IDisposable } from '@wendellhu/redi';
import { createIdentifier } from '@wendellhu/redi';
import type { Observable } from 'rxjs';
@@ -118,6 +118,42 @@ export interface IFormulaPromptService {
isHelping(): boolean;
dispose(): void;
+
+ getSequenceNodes(): Array<string | ISequenceNode>;
+
+ setSequenceNodes(nodes: Array<string | ISequenceNode>): void;
+
+ clearSequenceNodes(): void;
+
+ getCurrentSequenceNodeIndex(strIndex: number): number;
+
+ getCurrentSequenceNodeByIndex(nodeIndex: number): string | ISequenceNode;
+
+ getCurrentSequenceNode(strIndex: number): string | ISequenceNode;
+
+ updateSequenceRef(nodeIndex: number, refString: string): void;
+
+ insertSequenceRef(index: number, refString: string): void;
+
+ insertSequenceString(index: number, content: string): void;
+
+ enableSelectionMoving(): void;
+
+ disableSelectionMoving(): void;
+
+ isSelectionMoving(): boolean;
+
+ enableLockedSelectionChange(): void;
+
+ disableLockedSelectionChange(): void;
+
+ isLockedSelectionChange(): boolean;
+
+ enableLockedSelectionInsert(): void;
+
+ disableLockedSelectionInsert(): void;
+
+ isLockedSelectionInsert(): boolean;
}
export const IFormulaPromptService = createIdentifier<FormulaPromptService>('formula-ui.prompt-service');
@@ -146,14 +182,24 @@ export class FormulaPromptService implements IFormulaPromptService, IDisposable
private _searching: boolean = false;
private _helping: boolean = false;
+
private _isInsertRefString: boolean = false;
+ private _sequenceNodes: Array<string | ISequenceNode> = [];
+
+ private _isSelectionMoving = false;
+
+ private _isLockedOnSelectionChangeRefString: boolean = false;
+
+ private _isLockedOnSelectionInsertRefString: boolean = false;
+
dispose(): void {
this._search$.complete();
this._help$.complete();
this._navigate$.complete();
this._accept$.complete();
this._acceptFormulaName$.complete();
+ this._sequenceNodes = [];
}
search(param: ISearchFunctionOperationParams) {
@@ -185,4 +231,182 @@ export class FormulaPromptService implements IFormulaPromptService, IDisposable
acceptFormulaName(param: string) {
this._acceptFormulaName$.next(param);
}
+
+ getSequenceNodes() {
+ return [...this._sequenceNodes];
+ }
+
+ setSequenceNodes(nodes: Array<string | ISequenceNode>) {
+ this._sequenceNodes = nodes;
+ }
+
+ clearSequenceNodes() {
+ this._sequenceNodes = [];
+ }
+
+ getCurrentSequenceNode(strIndex: number) {
+ return this._sequenceNodes[this.getCurrentSequenceNodeIndex(strIndex)];
+ }
+
+ getCurrentSequenceNodeByIndex(nodeIndex: number) {
+ return this._sequenceNodes[nodeIndex];
+ }
+
+ /**
+ * Query the text coordinates in the sequenceNodes and determine the actual insertion index.
+ * @param strIndex
+ */
+ getCurrentSequenceNodeIndex(strIndex: number) {
+ let nodeIndex = 0;
+ for (let i = 0, len = this._sequenceNodes.length; i < len; i++) {
+ const node = this._sequenceNodes[i];
+
+ if (typeof node === 'string') {
+ nodeIndex++;
+ } else {
+ const { endIndex } = node;
+
+ nodeIndex = endIndex;
+ }
+
+ if (strIndex <= nodeIndex) {
+ return i;
+ }
+ }
+
+ return this._sequenceNodes.length;
+ }
+
+ /**
+ * Synchronize the reference text based on the changes of the selection.
+ * @param nodeIndex
+ * @param refString
+ */
+ updateSequenceRef(nodeIndex: number, refString: string) {
+ const node = this._sequenceNodes[nodeIndex];
+
+ if (typeof node === 'string' || node.nodeType !== sequenceNodeType.REFERENCE) {
+ return;
+ }
+
+ const difference = refString.length - node.token.length;
+
+ const newNode = { ...node };
+
+ newNode.token = refString;
+
+ newNode.endIndex += difference;
+
+ this._sequenceNodes[nodeIndex] = newNode;
+
+ for (let i = nodeIndex + 1, len = this._sequenceNodes.length; i < len; i++) {
+ const node = this._sequenceNodes[i];
+ if (typeof node === 'string') {
+ continue;
+ }
+
+ const newNode = { ...node };
+
+ newNode.startIndex += difference;
+ newNode.endIndex += difference;
+
+ this._sequenceNodes[i] = newNode;
+ }
+ }
+
+ /**
+ * When the cursor is on the right side of a formula token,
+ * you can add reference text to the formula by drawing a selection.
+ * @param index
+ * @param refString
+ */
+ insertSequenceRef(index: number, refString: string) {
+ const refStringCount = refString.length;
+
+ const nodeIndex = this.getCurrentSequenceNodeIndex(index);
+
+ this._sequenceNodes.splice(nodeIndex, 0, {
+ token: refString,
+ startIndex: index,
+ endIndex: index + refStringCount - 1,
+ nodeType: sequenceNodeType.REFERENCE,
+ });
+
+ for (let i = nodeIndex + 1, len = this._sequenceNodes.length; i < len; i++) {
+ const node = this._sequenceNodes[i];
+ if (typeof node === 'string') {
+ continue;
+ }
+
+ const newNode = { ...node };
+
+ newNode.startIndex += refStringCount;
+ newNode.endIndex += refStringCount;
+
+ this._sequenceNodes[i] = newNode;
+ }
+ }
+
+ /**
+ * Insert a string at the cursor position in the text corresponding to the sequenceNodes.
+ * @param index
+ * @param content
+ */
+ insertSequenceString(index: number, content: string) {
+ const nodeIndex = this.getCurrentSequenceNodeIndex(index);
+ const str = content.split('');
+ this._sequenceNodes.splice(nodeIndex, 0, ...str);
+
+ const contentCount = str.length;
+
+ for (let i = nodeIndex + contentCount, len = this._sequenceNodes.length; i < len; i++) {
+ const node = this._sequenceNodes[i];
+ if (typeof node === 'string') {
+ continue;
+ }
+
+ const newNode = { ...node };
+
+ newNode.startIndex += contentCount;
+ newNode.endIndex += contentCount;
+
+ this._sequenceNodes[i] = newNode;
+ }
+ }
+
+ enableSelectionMoving() {
+ this._isSelectionMoving = true;
+ }
+
+ disableSelectionMoving() {
+ this._isSelectionMoving = false;
+ }
+
+ isSelectionMoving() {
+ return this._isSelectionMoving;
+ }
+
+ enableLockedSelectionChange() {
+ this._isLockedOnSelectionChangeRefString = true;
+ }
+
+ disableLockedSelectionChange() {
+ this._isLockedOnSelectionChangeRefString = false;
+ }
+
+ isLockedSelectionChange() {
+ return this._isLockedOnSelectionChangeRefString;
+ }
+
+ enableLockedSelectionInsert() {
+ this._isLockedOnSelectionInsertRefString = true;
+ }
+
+ disableLockedSelectionInsert() {
+ this._isLockedOnSelectionInsertRefString = false;
+ }
+
+ isLockedSelectionInsert() {
+ return this._isLockedOnSelectionInsertRefString;
+ }
}
diff --git a/packages/sheets-formula/src/views/FormulaPromptContainer.tsx b/packages/sheets-formula/src/views/FormulaPromptContainer.tsx
index b7c410f9e3..09a27b37c7 100644
--- a/packages/sheets-formula/src/views/FormulaPromptContainer.tsx
+++ b/packages/sheets-formula/src/views/FormulaPromptContainer.tsx
@@ -16,7 +16,6 @@
import React from 'react';
-import { ErrorFunction } from './prompt/error-function/error-function';
import { HelpFunction } from './prompt/help-function/HelpFunction';
import { SearchFunction } from './prompt/search-function/SearchFunction';
@@ -25,7 +24,6 @@ export function RenderFormulaPromptContent() {
<>
<SearchFunction />
<HelpFunction />
- <ErrorFunction />
</>
);
}
diff --git a/packages/sheets-formula/src/views/more-functions/MoreFunctions.tsx b/packages/sheets-formula/src/views/more-functions/MoreFunctions.tsx
index fec12a7108..31334dbe1b 100644
--- a/packages/sheets-formula/src/views/more-functions/MoreFunctions.tsx
+++ b/packages/sheets-formula/src/views/more-functions/MoreFunctions.tsx
@@ -17,11 +17,10 @@
import { LocaleService } from '@univerjs/core';
import { Button } from '@univerjs/design';
import type { IFunctionInfo } from '@univerjs/engine-formula';
-import { ISidebarService } from '@univerjs/ui';
+import { IEditorService, ISidebarService } from '@univerjs/ui';
import { useDependency } from '@wendellhu/redi/react-bindings';
import React, { useState } from 'react';
-import { IFormulaInputService } from '../../services/formula-input.service';
import styles from './index.module.less';
import { InputParams } from './input-params/InputParams';
import { SelectFunction } from './select-function/SelectFunction';
@@ -34,7 +33,7 @@ export function MoreFunctions() {
const localeService = useDependency(LocaleService);
const sidebarService = useDependency(ISidebarService);
- const formulaInputService = useDependency(IFormulaInputService);
+ const editorService = useDependency(IEditorService);
function handleClickNextPrev() {
if (selectFunction) {
@@ -47,7 +46,7 @@ export function MoreFunctions() {
function handleConfirm() {
// TODO@Dushusir: save function `=${functionInfo?.functionName}(${params.join(',')})`
- formulaInputService.inputFormula(`=${functionInfo?.functionName}(`);
+ editorService.setFormula(`=${functionInfo?.functionName}(`);
}
return (
diff --git a/packages/sheets-formula/src/views/prompt/error-function/error-function.tsx b/packages/sheets-formula/src/views/prompt/error-function/error-function.tsx
deleted file mode 100644
index 20bbd7f628..0000000000
--- a/packages/sheets-formula/src/views/prompt/error-function/error-function.tsx
+++ /dev/null
@@ -1,57 +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 { ICellEditorManagerService } from '@univerjs/sheets-ui';
-import { useDependency } from '@wendellhu/redi/react-bindings';
-import React, { useEffect, useState } from 'react';
-
-import type { IHelpFunctionOperationParams } from '../../../services/prompt.service';
-import { IFormulaPromptService } from '../../../services/prompt.service';
-import styles from './index.module.less';
-
-export function ErrorFunction() {
- const [visible, setVisible] = useState(false);
- const [position, setPosition] = useState({ left: 0, top: 0 });
- const promptService = useDependency(IFormulaPromptService);
- const cellEditorManagerService = useDependency(ICellEditorManagerService);
- useEffect(() => {
- // TODO@Dushusir: use cell notification service
- const subscription = promptService.help$.subscribe((params: IHelpFunctionOperationParams) => {
- const selection = cellEditorManagerService.getState();
- if (!selection) return;
-
- const { visible } = params;
- if (!visible) {
- setVisible(visible);
- return;
- }
-
- const { endX = 0, startY = 0 } = selection;
- setPosition({ left: endX, top: startY });
- setVisible(visible);
- });
-
- return () => {
- subscription?.unsubscribe();
- };
- }, []);
- return visible ? (
- <div className={styles.formulaErrorFunction} style={{ left: position.left, top: position.top }}>
- {/* TODO@Dushusir replace with CellError Component */}
- {/* CellError */}
- </div>
- ) : null;
-}
diff --git a/packages/sheets-formula/src/views/prompt/error-function/index.module.less b/packages/sheets-formula/src/views/prompt/error-function/index.module.less
deleted file mode 100644
index fd5fe8828f..0000000000
--- a/packages/sheets-formula/src/views/prompt/error-function/index.module.less
+++ /dev/null
@@ -1,3 +0,0 @@
-.formula-error-function {
- position: absolute;
-}
diff --git a/packages/sheets-formula/src/views/prompt/help-function/HelpFunction.tsx b/packages/sheets-formula/src/views/prompt/help-function/HelpFunction.tsx
index f6a4c88ee7..e2819bdfc4 100644
--- a/packages/sheets-formula/src/views/prompt/help-function/HelpFunction.tsx
+++ b/packages/sheets-formula/src/views/prompt/help-function/HelpFunction.tsx
@@ -14,14 +14,14 @@
* limitations under the License.
*/
-import { FOCUSING_FORMULA_EDITOR, IContextService, LocaleService } from '@univerjs/core';
+import { IUniverInstanceService, LocaleService } from '@univerjs/core';
import { Popup } from '@univerjs/design';
import type { IFunctionInfo, IFunctionParam } from '@univerjs/engine-formula';
import { CloseSingle, DetailsSingle, MoreSingle } from '@univerjs/icons';
-import { ICellEditorManagerService, IFormulaEditorManagerService } from '@univerjs/sheets-ui';
import { useDependency } from '@wendellhu/redi/react-bindings';
import React, { useEffect, useState } from 'react';
+import { IEditorService } from '@univerjs/ui';
import type { IHelpFunctionOperationParams } from '../../../services/prompt.service';
import { IFormulaPromptService } from '../../../services/prompt.service';
import styles from './index.module.less';
@@ -35,13 +35,13 @@ export function HelpFunction() {
const [decoratorPosition, setDecoratorPosition] = useState({ left: 0, top: 0 });
const [functionInfo, setFunctionInfo] = useState<IFunctionInfo | null>(null);
const promptService = useDependency(IFormulaPromptService);
- const cellEditorManagerService = useDependency(ICellEditorManagerService);
const localeService = useDependency(LocaleService);
- const formulaEditorManagerService = useDependency(IFormulaEditorManagerService);
- const contextService = useDependency(IContextService);
const required = localeService.t('formula.prompt.required');
const optional = localeService.t('formula.prompt.optional');
+ const univerInstanceService = useDependency(IUniverInstanceService);
+ const editorService = useDependency(IEditorService);
+
useEffect(() => {
const subscription = promptService.help$.subscribe((params: IHelpFunctionOperationParams) => {
const { visible, paramIndex, functionInfo } = params;
@@ -50,11 +50,7 @@ export function HelpFunction() {
return;
}
- const isFocusFormulaEditor = contextService.getContextValue(FOCUSING_FORMULA_EDITOR);
-
- const position = isFocusFormulaEditor
- ? formulaEditorManagerService.getPosition()
- : cellEditorManagerService.getRect();
+ const position = getPosition();
if (position == null) {
return;
@@ -78,6 +74,19 @@ export function HelpFunction() {
};
}, []);
+ function getPosition() {
+ const documentDataModel = univerInstanceService.getCurrentUniverDocInstance();
+
+ const editorUnitId = documentDataModel.getUnitId();
+
+ if (!editorService.isEditor(editorUnitId)) {
+ return;
+ }
+
+ const editor = editorService.getEditor(editorUnitId);
+ return editor?.getBoundingClientRect();
+ }
+
function handleSwitchActive(paramIndex: number) {
setParamIndex(paramIndex);
}
diff --git a/packages/sheets-formula/src/views/prompt/help-function/index.module.less b/packages/sheets-formula/src/views/prompt/help-function/index.module.less
index 89cae77703..001a5523dd 100644
--- a/packages/sheets-formula/src/views/prompt/help-function/index.module.less
+++ b/packages/sheets-formula/src/views/prompt/help-function/index.module.less
@@ -26,7 +26,7 @@
box-sizing: border-box;
padding: var(--padding-base) var(--padding-lg);
- font-size: var(--font-size-xs);
+ font-size: var(--font-size-xxs);
font-weight: 500;
color: rgb(var(--text-color));
overflow-wrap: anywhere;
@@ -49,7 +49,7 @@
margin-left: var(--margin-xs);
padding: 0;
- font-size: var(--font-size-lg);
+ font-size: var(--font-size-xs);
color: rgb(var(--text-color-secondary));
background-color: transparent;
diff --git a/packages/sheets-formula/src/views/prompt/search-function/SearchFunction.tsx b/packages/sheets-formula/src/views/prompt/search-function/SearchFunction.tsx
index 954c2ed1f0..4ed87ffa5b 100644
--- a/packages/sheets-formula/src/views/prompt/search-function/SearchFunction.tsx
+++ b/packages/sheets-formula/src/views/prompt/search-function/SearchFunction.tsx
@@ -14,12 +14,12 @@
* limitations under the License.
*/
-import { Direction, FOCUSING_FORMULA_EDITOR, IContextService } from '@univerjs/core';
+import { Direction, IUniverInstanceService } from '@univerjs/core';
import { Popup } from '@univerjs/design';
-import { ICellEditorManagerService, IFormulaEditorManagerService } from '@univerjs/sheets-ui';
import { useDependency } from '@wendellhu/redi/react-bindings';
import React, { useEffect, useRef, useState } from 'react';
+import { IEditorService } from '@univerjs/ui';
import type { ISearchItem } from '../../../services/description.service';
import type { INavigateParam, ISearchFunctionOperationParams } from '../../../services/prompt.service';
import { IFormulaPromptService } from '../../../services/prompt.service';
@@ -33,9 +33,8 @@ export function SearchFunction() {
const [searchText, setSearchText] = useState<string>('');
const ulRef = useRef<HTMLUListElement>(null);
const promptService = useDependency(IFormulaPromptService);
- const cellEditorManagerService = useDependency(ICellEditorManagerService);
- const formulaEditorManagerService = useDependency(IFormulaEditorManagerService);
- const contextService = useDependency(IContextService);
+ const univerInstanceService = useDependency(IUniverInstanceService);
+ const editorService = useDependency(IEditorService);
useEffect(() => {
// TODO@Dushusir: How to get updated values in subscribe callback better
@@ -48,11 +47,9 @@ export function SearchFunction() {
return;
}
- const isFocusFormulaEditor = contextService.getContextValue(FOCUSING_FORMULA_EDITOR);
+ // const isFocusFormulaEditor = contextService.getContextValue(FOCUSING_FORMULA_EDITOR);
- const position = isFocusFormulaEditor
- ? formulaEditorManagerService.getPosition()
- : cellEditorManagerService.getRect();
+ const position = getPosition();
if (position == null) {
return;
@@ -98,6 +95,20 @@ export function SearchFunction() {
};
}, []);
+ function getPosition() {
+ const documentDataModel = univerInstanceService.getCurrentUniverDocInstance();
+
+ const editorUnitId = documentDataModel.getUnitId();
+
+ if (!editorService.isEditor(editorUnitId)) {
+ return;
+ }
+
+ const editor = editorService.getEditor(editorUnitId);
+
+ return editor?.getBoundingClientRect();
+ }
+
function handleLiMouseEnter(index: number) {
setActive(index);
}
diff --git a/packages/sheets-formula/src/views/prompt/search-function/index.module.less b/packages/sheets-formula/src/views/prompt/search-function/index.module.less
index c945e13acf..5ad7899b7e 100644
--- a/packages/sheets-formula/src/views/prompt/search-function/index.module.less
+++ b/packages/sheets-formula/src/views/prompt/search-function/index.module.less
@@ -32,7 +32,7 @@
transition: background 0.2s;
&-name {
- font-size: var(--font-size-xs);
+ font-size: var(--font-size-xxs);
&-light {
color: rgb(var(--error-color));
diff --git a/packages/sheets-ui/src/commands/commands/__tests__/auto-fill.controller.spec.ts b/packages/sheets-ui/src/commands/commands/__tests__/auto-fill.controller.spec.ts
index 249104cb4a..7353bd56e3 100644
--- a/packages/sheets-ui/src/commands/commands/__tests__/auto-fill.controller.spec.ts
+++ b/packages/sheets-ui/src/commands/commands/__tests__/auto-fill.controller.spec.ts
@@ -30,10 +30,11 @@ import {
SetRangeValuesMutation,
SetSelectionsOperation,
} from '@univerjs/sheets';
-import { DesktopPlatformService, DesktopShortcutService, IPlatformService, IShortcutService } from '@univerjs/ui';
+import { DesktopPlatformService, DesktopShortcutService, EditorService, IEditorService, IPlatformService, IShortcutService } from '@univerjs/ui';
import type { Injector } from '@wendellhu/redi';
import { beforeEach, describe, expect, it } from 'vitest';
+import { IRenderManagerService, RenderManagerService } from '@univerjs/engine-render';
import { AutoFillController } from '../../../controllers/auto-fill.controller';
import { AutoFillService, IAutoFillService } from '../../../services/auto-fill/auto-fill.service';
import { APPLY_TYPE } from '../../../services/auto-fill/type';
@@ -79,11 +80,11 @@ const TEST_WORKBOOK_DATA = {
// Extend Number
2: {
0: {
- v: '第1',
+ v: '第 1',
t: CellValueType.STRING,
},
1: {
- v: '第2',
+ v: '第 2',
t: CellValueType.STRING,
},
},
@@ -142,11 +143,11 @@ const TEST_WORKBOOK_DATA = {
t: CellValueType.NUMBER,
},
2: {
- v: '第1',
+ v: '第 1',
t: CellValueType.STRING,
},
3: {
- v: '第2',
+ v: '第 2',
t: CellValueType.STRING,
},
},
@@ -267,6 +268,8 @@ describe('Test auto fill rules in controller', () => {
[IShortcutService, { useClass: DesktopShortcutService }],
[IPlatformService, { useClass: DesktopPlatformService }],
[IEditorBridgeService, { useClass: EditorBridgeService }],
+ [IEditorService, { useClass: EditorService }],
+ [IRenderManagerService, { useClass: RenderManagerService }],
[SheetSkeletonManagerService],
[AutoFillController],
]);
@@ -370,8 +373,8 @@ describe('Test auto fill rules in controller', () => {
endColumn: 3,
}
);
- expect(workbook.getSheetBySheetId('sheet1')?.getCell(2, 2)?.v).toBe('第3');
- expect(workbook.getSheetBySheetId('sheet1')?.getCell(2, 3)?.v).toBe('第4');
+ expect(workbook.getSheetBySheetId('sheet1')?.getCell(2, 2)?.v).toBe('第 3');
+ expect(workbook.getSheetBySheetId('sheet1')?.getCell(2, 3)?.v).toBe('第 4');
});
});
@@ -493,8 +496,8 @@ describe('Test auto fill rules in controller', () => {
);
expect(workbook.getSheetBySheetId('sheet1')?.getCell(7, 4)?.v).toBe(3);
expect(workbook.getSheetBySheetId('sheet1')?.getCell(7, 5)?.v).toBe(4);
- expect(workbook.getSheetBySheetId('sheet1')?.getCell(7, 6)?.v).toBe('第3');
- expect(workbook.getSheetBySheetId('sheet1')?.getCell(7, 7)?.v).toBe('第4');
+ expect(workbook.getSheetBySheetId('sheet1')?.getCell(7, 6)?.v).toBe('第 3');
+ expect(workbook.getSheetBySheetId('sheet1')?.getCell(7, 7)?.v).toBe('第 4');
// undo redo
await commandService.executeCommand(UndoCommand.id);
@@ -506,8 +509,8 @@ describe('Test auto fill rules in controller', () => {
await commandService.executeCommand(RedoCommand.id);
expect(workbook.getSheetBySheetId('sheet1')?.getCell(7, 4)?.v).toBe(3);
expect(workbook.getSheetBySheetId('sheet1')?.getCell(7, 5)?.v).toBe(4);
- expect(workbook.getSheetBySheetId('sheet1')?.getCell(7, 6)?.v).toBe('第3');
- expect(workbook.getSheetBySheetId('sheet1')?.getCell(7, 7)?.v).toBe('第4');
+ expect(workbook.getSheetBySheetId('sheet1')?.getCell(7, 6)?.v).toBe('第 3');
+ expect(workbook.getSheetBySheetId('sheet1')?.getCell(7, 7)?.v).toBe('第 4');
});
});
});
diff --git a/packages/sheets-ui/src/controllers/editor-bridge.controller.ts b/packages/sheets-ui/src/controllers/editor-bridge.controller.ts
index f52a694b23..a37c432e08 100644
--- a/packages/sheets-ui/src/controllers/editor-bridge.controller.ts
+++ b/packages/sheets-ui/src/controllers/editor-bridge.controller.ts
@@ -15,7 +15,7 @@
*/
import type { ICommandInfo, IExecutionOptions, Nullable } from '@univerjs/core';
-import { ICommandService, IUniverInstanceService, LifecycleStages, OnLifecycle, RxDisposable } from '@univerjs/core';
+import { FOCUSING_DOC, FOCUSING_SHEET, ICommandService, IContextService, IUniverInstanceService, LifecycleStages, OnLifecycle, RxDisposable } from '@univerjs/core';
import { DeviceInputEventType, IRenderManagerService, ITextSelectionRenderManager } from '@univerjs/engine-render';
import type { ISelectionWithStyle } from '@univerjs/sheets';
import {
@@ -26,7 +26,7 @@ import {
} from '@univerjs/sheets';
import { Inject, Injector, Quantity } from '@wendellhu/redi';
import { merge, takeUntil } from 'rxjs';
-import { ILayoutService } from '@univerjs/ui';
+import { IEditorService, ILayoutService } from '@univerjs/ui';
import { SetZoomRatioCommand } from '../commands/commands/set-zoom-ratio.command';
import { SetActivateCellEditOperation } from '../commands/operations/activate-cell-edit.operation';
@@ -45,6 +45,8 @@ export class EditorBridgeController extends RxDisposable {
@IRenderManagerService private readonly _renderManagerService: IRenderManagerService,
@IEditorBridgeService private readonly _editorBridgeService: IEditorBridgeService,
@ILayoutService private readonly _layoutService: ILayoutService,
+ @IEditorService private readonly _editorService: IEditorService,
+ @IContextService private readonly _contextService: IContextService,
@Inject(SelectionManagerService) private readonly _selectionManagerService: SelectionManagerService
) {
super();
@@ -59,6 +61,7 @@ export class EditorBridgeController extends RxDisposable {
private _initialize() {
this._initSelectionChangeListener();
this._initialEventListener();
+ this._initialChangeEditorListener();
}
private _initSelectionChangeListener() {
@@ -141,6 +144,38 @@ export class EditorBridgeController extends RxDisposable {
spreadsheetRowHeader.onPointerDownObserver.add(this._keepVisibleHideEditor.bind(this));
}
+ private _initialChangeEditorListener() {
+ this.disposeWithMe(
+ this._currentUniverService.currentDoc$.subscribe((documentDataModel) => {
+ if (documentDataModel == null) {
+ return;
+ }
+
+ const editorId = documentDataModel.getUnitId();
+
+ if (!this._editorService.isEditor(editorId)) {
+ return;
+ }
+
+ if (this._editorService.isSheetEditor(editorId)) {
+ this._contextService.setContextValue(FOCUSING_DOC, false);
+ // this._contextService.setContextValue(FOCUSING_FORMULA_EDITOR, true);
+ this._contextService.setContextValue(FOCUSING_SHEET, true);
+ } else {
+ // this._contextService.setContextValue(FOCUSING_EDITOR_INPUT_FORMULA, false);
+ // this._contextService.setContextValue(EDITOR_ACTIVATED, false);
+ // this._contextService.setContextValue(FOCUSING_EDITOR_BUT_HIDDEN, false);
+ // this._contextService.setContextValue(FOCUSING_FORMULA_EDITOR, false);
+
+ this._contextService.setContextValue(FOCUSING_SHEET, false);
+ this._contextService.setContextValue(FOCUSING_DOC, true);
+
+ this._hideEditor();
+ }
+ })
+ );
+ }
+
/**
* In the activated state of formula editing,
* prohibit closing the editor according to the state to facilitate generating selection reference text.
@@ -149,6 +184,7 @@ export class EditorBridgeController extends RxDisposable {
if (this._editorBridgeService.isForceKeepVisible()) {
return;
}
+ this._editorService.changeEditorFocus();
this._hideEditor();
}
diff --git a/packages/sheets-ui/src/controllers/editor/end-edit.controller.ts b/packages/sheets-ui/src/controllers/editor/end-edit.controller.ts
index f422d91afe..19fb8bfe41 100644
--- a/packages/sheets-ui/src/controllers/editor/end-edit.controller.ts
+++ b/packages/sheets-ui/src/controllers/editor/end-edit.controller.ts
@@ -42,11 +42,9 @@ import {
SetRangeValuesCommand,
SetSelectionsOperation,
SetWorksheetActivateCommand,
- SheetInterceptorService,
} from '@univerjs/sheets';
-import { KeyCode } from '@univerjs/ui';
+import { IEditorService, KeyCode } from '@univerjs/ui';
import { Inject } from '@wendellhu/redi';
-import type { Subscription } from 'rxjs';
import { getEditorObject } from '../../basics/editor/get-editor-object';
import { MoveSelectionCommand, MoveSelectionEnterAndTabCommand } from '../../commands/commands/set-selection.command';
@@ -74,8 +72,6 @@ enum CursorChange {
@OnLifecycle(LifecycleStages.Steady, EndEditController)
export class EndEditController extends Disposable {
- private _onInputSubscription: Nullable<Subscription>;
-
private _cursorChangeObservers: Nullable<Observer<IPointerEvent | IMouseEvent>>;
private _editorVisiblePrevious = false;
@@ -94,8 +90,8 @@ export class EndEditController extends Disposable {
@ICellEditorManagerService private readonly _cellEditorManagerService: ICellEditorManagerService,
@Inject(LexerTreeBuilder) private readonly _lexerTreeBuilder: LexerTreeBuilder,
@IUndoRedoService private _undoRedoService: IUndoRedoService,
- @Inject(SheetInterceptorService) private readonly _sheetInterceptorService: SheetInterceptorService,
- @Inject(SelectionManagerService) private readonly _selectionManagerService: SelectionManagerService
+ @Inject(SelectionManagerService) private readonly _selectionManagerService: SelectionManagerService,
+ @IEditorService private _editorService: IEditorService
) {
super();
@@ -105,8 +101,6 @@ export class EndEditController extends Disposable {
}
override dispose(): void {
- this._onInputSubscription?.unsubscribe();
-
const editorObject = this._getEditorObject();
if (editorObject == null) {
@@ -124,129 +118,131 @@ export class EndEditController extends Disposable {
}
private _initialExitInput() {
- this._onInputSubscription = this._editorBridgeService.visible$.subscribe((param) => {
- const { visible, keycode, eventType } = param;
+ this.disposeWithMe(
+ this._editorBridgeService.visible$.subscribe((param) => {
+ const { visible, keycode, eventType } = param;
- if (visible === this._editorVisiblePrevious) {
- return;
- }
+ if (visible === this._editorVisiblePrevious) {
+ return;
+ }
- this._editorVisiblePrevious = visible;
+ this._editorVisiblePrevious = visible;
- if (visible === true) {
+ if (visible === true) {
// Change `CursorChange` to changed status, when formula bar clicked.
- this._isCursorChange =
+ this._isCursorChange =
eventType === DeviceInputEventType.PointerDown
? CursorChange.CursorChange
: CursorChange.StartEditor;
- return;
- }
+ return;
+ }
- this._isCursorChange = CursorChange.InitialState;
+ this._isCursorChange = CursorChange.InitialState;
- const selections = this._selectionManagerService.getSelections();
- const currentSelection = this._selectionManagerService.getCurrent();
+ const selections = this._selectionManagerService.getSelections();
+ const currentSelection = this._selectionManagerService.getCurrent();
- if (currentSelection == null) {
- return;
- }
+ if (currentSelection == null) {
+ return;
+ }
- const { unitId: workbookId, sheetId: worksheetId, pluginName } = currentSelection;
+ const { unitId: workbookId, sheetId: worksheetId, pluginName } = currentSelection;
- this._exitInput(param);
+ this._exitInput(param);
- if (keycode === KeyCode.ESC) {
- // Reselect the current selections, when exist cell editor by press ESC.
- this._commandService.syncExecuteCommand(SetSelectionsOperation.id, {
- unitId: workbookId,
- subUnitId: worksheetId,
- pluginName,
- selections,
- });
+ if (keycode === KeyCode.ESC) {
+ // Reselect the current selections, when exist cell editor by press ESC.
+ this._commandService.syncExecuteCommand(SetSelectionsOperation.id, {
+ unitId: workbookId,
+ subUnitId: worksheetId,
+ pluginName,
+ selections,
+ });
- return;
- }
+ return;
+ }
- const editCellState = this._editorBridgeService.getEditCellState();
+ const editCellState = this._editorBridgeService.getEditCellState();
- if (editCellState == null) {
- return;
- }
+ if (editCellState == null) {
+ return;
+ }
- const { unitId, sheetId, row, column, documentLayoutObject } = editCellState;
+ const { unitId, sheetId, row, column, documentLayoutObject } = editCellState;
- // If neither the formula bar editor nor the cell editor has been edited,
- // it is considered that the content has not changed and returns directly.
- const editorIsDirty = this._editorBridgeService.getEditorDirty();
- if (editorIsDirty === false) {
- this._moveCursor(keycode);
+ // If neither the formula bar editor nor the cell editor has been edited,
+ // it is considered that the content has not changed and returns directly.
+ const editorIsDirty = this._editorBridgeService.getEditorDirty();
+ if (editorIsDirty === false) {
+ this._moveCursor(keycode);
- return;
- }
+ return;
+ }
- const workbook = this._currentUniverService.getUniverSheetInstance(unitId);
+ const workbook = this._currentUniverService.getUniverSheetInstance(unitId);
- const worksheet = workbook?.getSheetBySheetId(sheetId);
+ const worksheet = workbook?.getSheetBySheetId(sheetId);
- if (worksheet == null) {
- return;
- }
+ if (worksheet == null) {
+ return;
+ }
- const cellData: Nullable<ICellData> = getCellDataByInput(
- worksheet.getCellRaw(row, column) || {},
- documentLayoutObject,
- this._lexerTreeBuilder
- );
+ const cellData: Nullable<ICellData> = getCellDataByInput(
+ worksheet.getCellRaw(row, column) || {},
+ documentLayoutObject,
+ this._lexerTreeBuilder
+ );
- if (cellData == null) {
- this._moveCursor(keycode);
+ if (cellData == null) {
+ this._moveCursor(keycode);
- return;
- }
+ return;
+ }
- const context = {
- subUnitId: sheetId,
- unitId,
- workbook: workbook!,
- worksheet,
- row,
- col: column,
- };
- const cell = this._editorBridgeService.interceptor.fetchThroughInterceptors(
- this._editorBridgeService.interceptor.getInterceptPoints().AFTER_CELL_EDIT
- )(cellData, context);
-
- this._commandService.executeCommand(SetRangeValuesCommand.id, {
- subUnitId: sheetId,
- unitId,
- range: {
- startRow: row,
- startColumn: column,
- endRow: row,
- endColumn: column,
- },
- value: cell,
- });
+ const context = {
+ subUnitId: sheetId,
+ unitId,
+ workbook: workbook!,
+ worksheet,
+ row,
+ col: column,
+ };
+ const cell = this._editorBridgeService.interceptor.fetchThroughInterceptors(
+ this._editorBridgeService.interceptor.getInterceptPoints().AFTER_CELL_EDIT
+ )(cellData, context);
+
+ this._commandService.executeCommand(SetRangeValuesCommand.id, {
+ subUnitId: sheetId,
+ unitId,
+ range: {
+ startRow: row,
+ startColumn: column,
+ endRow: row,
+ endColumn: column,
+ },
+ value: cell,
+ });
// moveCursor need to put behind of SetRangeValuesCommand, fix https://github.com/dream-num/univer/issues/1155
- this._moveCursor(keycode);
+ this._moveCursor(keycode);
/**
* When closing the editor, switch to the current tab of the editor.
*/
- if (workbookId === unitId && sheetId !== worksheetId && this._editorBridgeService.isForceKeepVisible()) {
- this._commandService.executeCommand(SetWorksheetActivateCommand.id, {
- subUnitId: sheetId,
- unitId,
- });
- }
+ if (workbookId === unitId && sheetId !== worksheetId && this._editorBridgeService.isForceKeepVisible()) {
+ this._commandService.executeCommand(SetWorksheetActivateCommand.id, {
+ subUnitId: sheetId,
+ unitId,
+ });
+ }
/**
* When switching tabs while the editor is open,
* the operation to refresh the selection will be blocked and needs to be triggered manually.
*/
- this._selectionManagerService.refreshSelection();
- });
+ this._selectionManagerService.refreshSelection();
+ })
+ );
}
private _exitInput(param: IEditorBridgeServiceVisibleParam) {
@@ -259,7 +255,7 @@ export class EndEditController extends Disposable {
show: param.visible,
});
const editorUnitId = this._editorBridgeService.getCurrentEditorId();
- if (editorUnitId == null) {
+ if (editorUnitId == null || !this._editorService.isSheetEditor(editorUnitId)) {
return;
}
this._undoRedoService.clearUndoRedo(editorUnitId);
diff --git a/packages/sheets-ui/src/controllers/editor/formula-editor.controller.ts b/packages/sheets-ui/src/controllers/editor/formula-editor.controller.ts
index ec49923426..55a484efd8 100644
--- a/packages/sheets-ui/src/controllers/editor/formula-editor.controller.ts
+++ b/packages/sheets-ui/src/controllers/editor/formula-editor.controller.ts
@@ -47,8 +47,8 @@ import { MoveRangeMutation, SetRangeValuesMutation } from '@univerjs/sheets';
import { Inject } from '@wendellhu/redi';
import { takeUntil } from 'rxjs';
+import { SetEditorResizeOperation } from '@univerjs/ui';
import { getEditorObject } from '../../basics/editor/get-editor-object';
-import { SetEditorResizeOperation } from '../../commands/operations/set-editor-resize.operation';
import { IFormulaEditorManagerService } from '../../services/editor/formula-editor-manager.service';
import type { IEditorBridgeServiceParam } from '../../services/editor-bridge.service';
import { IEditorBridgeService } from '../../services/editor-bridge.service';
@@ -82,16 +82,11 @@ export class FormulaEditorController extends RxDisposable {
this._listenFoldBtnClick();
this._renderManagerService.currentRender$.pipe(takeUntil(this.dispose$)).subscribe((unitId) => {
- if (unitId !== DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY) {
- return;
- }
-
- if (!this._loadedMap.has(unitId)) {
- this._initialMain(unitId);
- this._loadedMap.add(unitId);
- }
+ this._create(unitId);
});
+ this._create(DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY);
+
this._textSelectionManagerService.textSelection$.pipe(takeUntil(this.dispose$)).subscribe((param) => {
if (param == null) {
return;
@@ -105,6 +100,17 @@ export class FormulaEditorController extends RxDisposable {
});
}
+ private _create(unitId: Nullable<string>) {
+ if (unitId !== DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY) {
+ return;
+ }
+
+ if (!this._loadedMap.has(unitId)) {
+ this._initialMain(unitId);
+ this._loadedMap.add(unitId);
+ }
+ }
+
private _listenFxBtnClick() {
this._formulaEditorManagerService.fxBtnClick$.pipe(takeUntil(this.dispose$)).subscribe(() => {
const isFocusButHidden =
diff --git a/packages/sheets-ui/src/controllers/editor/initialize-editor.controller.ts b/packages/sheets-ui/src/controllers/editor/initialize-editor.controller.ts
deleted file mode 100644
index 212d3c7f34..0000000000
--- a/packages/sheets-ui/src/controllers/editor/initialize-editor.controller.ts
+++ /dev/null
@@ -1,91 +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_EMPTY_DOCUMENT_VALUE,
- Disposable,
- DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY,
- DOCS_NORMAL_EDITOR_UNIT_ID_KEY,
- HorizontalAlign,
- IUniverInstanceService,
- LifecycleStages,
- OnLifecycle,
- VerticalAlign,
- WrapStrategy,
-} from '@univerjs/core';
-
-@OnLifecycle(LifecycleStages.Rendered, InitializeEditorController)
-export class InitializeEditorController extends Disposable {
- constructor(@IUniverInstanceService private readonly _currentUniverService: IUniverInstanceService) {
- super();
-
- // TODO: @JOCS, remove use setTimeout.
- setTimeout(() => {
- this._initialize();
- }, 0);
- }
-
- private _initialize() {
- // create univer doc sheet cell editor instance
- this._currentUniverService.createDoc({
- id: DOCS_NORMAL_EDITOR_UNIT_ID_KEY,
- body: {
- dataStream: `${DEFAULT_EMPTY_DOCUMENT_VALUE}`,
- textRuns: [],
- paragraphs: [
- {
- startIndex: 0,
- },
- ],
- },
- documentStyle: {},
- });
-
- // create univer doc formula bar editor instance
- const INITIAL_SNAPSHOT = {
- id: DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY,
- body: {
- dataStream: `${DEFAULT_EMPTY_DOCUMENT_VALUE}`,
- textRuns: [],
- paragraphs: [
- {
- startIndex: 0,
- },
- ],
- },
- documentStyle: {
- pageSize: {
- width: Number.POSITIVE_INFINITY,
- height: Number.POSITIVE_INFINITY,
- },
- marginTop: 5,
- marginBottom: 5,
- marginRight: 0,
- marginLeft: 0,
- paragraphLineGapDefault: 0,
- renderConfig: {
- horizontalAlign: HorizontalAlign.UNSPECIFIED,
- verticalAlign: VerticalAlign.UNSPECIFIED,
- centerAngle: 0,
- vertexAngle: 0,
- wrapStrategy: WrapStrategy.WRAP,
- },
- },
- };
-
- this._currentUniverService.createDoc(INITIAL_SNAPSHOT);
- }
-}
diff --git a/packages/sheets-ui/src/controllers/editor/start-edit.controller.ts b/packages/sheets-ui/src/controllers/editor/start-edit.controller.ts
index 198b159633..d744c42069 100644
--- a/packages/sheets-ui/src/controllers/editor/start-edit.controller.ts
+++ b/packages/sheets-ui/src/controllers/editor/start-edit.controller.ts
@@ -18,8 +18,6 @@ import type { ICommandInfo, IDocumentBody, IDocumentData, IPosition, ITextRotati
import {
DEFAULT_EMPTY_DOCUMENT_VALUE,
Disposable,
- DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY,
- DOCS_NORMAL_EDITOR_UNIT_ID_KEY,
EDITOR_ACTIVATED,
FOCUSING_EDITOR_BUT_HIDDEN,
FOCUSING_FORMULA_EDITOR,
@@ -55,13 +53,11 @@ import {
Rect,
ScrollBar,
} from '@univerjs/engine-render';
-import { KeyCode } from '@univerjs/ui';
+import { IEditorService, KeyCode, SetEditorResizeOperation } from '@univerjs/ui';
import { Inject } from '@wendellhu/redi';
-import type { Subscription } from 'rxjs';
import { getEditorObject } from '../../basics/editor/get-editor-object';
import { SetCellEditVisibleOperation } from '../../commands/operations/cell-edit.operation';
-import { SetEditorResizeOperation } from '../../commands/operations/set-editor-resize.operation';
import { ICellEditorManagerService } from '../../services/editor/cell-editor-manager.service';
import { IEditorBridgeService } from '../../services/editor-bridge.service';
import styles from '../../views/sheet-container/index.module.less';
@@ -79,10 +75,6 @@ interface ICanvasOffset {
@OnLifecycle(LifecycleStages.Steady, StartEditController)
export class StartEditController extends Disposable {
- private _onInputSubscription: Nullable<Subscription>;
-
- private _onInputActivateSubscription: Nullable<Subscription>;
-
private _editorVisiblePrevious = false;
constructor(
@@ -96,7 +88,8 @@ export class StartEditController extends Disposable {
@ITextSelectionRenderManager private readonly _textSelectionRenderManager: ITextSelectionRenderManager,
@Inject(TextSelectionManagerService) private readonly _textSelectionManagerService: TextSelectionManagerService,
@ICommandService private readonly _commandService: ICommandService,
- @Inject(LocaleService) protected readonly _localService: LocaleService
+ @Inject(LocaleService) protected readonly _localService: LocaleService,
+ @IEditorService private readonly _editorService: IEditorService
) {
super();
@@ -106,9 +99,7 @@ export class StartEditController extends Disposable {
}
override dispose(): void {
- this._onInputSubscription?.unsubscribe();
- this._onInputActivateSubscription?.unsubscribe();
}
private _initialize() {
@@ -134,7 +125,7 @@ export class StartEditController extends Disposable {
const param = this._editorBridgeService.getEditCellState();
const unitId = this._editorBridgeService.getCurrentEditorId();
- if (param == null || unitId == null) {
+ if (param == null || unitId == null || !this._editorService.isSheetEditor(unitId)) {
return;
}
@@ -154,50 +145,54 @@ export class StartEditController extends Disposable {
}
private _initialCursorSync() {
- this._cellEditorManagerService.focus$.subscribe(() => {
- this._textSelectionRenderManager.sync();
- });
+ this.disposeWithMe(
+ this._cellEditorManagerService.focus$.subscribe(() => {
+ this._textSelectionRenderManager.sync();
+ })
+ );
}
private _initialEditFocusListener() {
- this._onInputSubscription = this._editorBridgeService.currentEditCellState$.subscribe((editCellState) => {
- if (editCellState == null || this._editorBridgeService.isForceKeepVisible()) {
- return;
- }
+ this.disposeWithMe(
+ this._editorBridgeService.currentEditCellState$.subscribe((editCellState) => {
+ if (editCellState == null || this._editorBridgeService.isForceKeepVisible()) {
+ return;
+ }
- const { position, documentLayoutObject, scaleX, editorUnitId } = editCellState;
+ const { position, documentLayoutObject, scaleX, editorUnitId } = editCellState;
- const editorObject = this._getEditorObject();
+ const editorObject = this._getEditorObject();
- if (editorObject == null) {
- return;
- }
+ if (editorObject == null) {
+ return;
+ }
- const { startX, endX } = position;
+ const { startX, endX } = position;
- const { textRotation, wrapStrategy, documentModel } = documentLayoutObject;
+ const { textRotation, wrapStrategy, documentModel } = documentLayoutObject;
- const { a: angle } = textRotation as ITextRotation;
+ const { a: angle } = textRotation as ITextRotation;
- documentModel!.updateDocumentId(editorUnitId);
+ documentModel!.updateDocumentId(editorUnitId);
- if (wrapStrategy === WrapStrategy.WRAP && angle === 0) {
- documentModel!.updateDocumentDataPageSize((endX - startX) / scaleX);
- }
+ if (wrapStrategy === WrapStrategy.WRAP && angle === 0) {
+ documentModel!.updateDocumentDataPageSize((endX - startX) / scaleX);
+ }
- this._currentUniverService.changeDoc(editorUnitId, documentModel!);
+ this._currentUniverService.changeDoc(editorUnitId, documentModel!);
- this._contextService.setContextValue(FOCUSING_EDITOR_BUT_HIDDEN, true);
+ this._contextService.setContextValue(FOCUSING_EDITOR_BUT_HIDDEN, true);
- this._textSelectionManagerService.replaceTextRanges([
- {
- startOffset: 0,
- endOffset: 0,
- },
- ]);
+ this._textSelectionManagerService.replaceTextRanges([
+ {
+ startOffset: 0,
+ endOffset: 0,
+ },
+ ]);
- this._textSelectionRenderManager.activate(HIDDEN_EDITOR_POSITION, HIDDEN_EDITOR_POSITION);
- });
+ this._textSelectionRenderManager.activate(HIDDEN_EDITOR_POSITION, HIDDEN_EDITOR_POSITION);
+ })
+ );
}
private _fitTextSize(
@@ -455,102 +450,104 @@ export class StartEditController extends Disposable {
// You can double-click on the cell or input content by keyboard to put the cell into the edit state.
private _initialStartEdit() {
- this._onInputActivateSubscription = this._editorBridgeService.visible$.subscribe((param) => {
- const { visible, eventType, keycode } = param;
+ this.disposeWithMe(
+ this._editorBridgeService.visible$.subscribe((param) => {
+ const { visible, eventType, keycode } = param;
- if (visible === this._editorVisiblePrevious) {
- return;
- }
+ if (visible === this._editorVisiblePrevious) {
+ return;
+ }
- this._editorVisiblePrevious = visible;
+ this._editorVisiblePrevious = visible;
- if (visible === false) {
- return;
- }
+ if (visible === false) {
+ return;
+ }
- const editCellState = this._editorBridgeService.getEditCellState();
+ const editCellState = this._editorBridgeService.getEditCellState();
- if (editCellState == null) {
- return;
- }
+ if (editCellState == null) {
+ return;
+ }
- const {
- position,
- documentLayoutObject,
- canvasOffset,
- scaleX,
- scaleY,
- editorUnitId,
- unitId,
- isInArrayFormulaRange = false,
- } = editCellState;
-
- const editorObject = this._getEditorObject();
-
- if (editorObject == null) {
- return;
- }
+ const {
+ position,
+ documentLayoutObject,
+ canvasOffset,
+ scaleX,
+ scaleY,
+ editorUnitId,
+ unitId,
+ isInArrayFormulaRange = false,
+ } = editCellState;
+
+ const editorObject = this._getEditorObject();
+
+ if (editorObject == null) {
+ return;
+ }
- const { document, scene } = editorObject;
+ const { document, scene } = editorObject;
- this._contextService.setContextValue(EDITOR_ACTIVATED, true);
+ this._contextService.setContextValue(EDITOR_ACTIVATED, true);
- const { documentModel: documentDataModel } = documentLayoutObject;
+ const { documentModel: documentDataModel } = documentLayoutObject;
- const docParam = this._docSkeletonManagerService.getSkeletonByUnitId(editorUnitId);
+ const docParam = this._docSkeletonManagerService.getSkeletonByUnitId(editorUnitId);
- if (docParam == null || documentDataModel == null) {
- return;
- }
+ if (docParam == null || documentDataModel == null) {
+ return;
+ }
- const { skeleton } = docParam;
+ const { skeleton } = docParam;
- this._fitTextSize(position, canvasOffset, skeleton, documentLayoutObject, scaleX, scaleY);
+ this._fitTextSize(position, canvasOffset, skeleton, documentLayoutObject, scaleX, scaleY);
- // move selection
- if (
- eventType === DeviceInputEventType.Keyboard ||
+ // move selection
+ if (
+ eventType === DeviceInputEventType.Keyboard ||
(eventType === DeviceInputEventType.Dblclick && isInArrayFormulaRange)
- ) {
- const snapshot = Tools.deepClone(documentDataModel.snapshot) as IDocumentData;
- const documentViewModel = this._docViewModelManagerService.getCurrent()?.docViewModel!;
- this._resetBodyStyle(snapshot.body!);
+ ) {
+ const snapshot = Tools.deepClone(documentDataModel.snapshot) as IDocumentData;
+ const documentViewModel = this._docViewModelManagerService.getCurrent()?.docViewModel!;
+ this._resetBodyStyle(snapshot.body!);
- documentDataModel.reset(snapshot);
- documentViewModel.reset(documentDataModel);
+ documentDataModel.reset(snapshot);
+ documentViewModel.reset(documentDataModel);
- document.makeDirty();
+ document.makeDirty();
- // @JOCS, Why calculate here?
- if (keycode === KeyCode.BACKSPACE || eventType === DeviceInputEventType.Dblclick) {
- skeleton.calculate();
- this._editorBridgeService.changeEditorDirty(true);
- }
-
- this._textSelectionManagerService.replaceTextRanges([
- {
- startOffset: 0,
- endOffset: 0,
- },
- ]);
- } else if (eventType === DeviceInputEventType.Dblclick) {
- // TODO: @JOCS, Get the position close to the cursor after clicking on the cell.
- const cursor = documentDataModel.getBody()!.dataStream.length - 2 || 0;
-
- scene.getViewport(VIEWPORT_KEY.VIEW_MAIN)?.scrollTo({
- y: Number.POSITIVE_INFINITY,
- });
+ // @JOCS, Why calculate here?
+ if (keycode === KeyCode.BACKSPACE || eventType === DeviceInputEventType.Dblclick) {
+ skeleton.calculate();
+ this._editorBridgeService.changeEditorDirty(true);
+ }
- this._textSelectionManagerService.replaceTextRanges([
- {
- startOffset: cursor,
- endOffset: cursor,
- },
- ]);
- }
+ this._textSelectionManagerService.replaceTextRanges([
+ {
+ startOffset: 0,
+ endOffset: 0,
+ },
+ ]);
+ } else if (eventType === DeviceInputEventType.Dblclick) {
+ // TODO: @JOCS, Get the position close to the cursor after clicking on the cell.
+ const cursor = documentDataModel.getBody()!.dataStream.length - 2 || 0;
+
+ scene.getViewport(VIEWPORT_KEY.VIEW_MAIN)?.scrollTo({
+ y: Number.POSITIVE_INFINITY,
+ });
+
+ this._textSelectionManagerService.replaceTextRanges([
+ {
+ startOffset: cursor,
+ endOffset: cursor,
+ },
+ ]);
+ }
- this._renderManagerService.getRenderById(unitId)?.scene.resetCursor();
- });
+ this._renderManagerService.getRenderById(unitId)?.scene.resetCursor();
+ })
+ );
}
private _resetBodyStyle(body: IDocumentBody) {
@@ -595,14 +592,17 @@ export class StartEditController extends Disposable {
}
private _initialKeyboardListener() {
- this._textSelectionRenderManager.onInputBefore$.subscribe((config) => {
- const isFocusFormulaEditor = this._contextService.getContextValue(FOCUSING_FORMULA_EDITOR);
- const isFocusSheets = this._contextService.getContextValue(FOCUSING_SHEET);
+ this.disposeWithMe(
+ this._textSelectionRenderManager.onInputBefore$.subscribe((config) => {
+ const isFocusFormulaEditor = this._contextService.getContextValue(FOCUSING_FORMULA_EDITOR);
+ const isFocusSheets = this._contextService.getContextValue(FOCUSING_SHEET);
+ const unitId = this._currentUniverService.getCurrentUniverDocInstance().getUnitId();
- if (isFocusSheets && !isFocusFormulaEditor) {
- this._showEditorByKeyboard(config);
- }
- });
+ if (isFocusSheets && !isFocusFormulaEditor && this._editorService.isSheetEditor(unitId)) {
+ this._showEditorByKeyboard(config);
+ }
+ })
+ );
}
private _showEditorByKeyboard(config: Nullable<IEditorInputConfig>) {
@@ -619,17 +619,22 @@ export class StartEditController extends Disposable {
});
}
- // Listen to document edits to refresh the size of the editor.
+ /**
+ * Listen to document edits to refresh the size of the sheet editor, not for normal editor.
+ */
private _commandExecutedListener() {
const updateCommandList = [RichTextEditingMutation.id, SetEditorResizeOperation.id];
- const excludeUnitList = [DOCS_NORMAL_EDITOR_UNIT_ID_KEY, DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY];
-
this.disposeWithMe(
this._commandService.onCommandExecuted((command: ICommandInfo) => {
if (updateCommandList.includes(command.id)) {
const params = command.params as IRichTextEditingMutationParams;
const { unitId: commandUnitId } = params;
+
+ if (!this._editorService.isSheetEditor(commandUnitId)) {
+ return;
+ }
+
const unitId = this._editorBridgeService.getCurrentEditorId();
if (unitId == null) {
@@ -644,10 +649,6 @@ export class StartEditController extends Disposable {
return;
}
- if (!excludeUnitList.includes(commandUnitId)) {
- return;
- }
-
const param = this._editorBridgeService.getEditCellState();
if (param == null) {
return;
diff --git a/packages/sheets-ui/src/controllers/sheet-render.controller.ts b/packages/sheets-ui/src/controllers/sheet-render.controller.ts
index 888dd0a31c..17ebbdf686 100644
--- a/packages/sheets-ui/src/controllers/sheet-render.controller.ts
+++ b/packages/sheets-ui/src/controllers/sheet-render.controller.ts
@@ -22,20 +22,17 @@ import {
IUniverInstanceService,
LifecycleStages,
OnLifecycle,
- toDisposable,
} from '@univerjs/core';
import type { Rect, Spreadsheet, SpreadsheetColumnHeader, SpreadsheetRowHeader } from '@univerjs/engine-render';
import { IRenderManagerService } from '@univerjs/engine-render';
import {
COMMAND_LISTENER_SKELETON_CHANGE,
COMMAND_LISTENER_VALUE_CHANGE,
- SelectionManagerService,
SetWorksheetActiveOperation,
} from '@univerjs/sheets';
import { Inject } from '@wendellhu/redi';
import { SHEET_VIEW_KEY } from '../common/keys';
-import { ISelectionRenderService } from '../services/selection/selection-render.service';
import { SheetSkeletonManagerService } from '../services/sheet-skeleton-manager.service';
interface ISetWorksheetMutationParams {
@@ -49,10 +46,7 @@ export class SheetRenderController extends Disposable {
@Inject(SheetSkeletonManagerService) private readonly _sheetSkeletonManagerService: SheetSkeletonManagerService,
@IUniverInstanceService private readonly _currentUniverService: IUniverInstanceService,
@IRenderManagerService private readonly _renderManagerService: IRenderManagerService,
- @ICommandService private readonly _commandService: ICommandService,
- @ISelectionRenderService
- private readonly _selectionRenderService: ISelectionRenderService,
- @Inject(SelectionManagerService) private readonly _selectionManagerService: SelectionManagerService
+ @ICommandService private readonly _commandService: ICommandService
) {
super();
@@ -71,52 +65,50 @@ export class SheetRenderController extends Disposable {
private _initialRenderRefresh() {
this.disposeWithMe(
- toDisposable(
- this._sheetSkeletonManagerService.currentSkeleton$.subscribe((param) => {
- if (param == null) {
- return;
- }
+ this._sheetSkeletonManagerService.currentSkeleton$.subscribe((param) => {
+ if (param == null) {
+ return;
+ }
- const { skeleton: spreadsheetSkeleton, unitId, sheetId } = param;
+ const { skeleton: spreadsheetSkeleton, unitId, sheetId } = param;
- const workbook = this._currentUniverService.getUniverSheetInstance(unitId);
+ const workbook = this._currentUniverService.getUniverSheetInstance(unitId);
- const worksheet = workbook?.getSheetBySheetId(sheetId);
+ const worksheet = workbook?.getSheetBySheetId(sheetId);
- if (workbook == null || worksheet == null) {
- return;
- }
+ if (workbook == null || worksheet == null) {
+ return;
+ }
- 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 } = currentRender;
- const spreadsheet = mainComponent as Spreadsheet;
- const spreadsheetRowHeader = components.get(SHEET_VIEW_KEY.ROW) as SpreadsheetRowHeader;
- const spreadsheetColumnHeader = components.get(SHEET_VIEW_KEY.COLUMN) as SpreadsheetColumnHeader;
- const spreadsheetLeftTopPlaceholder = components.get(SHEET_VIEW_KEY.LEFT_TOP) as Rect;
+ const spreadsheet = mainComponent as Spreadsheet;
+ const spreadsheetRowHeader = components.get(SHEET_VIEW_KEY.ROW) as SpreadsheetRowHeader;
+ const spreadsheetColumnHeader = components.get(SHEET_VIEW_KEY.COLUMN) as SpreadsheetColumnHeader;
+ const spreadsheetLeftTopPlaceholder = components.get(SHEET_VIEW_KEY.LEFT_TOP) as Rect;
- const { rowHeaderWidth, columnHeaderHeight } = spreadsheetSkeleton;
+ const { rowHeaderWidth, columnHeaderHeight } = spreadsheetSkeleton;
- spreadsheet?.updateSkeleton(spreadsheetSkeleton);
- spreadsheetRowHeader?.updateSkeleton(spreadsheetSkeleton);
- spreadsheetColumnHeader?.updateSkeleton(spreadsheetSkeleton);
- spreadsheetLeftTopPlaceholder?.transformByState({
- width: rowHeaderWidth,
- height: columnHeaderHeight,
- });
- })
- )
+ spreadsheet?.updateSkeleton(spreadsheetSkeleton);
+ spreadsheetRowHeader?.updateSkeleton(spreadsheetSkeleton);
+ spreadsheetColumnHeader?.updateSkeleton(spreadsheetSkeleton);
+ spreadsheetLeftTopPlaceholder?.transformByState({
+ width: rowHeaderWidth,
+ height: columnHeaderHeight,
+ });
+ })
);
}
private _commandExecutedListener() {
this.disposeWithMe(
- this._commandService.onCommandExecuted((command: ICommandInfo, params) => {
+ this._commandService.onCommandExecuted((command: ICommandInfo) => {
const workbook = this._currentUniverService.getCurrentUniverSheetInstance();
const unitId = workbook.getUnitId();
diff --git a/packages/sheets-ui/src/controllers/sheet-ui.controller.ts b/packages/sheets-ui/src/controllers/sheet-ui.controller.ts
index 18b93a3c82..ee582db1f7 100644
--- a/packages/sheets-ui/src/controllers/sheet-ui.controller.ts
+++ b/packages/sheets-ui/src/controllers/sheet-ui.controller.ts
@@ -81,7 +81,6 @@ import {
} from '../commands/operations/cell-edit.operation';
import { RenameSheetOperation } from '../commands/operations/rename-sheet.operation';
import { SetScrollOperation } from '../commands/operations/scroll.operation';
-import { SetEditorResizeOperation } from '../commands/operations/set-editor-resize.operation';
import { SetFormatPainterOperation } from '../commands/operations/set-format-painter.operation';
import { SetZoomRatioOperation } from '../commands/operations/set-zoom-ratio.operation';
import { BorderPanel } from '../components/border-panel/BorderPanel';
@@ -268,7 +267,6 @@ export class SheetUIController extends Disposable {
ScrollCommand,
SelectAllCommand,
SetActivateCellEditOperation,
- SetEditorResizeOperation,
SetBoldCommand,
SetCellEditVisibleArrowOperation,
SetCellEditVisibleOperation,
diff --git a/packages/sheets-ui/src/controllers/status-bar.controller.ts b/packages/sheets-ui/src/controllers/status-bar.controller.ts
index 4187e735d7..a92e9ee067 100644
--- a/packages/sheets-ui/src/controllers/status-bar.controller.ts
+++ b/packages/sheets-ui/src/controllers/status-bar.controller.ts
@@ -74,7 +74,7 @@ export class StatusBarController extends Disposable {
if (selections) {
clearTimeout(this._calculateTimeout);
this._calculateTimeout = setTimeout(() => {
- const primary = selections[selections.length - 1].primary;
+ const primary = selections[selections.length - 1]?.primary;
this._calculateSelection(
selections.map((selection) => selection.range),
primary
@@ -93,7 +93,7 @@ export class StatusBarController extends Disposable {
return;
}
if (selections) {
- const primary = selections[selections.length - 1].primary;
+ const primary = selections[selections.length - 1]?.primary;
this._calculateSelection(
selections.map((selection) => selection.range),
primary
diff --git a/packages/sheets-ui/src/index.ts b/packages/sheets-ui/src/index.ts
index c49e06113a..0bc7fa1f6a 100644
--- a/packages/sheets-ui/src/index.ts
+++ b/packages/sheets-ui/src/index.ts
@@ -22,7 +22,6 @@ export { SheetCopyCommand } from './commands/commands/clipboard.command';
export { ExpandSelectionCommand, JumpOver, MoveSelectionCommand } from './commands/commands/set-selection.command';
export { SetCellEditVisibleArrowOperation } from './commands/operations/cell-edit.operation';
export { SetScrollOperation } from './commands/operations/scroll.operation';
-export { SetEditorResizeOperation } from './commands/operations/set-editor-resize.operation';
export { SetZoomRatioOperation } from './commands/operations/set-zoom-ratio.operation';
export { VIEWPORT_KEY } from './common/keys';
export { RangeSelector } from './components/range-selector/RangeSelector';
diff --git a/packages/sheets-ui/src/services/clipboard/html-to-usm/utils.ts b/packages/sheets-ui/src/services/clipboard/html-to-usm/utils.ts
index 7b709e3164..744d1d152d 100644
--- a/packages/sheets-ui/src/services/clipboard/html-to-usm/utils.ts
+++ b/packages/sheets-ui/src/services/clipboard/html-to-usm/utils.ts
@@ -16,6 +16,7 @@
import type { IParagraph, IParagraphStyle, Nullable } from '@univerjs/core';
import { DataStreamTreeTokenType, Tools } from '@univerjs/core';
+import { ptToPixel } from '@univerjs/engine-render';
export default function parseToDom(rawHtml: string) {
const parser = new DOMParser();
@@ -59,13 +60,6 @@ export function getParagraphStyle(el: HTMLElement): Nullable<IParagraphStyle> {
return Object.getOwnPropertyNames(paragraphStyle).length ? paragraphStyle : null;
}
-export function ptToPixel(pt: number) {
- // 1 pixel * 0.75 = 1 pt
- const PX_TO_PT_RATIO = 0.75;
-
- return pt / PX_TO_PT_RATIO;
-}
-
export function generateParagraphs(dataStream: string, prevParagraph?: IParagraph): IParagraph[] {
const paragraphs: IParagraph[] = [];
diff --git a/packages/sheets-ui/src/services/editor-bridge.service.ts b/packages/sheets-ui/src/services/editor-bridge.service.ts
index e3cba74b03..b9b9d3f4ae 100644
--- a/packages/sheets-ui/src/services/editor-bridge.service.ts
+++ b/packages/sheets-ui/src/services/editor-bridge.service.ts
@@ -28,6 +28,7 @@ import {
import type { Engine, IDocumentLayoutObject, Scene } from '@univerjs/engine-render';
import { convertTextRotation, DeviceInputEventType, fixLineWidthByScale, getCanvasOffsetByEngine } from '@univerjs/engine-render';
import type { ISheetLocation } from '@univerjs/sheets';
+import { IEditorService } from '@univerjs/ui';
import type { KeyCode } from '@univerjs/ui';
import type { IDisposable } from '@wendellhu/redi';
import { createIdentifier, Inject } from '@wendellhu/redi';
@@ -123,7 +124,8 @@ export class EditorBridgeService extends Disposable implements IEditorBridgeServ
@Inject(SheetSkeletonManagerService) private readonly _sheetSkeletonManagerService: SheetSkeletonManagerService,
@ISelectionRenderService private readonly _selectionRenderService: ISelectionRenderService,
@Inject(ThemeService) private readonly _themeService: ThemeService,
- @IUniverInstanceService private readonly _currentUniverService: IUniverInstanceService
+ @IUniverInstanceService private readonly _currentUniverService: IUniverInstanceService,
+ @IEditorService private readonly _editorService: IEditorService
) {
super();
@@ -263,6 +265,10 @@ export class EditorBridgeService extends Disposable implements IEditorBridgeServ
}
}
+ this._editorService.setOperationSheetUnitId(unitId);
+
+ this._editorService.setOperationSheetSubUnitId(sheetId);
+
return {
position: {
startX,
diff --git a/packages/sheets-ui/src/sheets-ui-plugin.ts b/packages/sheets-ui/src/sheets-ui-plugin.ts
index 294711cf37..c80f72922b 100644
--- a/packages/sheets-ui/src/sheets-ui-plugin.ts
+++ b/packages/sheets-ui/src/sheets-ui-plugin.ts
@@ -28,7 +28,6 @@ import { SheetContextMenuController } from './controllers/contextmenu/contextmen
import { EditingController } from './controllers/editor/editing.controller';
import { EndEditController } from './controllers/editor/end-edit.controller';
import { FormulaEditorController } from './controllers/editor/formula-editor.controller';
-import { InitializeEditorController } from './controllers/editor/initialize-editor.controller';
import { StartEditController } from './controllers/editor/start-edit.controller';
import { EditorBridgeController } from './controllers/editor-bridge.controller';
import { FormatPainterController } from './controllers/format-painter/format-painter.controller';
@@ -119,7 +118,7 @@ export class UniverSheetsUIPlugin extends Plugin {
[HeaderMoveController],
[HeaderResizeController],
[HeaderUnhideController],
- [InitializeEditorController],
+ // [InitializeEditorController],
[MoveRangeController],
[ScrollController],
[SelectionController],
diff --git a/packages/sheets-ui/src/views/editor-container/EditorContainer.tsx b/packages/sheets-ui/src/views/editor-container/EditorContainer.tsx
index 3abc8e1014..67a87e71fc 100644
--- a/packages/sheets-ui/src/views/editor-container/EditorContainer.tsx
+++ b/packages/sheets-ui/src/views/editor-container/EditorContainer.tsx
@@ -14,12 +14,12 @@
* limitations under the License.
*/
-import { DOCS_NORMAL_EDITOR_UNIT_ID_KEY } from '@univerjs/core';
-import { IRenderManagerService } from '@univerjs/engine-render';
+import type { IDocumentData } from '@univerjs/core';
+import { DEFAULT_EMPTY_DOCUMENT_VALUE, DOCS_NORMAL_EDITOR_UNIT_ID_KEY } from '@univerjs/core';
import { useDependency } from '@wendellhu/redi/react-bindings';
-import React, { useEffect, useRef, useState } from 'react';
-import { switchMap } from 'rxjs/operators';
+import React, { useEffect, useState } from 'react';
+import { IEditorService, TextEditor } from '@univerjs/ui';
import { ICellEditorManagerService } from '../../services/editor/cell-editor-manager.service';
import styles from './index.module.less';
@@ -43,63 +43,61 @@ export const EditorContainer: React.FC<ICellIEditorProps> = () => {
...EDITOR_DEFAULT_POSITION,
});
- const editorRef = useRef<HTMLDivElement>(null);
-
- const renderManagerService: IRenderManagerService = useDependency(IRenderManagerService);
const cellEditorManagerService: ICellEditorManagerService = useDependency(ICellEditorManagerService);
+ const editorService: IEditorService = useDependency(IEditorService);
+
+ const snapshot: IDocumentData = {
+ id: DOCS_NORMAL_EDITOR_UNIT_ID_KEY,
+ body: {
+ dataStream: `${DEFAULT_EMPTY_DOCUMENT_VALUE}`,
+ textRuns: [],
+ paragraphs: [
+ {
+ startIndex: 0,
+ },
+ ],
+ },
+ documentStyle: {},
+ };
+
useEffect(() => {
- const editor = editorRef.current;
- if (!editor) {
- return;
- }
-
- const renderSubscription = renderManagerService.currentRender$
- .pipe(
- switchMap(() => {
- const engine = renderManagerService.getRenderById(DOCS_NORMAL_EDITOR_UNIT_ID_KEY)?.engine;
- engine?.setContainer(editor);
-
- return cellEditorManagerService.state$;
- })
- )
- .subscribe((param) => {
- if (param == null) {
+ cellEditorManagerService.state$.subscribe((param) => {
+ if (param == null) {
+ return;
+ }
+
+ const {
+ startX = HIDDEN_EDITOR_POSITION,
+ startY = HIDDEN_EDITOR_POSITION,
+ endX = 0,
+ endY = 0,
+ show = false,
+ } = param;
+
+ if (!show) {
+ setState({
+ ...EDITOR_DEFAULT_POSITION,
+ });
+ } else {
+ setState({
+ width: endX - startX,
+ height: endY - startY,
+ left: startX,
+ top: startY,
+ });
+
+ const editor = editorService.getEditor(DOCS_NORMAL_EDITOR_UNIT_ID_KEY);
+
+ if (editor == null) {
return;
}
- const {
- startX = HIDDEN_EDITOR_POSITION,
- startY = HIDDEN_EDITOR_POSITION,
- endX = 0,
- endY = 0,
- show = false,
- } = param;
-
- if (!show) {
- setState({
- ...EDITOR_DEFAULT_POSITION,
- });
- } else {
- setState({
- width: endX - startX,
- height: endY - startY,
- left: startX,
- top: startY,
- });
-
- // update editor's rect
- const editor = editorRef.current;
- if (!editor) return;
-
- const { left, top, width, height } = editor.getBoundingClientRect();
- cellEditorManagerService.setRect({ left, top, width, height });
- }
- });
+ const { left, top, width, height } = editor.getBoundingClientRect();
- return () => {
- renderSubscription.unsubscribe();
- };
+ cellEditorManagerService.setRect({ left, top, width, height });
+ }
+ });
}, []); // Empty dependency array means this effect runs once on mount and clean up on unmount
useEffect(() => {
@@ -116,7 +114,7 @@ export const EditorContainer: React.FC<ICellIEditorProps> = () => {
height: state.height,
}}
>
- <div className={styles.editorInput} ref={editorRef} />
+ <TextEditor id={DOCS_NORMAL_EDITOR_UNIT_ID_KEY} className={styles.editorInput} snapshot={snapshot} cancelDefaultResizeListener={true} isSheetEditor={true} />
</div>
);
};
diff --git a/packages/sheets-ui/src/views/formula-bar/FormulaBar.tsx b/packages/sheets-ui/src/views/formula-bar/FormulaBar.tsx
index aef7388ff4..7ec9ff4f51 100644
--- a/packages/sheets-ui/src/views/formula-bar/FormulaBar.tsx
+++ b/packages/sheets-ui/src/views/formula-bar/FormulaBar.tsx
@@ -14,13 +14,14 @@
* limitations under the License.
*/
-import { DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY } from '@univerjs/core';
-import { DeviceInputEventType, IRenderManagerService } from '@univerjs/engine-render';
+import type { Nullable } from '@univerjs/core';
+import { DEFAULT_EMPTY_DOCUMENT_VALUE, DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY, HorizontalAlign, VerticalAlign, WrapStrategy } from '@univerjs/core';
+import { DeviceInputEventType } from '@univerjs/engine-render';
import { CheckMarkSingle, CloseSingle, DropdownSingle, FxSingle } from '@univerjs/icons';
-import { KeyCode } from '@univerjs/ui';
+import { KeyCode, TextEditor } from '@univerjs/ui';
import { useDependency } from '@wendellhu/redi/react-bindings';
import clsx from 'clsx';
-import React, { useEffect, useRef, useState } from 'react';
+import React, { useEffect, useState } from 'react';
import { IFormulaEditorManagerService } from '../../services/editor/formula-editor-manager.service';
import { IEditorBridgeService } from '../../services/editor-bridge.service';
@@ -35,48 +36,56 @@ export function FormulaBar() {
const [iconStyle, setIconStyle] = useState<string>(styles.formulaGrey);
const [arrowDirection, setArrowDirection] = useState<ArrowDirection>(ArrowDirection.Down);
- const editorRef = useRef<HTMLDivElement>(null);
-
- const renderManagerService: IRenderManagerService = useDependency(IRenderManagerService);
-
const formulaEditorManagerService = useDependency(IFormulaEditorManagerService);
const editorBridgeService = useDependency(IEditorBridgeService);
+ const INITIAL_SNAPSHOT = {
+ id: DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY,
+ body: {
+ dataStream: `${DEFAULT_EMPTY_DOCUMENT_VALUE}`,
+ textRuns: [],
+ paragraphs: [
+ {
+ startIndex: 0,
+ },
+ ],
+ },
+ documentStyle: {
+ pageSize: {
+ width: Number.POSITIVE_INFINITY,
+ height: Number.POSITIVE_INFINITY,
+ },
+ marginTop: 5,
+ marginBottom: 5,
+ marginRight: 0,
+ marginLeft: 0,
+ paragraphLineGapDefault: 0,
+ renderConfig: {
+ horizontalAlign: HorizontalAlign.UNSPECIFIED,
+ verticalAlign: VerticalAlign.TOP,
+ centerAngle: 0,
+ vertexAngle: 0,
+ wrapStrategy: WrapStrategy.WRAP,
+ },
+ },
+ };
+
useEffect(() => {
- const editor = editorRef.current;
+ editorBridgeService.visible$.subscribe((visibleInfo) => {
+ setIconStyle(visibleInfo.visible ? styles.formulaActive : styles.formulaGrey);
+ });
+ }, []); // Empty dependency array means this effect runs once on mount and clean up on unmount
- if (!editor) {
+ function resizeCallBack(editor: Nullable<HTMLDivElement>) {
+ if (editor == null) {
return;
}
- const renderSubscription = renderManagerService.currentRender$.subscribe((param) => {
- if (param !== DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY) {
- return;
- }
-
- const engine = renderManagerService.getRenderById(DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY)?.engine;
- engine?.setContainer(editor);
- });
-
- const resizeObserver = new ResizeObserver(() => {
- const editorRect = editor.getBoundingClientRect();
+ const editorRect = editor.getBoundingClientRect();
- formulaEditorManagerService.setPosition(editorRect);
- });
-
- resizeObserver.observe(editor);
-
- editorBridgeService.visible$.subscribe((visibleInfo) => {
- setIconStyle(visibleInfo.visible ? styles.formulaActive : styles.formulaGrey);
- });
-
- // Clean up on unmount
- return () => {
- resizeObserver.unobserve(editor);
- renderSubscription.unsubscribe();
- };
- }, []); // Empty dependency array means this effect runs once on mount and clean up on unmount
+ formulaEditorManagerService.setPosition(editorRect);
+ }
function handleArrowClick() {
setArrowDirection(arrowDirection === ArrowDirection.Down ? ArrowDirection.Up : ArrowDirection.Down);
@@ -142,7 +151,15 @@ export function FormulaBar() {
</div>
<div className={styles.formulaInput}>
- <div onContextMenu={(e) => e.preventDefault()} className={styles.formulaContent} ref={editorRef} />
+ <TextEditor
+ id={DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY}
+ isSheetEditor={true}
+ resizeCallBack={resizeCallBack}
+ cancelDefaultResizeListener={true}
+ onContextMenu={(e) => e.preventDefault()}
+ className={styles.formulaContent}
+ snapshot={INITIAL_SNAPSHOT}
+ />
<div className={styles.arrowContainer} onClick={handleArrowClick}>
{arrowDirection === ArrowDirection.Down
? (
diff --git a/packages/sheets-ui/src/views/formula-bar/index.module.less b/packages/sheets-ui/src/views/formula-bar/index.module.less
index 040d92f104..ee087cae30 100644
--- a/packages/sheets-ui/src/views/formula-bar/index.module.less
+++ b/packages/sheets-ui/src/views/formula-bar/index.module.less
@@ -13,7 +13,8 @@
box-sizing: border-box;
width: 80px;
height: 100%;
- padding: 6px 0;
+ // padding: 6px 0;
+ position: relative;
&-input {
height: 100%;
diff --git a/packages/sheets-ui/src/views/sheet-canvas-view.ts b/packages/sheets-ui/src/views/sheet-canvas-view.ts
index a2bb7b7267..2821af37bb 100644
--- a/packages/sheets-ui/src/views/sheet-canvas-view.ts
+++ b/packages/sheets-ui/src/views/sheet-canvas-view.ts
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-import type { Workbook, Worksheet } from '@univerjs/core';
+import type { Nullable, Workbook, Worksheet } from '@univerjs/core';
import { ICommandService, IUniverInstanceService, LifecycleStages, OnLifecycle, RxDisposable } from '@univerjs/core';
import type { IRender, IWheelEvent, Scene } from '@univerjs/engine-render';
import {
@@ -65,25 +65,41 @@ export class SheetCanvasView extends RxDisposable {
@Inject(SheetSkeletonManagerService) private readonly _sheetSkeletonManagerService: SheetSkeletonManagerService
) {
super();
- this._currentUniverService.currentSheet$.subscribe((workbook) => {
- if (workbook == null) {
- return;
- // throw new Error('workbook is null');
- }
+ this._initialize();
+ }
- const unitId = workbook.getUnitId();
- if (!this._loadedMap.has(unitId)) {
- this._currentWorkbook = workbook;
- this._addNewRender();
- this._loadedMap.add(unitId);
- }
- });
+ private _initialize() {
+ this._init();
}
override dispose(): void {
this._fps$.complete();
}
+ private _init() {
+ this._currentUniverService.currentSheet$.subscribe((workbook) => {
+ this._create(workbook);
+ });
+
+ this._currentUniverService.getAllUniverSheetsInstance().forEach((workbook) => {
+ this._create(workbook);
+ });
+ }
+
+ private _create(workbook: Nullable<Workbook>) {
+ if (workbook == null) {
+ return;
+ // throw new Error('workbook is null');
+ }
+
+ const unitId = workbook.getUnitId();
+ if (!this._loadedMap.has(unitId)) {
+ this._currentWorkbook = workbook;
+ this._addNewRender();
+ this._loadedMap.add(unitId);
+ }
+ }
+
private _addNewRender() {
const workbook = this._currentWorkbook;
diff --git a/packages/sheets-zen-editor/src/controllers/zen-editor.controller.ts b/packages/sheets-zen-editor/src/controllers/zen-editor.controller.ts
index 492362222a..9a4f056ab2 100644
--- a/packages/sheets-zen-editor/src/controllers/zen-editor.controller.ts
+++ b/packages/sheets-zen-editor/src/controllers/zen-editor.controller.ts
@@ -321,8 +321,6 @@ export class ZenEditorController extends RxDisposable {
const editCommandList = [RichTextEditingMutation.id];
- // const INCLUDE_LIST = [DOCS_NORMAL_EDITOR_UNIT_ID_KEY, DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY];
-
this.disposeWithMe(
this._commandService.onCommandExecuted((command: ICommandInfo) => {
if (editCommandList.includes(command.id)) {
diff --git a/packages/ui/package.json b/packages/ui/package.json
index 78beef3dc0..6dd36fe7ba 100644
--- a/packages/ui/package.json
+++ b/packages/ui/package.json
@@ -86,6 +86,7 @@
"@types/react-transition-group": "^4.4.10",
"@univerjs/core": "workspace:*",
"@univerjs/design": "workspace:*",
+ "@univerjs/engine-formula": "workspace:*",
"@univerjs/engine-render": "workspace:*",
"@univerjs/shared": "workspace:*",
"@wendellhu/redi": "^0.13.0",
diff --git a/packages/sheets-ui/src/commands/operations/set-editor-resize.operation.ts b/packages/ui/src/commands/operations/editor/set-editor-resize.operation.ts
similarity index 100%
rename from packages/sheets-ui/src/commands/operations/set-editor-resize.operation.ts
rename to packages/ui/src/commands/operations/editor/set-editor-resize.operation.ts
diff --git a/packages/ui/src/components/editor/TextEditor.tsx b/packages/ui/src/components/editor/TextEditor.tsx
new file mode 100644
index 0000000000..dfe07823aa
--- /dev/null
+++ b/packages/ui/src/components/editor/TextEditor.tsx
@@ -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 { IDocumentData, Nullable } from '@univerjs/core';
+import { useDependency } from '@wendellhu/redi/react-bindings';
+import React, { useEffect, useRef } from 'react';
+import type { IEditorCanvasStyle } from '../../services/editor/editor.service';
+import { IEditorService } from '../../services/editor/editor.service';
+
+type MyComponentProps = React.DetailedHTMLProps<React.HTMLAttributes<HTMLDivElement>, HTMLDivElement>;
+
+const excludeProps = ['snapshot', 'resizeCallBack', 'cancelDefaultResizeListener', 'isSheetEditor', 'canvasStyle'];
+
+export interface ITextEditorProps {
+ id: string;
+ snapshot?: IDocumentData;
+ resizeCallBack?: (editor: Nullable<HTMLDivElement>) => void;
+ cancelDefaultResizeListener?: boolean;
+ isSheetEditor?: boolean;
+ canvasStyle?: IEditorCanvasStyle;
+ value?: string;
+}
+
+/**
+ * The component to render toolbar item label and menu item label.
+ * @param props
+ * @returns
+ */
+export function TextEditor(props: ITextEditorProps & MyComponentProps): JSX.Element | null {
+ const { id, snapshot, resizeCallBack, cancelDefaultResizeListener, isSheetEditor = false, canvasStyle = {}, value } = props;
+
+ const editorService = useDependency(IEditorService);
+
+ const editorRef = useRef<HTMLDivElement>(null);
+
+ useEffect(() => {
+ const editor = editorRef.current;
+
+ if (!editor) {
+ return;
+ }
+
+ const resizeObserver = new ResizeObserver(() => {
+ if (cancelDefaultResizeListener !== true) {
+ editorService.resize(id);
+ }
+ resizeCallBack && resizeCallBack(editor);
+ });
+
+ resizeObserver.observe(editor);
+
+ editorService.register({ editorUnitId: id, initialSnapshot: snapshot, cancelDefaultResizeListener, isSheetEditor, canvasStyle, isSingle: true }, editor);
+
+ // Clean up on unmount
+ return () => {
+ resizeObserver.unobserve(editor);
+ };
+ }, []);
+
+ useEffect(() => {
+ if (value == null) {
+ return;
+ }
+ editorService.setValue(value, id);
+ }, [value]);
+
+ const propsNew = Object.fromEntries(
+ Object.entries(props).filter(([key]) => !excludeProps.includes(key))
+ );
+
+ return <div {...propsNew} ref={editorRef}></div>;
+}
diff --git a/packages/ui/src/controllers/shared-shortcut.controller.ts b/packages/ui/src/controllers/shared-shortcut.controller.ts
index e12f2786c0..a5f89a19e2 100644
--- a/packages/ui/src/controllers/shared-shortcut.controller.ts
+++ b/packages/ui/src/controllers/shared-shortcut.controller.ts
@@ -24,6 +24,7 @@ import type { IShortcutItem } from '../services/shortcut/shortcut.service';
import { IShortcutService } from '../services/shortcut/shortcut.service';
import { IClipboardInterfaceService } from '../services/clipboard/clipboard-interface.service';
import { supportClipboardAPI } from '../services/clipboard/clipboard-utils';
+import { SetEditorResizeOperation } from '../commands/operations/editor/set-editor-resize.operation';
import { RedoMenuItemFactory, UndoMenuItemFactory } from './menus/menus';
// Not that the clipboard shortcut items would only be invoked when the browser fully supports clipboard API.
@@ -98,7 +99,7 @@ export class SharedController extends Disposable {
}
private _registerCommands(): void {
- [CutCommand, CopyCommand, PasteCommand].forEach((command) =>
+ [CutCommand, CopyCommand, PasteCommand, SetEditorResizeOperation].forEach((command) =>
this.disposeWithMe(this._commandService.registerMultipleCommand(command))
);
}
diff --git a/packages/ui/src/controllers/ui/ui-desktop.controller.tsx b/packages/ui/src/controllers/ui/ui-desktop.controller.tsx
index b74ec4dd73..309b319766 100644
--- a/packages/ui/src/controllers/ui/ui-desktop.controller.tsx
+++ b/packages/ui/src/controllers/ui/ui-desktop.controller.tsx
@@ -104,8 +104,8 @@ export class DesktopUIController extends Disposable implements IDesktopUIControl
}
private _initializeEngine(element: HTMLElement) {
- const engine = this._renderManagerService.getCurrent()!.engine;
- engine.setContainer(element);
+ const engine = this._renderManagerService.getFirst()?.engine;
+ engine?.setContainer(element);
}
registerComponent(part: DesktopUIPart, component: () => React.ComponentType): IDisposable {
diff --git a/packages/ui/src/index.ts b/packages/ui/src/index.ts
index d3fb861d7c..74c6a49e68 100644
--- a/packages/ui/src/index.ts
+++ b/packages/ui/src/index.ts
@@ -76,3 +76,9 @@ export { IZenZoneService } from './services/zen-zone/zen-zone.service';
export { UniverUIPlugin } from './ui-plugin';
export * from './utils';
export { type IConfirmPartMethodOptions } from './views/components/confirm-part/interface';
+
+export { IEditorService, EditorService } from './services/editor/editor.service';
+
+export { TextEditor } from './components/editor/TextEditor';
+
+export { SetEditorResizeOperation } from './commands/operations/editor/set-editor-resize.operation';
diff --git a/packages/ui/src/services/editor/editor.service.ts b/packages/ui/src/services/editor/editor.service.ts
new file mode 100644
index 0000000000..e7b0e7efc5
--- /dev/null
+++ b/packages/ui/src/services/editor/editor.service.ts
@@ -0,0 +1,485 @@
+/**
+ * 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, IDocumentBody, IDocumentData, IDocumentStyle, IPosition, Nullable } from '@univerjs/core';
+import { DEFAULT_EMPTY_DOCUMENT_VALUE, Disposable, HorizontalAlign, IUniverInstanceService, toDisposable, VerticalAlign } 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 { IRender, ISuccinctTextRangeParam, Scene } from '@univerjs/engine-render';
+import { IRenderManagerService, UNIVER_GLOBAL_DEFAULT_FONT_SIZE } from '@univerjs/engine-render';
+
+export interface IEditorStateParam extends Partial<IPosition> {
+ visible?: boolean;
+}
+
+export interface IEditorCanvasStyle {
+ fontSize?: number;
+}
+
+export interface IEditorConfigParam {
+ editorUnitId: string;
+
+ initialSnapshot?: IDocumentData;
+ cancelDefaultResizeListener?: boolean;
+ canvasStyle?: IEditorCanvasStyle;
+ isSingle?: boolean;
+ isSheetEditor: boolean;
+}
+
+export interface IEditorSetParam extends IEditorConfigParam, IEditorStateParam {
+ render: IRender;
+ documentDataModel: DocumentDataModel;
+ editorDom: HTMLDivElement;
+}
+
+export interface IEditorSetValueParam {
+ editorUnitId: string;
+ body: IDocumentBody;
+}
+
+export interface IEditorInputFormulaParam {
+ editorUnitId: string;
+ formulaString: string;
+}
+
+class Editor {
+ constructor(private _param: IEditorSetParam) {
+
+ }
+
+ get editorUnitId() {
+ return this._param.editorUnitId;
+ }
+
+ get cancelDefaultResizeListener() {
+ return this._param.cancelDefaultResizeListener;
+ }
+
+ get render() {
+ return this._param.render;
+ }
+
+ get isSingle() {
+ return this._param.isSingle;
+ }
+
+ getBoundingClientRect() {
+ return this._param.editorDom.getBoundingClientRect();
+ }
+
+ isVisible() {
+ return this._param.visible;
+ }
+
+ isSheetEditor() {
+ return this._param.isSheetEditor === true;
+ }
+
+ getValue() {
+ return this._param.documentDataModel.getBody()?.dataStream || '';
+ }
+
+ getBody() {
+ return this._param.documentDataModel.getBody();
+ }
+
+ update(param: IEditorStateParam) {
+ this._param = {
+ ...this._param,
+ ...param,
+ };
+ }
+
+ verticalAlign() {
+ const documentDataModel = this._param?.documentDataModel;
+
+ if (documentDataModel == null || this._param.isSingle === false) {
+ return;
+ }
+
+ let fontSize = UNIVER_GLOBAL_DEFAULT_FONT_SIZE;
+
+ if (this._param.canvasStyle?.fontSize) {
+ fontSize = this._param.canvasStyle.fontSize;
+ }
+
+ const { height } = this._param.editorDom.getBoundingClientRect();
+
+ const top = (height - (fontSize * 4 / 3)) / 2 - 2;
+
+ documentDataModel.updateDocumentDataMargin({
+ t: top < 0 ? 0 : top,
+ });
+ }
+
+ updateCanvasStyle() {
+ const documentDataModel = this._param.documentDataModel;
+ if (documentDataModel == null) {
+ return;
+ }
+
+ const documentStyle: IDocumentStyle = {};
+
+ if (this._param.canvasStyle?.fontSize) {
+ if (documentStyle.textStyle == null) {
+ documentStyle.textStyle = {};
+ }
+
+ documentStyle.textStyle.fs = this._param.canvasStyle.fontSize;
+ }
+
+ documentDataModel.updateDocumentStyle(documentStyle);
+ }
+}
+
+export interface IEditorService {
+ getEditor(id?: string): Readonly<Nullable<Editor>>;
+
+ setState(param: IEditorStateParam, id: string): void;
+
+ register(config: IEditorConfigParam, container: HTMLDivElement): IDisposable;
+
+ unRegister(editorUnitId: string): void;
+
+ isVisible(id: string): Nullable<boolean>;
+
+ inputFormula$: Observable<IEditorInputFormulaParam>;
+
+ setFormula(formulaString: string): void;
+
+ resize$: Observable<string>;
+
+ resize(id: string): void;
+
+ getAllEditor(): Map<string, Editor>;
+
+ setOperationSheetUnitId(unitId: Nullable<string>): void;
+
+ getOperationSheetUnitId(): Nullable<string>;
+
+ setOperationSheetSubUnitId(sheetId: Nullable<string>): void;
+
+ getOperationSheetSubUnitId(): Nullable<string>;
+
+ isEditor(editorUnitId: string): boolean;
+
+ isSheetEditor(editorUnitId: string): boolean;
+
+ changeEditorFocus$: Observable<unknown>;
+
+ changeEditorFocus(): void;
+
+ blur$: Observable<unknown>;
+
+ blur(): void;
+
+ focus$: Observable<ISuccinctTextRangeParam>;
+
+ focus(editorUnitId?: string): void;
+
+ setValue$: Observable<IEditorSetValueParam>;
+
+ valueChange$: Observable<Readonly<Editor>>;
+
+ setValue(val: string, editorUnitId?: string): void;
+
+ setRichValue(body: IDocumentBody, editorUnitId?: string): void;
+
+ getFirstEditor(): Editor;
+}
+
+export class EditorService extends Disposable implements IEditorService, IDisposable {
+ private _editors = new Map<string, Editor>();
+
+ private readonly _state$ = new Subject<Nullable<IEditorStateParam>>();
+
+ readonly state$ = this._state$.asObservable();
+
+ private _currentSheetUnitId: Nullable<string>;
+
+ private _currentSheetSubUnitId: Nullable<string>;
+
+ private readonly _inputFormula$ = new Subject<IEditorInputFormulaParam>();
+
+ readonly inputFormula$ = this._inputFormula$.asObservable();
+
+ private readonly _resize$ = new Subject<string>();
+
+ readonly resize$ = this._resize$.asObservable();
+
+ private readonly _changeEditorFocus$ = new Subject<unknown>();
+
+ readonly changeEditorFocus$ = this._changeEditorFocus$.asObservable();
+
+ private readonly _blur$ = new Subject();
+
+ readonly blur$ = this._blur$.asObservable();
+
+ private readonly _focus$ = new Subject<ISuccinctTextRangeParam>();
+
+ readonly focus$ = this._focus$.asObservable();
+
+ private readonly _setValue$ = new Subject<IEditorSetValueParam>();
+
+ readonly setValue$ = this._setValue$.asObservable();
+
+ private readonly _valueChange$ = new Subject<Readonly<Editor>>();
+
+ readonly valueChange$ = this._valueChange$.asObservable();
+
+ constructor(
+ @IUniverInstanceService private readonly _currentUniverService: IUniverInstanceService,
+ @IRenderManagerService private readonly _renderManagerService: IRenderManagerService
+ ) {
+ super();
+ }
+
+ isEditor(editorUnitId: string) {
+ return this._editors.has(editorUnitId);
+ }
+
+ isSheetEditor(editorUnitId: string) {
+ const editor = this._editors.get(editorUnitId);
+ return !!(editor && editor.isSheetEditor());
+ }
+
+ changeEditorFocus() {
+ const documentDataModel = this._currentUniverService.getCurrentUniverDocInstance();
+ const editorUnitId = documentDataModel.getUnitId();
+ if (!this.isEditor(editorUnitId) || this.isSheetEditor(editorUnitId)) {
+ return;
+ }
+ // const editor = this._editors.get(editorUnitId);
+ this._changeEditorFocus$.next(null);
+
+ this.blur();
+ }
+
+ blur() {
+ this._blur$.next(null);
+ }
+
+ focus(editorUnitId?: string) {
+ if (editorUnitId == null) {
+ const documentDataModel = this._currentUniverService.getCurrentUniverDocInstance();
+ editorUnitId = documentDataModel.getUnitId();
+ }
+
+ const editor = this.getEditor(editorUnitId);
+
+ if (editor == null) {
+ return;
+ }
+
+ this._currentUniverService.setCurrentUniverDocInstance(editorUnitId);
+
+ const valueCount = editor.getValue().length;
+
+ this._focus$.next({
+ startOffset: valueCount - 2,
+ endOffset: valueCount - 2,
+ });
+ }
+
+ setFormula(formulaString: string, editorUnitId?: string) {
+ if (editorUnitId == null) {
+ editorUnitId = this._getCurrentEditorUnitId();
+ }
+ this._inputFormula$.next({ formulaString, editorUnitId });
+ }
+
+ setValue(val: string, editorUnitId?: string) {
+ if (editorUnitId == null) {
+ editorUnitId = this._getCurrentEditorUnitId();
+ }
+
+ if (val.substring(0, 1) === '=') {
+ this.setFormula(val, editorUnitId);
+ } else {
+ this._setValue$.next({ body: {
+ dataStream: val,
+ }, editorUnitId });
+ }
+
+ this._refreshValueChange(editorUnitId);
+ }
+
+ getValue(id?: string) {
+ const editor = this.getEditor(id);
+
+ return editor?.getValue();
+ }
+
+ setRichValue(body: IDocumentBody, editorUnitId?: string) {
+ if (editorUnitId == null) {
+ editorUnitId = this._getCurrentEditorUnitId();
+ }
+
+ this._setValue$.next({ body, editorUnitId });
+
+ this._refreshValueChange(editorUnitId);
+ }
+
+ getRichValue(id?: string) {
+ const editor = this.getEditor(id);
+
+ return editor?.getBody();
+ }
+
+ dispose(): void {
+ this._state$.complete();
+ this._editors.clear();
+ }
+
+ getEditor(id?: string): Readonly<Nullable<Editor>> {
+ if (id == null) {
+ id = this._getCurrentEditorUnitId();
+ }
+ return this._editors.get(id);
+ }
+
+ getAllEditor() {
+ return this._editors;
+ }
+
+ getFirstEditor() {
+ return [...this.getAllEditor().values()][0];
+ }
+
+ resize(unitId: string) {
+ const editor = this.getEditor(unitId);
+ if (editor == null) {
+ return;
+ }
+
+ editor.verticalAlign();
+
+ this._resize$.next(unitId);
+ }
+
+ setState(param: IEditorStateParam, id: string) {
+ const editor = this._editors.get(id);
+ if (editor) {
+ editor.update(param);
+ }
+
+ this._refresh(param);
+ }
+
+ isVisible(id: string) {
+ return this.getEditor(id)?.isVisible();
+ }
+
+ setOperationSheetUnitId(unitId: Nullable<string>) {
+ this._currentSheetUnitId = unitId;
+ }
+
+ getOperationSheetUnitId() {
+ return this._currentSheetUnitId;
+ }
+
+ setOperationSheetSubUnitId(sheetId: Nullable<string>) {
+ this._currentSheetSubUnitId = sheetId;
+ }
+
+ getOperationSheetSubUnitId() {
+ return this._currentSheetSubUnitId;
+ }
+
+ register(config: IEditorConfigParam, container: HTMLDivElement): IDisposable {
+ const { initialSnapshot, editorUnitId, isSheetEditor, canvasStyle = {}, isSingle = true } = config;
+
+ const documentDataModel = this._currentUniverService.createDoc(initialSnapshot || this._getBlank(editorUnitId));
+
+ let render = this._renderManagerService.getRenderById(editorUnitId);
+
+ if (render == null) {
+ this._renderManagerService.create(editorUnitId);
+ render = this._renderManagerService.getRenderById(editorUnitId)!;
+ }
+
+ render.engine.setContainer(container);
+
+ const editor = new Editor({ ...config, isSheetEditor, render, documentDataModel, editorDom: container, canvasStyle, isSingle });
+
+ this._editors.set(editorUnitId, editor);
+
+ // Delete scroll bar
+ (render.mainComponent?.getScene() as Scene)?.getViewports()?.[0].getScrollBar()?.dispose();
+
+ if (!editor.isSheetEditor()) {
+ editor.verticalAlign();
+ editor.updateCanvasStyle();
+ }
+
+ return toDisposable(() => {
+ this.unRegister(editorUnitId);
+ });
+ }
+
+ unRegister(editorUnitId: string) {
+ this._editors.delete(editorUnitId);
+
+ this._currentUniverService.disposeDocument(editorUnitId);
+ }
+
+ private _refreshValueChange(editorId: string) {
+ const editor = this.getEditor(editorId);
+ if (editor == null) {
+ return;
+ }
+
+ this._valueChange$.next(editor);
+ }
+
+ private _getCurrentEditorUnitId() {
+ const current = this._currentUniverService.getCurrentUniverDocInstance();
+ return current.getUnitId();
+ }
+
+ private _refresh(param: IEditorStateParam): void {
+ this._state$.next(param);
+ }
+
+ private _getBlank(id: string) {
+ return {
+ id,
+ body: {
+ dataStream: `${DEFAULT_EMPTY_DOCUMENT_VALUE}`,
+ textRuns: [],
+ paragraphs: [
+ {
+ startIndex: 0,
+ },
+ ],
+ },
+ documentStyle: {
+ renderConfig: {
+ verticalAlign: VerticalAlign.TOP,
+ horizontalAlign: HorizontalAlign.LEFT,
+ },
+ marginLeft: 2,
+ marginTop: 2,
+ },
+ } as IDocumentData;
+ }
+}
+
+export const IEditorService = createIdentifier<IEditorService>(
+ 'univer.editor.service'
+);
diff --git a/packages/ui/src/ui-plugin.ts b/packages/ui/src/ui-plugin.ts
index 8003a4320f..c9bdf8124f 100644
--- a/packages/ui/src/ui-plugin.ts
+++ b/packages/ui/src/ui-plugin.ts
@@ -50,6 +50,7 @@ import { DesktopSidebarService } from './services/sidebar/desktop-sidebar.servic
import { ISidebarService } from './services/sidebar/sidebar.service';
import { DesktopZenZoneService } from './services/zen-zone/desktop-zen-zone.service';
import { IZenZoneService } from './services/zen-zone/zen-zone.service';
+import { EditorService, IEditorService } from './services/editor/editor.service';
const PLUGIN_NAME = 'ui';
@@ -110,6 +111,7 @@ export class UniverUIPlugin extends Plugin {
[IMessageService, { useClass: DesktopMessageService, lazy: true }],
[ILocalStorageService, { useClass: DesktopLocalStorageService, lazy: true }],
[IBeforeCloseService, { useClass: DesktopBeforeCloseService }],
+ [IEditorService, { useClass: EditorService }],
// controllers
[IUIController, { useClass: DesktopUIController }],
diff --git a/packages/ui/src/views/app.module.less b/packages/ui/src/views/app.module.less
index 07669db239..d8e716c655 100644
--- a/packages/ui/src/views/app.module.less
+++ b/packages/ui/src/views/app.module.less
@@ -26,6 +26,7 @@
display: grid;
grid-template-columns: 1fr auto;
height: 100%;
+ overflow: hidden;
}
&-content {
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index adf058b210..9fa96ee7d8 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -1053,6 +1053,9 @@ importers:
'@univerjs/design':
specifier: workspace:*
version: link:../design
+ '@univerjs/engine-formula':
+ specifier: workspace:*
+ version: link:../engine-formula
'@univerjs/engine-render':
specifier: workspace:*
version: link:../engine-render