Build your own AI office with Univer Office SDK. Bring editing, calculation, collaboration, and file processing into your product for people and AI agents. Built on an extensible open-source core.
TypeScript boardcollaborationdocdocxexceloffce365officepdfpptpptxpresentationsdksheetslidesspreadsheetuniverwordwordprocessorworkspacexlsx
feat: unify drawing glow and shadow effects (#7336)
Univer6bad31acf8df
diff --git a/packages/core/src/docs/data-model/rich-text-builder.ts b/packages/core/src/docs/data-model/rich-text-builder.tsindex 7526c549b9..7b912fb3dc 100644--- a/packages/core/src/docs/data-model/rich-text-builder.ts+++ b/packages/core/src/docs/data-model/rich-text-builder.ts@@ -126,7 +126,9 @@ export function normalizeData(data: IDocumentData) {* Agent-friendly text style aliases accepted by `RichTextBuilder.span()`.** The readable aliases can be combined in one object and apply only to the appended span. Native `ITextStyle` fields- * remain available for advanced document integrations.+ * remain available for advanced document integrations. Drawing effects such as `glow` and `outerShadow` are+ * especially useful when the resulting rich text is attached to a Shape; standalone document products may not expose+ * dedicated controls for them.** @example* ```ts@@ -137,6 +139,14 @@ export function normalizeData(data: IDocumentData) {* italic: true,* color: '#dc2626',* background: '#fee2e2',+ * glow: { color: '#f97316', radius: 6 },+ * outerShadow: {+ * color: '#000000',+ * opacity: 0.35,+ * blurRadius: 4,+ * distance: 3,+ * direction: 45,+ * },* });* ```*/diff --git a/packages/core/src/types/interfaces/i-document-data.ts b/packages/core/src/types/interfaces/i-document-data.tsindex b7d77b0067..32ebdcc826 100644--- a/packages/core/src/types/interfaces/i-document-data.ts+++ b/packages/core/src/types/interfaces/i-document-data.ts@@ -20,7 +20,7 @@ import type { ISize } from '../../shared/shape';import type { BooleanNumber, CellValueType, HorizontalAlign, LocaleType, TextDirection, VerticalAlign, WrapStrategy } from '../enum';import type { IDrawingParam } from './i-drawing';import type { IMention } from './i-mention';-import type { IColorStyle, IStyleBase } from './i-style-data';+import type { IColorStyle, IGlowEffect, IShadowEffect, IStyleBase } from './i-style-data';// Attention: all dimensional units, unless otherwise stated, refer to pt,1 pt = 1 / 72 in/**@@ -833,6 +833,20 @@ export interface ITextStyle extends IStyleBase {pos?: number; // positionsa?: number; // scaletextFill?: IDocTextFill;+ /**+ * DrawingML-style glow around the rendered glyphs.+ *+ * This is primarily intended for embedded rich text such as Shape text. A standalone document product may+ * preserve and render the value without exposing dedicated authoring controls.+ */+ glow?: IGlowEffect;+ /**+ * DrawingML-style outer shadow around the rendered glyphs.+ *+ * This is primarily intended for embedded rich text such as Shape text. A standalone document product may+ * preserve and render the value without exposing dedicated authoring controls.+ */+ outerShadow?: IShadowEffect;}export interface IIndentStart {diff --git a/packages/core/src/types/interfaces/i-style-data.ts b/packages/core/src/types/interfaces/i-style-data.tsindex ef6ea79ff4..69840f89d3 100644--- a/packages/core/src/types/interfaces/i-style-data.ts+++ b/packages/core/src/types/interfaces/i-style-data.ts@@ -105,6 +105,52 @@ export interface IColor {a?: number; // Alpha}+/**+ * Glow applied around drawing content.+ *+ * Dimensional values use the owning unit's drawing coordinate system.+ */+export interface IGlowEffect {+ /** Glow color as a CSS color string. */+ color: string;+ /** Glow radius. */+ radius?: number;+}++export type OuterShadowAlignment = 'tl' | 't' | 'tr' | 'l' | 'ctr' | 'r' | 'bl' | 'b' | 'br';++/**+ * Outer shadow applied to drawing content.+ *+ * Dimensional values use the owning unit's drawing coordinate system.+ */+export interface IShadowEffect {+ /** Shadow color as a CSS color string. */+ color: string;+ /** OOXML preset shadow token, when the effect originated from `prstShdw`. */+ preset?: string;+ /** Shadow opacity, from 0 (transparent) to 1 (opaque). */+ opacity?: number;+ /** Blur radius. */+ blurRadius?: number;+ /** Direction in degrees, with 0 pointing right and 90 pointing down. */+ direction?: number;+ /** Offset distance from the source. */+ distance?: number;+ /** Horizontal scale factor; 1 means 100%. */+ sx?: number;+ /** Vertical scale factor; 1 means 100%. */+ sy?: number;+ /** Horizontal skew angle in degrees. */+ skewX?: number;+ /** Vertical skew angle in degrees. */+ skewY?: number;+ /** Alignment point used while scaling or skewing the shadow. */+ alignment?: OuterShadowAlignment;+ /** Whether the shadow rotates together with its source. */+ rotateWithShape?: boolean;+}+/*** Style properties of border*/diff --git a/packages/engine-render/src/__tests__/drawing-group.spec.ts b/packages/engine-render/src/__tests__/drawing-group.spec.tsindex b0ced29113..6a758bb7aa 100644--- a/packages/engine-render/src/__tests__/drawing-group.spec.ts+++ b/packages/engine-render/src/__tests__/drawing-group.spec.ts@@ -47,6 +47,7 @@ function createContext() {shadowBlur: 0,shadowOffsetX: 0,shadowOffsetY: 0,+ filter: 'none',} as any;}@@ -132,8 +133,12 @@ describe('drawing group', () => {drawingGroup.setOuterShadow({shadowColor: 'rgba(0, 0, 0, 0.5)',shadowBlur: 12,- shadowOffsetX: -4,- shadowOffsetY: 4,+ shadowOffsetX: 4,+ shadowOffsetY: 0,+ });+ drawingGroup.setGlow({+ color: '#5b9bd5',+ radius: 4,});const ctx = createContext();@@ -143,10 +148,10 @@ describe('drawing group', () => {expect(ctx.transform).toHaveBeenCalled();expect(childRenderSpy).toHaveBeenCalled();+ expect(ctx.filter).toContain('drop-shadow(0px 0px 2px #5b9bd5)');expect(ctx.shadowColor).toBe('rgba(0, 0, 0, 0.5)');expect(ctx.shadowBlur).toBe(12);- expect(ctx.shadowOffsetX).toBe(-4);- expect(ctx.shadowOffsetY).toBe(4);+ expect(ctx.shadowOffsetX).toBe(4);});it('maps children of nested drawing groups through the parent rendered bound', () => {diff --git a/packages/engine-render/src/basics/__tests__/drawing-effect.spec.ts b/packages/engine-render/src/basics/__tests__/drawing-effect.spec.tsnew file mode 100644index 0000000000..0a02e717fa--- /dev/null+++ b/packages/engine-render/src/basics/__tests__/drawing-effect.spec.ts@@ -0,0 +1,80 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * 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 { describe, expect, it } from 'vitest';+import {+ combineDrawingEffectFilter,+ createDrawingEffectFilter,+ resolveDrawingEffectMasks,+ resolveGlowEffect,+ resolveOuterShadowEffect,+} from '../drawing-effect';++describe('drawing effect', () => {+ it('resolves an outer shadow using opacity, direction, distance, and scale', () => {+ const resolved = resolveOuterShadowEffect({+ color: '#336699',+ opacity: 0.5,+ blurRadius: 8,+ direction: 90,+ distance: 4,+ sx: 2,+ sy: 2,+ });++ expect(resolved).toMatchObject({+ color: 'rgba(51,102,153,0.5)',+ blurRadius: 16,+ offsetY: 8,+ });+ expect(resolved?.offsetX).toBeCloseTo(0);+ });++ it('resolves a centered glow with the DrawingML calibration', () => {+ expect(resolveGlowEffect({+ color: '#5b9bd5',+ radius: 12,+ })).toEqual({+ color: '#5b9bd5',+ blurRadius: 6,+ offsetX: 0,+ offsetY: 0,+ });+ });++ it('creates one filter chain for glow and shadow without duplicating the source draw', () => {+ expect(createDrawingEffectFilter(+ { color: '#5b9bd5', radius: 4 },+ { color: '#000000', opacity: 0.4, blurRadius: 3, distance: 2, direction: 0 }+ )).toBe(+ 'drop-shadow(0px 0px 2px #5b9bd5) '+ + 'drop-shadow(2px 0px 3px rgba(0,0,0,0.4))'+ );+ expect(combineDrawingEffectFilter('blur(1px)', 'drop-shadow(0 0 1px red)'))+ .toBe('blur(1px) drop-shadow(0 0 1px red)');+ });++ it('resolves alpha-mask passes for glow and outer shadow', () => {+ expect(resolveDrawingEffectMasks(+ { color: '#5b9bd5', radius: 4 },+ { color: '#000000', blurRadius: 3 }+ )).toEqual([+ { color: '#5b9bd5', blurRadius: 2, offsetX: 0, offsetY: 0 },+ { color: '#5b9bd5', blurRadius: 2, offsetX: 0, offsetY: 0 },+ { color: '#000000', blurRadius: 3, offsetX: 0, offsetY: 0 },+ ]);+ });+});diff --git a/packages/engine-render/src/basics/drawing-effect.ts b/packages/engine-render/src/basics/drawing-effect.tsnew file mode 100644index 0000000000..d137ee83c6--- /dev/null+++ b/packages/engine-render/src/basics/drawing-effect.ts@@ -0,0 +1,133 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * 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 { IGlowEffect, IShadowEffect } from '@univerjs/core';+import { ColorKit } from '@univerjs/core';++// Canvas blur visually spans about twice the DrawingML glow radius. This factor is verified against PowerPoint output.+const DRAWINGML_GLOW_BLUR_SCALE = 0.5;++export interface IResolvedDrawingShadow {+ color: string;+ blurRadius: number;+ offsetX: number;+ offsetY: number;+}++function clamp(value: number, min: number, max: number): number {+ return Math.max(min, Math.min(max, value));+}++function colorWithOpacity(color: string, opacity: number | undefined): string {+ if (opacity === undefined) {+ return color;+ }++ const parsedColor = new ColorKit(color);+ if (!parsedColor.isValid) {+ return color;+ }++ return parsedColor.setAlpha(parsedColor.getAlpha() * clamp(opacity, 0, 1)).toRgbString();+}++function cssPixels(value: number): string {+ return `${Math.abs(value) < Number.EPSILON ? 0 : value}px`;+}++function toDropShadowFilter(effect: IResolvedDrawingShadow): string {+ return `drop-shadow(${cssPixels(effect.offsetX)} ${cssPixels(effect.offsetY)} ${cssPixels(effect.blurRadius)} ${effect.color})`;+}++export function resolveOuterShadowEffect(effect: IShadowEffect | undefined): IResolvedDrawingShadow | undefined {+ if (!effect?.color) {+ return undefined;+ }++ const distance = effect.distance ?? 0;+ const direction = ((effect.direction ?? 0) * Math.PI) / 180;+ const sizeScale = ((effect.sx ?? 1) + (effect.sy ?? 1)) / 2;++ return {+ color: colorWithOpacity(effect.color, effect.opacity),+ blurRadius: Math.max(0, effect.blurRadius ?? 0) * sizeScale,+ offsetX: Math.cos(direction) * distance * sizeScale,+ offsetY: Math.sin(direction) * distance * sizeScale,+ };+}++export function resolveGlowEffect(effect: IGlowEffect | undefined): IResolvedDrawingShadow | undefined {+ if (!effect?.color) {+ return undefined;+ }++ return {+ color: effect.color,+ blurRadius: Math.max(0, effect.radius ?? 0) * DRAWINGML_GLOW_BLUR_SCALE,+ offsetX: 0,+ offsetY: 0,+ };+}++/**+ * Resolves effects painted from an off-screen alpha mask.+ *+ * A glow uses two centered mask passes to match PowerPoint's DrawingML glow density without repainting source content.+ */+export function resolveDrawingEffectMasks(+ glow: IGlowEffect | undefined,+ outerShadow: IShadowEffect | undefined+): IResolvedDrawingShadow[] {+ const effects: IResolvedDrawingShadow[] = [];+ const resolvedGlow = resolveGlowEffect(glow);+ const resolvedOuterShadow = resolveOuterShadowEffect(outerShadow);++ if (resolvedGlow) {+ effects.push(resolvedGlow, resolvedGlow);+ }+ if (resolvedOuterShadow) {+ effects.push(resolvedOuterShadow);+ }++ return effects;+}++export function createDrawingEffectFilter(+ glow: IGlowEffect | undefined,+ outerShadow: IShadowEffect | undefined+): string {+ const filters: string[] = [];+ const resolvedGlow = resolveGlowEffect(glow);+ const resolvedOuterShadow = resolveOuterShadowEffect(outerShadow);++ if (resolvedGlow) {+ filters.push(toDropShadowFilter(resolvedGlow));+ }++ if (resolvedOuterShadow) {+ filters.push(toDropShadowFilter(resolvedOuterShadow));+ }++ return filters.join(' ');+}++export function combineDrawingEffectFilter(currentFilter: string, effectFilter: string): string {+ if (!effectFilter) {+ return currentFilter;+ }++ return currentFilter && currentFilter !== 'none' ? `${currentFilter} ${effectFilter}` : effectFilter;+}diff --git a/packages/engine-render/src/components/docs/extensions/__tests__/font-and-base-line.spec.ts b/packages/engine-render/src/components/docs/extensions/__tests__/font-and-base-line.spec.tsindex e853716240..cb6407f3b9 100644--- a/packages/engine-render/src/components/docs/extensions/__tests__/font-and-base-line.spec.ts+++ b/packages/engine-render/src/components/docs/extensions/__tests__/font-and-base-line.spec.ts@@ -52,6 +52,7 @@ function createContext(): MockRenderContext {};return {fillStyle: '',+ filter: 'none',font: '10px Arial',save: vi.fn(),restore: vi.fn(),@@ -113,6 +114,48 @@ function createGlyph(content: string, overrides?: GlyphOverrides): IDocumentSkel}describe('docs font and baseline extension', () => {+ it('renders public glow and outer shadow fields in one text draw', () => {+ const extension = new FontAndBaseLine();+ const TestContext = createContext();+ let filterDuringDraw = '';+ TestContext.fillText.mockImplementation(() => {+ filterDuringDraw = TestContext.filter;+ });+ extension.extensionOffset = {+ spanPointWithFont: Vector2.create(12, 20),+ spanStartPoint: Vector2.create(10, 10),+ centerPoint: Vector2.create(8, 8),+ renderConfig: {+ vertexAngle: 0,+ centerAngle: 0,+ },+ };++ extension.draw(TestContext, DEFAULT_SCALE, createGlyph('A', {+ ts: {+ fs: 12,+ cl: { rgb: '#223344' },+ glow: {+ color: '#5b9bd5',+ radius: 4,+ },+ outerShadow: {+ color: '#000000',+ opacity: 0.4,+ blurRadius: 3,+ distance: 2,+ direction: 0,+ },+ },+ }));++ expect(TestContext.fillText).toHaveBeenCalledTimes(1);+ expect(filterDuringDraw).toContain('drop-shadow(0px 0px 2px #5b9bd5)');+ expect(filterDuringDraw).toContain('drop-shadow(2px 0px 3px rgba(0,0,0,0.4))');+ expect(TestContext.save).toHaveBeenCalledTimes(1);+ expect(TestContext.restore).toHaveBeenCalledTimes(1);+ });+it('handles text drawing with baseline offsets and vertical text branch', () => {const extension = new FontAndBaseLine();const TestContext = createContext();diff --git a/packages/engine-render/src/components/docs/extensions/font-and-base-line.ts b/packages/engine-render/src/components/docs/extensions/font-and-base-line.tsindex 4b9c94bafc..12599b97bc 100644--- a/packages/engine-render/src/components/docs/extensions/font-and-base-line.ts+++ b/packages/engine-render/src/components/docs/extensions/font-and-base-line.ts@@ -23,6 +23,7 @@ import { BaselineOffset, getColorStyle } from '@univerjs/core';import { GlyphType } from '../../../basics';import { cjk } from '../../../basics/cjk-regexp';import { COLOR_BLACK_RGB } from '../../../basics/const';+import { combineDrawingEffectFilter, createDrawingEffectFilter } from '../../../basics/drawing-effect';import { Vector2 } from '../../../basics/vector2';import { CheckboxShape } from '../../../shape';import { DocumentsSpanAndLineExtensionRegistry } from '../../extension';@@ -97,7 +98,7 @@ export class FontAndBaseLine extends docExtension {}}- const { cl: colorStyle, va: baselineOffset, textFill } = textStyle;+ const { cl: colorStyle, va: baselineOffset, textFill, glow, outerShadow } = textStyle;const fontColor = getColorStyle(colorStyle) || COLOR_BLACK_RGB;if (baselineOffset === BaselineOffset.SUPERSCRIPT) {@@ -106,15 +107,32 @@ export class FontAndBaseLine extends docExtension {spanPointWithFont.y += bBox.sbo;}- if (this._fillTextWithTextFill(ctx, glyph, spanPointWithFont, textFill, fontColor)) {+ const drawText = () => {+ if (this._fillTextWithTextFill(ctx, glyph, spanPointWithFont, textFill, fontColor)) {+ return;+ }++ if (fontColor && this._preFontColor !== fontColor) {+ ctx.fillStyle = fontColor;+ }++ this._fillText(ctx, glyph, spanPointWithFont);+ };+ if (!glow && !outerShadow) {+ drawText();return;}- if (fontColor && this._preFontColor !== fontColor) {- ctx.fillStyle = fontColor;+ const effectFilter = createDrawingEffectFilter(glow, outerShadow);+ if (!effectFilter) {+ drawText();+ return;}- this._fillText(ctx, glyph, spanPointWithFont);+ ctx.save();+ ctx.filter = combineDrawingEffectFilter(ctx.filter, effectFilter);+ drawText();+ ctx.restore();}private _fillTextWithTextFill(diff --git a/packages/engine-render/src/drawing-group.ts b/packages/engine-render/src/drawing-group.tsindex 12d04a20b4..24eadc2587 100644--- a/packages/engine-render/src/drawing-group.ts+++ b/packages/engine-render/src/drawing-group.ts@@ -14,11 +14,12 @@* limitations under the License.*/-import type { IGroupBaseBound } from '@univerjs/core';+import type { IGlowEffect, IGroupBaseBound } from '@univerjs/core';import type { BaseObject } from './base-object';import type { IViewportInfo, Vector2 } from './basics';import type { UniverRenderingContext } from './context';import { RENDER_CLASS_TYPE, Transform } from './basics';+import { combineDrawingEffectFilter, createDrawingEffectFilter } from './basics/drawing-effect';import { Group } from './group';export interface IDrawingGroupShadow {@@ -45,11 +46,18 @@ export class DrawingGroupObject extends Group {private _outerShadow?: IDrawingGroupShadow;+ private _glow?: IGlowEffect;+setOuterShadow(shadow?: IDrawingGroupShadow): void {this._outerShadow = shadow;this.makeDirty(true);}+ setGlow(glow?: IGlowEffect): void {+ this._glow = glow;+ this.makeDirty(true);+ }+/*** Set the baseBound (chOff/chExt in OOXML) for this group.* This defines the coordinate space of children within the group.@@ -103,6 +111,10 @@ export class DrawingGroupObject extends Group {const centerX = realLeft + realWidth / 2;const centerY = realTop + realHeight / 2;ctx.transform(m[0], m[1], m[2], m[3], centerX, centerY);+ const effectFilter = createDrawingEffectFilter(this._glow, undefined);+ if (effectFilter) {+ ctx.filter = combineDrawingEffectFilter(ctx.filter, effectFilter);+ }if (this._outerShadow) {ctx.shadowColor = this._outerShadow.shadowColor;ctx.shadowBlur = this._outerShadow.shadowBlur;diff --git a/packages/engine-render/src/index.ts b/packages/engine-render/src/index.tsindex 2e6c1d7a7d..e2cb4f58da 100644--- a/packages/engine-render/src/index.ts+++ b/packages/engine-render/src/index.ts@@ -16,6 +16,14 @@export * from './base-object';export * from './basics';+export {+ combineDrawingEffectFilter,+ createDrawingEffectFilter,+ resolveDrawingEffectMasks,+ resolveGlowEffect,+ resolveOuterShadowEffect,+} from './basics/drawing-effect';+export type { IResolvedDrawingShadow } from './basics/drawing-effect';export { getOffsetRectForDom } from './basics/position';export * from './canvas';export * from './components';