Skip to content

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

feat(engine-render): add reusable line primitive (#7339)

Univer0793534d6846
diff --git a/packages/engine-render/src/__tests__/engine-scene-viewport.spec.ts b/packages/engine-render/src/__tests__/engine-scene-viewport.spec.ts
index e4bffaaca9..df06fa91fc 100644
--- a/packages/engine-render/src/__tests__/engine-scene-viewport.spec.ts
+++ b/packages/engine-render/src/__tests__/engine-scene-viewport.spec.ts
@@ -22,6 +22,7 @@ import { Engine } from '../engine';
import { Group } from '../group';
import { MAIN_VIEW_PORT_KEY, Scene } from '../scene';
import { Transformer } from '../scene.transformer';
+import { Line } from '../shape/line';
import { Rect } from '../shape/rect';
import { ScrollBar } from '../shape/scroll-bar';
import { Viewport } from '../viewport';
@@ -689,11 +690,19 @@ describe('engine scene viewport extra', () => {
transformer.setSelectedControl(rect);
const control = (transformer as any)._transformerControlMap.get(rect.oKey) as Group;
const controlObjects = control.getObjects();
- const rotateLine = controlObjects.find((o) => o.oKey.includes('__SpreadsheetTransformerRotateLine__')) as Rect;
+ const rotateLine = controlObjects.find((o) => o.oKey.includes('__SpreadsheetTransformerRotateLine__'));
const rotate = controlObjects.find((o) => o.oKey.includes('__SpreadsheetTransformerRotate__') && !o.oKey.includes('_ICON_')) as Rect;
const rotateIcon = controlObjects.find((o) => o.oKey.includes('_ICON_')) as Rect;
+ expect(rotateLine).toBeInstanceOf(Line);
+ if (!(rotateLine instanceof Line)) {
+ throw new TypeError('Rotate line should use the Line render primitive');
+ }
+
expect(rotateLine.stroke).toBe('#d1d5db');
+ expect(rotateLine.startX).toBe(rotateLine.endX);
+ expect(rotateLine.endY - rotateLine.startY).toBe(20);
+ expect(rotateLine.startX).toBe(rotate.left + rotate.width / 2);
expect(rotate.radius).toBe(4);
expect(rotateIcon.width).toBe(10);
expect(rotateIcon.height).toBe(10);
diff --git a/packages/engine-render/src/scene.transformer.ts b/packages/engine-render/src/scene.transformer.ts
index da2396d00f..e37be59218 100644
--- a/packages/engine-render/src/scene.transformer.ts
+++ b/packages/engine-render/src/scene.transformer.ts
@@ -34,6 +34,7 @@ import { degToRad, precisionTo, radToDeg } from './basics/tools';
import { Vector2 } from './basics/vector2';
import { Group } from './group';
import { ScrollTimer } from './scroll-timer';
+import { Line } from './shape/line';
import { Rect } from './shape/rect';
import { RegularPolygon } from './shape/regular-polygon';
@@ -1867,14 +1868,15 @@ export class Transformer extends Disposable implements ITransformerConfig {
applyObject
);
if (rotateEnabled) {
- const rotateLine = new Rect(`${TransformerManagerType.ROTATE_LINE}_${zIndex}`, {
+ const rotateLine = new Line(`${TransformerManagerType.ROTATE_LINE}_${zIndex}`, {
zIndex: zIndex - 1,
evented: false,
- left: lineLeft,
- top: lineTop,
- height: rotateAnchorOffset,
- width: 1,
+ startX: lineLeft,
+ startY: lineTop,
+ endX: lineLeft,
+ endY: lineTop + rotateAnchorOffset,
strokeWidth: borderStrokeWidth,
+ strokeLineCap: 'butt',
stroke: rotateStroke ?? borderStroke,
});
diff --git a/packages/engine-render/src/shape/__tests__/line.spec.ts b/packages/engine-render/src/shape/__tests__/line.spec.ts
new file mode 100644
index 0000000000..21dbf866da
--- /dev/null
+++ b/packages/engine-render/src/shape/__tests__/line.spec.ts
@@ -0,0 +1,120 @@
+/**
+ * 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 { ILineProps } from '../line';
+import { describe, expect, it, vi } from 'vitest';
+import { Vector2 } from '../../basics/vector2';
+import { UniverRenderingContext2D } from '../../context';
+import { Line } from '../line';
+
+function createLineContext() {
+ const nativeContext = document.createElement('canvas').getContext('2d');
+ if (!nativeContext) {
+ throw new Error('Canvas rendering context is unavailable');
+ }
+
+ return new UniverRenderingContext2D(nativeContext);
+}
+
+describe('Line', () => {
+ it('draws a single segment with the configured stroke style', () => {
+ const props: ILineProps = {
+ startX: 4,
+ startY: 8,
+ endX: 4,
+ endY: 28,
+ stroke: '#4285f4',
+ strokeWidth: 1,
+ strokeLineCap: 'butt',
+ strokeDashArray: [4, 2],
+ };
+ const ctx = createLineContext();
+ const moveTo = vi.spyOn(ctx, 'moveTo');
+ const lineTo = vi.spyOn(ctx, 'lineTo');
+ const setLineDash = vi.spyOn(ctx, 'setLineDash');
+ const stroke = vi.spyOn(ctx, 'stroke');
+
+ Line.drawWith(ctx, props);
+
+ expect(moveTo).toHaveBeenCalledOnce();
+ expect(moveTo).toHaveBeenCalledWith(4, 8);
+ expect(lineTo).toHaveBeenCalledOnce();
+ expect(lineTo).toHaveBeenCalledWith(4, 28);
+ expect(setLineDash).toHaveBeenCalledWith([4, 2]);
+ expect(stroke).toHaveBeenCalledOnce();
+ });
+
+ it('derives bounds from endpoints and uses line distance for hit testing', () => {
+ const line = new Line('line', {
+ startX: 20,
+ startY: 10,
+ endX: 0,
+ endY: 10,
+ stroke: '#4285f4',
+ strokeWidth: 1,
+ hitStrokeWidth: 8,
+ });
+
+ expect(line.left).toBe(0);
+ expect(line.top).toBe(10);
+ expect(line.width).toBe(20);
+ expect(line.height).toBe(0);
+ expect(line.startX).toBe(20);
+ expect(line.endX).toBe(0);
+ expect(line.isHit(new Vector2(10, 13))).toBe(true);
+ expect(line.isHit(new Vector2(10, 15))).toBe(false);
+ expect(line.isHit(new Vector2(24, 10))).toBe(true);
+ expect(line.isHit(new Vector2(25, 10))).toBe(false);
+ });
+
+ it('updates and serializes endpoint geometry without exposing internal bounds', () => {
+ const line = new Line('line', {
+ startX: 4,
+ startY: 18,
+ endX: 14,
+ endY: 8,
+ stroke: '#4285f4',
+ strokeWidth: 1,
+ });
+
+ line.setPoints({
+ startX: 30,
+ startY: 40,
+ endX: 10,
+ endY: 20,
+ });
+ line.setProps({ endX: 50 });
+
+ expect(line.left).toBe(30);
+ expect(line.top).toBe(20);
+ expect(line.width).toBe(20);
+ expect(line.height).toBe(20);
+ expect(line.startX).toBe(30);
+ expect(line.startY).toBe(40);
+ expect(line.endX).toBe(50);
+ expect(line.endY).toBe(20);
+ expect(line.toJson()).toEqual(expect.objectContaining({
+ startX: 30,
+ startY: 40,
+ endX: 50,
+ endY: 20,
+ }));
+ expect(line.toJson()).not.toHaveProperty('left');
+ expect(line.toJson()).not.toHaveProperty('top');
+ expect(line.toJson()).not.toHaveProperty('width');
+ expect(line.toJson()).not.toHaveProperty('height');
+ });
+});
diff --git a/packages/engine-render/src/shape/index.ts b/packages/engine-render/src/shape/index.ts
index 232c1ad33c..3134b33476 100644
--- a/packages/engine-render/src/shape/index.ts
+++ b/packages/engine-render/src/shape/index.ts
@@ -20,6 +20,7 @@ export * from './control';
export * from './dashedrect';
export * from './drawing';
export * from './image';
+export { type ILineProps, Line } from './line';
export * from './path';
export * from './rect';
export * from './regular-polygon';
diff --git a/packages/engine-render/src/shape/line.ts b/packages/engine-render/src/shape/line.ts
new file mode 100644
index 0000000000..bffb1ea168
--- /dev/null
+++ b/packages/engine-render/src/shape/line.ts
@@ -0,0 +1,211 @@
+/**
+ * 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 { IPosition } from '@univerjs/core';
+import type { Vector2 } from '../basics/vector2';
+import type { UniverRenderingContext } from '../context';
+import type { IShapeProps } from './shape';
+import { Shape } from './shape';
+
+export interface ILineProps extends Omit<IShapeProps, 'left' | 'top' | 'width' | 'height'>, IPosition {}
+
+function normalizeLinePosition(position: IPosition) {
+ const left = Math.min(position.startX, position.endX);
+ const top = Math.min(position.startY, position.endY);
+
+ return {
+ left,
+ top,
+ width: Math.abs(position.endX - position.startX),
+ height: Math.abs(position.endY - position.startY),
+ startX: position.startX - left,
+ startY: position.startY - top,
+ endX: position.endX - left,
+ endY: position.endY - top,
+ };
+}
+
+/**
+ * A line segment defined by two endpoints in its parent's coordinate system.
+ *
+ * The BaseObject bounds are derived internally so callers only describe line geometry.
+ */
+export class Line extends Shape<ILineProps> {
+ private _startX: number = 0;
+ private _startY: number = 0;
+ private _endX: number = 0;
+ private _endY: number = 0;
+
+ constructor(key?: string, props?: ILineProps) {
+ const position = {
+ startX: props?.startX ?? 0,
+ startY: props?.startY ?? 0,
+ endX: props?.endX ?? 0,
+ endY: props?.endY ?? 0,
+ };
+ const geometry = normalizeLinePosition(position);
+ const lineProps: ILineProps = props ?? position;
+ const normalizedProps = {
+ ...lineProps,
+ left: geometry.left,
+ top: geometry.top,
+ width: geometry.width,
+ height: geometry.height,
+ };
+
+ super(key, normalizedProps);
+
+ this._startX = geometry.startX;
+ this._startY = geometry.startY;
+ this._endX = geometry.endX;
+ this._endY = geometry.endY;
+ }
+
+ get startX() {
+ return this.left + this._startX;
+ }
+
+ get startY() {
+ return this.top + this._startY;
+ }
+
+ get endX() {
+ return this.left + this._endX;
+ }
+
+ get endY() {
+ return this.top + this._endY;
+ }
+
+ static override drawWith(ctx: UniverRenderingContext, props: ILineProps) {
+ Line._drawSegment(
+ ctx,
+ props.startX,
+ props.startY,
+ props.endX,
+ props.endY,
+ props
+ );
+ }
+
+ setPoints(position: IPosition) {
+ const geometry = normalizeLinePosition(position);
+
+ this._startX = geometry.startX;
+ this._startY = geometry.startY;
+ this._endX = geometry.endX;
+ this._endY = geometry.endY;
+ this.transformByState({
+ left: geometry.left,
+ top: geometry.top,
+ width: geometry.width,
+ height: geometry.height,
+ });
+
+ return this;
+ }
+
+ override setProps(props?: Partial<ILineProps>) {
+ if (!props) {
+ return this;
+ }
+
+ const position = {
+ startX: props.startX ?? this.startX,
+ startY: props.startY ?? this.startY,
+ endX: props.endX ?? this.endX,
+ endY: props.endY ?? this.endY,
+ };
+ const lineProps: ILineProps = {
+ ...props,
+ ...position,
+ };
+
+ super.setProps(lineProps);
+ this.setPoints(position);
+
+ return this;
+ }
+
+ override isHit(coord: Vector2) {
+ const point = this.getInverseCoord(coord);
+ const width = this._endX - this._startX;
+ const height = this._endY - this._startY;
+ const lengthSquared = width * width + height * height;
+ const parsedHitStrokeWidth = typeof this.hitStrokeWidth === 'number'
+ ? this.hitStrokeWidth
+ : Number.parseFloat(this.hitStrokeWidth);
+ const hitStrokeWidth = Number.isFinite(parsedHitStrokeWidth) ? parsedHitStrokeWidth : 0;
+ const tolerance = Math.max(this.strokeWidth, hitStrokeWidth) / 2;
+ const pointX = point.x - this._startX;
+ const pointY = point.y - this._startY;
+
+ if (lengthSquared === 0) {
+ return pointX * pointX + pointY * pointY <= tolerance * tolerance;
+ }
+
+ const projection = Math.max(0, Math.min(1, (pointX * width + pointY * height) / lengthSquared));
+ const offsetX = pointX - projection * width;
+ const offsetY = pointY - projection * height;
+
+ return offsetX * offsetX + offsetY * offsetY <= tolerance * tolerance;
+ }
+
+ override toJson() {
+ const props = super.toJson();
+ delete props.left;
+ delete props.top;
+ delete props.width;
+ delete props.height;
+
+ return {
+ ...props,
+ startX: this.startX,
+ startY: this.startY,
+ endX: this.endX,
+ endY: this.endY,
+ };
+ }
+
+ protected override _draw(ctx: UniverRenderingContext) {
+ Line._drawSegment(ctx, this._startX, this._startY, this._endX, this._endY, this);
+ }
+
+ private static _drawSegment(
+ ctx: UniverRenderingContext,
+ startX: number,
+ startY: number,
+ endX: number,
+ endY: number,
+ props: IShapeProps
+ ) {
+ if (!props.stroke || props.strokeWidth === 0) {
+ return;
+ }
+
+ ctx.save();
+ ctx.beginPath();
+
+ if (props.strokeDashArray) {
+ ctx.setLineDash(props.strokeDashArray);
+ }
+
+ ctx.moveTo(startX, startY);
+ ctx.lineTo(endX, endY);
+ this._renderPaintInOrder(ctx, props);
+ ctx.restore();
+ }
+}