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(sheets-formula-ui): keep formula references readable in dark mode (#7897)

白熱eccd4b24df97
diff --git a/packages/sheets-formula-ui/src/views/formula-editor/hooks/__tests__/use-highlight.spec.ts b/packages/sheets-formula-ui/src/views/formula-editor/hooks/__tests__/use-highlight.spec.ts
index 9a2e750b0a..b1151ebdf3 100644
--- a/packages/sheets-formula-ui/src/views/formula-editor/hooks/__tests__/use-highlight.spec.ts
+++ b/packages/sheets-formula-ui/src/views/formula-editor/hooks/__tests__/use-highlight.spec.ts
@@ -16,8 +16,28 @@
// @vitest-environment jsdom
-import { describe, expect, it, vi } from 'vitest';
-import { calcHighlightRanges, createFormulaHighlightBody, createHighlightTextRuns } from '../use-highlight';
+import { ColorKit, Injector, ThemeService } from '@univerjs/core';
+import { CanvasColorService, ICanvasColorService } from '@univerjs/engine-render';
+import { RediContext, useDependency } from '@univerjs/ui';
+import { act, createElement } from 'react';
+import { createRoot } from 'react-dom/client';
+import { describe, expect, it, onTestFinished, vi } from 'vitest';
+import { calcHighlightRanges, createFormulaHighlightBody, createHighlightTextRuns, useColor } from '../use-highlight';
+
+(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+function FormulaReferenceColors() {
+ const colors = useColor();
+ const canvasColorService = useDependency(ICanvasColorService);
+ const themeService = useDependency(ThemeService);
+ const background = themeService.getColorFromTheme(themeService.darkMode ? 'gray.800' : 'gray.0');
+
+ return createElement('div', null, colors.formulaRefColors.map((color) => createElement('span', {
+ key: color,
+ 'data-color': color,
+ 'data-contrast': ColorKit.getContrastRatio(canvasColorService.getRenderColor(color), background),
+ })));
+}
function range(row: number, col: number, sheetId = 'sheet1', unitId = 'unit1') {
return {
@@ -31,6 +51,50 @@ function range(row: number, col: number, sheetId = 'sheet1', unitId = 'unit1') {
}
describe('use-highlight regression scenarios', () => {
+ it('keeps formula references readable after switching to dark mode and restores light colors', async () => {
+ const injector = new Injector([
+ [ThemeService],
+ [ICanvasColorService, { useClass: CanvasColorService }],
+ ]);
+ const themeService = injector.get(ThemeService);
+ const container = document.createElement('div');
+ const root = createRoot(container);
+ onTestFinished(() => {
+ act(() => root.unmount());
+ injector.dispose();
+ });
+
+ await act(async () => root.render(createElement(
+ RediContext.Provider,
+ { value: { injector } },
+ createElement(FormulaReferenceColors)
+ )));
+
+ const lightColors = Array.from(container.querySelectorAll('span'), (reference) => reference.dataset.color);
+ expect(lightColors).not.toHaveLength(0);
+
+ await act(async () => themeService.setDarkMode(true));
+ for (const reference of container.querySelectorAll('span')) {
+ expect(Number(reference.dataset.contrast)).toBeGreaterThanOrEqual(4.5);
+ }
+
+ await act(async () => themeService.setDarkMode(false));
+ expect(Array.from(container.querySelectorAll('span'), (reference) => reference.dataset.color)).toEqual(lightColors);
+
+ await act(async () => {
+ themeService.setDarkMode(true);
+ const theme = themeService.getCurrentTheme();
+ themeService.setTheme({
+ ...theme,
+ gray: { ...theme.gray, 800: '#30343d' },
+ 'loop-color': { ...theme['loop-color'], 1: 'rgb(210, 190, 250)' },
+ });
+ });
+ for (const reference of container.querySelectorAll('span')) {
+ expect(Number(reference.dataset.contrast)).toBeGreaterThanOrEqual(4.5);
+ }
+ });
+
it('does not cover the first highlighted character when there is no leading marker', () => {
const textRuns = [{ st: 0, ed: 12, ts: { cl: { rgb: '#ff0000' } } }];
diff --git a/packages/sheets-formula-ui/src/views/formula-editor/hooks/use-highlight.ts b/packages/sheets-formula-ui/src/views/formula-editor/hooks/use-highlight.ts
index 88f72f00ce..b09a09b3b2 100644
--- a/packages/sheets-formula-ui/src/views/formula-editor/hooks/use-highlight.ts
+++ b/packages/sheets-formula-ui/src/views/formula-editor/hooks/use-highlight.ts
@@ -16,10 +16,10 @@
import type { IDocumentBody, IRange, ITextRange, ITextRun, Workbook } from '@univerjs/core';
import type { Editor } from '@univerjs/docs-ui';
-import type { ISequenceNode } from '@univerjs/engine-formula';
+import type { IFormulaHighlightColors } from '@univerjs/engine-formula';
import type { ISelectionWithStyle, SheetsSelectionsService } from '@univerjs/sheets';
import type { INode } from './use-formula-token';
-import { ICommandService, IUniverInstanceService, ThemeService, UniverInstanceType } from '@univerjs/core';
+import { ColorKit, ICommandService, IUniverInstanceService, ThemeService, UniverInstanceType } from '@univerjs/core';
import { ReplaceTextRunsCommand } from '@univerjs/docs-ui';
import {
buildFormulaTextRuns,
@@ -27,10 +27,10 @@ import {
getFormulaHighlightDataStream,
IDescriptionService,
} from '@univerjs/engine-formula';
-import { IRenderManagerService } from '@univerjs/engine-render';
+import { ICanvasColorService, IRenderManagerService } from '@univerjs/engine-render';
import { IRefSelectionsService, setEndForRange } from '@univerjs/sheets';
import { ISheetSelectionRenderService, SheetSkeletonManagerService } from '@univerjs/sheets-ui';
-import { useDependency, useEvent } from '@univerjs/ui';
+import { useDependency, useEvent, useObservable } from '@univerjs/ui';
import { useEffect, useMemo } from 'react';
import { genFormulaRefSelectionStyle } from '../../../common/selection';
import { RefSelectionsRenderService } from '../../../services/render-services/ref-selections.render.service';
@@ -261,7 +261,7 @@ export function useDocHight(_leadingCharacter: string = '') {
});
return [];
} else {
- const { textRuns, refSelections } = buildTextRuns(descriptionService, colorMap, sequenceNodes);
+ const { textRuns, refSelections } = buildFormulaTextRuns(descriptionService, colorMap, sequenceNodes);
if (leadingCharacterLength) {
textRuns.forEach((e) => {
e.ed = e.ed + leadingCharacterLength;
@@ -275,7 +275,7 @@ export function useDocHight(_leadingCharacter: string = '') {
if (isNeedResetSelection) {
// Switching between uppercase and lowercase will trigger a reflow, causing the cursor to be misplaced. Let's refresh the cursor position here.
selections = editor.getSelectionRanges();
- // After 'buildTextRuns' , the content changes, most of it is deleted, and the cursor position needs to be corrected
+ // Clamp the cursor after rebuilding the formula text.
const maxOffset = highlightDataStream.length - 2 + leadingCharacterLength;
selections.forEach((selection) => {
selection.startOffset = Math.max(0, Math.min(selection.startOffset, maxOffset));
@@ -308,39 +308,27 @@ export function createHighlightTextRuns(textRuns: ITextRun[], leadingCharacterLe
: textRuns;
}
-interface IColorMap {
- formulaRefColors: string[];
- numberColor: string;
- stringColor: string;
- plainTextColor: string;
-}
-
-export function useColor(): IColorMap {
+export function useColor(): IFormulaHighlightColors {
const themeService = useDependency(ThemeService);
- const theme = themeService.getCurrentTheme();
+ const canvasColorService = useDependency(ICanvasColorService);
+ const theme = useObservable(themeService.currentTheme$, themeService.getCurrentTheme());
+ const darkMode = useObservable(themeService.darkMode$, themeService.darkMode);
const result = useMemo(() => {
- const formulaRefColors = [
- themeService.getColorFromTheme('loop-color.1'),
- themeService.getColorFromTheme('loop-color.2'),
- themeService.getColorFromTheme('loop-color.3'),
- themeService.getColorFromTheme('loop-color.4'),
- themeService.getColorFromTheme('loop-color.5'),
- themeService.getColorFromTheme('loop-color.6'),
- themeService.getColorFromTheme('loop-color.7'),
- themeService.getColorFromTheme('loop-color.8'),
- themeService.getColorFromTheme('loop-color.9'),
- themeService.getColorFromTheme('loop-color.10'),
- themeService.getColorFromTheme('loop-color.11'),
- themeService.getColorFromTheme('loop-color.12'),
- ].map((color) => themeService.isValidThemeColor(color) ? themeService.getColorFromTheme(color) : color);
+ const formulaRefColors = Object.values(theme['loop-color']).map((color) => {
+ const resolvedColor = themeService.isValidThemeColor(color) ? themeService.getColorFromTheme(color) : color;
+ if (!darkMode) return resolvedColor;
+
+ let referenceColor = new ColorKit(resolvedColor);
+ // Canvas inverts these colors, so darken the source to brighten rendered references.
+ while (referenceColor.toHsl().l > 0 && ColorKit.getContrastRatio(canvasColorService.getRenderColor(referenceColor.toHexString()), theme.gray[800]) < 4.5) {
+ referenceColor = referenceColor.darken(5);
+ }
+ return referenceColor.toHexString();
+ });
const numberColor = themeService.getColorFromTheme('blue.700');
const stringColor = themeService.getColorFromTheme('jiqing.800');
const plainTextColor = themeService.getColorFromTheme('gray.1000');
return { formulaRefColors, numberColor, stringColor, plainTextColor };
- }, [theme]);
+ }, [theme, darkMode, themeService, canvasColorService]);
return result;
}
-
-function buildTextRuns(descriptionService: IDescriptionService, colorMap: IColorMap, sequenceNodes: Array<ISequenceNode | string>) {
- return buildFormulaTextRuns(descriptionService, colorMap, sequenceNodes);
-};
diff --git a/packages/sheets-formula-ui/src/views/range-selector/__tests__/index.spec.tsx b/packages/sheets-formula-ui/src/views/range-selector/__tests__/index.spec.tsx
index 6a9c465af3..b8909c55cd 100644
--- a/packages/sheets-formula-ui/src/views/range-selector/__tests__/index.spec.tsx
+++ b/packages/sheets-formula-ui/src/views/range-selector/__tests__/index.spec.tsx
@@ -31,6 +31,7 @@ import {
} from '@univerjs/core';
import { IEditorService } from '@univerjs/docs-ui';
import { IDescriptionService, LexerTreeBuilder } from '@univerjs/engine-formula';
+import { CanvasColorService, ICanvasColorService } from '@univerjs/engine-render';
import { SetSelectionsOperation, SheetsSelectionsService } from '@univerjs/sheets';
import { IMarkSelectionService } from '@univerjs/sheets-ui';
import { IDialogService, RediContext } from '@univerjs/ui';
@@ -177,6 +178,7 @@ function createGlobalRangeSelectorTestBed() {
const injector = new Injector();
injector.add([LocaleService, { useClass: LocaleService }]);
injector.add([ThemeService, { useClass: ThemeService }]);
+ injector.add([ICanvasColorService, { useClass: CanvasColorService }]);
injector.add([LexerTreeBuilder, { useClass: LexerTreeBuilder }]);
injector.add([IDescriptionService, { useClass: TestDescriptionService as never }]);
injector.add([ICommandService, { useClass: TestCommandService as never }]);