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.

fix(doc): keep editor backgrounds transparent in dark mode (#7099)

Univer5f443a22ddb3
diff --git a/packages/docs-ui/src/controllers/__tests__/doc-render-controller.spec.ts b/packages/docs-ui/src/controllers/__tests__/doc-render-controller.spec.ts
index 381d5db01e..ad58a6ad1d 100644
--- a/packages/docs-ui/src/controllers/__tests__/doc-render-controller.spec.ts
+++ b/packages/docs-ui/src/controllers/__tests__/doc-render-controller.spec.ts
@@ -15,7 +15,7 @@
*/
import type { ICommandInfo } from '@univerjs/core';
-import { DocumentFlavor } from '@univerjs/core';
+import { DOCS_NORMAL_EDITOR_UNIT_ID_KEY, DocumentFlavor } from '@univerjs/core';
import { RichTextEditingMutation } from '@univerjs/docs';
import { Subject } from 'rxjs';
import { describe, expect, it, vi } from 'vitest';
@@ -37,9 +37,17 @@ vi.mock('@univerjs/engine-render', async (importOriginal) => {
pageLayoutType = PageLayoutType.VERTICAL;
zIndex = 0;
- constructor(_key: string, _skeleton?: unknown, config?: { pageMarginLeft?: number; pageMarginTop?: number }) {
+ fillColors: unknown[] | null = null;
+
+ constructor(_key: string, _skeleton?: unknown, config?: { pageMarginLeft?: number; pageMarginTop?: number; backgroundFillColor?: string; pageFillColor?: string; pageStrokeColor?: string; marginStrokeColor?: string }) {
this.pageMarginLeft = config?.pageMarginLeft ?? 0;
this.pageMarginTop = config?.pageMarginTop ?? 0;
+ this.fillColors = [
+ config?.backgroundFillColor,
+ config?.pageFillColor,
+ config?.pageStrokeColor,
+ config?.marginStrokeColor,
+ ];
}
changeSkeleton() {
@@ -55,6 +63,11 @@ vi.mock('@univerjs/engine-render', async (importOriginal) => {
makeDirty() {
return this;
}
+
+ setFillColors(...colors: unknown[]) {
+ this.fillColors = colors;
+ return this;
+ }
}
return {
@@ -79,9 +92,16 @@ vi.mock('@univerjs/engine-render', async (importOriginal) => {
function createControllerFixture(options?: {
documentFlavor?: DocumentFlavor;
+ pendingEditorBackgroundColor?: string | null;
pages?: Array<Record<string, unknown>>;
+ unitId?: string;
}) {
const commandCallbacks: Array<(command: ICommandInfo) => void> = [];
+ const darkMode$ = new Subject<boolean>();
+ const canvasElement = { style: {} as Record<string, string> };
+ const canvasColorService = {
+ getRenderColor: vi.fn((color: string) => color),
+ };
const skeleton = {
calculate: vi.fn(),
getSkeletonData: vi.fn(() => ({
@@ -102,10 +122,11 @@ function createControllerFixture(options?: {
currentSkeletonBefore$: new Subject(),
getSkeleton: vi.fn(() => skeleton),
};
+ const unitId = options?.unitId ?? 'doc-unit';
const context = {
- unitId: 'doc-unit',
+ unitId,
unit: {
- getUnitId: vi.fn(() => 'doc-unit'),
+ getUnitId: vi.fn(() => unitId),
getSnapshot: vi.fn(() => ({
documentStyle: {
documentFlavor: options?.documentFlavor ?? DocumentFlavor.TRADITIONAL,
@@ -121,10 +142,11 @@ function createControllerFixture(options?: {
resize: vi.fn(),
},
engine: {
+ canvasColorService,
runRenderLoop: vi.fn(),
stopRenderLoop: vi.fn(),
getCanvas: vi.fn(() => ({
- getCanvasEle: vi.fn(() => ({ style: {} })),
+ getCanvasEle: vi.fn(() => canvasElement),
})),
},
mainComponent: undefined as { width: number } | undefined,
@@ -137,6 +159,14 @@ function createControllerFixture(options?: {
return { dispose: vi.fn() };
}),
};
+ const pendingEditorRenderConfig = options?.pendingEditorBackgroundColor === undefined
+ ? null
+ : {
+ canvasStyle: options.pendingEditorBackgroundColor == null
+ ? {}
+ : { backgroundColor: options.pendingEditorBackgroundColor },
+ };
+ const editorRenderConfig = pendingEditorRenderConfig;
const pageLayoutService = {
calculatePagePosition: vi.fn(),
};
@@ -145,14 +175,15 @@ function createControllerFixture(options?: {
};
const Controller = DocRenderController as unknown as new (...args: unknown[]) => DocRenderController;
- new Controller(
+ const controller = new Controller(
context,
commandService,
{ __attachScrollEvent: vi.fn() },
skeletonManager,
{
- isEditor: vi.fn(() => false),
+ isEditor: vi.fn(() => editorRenderConfig != null),
getEditor: vi.fn(() => null),
+ getEditorRenderConfig: vi.fn(() => editorRenderConfig),
},
{
getRenderById: vi.fn(() => ({
@@ -161,16 +192,20 @@ function createControllerFixture(options?: {
},
{
getCurrentUnitOfType: vi.fn(() => ({
- getUnitId: vi.fn(() => 'doc-unit'),
+ getUnitId: vi.fn(() => unitId),
})),
},
pageLayoutService,
- selectionManager
+ selectionManager,
+ { darkMode$ }
);
return {
commandCallbacks,
+ controller,
context,
+ canvasElement,
+ canvasColorService,
skeletonManager,
pageLayoutService,
selectionManager,
@@ -220,4 +255,50 @@ describe('doc render controller', () => {
expect(context.mainComponent?.width).toBe(960);
expect((context.components.get(DOCS_VIEW_KEY.BACKGROUND) as { width: number }).width).toBe(960);
});
+
+ it('keeps internal editor doc background transparent before the render config is registered', () => {
+ const { canvasElement, context, skeletonManager } = createControllerFixture({
+ documentFlavor: DocumentFlavor.UNSPECIFIED,
+ unitId: DOCS_NORMAL_EDITOR_UNIT_ID_KEY,
+ pages: [{
+ pageWidth: 300,
+ pageHeight: 80,
+ skeDrawings: new Map(),
+ skeTables: new Map(),
+ }],
+ });
+
+ skeletonManager.currentSkeletonBefore$.next(skeletonManager.getSkeleton());
+
+ expect(canvasElement.style.backgroundColor).toBe('transparent');
+ expect((context.components.get(DOCS_VIEW_KEY.BACKGROUND) as { fillColors: unknown[] }).fillColors).toEqual([
+ 'transparent',
+ 'transparent',
+ 'transparent',
+ 'transparent',
+ ]);
+ });
+
+ it('keeps editor doc background transparent when the host provides a surface color', () => {
+ const { canvasElement, context, skeletonManager } = createControllerFixture({
+ documentFlavor: DocumentFlavor.UNSPECIFIED,
+ pendingEditorBackgroundColor: '#fff',
+ pages: [{
+ pageWidth: 300,
+ pageHeight: 80,
+ skeDrawings: new Map(),
+ skeTables: new Map(),
+ }],
+ });
+
+ skeletonManager.currentSkeletonBefore$.next(skeletonManager.getSkeleton());
+
+ expect(canvasElement.style.backgroundColor).toBe('#fff');
+ expect((context.components.get(DOCS_VIEW_KEY.BACKGROUND) as { fillColors: unknown[] }).fillColors).toEqual([
+ 'transparent',
+ 'transparent',
+ 'transparent',
+ 'transparent',
+ ]);
+ });
});
diff --git a/packages/docs-ui/src/controllers/render-controllers/doc.render-controller.ts b/packages/docs-ui/src/controllers/render-controllers/doc.render-controller.ts
index 72e82b3bb7..4156ef5fcc 100644
--- a/packages/docs-ui/src/controllers/render-controllers/doc.render-controller.ts
+++ b/packages/docs-ui/src/controllers/render-controllers/doc.render-controller.ts
@@ -17,13 +17,13 @@
import type { DocumentDataModel, EventState, ICommandInfo, Nullable } from '@univerjs/core';
import type { IRichTextEditingMutationParams } from '@univerjs/docs';
import type { DocumentSkeleton, IDocumentSkeletonPage, IRenderContext, IRenderModule, IWheelEvent } from '@univerjs/engine-render';
-import { DocumentFlavor, ICommandService, Inject, IUniverInstanceService, RxDisposable, UniverInstanceType } from '@univerjs/core';
+import { DocumentFlavor, ICommandService, Inject, isInternalEditorID, IUniverInstanceService, RxDisposable, ThemeService, UniverInstanceType } from '@univerjs/core';
import { DocSelectionManagerService, DocSkeletonManagerService, RichTextEditingMutation } from '@univerjs/docs';
import { DocBackground, Documents, IRenderManagerService, Layer, PageLayoutType, ScrollBar, Viewport } from '@univerjs/engine-render';
import { takeUntil } from 'rxjs';
import { DOCS_COMPONENT_BACKGROUND_LAYER_INDEX, DOCS_COMPONENT_DEFAULT_Z_INDEX, DOCS_COMPONENT_HEADER_LAYER_INDEX, DOCS_COMPONENT_MAIN_LAYER_INDEX, DOCS_VIEW_KEY, VIEWPORT_KEY } from '../../basics/docs-view-key';
import { DocPageLayoutService } from '../../services/doc-page-layout.service';
-import { getDocsCanvasBackgroundColor } from '../../services/docs-render.service';
+import { resolveDocsCanvasBackground } from '../../services/docs-render.service';
import { IEditorService } from '../../services/editor/editor-manager.service';
import { DocSelectionRenderService } from '../../services/selection/doc-selection-render.service';
@@ -37,13 +37,15 @@ export class DocRenderController extends RxDisposable implements IRenderModule {
@IRenderManagerService private readonly _renderManagerService: IRenderManagerService,
@IUniverInstanceService private readonly _univerInstanceService: IUniverInstanceService,
@Inject(DocPageLayoutService) private readonly _docPageLayoutService: DocPageLayoutService,
- @Inject(DocSelectionManagerService) private readonly _textSelectionManagerService: DocSelectionManagerService
+ @Inject(DocSelectionManagerService) private readonly _textSelectionManagerService: DocSelectionManagerService,
+ @Inject(ThemeService) private readonly _themeService: ThemeService
) {
super();
this._addNewRender();
this._initRenderRefresh();
this._initCommandListener();
+ this._initThemeListener();
}
reRender(unitId: string) {
@@ -62,8 +64,8 @@ export class DocRenderController extends RxDisposable implements IRenderModule {
skeleton.calculate();
// REFACTOR: @Jocs, should not use scroll bar to indicate a Zen Editor. refactor after support modern doc.
- const editor = this._editorService.getEditor(unitId);
- if (this._editorService.isEditor(unitId) && !editor?.params.scrollBar) {
+ const editorRenderConfig = this._editorService.getEditorRenderConfig(unitId);
+ if (editorRenderConfig && !editorRenderConfig.scrollBar) {
this._context.mainComponent?.makeDirty();
return;
@@ -167,7 +169,7 @@ export class DocRenderController extends RxDisposable implements IRenderModule {
scene.addObjects([documents], DOCS_COMPONENT_MAIN_LAYER_INDEX);
scene.addObjects([docBackground], DOCS_COMPONENT_BACKGROUND_LAYER_INDEX);
- if (this._editorService.getEditor(documentModel.getUnitId()) == null) {
+ if (!this._isEditorRenderUnit(documentModel.getUnitId())) {
scene.enableLayerCache(DOCS_COMPONENT_MAIN_LAYER_INDEX);
}
}
@@ -195,8 +197,8 @@ export class DocRenderController extends RxDisposable implements IRenderModule {
const { unitId } = this._context;
// REFACTOR: @Jocs, should not use scroll bar to indicate a Zen Editor. refactor after support modern doc.
- const editor = this._editorService.getEditor(unitId);
- if (this._editorService.isEditor(unitId) && !editor?.params.scrollBar) {
+ const editorRenderConfig = this._editorService.getEditorRenderConfig(unitId);
+ if (editorRenderConfig && !editorRenderConfig.scrollBar) {
this._context.mainComponent?.makeDirty();
return;
@@ -220,8 +222,16 @@ export class DocRenderController extends RxDisposable implements IRenderModule {
}));
}
+ private _initThemeListener() {
+ this.disposeWithMe(this._themeService.darkMode$.pipe(takeUntil(this.dispose$)).subscribe(() => {
+ this._syncCanvasBackground();
+ this._context.mainComponent?.makeDirty(true);
+ this._context.components.get(DOCS_VIEW_KEY.BACKGROUND)?.makeDirty(true);
+ }));
+ }
+
private _refreshPagePositionAndSelection() {
- if (this._editorService.isEditor(this._context.unitId)) {
+ if (this._isEditorRenderUnit()) {
return;
}
@@ -284,32 +294,49 @@ export class DocRenderController extends RxDisposable implements IRenderModule {
docsComponent.resize(width, height);
docBackground.resize(width, height);
- const editor = this._editorService.getEditor(unitId);
+ const editorRenderConfig = this._editorService.getEditorRenderConfig(unitId);
// REFACTOR: @JOCS show not use scrollBar to indicate it's a Zen Editor.
- if (!this._editorService.isEditor(unitId) || editor?.params.scrollBar) {
+ if (!editorRenderConfig || editorRenderConfig.scrollBar) {
scene.resize(width, height);
}
}
private _syncCanvasBackground(documentFlavor = this._context.unit.getSnapshot().documentStyle.documentFlavor) {
- const editor = this._editorService.getEditor(this._context.unitId);
- const editorBackgroundColor = editor?.params.canvasStyle?.backgroundColor;
- this._context.engine.getCanvas().getCanvasEle().style.backgroundColor = editorBackgroundColor ?? getDocsCanvasBackgroundColor(documentFlavor);
+ const editorRenderConfig = this._editorService.getEditorRenderConfig(this._context.unitId);
+ const editorBackgroundColor = editorRenderConfig?.canvasStyle.backgroundColor;
+ const resolvedBackground = resolveDocsCanvasBackground({
+ documentFlavor,
+ canvasColorService: this._context.engine.canvasColorService,
+ editorBackgroundColor,
+ isEditor: this._isEditorRenderUnit(),
+ });
+ this._context.engine.getCanvas().getCanvasEle().style.backgroundColor = resolvedBackground.canvasElementBackgroundColor;
const docBackground = this._context.components.get(DOCS_VIEW_KEY.BACKGROUND) as DocBackground | undefined;
- docBackground?.setFillColors?.(editorBackgroundColor, editorBackgroundColor, editorBackgroundColor, editorBackgroundColor);
+ docBackground?.setFillColors?.(
+ resolvedBackground.docBackgroundFillColor,
+ resolvedBackground.docBackgroundFillColor,
+ resolvedBackground.docBackgroundFillColor,
+ resolvedBackground.docBackgroundFillColor
+ );
}
private _getEditorBackgroundConfig() {
- const editorBackgroundColor = this._editorService.getEditor(this._context.unitId)?.params.canvasStyle?.backgroundColor;
- return editorBackgroundColor == null
- ? {}
- : {
- backgroundFillColor: editorBackgroundColor,
- pageFillColor: editorBackgroundColor,
- pageStrokeColor: editorBackgroundColor,
- marginStrokeColor: editorBackgroundColor,
- };
+ if (!this._isEditorRenderUnit()) {
+ return {};
+ }
+
+ const editorBackgroundColor = 'transparent';
+ return {
+ backgroundFillColor: editorBackgroundColor,
+ pageFillColor: editorBackgroundColor,
+ pageStrokeColor: editorBackgroundColor,
+ marginStrokeColor: editorBackgroundColor,
+ };
+ }
+
+ private _isEditorRenderUnit(unitId = this._context.unitId) {
+ return this._editorService.isEditor(unitId) || isInternalEditorID(unitId);
}
}
diff --git a/packages/docs-ui/src/services/__tests__/doc-services.spec.ts b/packages/docs-ui/src/services/__tests__/doc-services.spec.ts
index 0e2bb55dde..21d4923c67 100644
--- a/packages/docs-ui/src/services/__tests__/doc-services.spec.ts
+++ b/packages/docs-ui/src/services/__tests__/doc-services.spec.ts
@@ -25,7 +25,7 @@ import { DocAutoFormatService } from '../doc-auto-format.service';
import { getListMarkerFallbackBound, getListMarkerFallbackHit, getListParagraphContextMenuHit, isChecklistListType } from '../doc-event-manager.service';
import { DocMenuStyleService } from '../doc-menu-style.service';
import { DocPrintInterceptorService } from '../doc-print-interceptor.service';
-import { DocsRenderService } from '../docs-render.service';
+import { DocsRenderService, getDocsCanvasBackgroundColor, resolveDocsCanvasBackground } from '../docs-render.service';
function createDocData(): IDocumentData {
return {
@@ -324,6 +324,34 @@ describe('docs ui services', () => {
expect(renderManagerService.removeRender).toHaveBeenCalledWith('doc-3');
});
+ it('resolves the docs canvas background through the canvas color service', () => {
+ const canvasColorService = {
+ getRenderColor: vi.fn((color: string) => `rendered:${color}`),
+ };
+
+ expect(getDocsCanvasBackgroundColor(DocumentFlavor.MODERN, canvasColorService as never)).toBe('rendered:#fff');
+ expect(getDocsCanvasBackgroundColor(DocumentFlavor.TRADITIONAL, canvasColorService as never)).toBe('rendered:#fafafa');
+ expect(getDocsCanvasBackgroundColor(DocumentFlavor.MODERN, canvasColorService as never, '#123456')).toBe('rendered:#123456');
+ expect(getDocsCanvasBackgroundColor(DocumentFlavor.UNSPECIFIED, canvasColorService as never, '#fff', true)).toBe('#fff');
+ expect(resolveDocsCanvasBackground({
+ documentFlavor: DocumentFlavor.UNSPECIFIED,
+ canvasColorService: canvasColorService as never,
+ editorBackgroundColor: '#fff',
+ isEditor: true,
+ })).toEqual({
+ canvasElementBackgroundColor: '#fff',
+ docBackgroundFillColor: 'transparent',
+ });
+ expect(resolveDocsCanvasBackground({
+ documentFlavor: DocumentFlavor.UNSPECIFIED,
+ canvasColorService: canvasColorService as never,
+ isEditor: true,
+ })).toEqual({
+ canvasElementBackgroundColor: 'transparent',
+ docBackgroundFillColor: 'transparent',
+ });
+ });
+
it('keeps print interceptor defaults as pass-through and stores component mappings', () => {
const service = new DocPrintInterceptorService();
const interceptPoints = service.interceptor.getInterceptPoints();
diff --git a/packages/docs-ui/src/services/docs-render.service.ts b/packages/docs-ui/src/services/docs-render.service.ts
index 90159d37f0..550d359510 100644
--- a/packages/docs-ui/src/services/docs-render.service.ts
+++ b/packages/docs-ui/src/services/docs-render.service.ts
@@ -15,20 +15,64 @@
*/
import type { DocumentDataModel } from '@univerjs/core';
-import { DocumentFlavor, IUniverInstanceService, RxDisposable, UniverInstanceType } from '@univerjs/core';
+import type { ICanvasColorService } from '@univerjs/engine-render';
+import { DocumentFlavor, isInternalEditorID, IUniverInstanceService, RxDisposable, UniverInstanceType } from '@univerjs/core';
import { IRenderManagerService } from '@univerjs/engine-render';
import { takeUntil } from 'rxjs';
const DOC_MAIN_CANVAS_ID = 'univer-doc-main-canvas';
const DOC_TRADITIONAL_WORKSPACE_BACKGROUND_COLOR = '#fafafa';
const DOC_MODERN_WORKSPACE_BACKGROUND_COLOR = '#fff';
+const DOC_EDITOR_DEFAULT_BACKGROUND_COLOR = 'transparent';
+
+export interface IResolveDocsCanvasBackgroundOptions {
+ documentFlavor?: DocumentFlavor;
+ canvasColorService?: ICanvasColorService;
+ editorBackgroundColor?: string;
+ isEditor?: boolean;
+}
+
+export interface IResolvedDocsCanvasBackground {
+ canvasElementBackgroundColor: string;
+ docBackgroundFillColor?: string;
+}
+
+export function resolveDocsCanvasBackground(options: IResolveDocsCanvasBackgroundOptions): IResolvedDocsCanvasBackground {
+ const { documentFlavor, canvasColorService, editorBackgroundColor, isEditor } = options;
+ const backgroundColor = editorBackgroundColor ?? getDefaultDocsCanvasBackgroundColor(documentFlavor, isEditor);
+
+ if (isEditor) {
+ return {
+ canvasElementBackgroundColor: backgroundColor,
+ docBackgroundFillColor: DOC_EDITOR_DEFAULT_BACKGROUND_COLOR,
+ };
+ }
+
+ return {
+ canvasElementBackgroundColor: canvasColorService?.getRenderColor(backgroundColor) ?? backgroundColor,
+ docBackgroundFillColor: undefined,
+ };
+}
+
+function getDefaultDocsCanvasBackgroundColor(documentFlavor?: DocumentFlavor, isEditor?: boolean) {
+ if (isEditor) {
+ return DOC_EDITOR_DEFAULT_BACKGROUND_COLOR;
+ }
-export function getDocsCanvasBackgroundColor(documentFlavor?: DocumentFlavor) {
return documentFlavor === DocumentFlavor.MODERN
? DOC_MODERN_WORKSPACE_BACKGROUND_COLOR
: DOC_TRADITIONAL_WORKSPACE_BACKGROUND_COLOR;
}
+export function getDocsCanvasBackgroundColor(documentFlavor?: DocumentFlavor, canvasColorService?: ICanvasColorService, editorBackgroundColor?: string, isEditor?: boolean) {
+ return resolveDocsCanvasBackground({
+ documentFlavor,
+ canvasColorService,
+ editorBackgroundColor,
+ isEditor,
+ }).canvasElementBackgroundColor;
+}
+
export class DocsRenderService extends RxDisposable {
constructor(
@IUniverInstanceService private readonly _instanceSrv: IUniverInstanceService,
@@ -64,7 +108,12 @@ export class DocsRenderService extends RxDisposable {
const canvas = renderer.engine.getCanvas();
canvas.setId(DOC_MAIN_CANVAS_ID);
canvas.getContext().setId(DOC_MAIN_CANVAS_ID);
- canvas.getCanvasEle().style.backgroundColor = getDocsCanvasBackgroundColor(documentFlavor);
+ canvas.getCanvasEle().style.backgroundColor = getDocsCanvasBackgroundColor(
+ documentFlavor,
+ renderer.engine.canvasColorService,
+ undefined,
+ isInternalEditorID(unitId)
+ );
}
});
diff --git a/packages/docs-ui/src/services/editor/editor-manager.service.ts b/packages/docs-ui/src/services/editor/editor-manager.service.ts
index 648d448f3a..2054d8a70d 100644
--- a/packages/docs-ui/src/services/editor/editor-manager.service.ts
+++ b/packages/docs-ui/src/services/editor/editor-manager.service.ts
@@ -17,14 +17,20 @@
import type { DocumentDataModel, IDisposable, IDocumentBody, IDocumentData, Nullable } from '@univerjs/core';
import type { DocBackground, ISuccinctDocRangeParam, Scene } from '@univerjs/engine-render';
import type { Observable } from 'rxjs';
-import type { IEditorConfigParams } from './editor';
+import type { IEditorCanvasStyle, IEditorConfigParams } from './editor';
import { createIdentifier, createParagraphId, DEFAULT_EMPTY_DOCUMENT_VALUE, Disposable, EDITOR_ACTIVATED, FOCUSING_COMMENT_EDITOR, FOCUSING_EDITOR_STANDALONE, HorizontalAlign, ICommandService, IContextService, Inject, Injector, isCommentEditorID, isInternalEditorID, IUndoRedoService, IUniverInstanceService, toDisposable, UniverInstanceType, VerticalAlign } from '@univerjs/core';
import { DocSelectionManagerService } from '@univerjs/docs';
import { IRenderManagerService } from '@univerjs/engine-render';
import { fromEvent, Subject } from 'rxjs';
import { DOCS_VIEW_KEY } from '../../basics/docs-view-key';
+import { resolveDocsCanvasBackground } from '../docs-render.service';
import { Editor } from './editor';
+export interface IEditorRenderConfig {
+ canvasStyle: IEditorCanvasStyle;
+ scrollBar?: boolean;
+}
+
/**
* Not these elements will be considered as editor blur.
*/
@@ -55,6 +61,8 @@ export interface IEditorService {
isEditor(editorUnitId: string): boolean;
+ getEditorRenderConfig(editorUnitId: string): Nullable<IEditorRenderConfig>;
+
isSheetEditor(editorUnitId: string): boolean;
blur$: Observable<unknown>;
@@ -70,6 +78,8 @@ export interface IEditorService {
export class EditorService extends Disposable implements IEditorService, IDisposable {
private _editors = new Map<string, Editor>();
+ private _editorRenderConfigs = new Map<string, IEditorRenderConfig>();
+
private _focusEditorUnitId: Nullable<string>;
private readonly _blur$ = new Subject();
@@ -129,7 +139,7 @@ export class EditorService extends Disposable implements IEditorService, IDispos
}
isEditor(editorUnitId: string) {
- return this._editors.has(editorUnitId);
+ return this._editorRenderConfigs.has(editorUnitId) || this._editors.has(editorUnitId);
}
isSheetEditor(editorUnitId: string) {
@@ -191,6 +201,7 @@ export class EditorService extends Disposable implements IEditorService, IDispos
override dispose(): void {
this._editors.clear();
+ this._editorRenderConfigs.clear();
super.dispose();
}
@@ -202,9 +213,25 @@ export class EditorService extends Disposable implements IEditorService, IDispos
return this._editors;
}
+ getEditorRenderConfig(editorUnitId: string): Nullable<IEditorRenderConfig> {
+ const editor = this._editors.get(editorUnitId);
+ if (editor) {
+ return {
+ canvasStyle: editor.params.canvasStyle ?? {},
+ scrollBar: editor.params.scrollBar,
+ };
+ }
+
+ return this._editorRenderConfigs.get(editorUnitId) ?? null;
+ }
+
register(config: IEditorConfigParams, container: HTMLDivElement): IDisposable {
const { initialSnapshot, canvasStyle = {} } = config;
const editorUnitId = initialSnapshot.id;
+ this._editorRenderConfigs.set(editorUnitId, {
+ canvasStyle,
+ scrollBar: config.scrollBar,
+ });
const documentDataModel = this._univerInstanceService.getUnit<DocumentDataModel>(editorUnitId, UniverInstanceType.UNIVER_DOC);
@@ -235,16 +262,20 @@ export class EditorService extends Disposable implements IEditorService, IDispos
);
this._editors.set(editorUnitId, editor);
- if (canvasStyle.backgroundColor != null) {
- render.engine.getCanvas().getCanvasEle().style.backgroundColor = canvasStyle.backgroundColor;
- const docBackground = render.components.get(DOCS_VIEW_KEY.BACKGROUND) as DocBackground | undefined;
- docBackground?.setFillColors(
- canvasStyle.backgroundColor,
- canvasStyle.backgroundColor,
- canvasStyle.backgroundColor,
- canvasStyle.backgroundColor
- );
- }
+
+ const resolvedEditorBackground = resolveDocsCanvasBackground({
+ canvasColorService: render.engine.canvasColorService,
+ editorBackgroundColor: canvasStyle.backgroundColor,
+ isEditor: true,
+ });
+ render.engine.getCanvas().getCanvasEle().style.backgroundColor = resolvedEditorBackground.canvasElementBackgroundColor;
+ const docBackground = render.components.get(DOCS_VIEW_KEY.BACKGROUND) as DocBackground | undefined;
+ docBackground?.setFillColors(
+ resolvedEditorBackground.docBackgroundFillColor,
+ resolvedEditorBackground.docBackgroundFillColor,
+ resolvedEditorBackground.docBackgroundFillColor,
+ resolvedEditorBackground.docBackgroundFillColor
+ );
// Delete scroll bar
if (!config.scrollBar) {
@@ -266,12 +297,14 @@ export class EditorService extends Disposable implements IEditorService, IDispos
private _unRegister(editorUnitId: string) {
const editor = this._editors.get(editorUnitId);
if (editor == null) {
+ this._editorRenderConfigs.delete(editorUnitId);
return;
}
this._renderManagerService.removeRender(editorUnitId);
editor.dispose();
this._editors.delete(editorUnitId);
+ this._editorRenderConfigs.delete(editorUnitId);
this._univerInstanceService.disposeUnit(editorUnitId);
}
diff --git a/packages/engine-render/src/services/__tests__/canvas-color.spec.ts b/packages/engine-render/src/services/__tests__/canvas-color.spec.ts
index d67da7382a..214b4c7720 100644
--- a/packages/engine-render/src/services/__tests__/canvas-color.spec.ts
+++ b/packages/engine-render/src/services/__tests__/canvas-color.spec.ts
@@ -63,6 +63,12 @@ describe('Test Canvas Color', () => {
expect(invertedColor2).toEqual('rgba(255,85,85, 1)');
});
+ it('keeps transparent named colors transparent in dark mode', async () => {
+ themeService.setDarkMode(true);
+
+ expect(canvasColorService.getRenderColor('transparent')).toBe('transparent');
+ });
+
it('uses stable dark-mode overrides for common canvas interaction colors', async () => {
themeService.setDarkMode(false);
expect(canvasColorService.getRenderColor('#f3f6fa')).toEqual('#f3f6fa');
diff --git a/packages/engine-render/src/services/canvas-color.service.ts b/packages/engine-render/src/services/canvas-color.service.ts
index de66715a6b..3693cff5f4 100644
--- a/packages/engine-render/src/services/canvas-color.service.ts
+++ b/packages/engine-render/src/services/canvas-color.service.ts
@@ -91,6 +91,11 @@ export class CanvasColorService extends Disposable implements ICanvasColorServic
return this._cache.get(color)!;
}
+ if (normalizeRenderColor(color) === 'transparent') {
+ this._cache.set(color, 'transparent');
+ return 'transparent';
+ }
+
let cachedColor = '';
const mappedColor = getDarkRenderColorOverride(color);
if (mappedColor) {
diff --git a/packages/sheets-formula-ui/src/views/formula-editor/index.tsx b/packages/sheets-formula-ui/src/views/formula-editor/index.tsx
index 0adf268eca..e79f6bde43 100644
--- a/packages/sheets-formula-ui/src/views/formula-editor/index.tsx
+++ b/packages/sheets-formula-ui/src/views/formula-editor/index.tsx
@@ -264,10 +264,7 @@ export const FormulaEditor = forwardRef((props: IFormulaEditorProps, ref: Ref<IF
},
},
},
- canvasStyle: {
- ...canvasStyle,
- backgroundColor: canvasStyle?.backgroundColor ?? '#fff',
- },
+ canvasStyle,
}, formulaEditorContainerRef.current);
const editor = editorService.getEditor(editorId)! as Editor;
editorRef.current = editor;
diff --git a/packages/sheets-ui/src/services/editor-bridge.service.ts b/packages/sheets-ui/src/services/editor-bridge.service.ts
index b5598ece89..dd210dc5a3 100644
--- a/packages/sheets-ui/src/services/editor-bridge.service.ts
+++ b/packages/sheets-ui/src/services/editor-bridge.service.ts
@@ -371,8 +371,6 @@ export class EditorBridgeService extends Disposable implements IEditorBridgeServ
}
documentLayoutObject = blankModel;
}
- // background of canvas is set to transparent, so if no bgcolor sepcified in curr cell, set it to white.
- documentLayoutObject.fill = documentLayoutObject.fill || '#fff';
documentLayoutObject.documentModel?.setZoomRatio(Math.max(scaleX, scaleY));
if (cell?.isInArrayFormulaRange === true) {
diff --git a/packages/sheets-ui/src/views/editor-container/EditorContainer.tsx b/packages/sheets-ui/src/views/editor-container/EditorContainer.tsx
index 29a65e9e64..b6afa698f9 100644
--- a/packages/sheets-ui/src/views/editor-container/EditorContainer.tsx
+++ b/packages/sheets-ui/src/views/editor-container/EditorContainer.tsx
@@ -14,8 +14,10 @@
* limitations under the License.
*/
+import type { Nullable } from '@univerjs/core';
import type { KeyCode } from '@univerjs/ui';
-import { DOCS_NORMAL_EDITOR_UNIT_ID_KEY, ICommandService, IContextService } from '@univerjs/core';
+import type { ICellEditorState } from '../../services/editor-bridge.service';
+import { DOCS_NORMAL_EDITOR_UNIT_ID_KEY, ICommandService, IContextService, ThemeService } from '@univerjs/core';
import { DocSelectionRenderService, IEditorService } from '@univerjs/docs-ui';
import { DeviceInputEventType } from '@univerjs/engine-render';
import { ComponentManager, DISABLE_AUTO_FOCUS_KEY, MetaKeys, useDependency, useEvent, useObservable, useSidebarClick } from '@univerjs/ui';
@@ -38,9 +40,31 @@ const EDITOR_DEFAULT_POSITION = {
left: HIDDEN_EDITOR_POSITION,
};
+const CELL_EDITOR_DARK_SURFACE_THEME_COLOR = 'gray.800';
+
+interface ICellEditorHostBackgroundOptions {
+ darkMode?: boolean;
+ getColorFromTheme?: (color: string) => string | undefined;
+}
+
+/**
+ * @returns the host background color for the cell editor.
+ */
+function getCellEditorHostBackgroundColor(
+ editState: Nullable<Pick<ICellEditorState, 'documentLayoutObject'>>,
+ options: ICellEditorHostBackgroundOptions = {}
+): string | undefined {
+ const cellFill = editState?.documentLayoutObject.fill;
+ if (cellFill) {
+ return cellFill;
+ }
+
+ return options.darkMode ? options.getColorFromTheme?.(CELL_EDITOR_DARK_SURFACE_THEME_COLOR) : undefined;
+}
+
/**
* Cell editor container.
- * @returns
+ * @returns the rendered cell editor container.
*/
export const EditorContainer: React.FC<ICellIEditorProps> = () => {
const [state, setState] = useState({
@@ -49,6 +73,7 @@ export const EditorContainer: React.FC<ICellIEditorProps> = () => {
const cellEditorManagerService = useDependency(ICellEditorManagerService);
const editorService = useDependency(IEditorService);
const contextService = useDependency(IContextService);
+ const themeService = useDependency(ThemeService);
const componentManager = useDependency(ComponentManager);
const editorBridgeService = useDependency(IEditorBridgeService);
const visible = useObservable(editorBridgeService.visible$);
@@ -60,7 +85,8 @@ export const EditorContainer: React.FC<ICellIEditorProps> = () => {
[contextService, DISABLE_AUTO_FOCUS_KEY]
);
const FormulaEditor = componentManager.get(EMBEDDING_FORMULA_EDITOR_COMPONENT_KEY);
- const editState = editorBridgeService.getEditLocation();
+ const editState = useObservable(editorBridgeService.currentEditCellState$);
+ const darkMode = useObservable(themeService.darkMode$, themeService.darkMode);
useEffect(() => {
const sub = cellEditorManagerService.state$.subscribe((param) => {
@@ -171,6 +197,10 @@ export const EditorContainer: React.FC<ICellIEditorProps> = () => {
top: state.top,
width: state.width,
height: state.height,
+ backgroundColor: getCellEditorHostBackgroundColor(editState, {
+ darkMode,
+ getColorFromTheme: themeService.getColorFromTheme.bind(themeService),
+ }),
}}
>
{FormulaEditor && (
diff --git a/packages/sheets-ui/src/views/formula-bar/FormulaBar.tsx b/packages/sheets-ui/src/views/formula-bar/FormulaBar.tsx
index 2261545300..0561affe00 100644
--- a/packages/sheets-ui/src/views/formula-bar/FormulaBar.tsx
+++ b/packages/sheets-ui/src/views/formula-bar/FormulaBar.tsx
@@ -297,7 +297,7 @@ export function FormulaBar(props: IProps) {
data-u-comp="formula-bar"
className={clsx(`
univer-box-border univer-flex univer-bg-white univer-transition-[height] univer-ease-linear
- dark:!univer-bg-gray-900
+ dark:!univer-bg-gray-800
`, borderBottomClassName, className, {
'univer-h-7': arrowDirection === ArrowDirection.Down,
'univer-h-20': arrowDirection === ArrowDirection.Up,
@@ -361,7 +361,7 @@ export function FormulaBar(props: IProps) {
ref={ref}
className="
univer-relative univer-flex-1 univer-bg-white
- dark:!univer-bg-gray-900
+ dark:!univer-bg-gray-800
"
onPointerDown={handlePointerDown}
onPointerUp={handlePointerUp}
@@ -392,16 +392,15 @@ export function FormulaBar(props: IProps) {
}}
autoScrollbar={false}
disableContextMenu={false}
- canvasStyle={{ backgroundColor: '#fff' }}
/>
)}
- {/* When the editor is hidden, we just cover a div on the editor because re-instantiate
- the formula editor will be expensive. */}
+ {/* Cover the hidden editor instead of re-instantiating the formula editor. */}
{hideEditor && (
<div
className={`
univer-pointer-events-none univer-relative univer-left-0 univer-top-0 univer-z-[100]
univer-size-full univer-cursor-not-allowed univer-bg-white
+ dark:!univer-bg-gray-800
`}
/>
)}