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.

style(base-render): eslint member ordering

Dushusir816c0242eb13
diff --git a/packages/base-render/src/BaseObject.ts b/packages/base-render/src/BaseObject.ts
index 6bc238a437..15e58b3617 100644
--- a/packages/base-render/src/BaseObject.ts
+++ b/packages/base-render/src/BaseObject.ts
@@ -14,6 +14,40 @@ import { IObjectFullState, ITransformChangeState, TRANSFORM_CHANGE_OBSERVABLE_TY
export const BASE_OBJECT_ARRAY = ['top', 'left', 'width', 'height', 'angle', 'scaleX', 'scaleY', 'skewX', 'skewY', 'flipX', 'flipY', 'strokeWidth'];
export abstract class BaseObject {
+ groupKey?: string;
+
+ isInGroup: boolean = false;
+
+ onTransformChangeObservable = new Observable<ITransformChangeState>();
+
+ onPointerDownObserver = new Observable<IPointerEvent | IMouseEvent>();
+
+ onPointerMoveObserver = new Observable<IPointerEvent | IMouseEvent>();
+
+ onPointerUpObserver = new Observable<IPointerEvent | IMouseEvent>();
+
+ onDblclickObserver = new Observable<IPointerEvent | IMouseEvent>();
+
+ onMouseWheelObserver = new Observable<IWheelEvent>();
+ // onKeyDownObservable = new Observable<IKeyboardEvent>();
+ // onKeyUpObservable = new Observable<IKeyboardEvent>();
+
+ onPointerOutObserver = new Observable<IPointerEvent | IMouseEvent>();
+
+ onPointerLeaveObserver = new Observable<IPointerEvent | IMouseEvent>();
+
+ onPointerOverObserver = new Observable<IPointerEvent | IMouseEvent>();
+
+ onPointerEnterObserver = new Observable<IPointerEvent | IMouseEvent>();
+
+ onIsAddedToParentObserver = new Observable<any>();
+
+ onDisposeObserver = new Observable<BaseObject>();
+
+ protected _oKey: string;
+
+ protected _dirty: boolean = true;
+
private _top: number = 0;
private _topOrigin: number | string = 0;
@@ -58,10 +92,6 @@ export abstract class BaseObject {
private _transform = new Transform();
- protected _oKey: string;
-
- protected _dirty: boolean = true;
-
private __debounceParentTimeout: number;
private _cursor: CURSOR_TYPE = CURSOR_TYPE.DEFAULT;
@@ -70,10 +100,6 @@ export abstract class BaseObject {
private _forceRender = false;
- groupKey?: string;
-
- isInGroup: boolean = false;
-
constructor(key?: string) {
if (key) {
this._oKey = key;
@@ -82,39 +108,10 @@ export abstract class BaseObject {
}
}
- makeDirty(state: boolean = true) {
- this._dirty = state;
- if (state) {
- window.clearTimeout(this.__debounceParentTimeout);
- this.__debounceParentTimeout = window.setTimeout(() => {
- this.parent?.makeDirty(state);
- }, 0);
- }
- return this;
- }
-
- makeDirtyNoDebounce(state: boolean = true) {
- this._dirty = state;
- if (state) {
- this.parent?.makeDirty(state);
- }
- return this;
- }
-
- isDirty(): boolean {
- return this._dirty;
- }
-
- onTransformChangeObservable = new Observable<ITransformChangeState>();
-
get transform() {
return this._transform;
}
- set transform(trans: Transform) {
- this._transform = trans;
- }
-
get topOrigin() {
return this._topOrigin;
}
@@ -135,6 +132,199 @@ export abstract class BaseObject {
return RENDER_CLASS_TYPE.BASE_OBJECT;
}
+ get top(): number {
+ return this._top;
+ }
+
+ get left(): number {
+ return this._left;
+ }
+
+ get width(): number {
+ return this._width;
+ }
+
+ get height(): number {
+ return this._height;
+ }
+
+ get strokeWidth() {
+ return this._strokeWidth;
+ }
+
+ get angle() {
+ return this._angle;
+ }
+
+ get scaleX() {
+ return this._scaleX;
+ }
+
+ get scaleY() {
+ return this._scaleY;
+ }
+
+ get ancestorScaleX() {
+ let pScale: number = this.getParent()?.ancestorScaleX || 1;
+ return this.scaleX * pScale;
+ }
+
+ get ancestorScaleY() {
+ let pScale: number = this.getParent()?.ancestorScaleY || 1;
+ return this.scaleY * pScale;
+ }
+
+ get skewX() {
+ return this._skewX;
+ }
+
+ get skewY() {
+ return this._skewY;
+ }
+
+ get flipX() {
+ return this._flipX;
+ }
+
+ get flipY() {
+ return this._flipY;
+ }
+
+ get parent() {
+ return this._parent;
+ }
+
+ get oKey() {
+ return this._oKey;
+ }
+
+ get zIndex() {
+ return this._zIndex;
+ }
+
+ get evented() {
+ return this._evented;
+ }
+
+ get visible() {
+ return this._visible;
+ }
+
+ get debounceParentDirty() {
+ return this._debounceParentDirty;
+ }
+
+ get isTransformer() {
+ return this._isTransformer;
+ }
+
+ get cursor() {
+ return this._cursor;
+ }
+
+ set transform(trans: Transform) {
+ this._transform = trans;
+ }
+
+ set zIndex(index: number) {
+ this._zIndex = index;
+ }
+
+ set parent(o: any) {
+ this._parent = o;
+ }
+
+ set evented(state: boolean) {
+ this._evented = state;
+ }
+
+ set debounceParentDirty(state: boolean) {
+ this._debounceParentDirty = state;
+ }
+
+ set isTransformer(state: boolean) {
+ this._isTransformer = state;
+ }
+
+ set cursor(val: CURSOR_TYPE) {
+ this.setCursor(val);
+ }
+
+ protected set top(num: number | string) {
+ this._topOrigin = num;
+ this._top = toPx(num, this._parent?.height);
+ }
+
+ protected set left(num: number | string) {
+ this._leftOrigin = num;
+ this._left = toPx(num, this._parent?.width);
+ }
+
+ protected set width(num: number | string) {
+ this._widthOrigin = num;
+ this._width = toPx(num, this._parent?.width);
+ }
+
+ protected set height(num: number | string) {
+ this._heightOrigin = num;
+ this._height = toPx(num, this._parent?.height);
+ }
+
+ protected set strokeWidth(width: number) {
+ this._strokeWidth = width;
+ }
+
+ protected set angle(angle: number) {
+ this._angle = angle;
+ }
+
+ protected set scaleX(scaleX: number) {
+ this._scaleX = scaleX;
+ }
+
+ protected set scaleY(scaleY: number) {
+ this._scaleY = scaleY;
+ }
+
+ protected set skewX(skewX: number) {
+ this._skewX = skewX;
+ }
+
+ protected set flipY(flipY: boolean) {
+ this._flipY = flipY;
+ }
+
+ protected set flipX(flipX: boolean) {
+ this._flipX = flipX;
+ }
+
+ protected set skewY(skewY: number) {
+ this._skewY = skewY;
+ }
+
+ makeDirty(state: boolean = true) {
+ this._dirty = state;
+ if (state) {
+ window.clearTimeout(this.__debounceParentTimeout);
+ this.__debounceParentTimeout = window.setTimeout(() => {
+ this.parent?.makeDirty(state);
+ }, 0);
+ }
+ return this;
+ }
+
+ makeDirtyNoDebounce(state: boolean = true) {
+ this._dirty = state;
+ if (state) {
+ this.parent?.makeDirty(state);
+ }
+ return this;
+ }
+
+ isDirty(): boolean {
+ return this._dirty;
+ }
+
translate(x?: number | string, y?: number | string) {
const preTop = this.top;
if (y !== undefined) {
@@ -274,192 +464,10 @@ export abstract class BaseObject {
return bounds && !this.isInGroup;
}
- private _makeDirtyMix() {
- if (this.debounceParentDirty) {
- this.makeDirty(true);
- } else {
- this.makeDirtyNoDebounce(true);
- }
- }
-
- protected _setTransForm() {
- const composeResult = Transform.create().composeMatrix({
- left: this.left + this.strokeWidth / 2,
- top: this.top + this.strokeWidth / 2,
- scaleX: this.scaleX,
- scaleY: this.scaleY,
- angle: this.angle,
- skewX: this.skewX,
- skewY: this.skewY,
- flipX: this.flipX,
- flipY: this.flipY,
- });
- this.transform = composeResult;
- this._makeDirtyMix();
- }
-
- get top(): number {
- return this._top;
- }
-
- protected set top(num: number | string) {
- this._topOrigin = num;
- this._top = toPx(num, this._parent?.height);
- }
-
- get left(): number {
- return this._left;
- }
-
- protected set left(num: number | string) {
- this._leftOrigin = num;
- this._left = toPx(num, this._parent?.width);
- }
-
- get width(): number {
- return this._width;
- }
-
- protected set width(num: number | string) {
- this._widthOrigin = num;
- this._width = toPx(num, this._parent?.width);
- }
-
- get height(): number {
- return this._height;
- }
-
- protected set height(num: number | string) {
- this._heightOrigin = num;
- this._height = toPx(num, this._parent?.height);
- }
-
- get strokeWidth() {
- return this._strokeWidth;
- }
-
- protected set strokeWidth(width: number) {
- this._strokeWidth = width;
- }
-
- get angle() {
- return this._angle;
- }
-
- protected set angle(angle: number) {
- this._angle = angle;
- }
-
- get scaleX() {
- return this._scaleX;
- }
-
- protected set scaleX(scaleX: number) {
- this._scaleX = scaleX;
- }
-
- get scaleY() {
- return this._scaleY;
- }
-
- protected set scaleY(scaleY: number) {
- this._scaleY = scaleY;
- }
-
- get ancestorScaleX() {
- let pScale: number = this.getParent()?.ancestorScaleX || 1;
- return this.scaleX * pScale;
- }
-
- get ancestorScaleY() {
- let pScale: number = this.getParent()?.ancestorScaleY || 1;
- return this.scaleY * pScale;
- }
-
- get skewX() {
- return this._skewX;
- }
-
- protected set skewX(skewX: number) {
- this._skewX = skewX;
- }
-
- get skewY() {
- return this._skewY;
- }
-
- protected set skewY(skewY: number) {
- this._skewY = skewY;
- }
-
- get flipX() {
- return this._flipX;
- }
-
- protected set flipX(flipX: boolean) {
- this._flipX = flipX;
- }
-
- get flipY() {
- return this._flipY;
- }
-
- protected set flipY(flipY: boolean) {
- this._flipY = flipY;
- }
-
- get parent() {
- return this._parent;
- }
-
- set parent(o: any) {
- this._parent = o;
- }
-
getParent() {
return this._parent;
}
- get oKey() {
- return this._oKey;
- }
-
- get zIndex() {
- return this._zIndex;
- }
-
- set zIndex(index: number) {
- this._zIndex = index;
- }
-
- get evented() {
- return this._evented;
- }
-
- set evented(state: boolean) {
- this._evented = state;
- }
-
- get visible() {
- return this._visible;
- }
-
- get debounceParentDirty() {
- return this._debounceParentDirty;
- }
-
- set debounceParentDirty(state: boolean) {
- this._debounceParentDirty = state;
- }
-
- get isTransformer() {
- return this._isTransformer;
- }
-
- set isTransformer(state: boolean) {
- this._isTransformer = state;
- }
-
getState() {
return {
left: this.left,
@@ -503,10 +511,6 @@ export abstract class BaseObject {
return false;
}
- protected _getInverseCoord(coord: Vector2) {
- return this._transform.clone().invert().applyPoint(coord);
- }
-
on(eventType: EVENT_TYPE, func: (evt: unknown, state: EventState) => void) {
const observable = this[`on${eventType}Observer`] as Observable<unknown>;
const observer = observable.add(func.bind(this));
@@ -630,30 +634,6 @@ export abstract class BaseObject {
this.onDisposeObserver.notifyObservers(this);
}
- onPointerDownObserver = new Observable<IPointerEvent | IMouseEvent>();
-
- onPointerMoveObserver = new Observable<IPointerEvent | IMouseEvent>();
-
- onPointerUpObserver = new Observable<IPointerEvent | IMouseEvent>();
-
- onDblclickObserver = new Observable<IPointerEvent | IMouseEvent>();
-
- onMouseWheelObserver = new Observable<IWheelEvent>();
- // onKeyDownObservable = new Observable<IKeyboardEvent>();
- // onKeyUpObservable = new Observable<IKeyboardEvent>();
-
- onPointerOutObserver = new Observable<IPointerEvent | IMouseEvent>();
-
- onPointerLeaveObserver = new Observable<IPointerEvent | IMouseEvent>();
-
- onPointerOverObserver = new Observable<IPointerEvent | IMouseEvent>();
-
- onPointerEnterObserver = new Observable<IPointerEvent | IMouseEvent>();
-
- onIsAddedToParentObserver = new Observable<any>();
-
- onDisposeObserver = new Observable<BaseObject>();
-
toJson() {
const props: IKeyValue = {};
BASE_OBJECT_ARRAY.forEach((key) => {
@@ -683,14 +663,6 @@ export abstract class BaseObject {
}
}
- get cursor() {
- return this._cursor;
- }
-
- set cursor(val: CURSOR_TYPE) {
- this.setCursor(val);
- }
-
resetCursor() {
this.setCursor(CURSOR_TYPE.DEFAULT);
}
@@ -710,4 +682,32 @@ export abstract class BaseObject {
}
return null;
}
+
+ protected _getInverseCoord(coord: Vector2) {
+ return this._transform.clone().invert().applyPoint(coord);
+ }
+
+ protected _setTransForm() {
+ const composeResult = Transform.create().composeMatrix({
+ left: this.left + this.strokeWidth / 2,
+ top: this.top + this.strokeWidth / 2,
+ scaleX: this.scaleX,
+ scaleY: this.scaleY,
+ angle: this.angle,
+ skewX: this.skewX,
+ skewY: this.skewY,
+ flipX: this.flipX,
+ flipY: this.flipY,
+ });
+ this.transform = composeResult;
+ this._makeDirtyMix();
+ }
+
+ private _makeDirtyMix() {
+ if (this.debounceParentDirty) {
+ this.makeDirty(true);
+ } else {
+ this.makeDirtyNoDebounce(true);
+ }
+ }
}
diff --git a/packages/base-render/src/Basics/FontCache.ts b/packages/base-render/src/Basics/FontCache.ts
index b8636bd592..e35b2b5d33 100644
--- a/packages/base-render/src/Basics/FontCache.ts
+++ b/packages/base-render/src/Basics/FontCache.ts
@@ -31,6 +31,12 @@ interface IGlyphHorizonData {
}
export class FontCache {
+ private static _getTextHeightCache: { [key: string]: { width: number; height: number } } = {};
+
+ private static _context: CanvasRenderingContext2D;
+
+ private static _fontDataMap: Map<string, IFontData> = new Map();
+
// 文字缓存全局变量
private static _globalFontMeasureCache: Map<string, Map<string, IMeasureTextCache>> = new Map();
@@ -124,21 +130,6 @@ export class FontCache {
return getDefaultBaselineOffset(fontSize);
}
- private static _clearMeasureCache(limit: number, values: Map<string, IMeasureTextCache>) {
- let valueIndex = 0;
- for (let txtItem of values) {
- const [txtKey] = txtItem;
- if (valueIndex > limit) {
- break;
- }
- values.delete(txtKey);
- valueIndex++;
- }
- return true;
- }
-
- private static _getTextHeightCache: { [key: string]: { width: number; height: number } } = {};
-
static getTextSizeByDom(text: string, fontStyle: string) {
if (fontStyle in this._getTextHeightCache) {
return this._getTextHeightCache[fontStyle];
@@ -161,9 +152,80 @@ export class FontCache {
return result;
}
- private static _context: CanvasRenderingContext2D;
+ static getTextSize(content: string, fontStyle: IDocumentSkeletonFontStyle): IDocumentSkeletonBoundingBox {
+ const { fontString, fontSize, fontFamily } = fontStyle;
- private static _fontDataMap: Map<string, IFontData> = new Map();
+ let bBox = this._getBoundingBoxByFont(fontFamily, fontSize);
+ if (!bBox) {
+ const measureText = this.getMeasureText(content, fontString);
+ bBox = this._calculateBoundingBoxByMeasureText(measureText, fontSize);
+ }
+ return bBox;
+ }
+
+ // 获取有值单元格文本大小
+ // let measureTextCache = {}, measureTextCacheTimeOut = null;
+ static getMeasureText(content: string, fontString: string): IMeasureTextCache {
+ if (!this._context) {
+ const canvas = document.createElement('canvas');
+ this._context = canvas.getContext('2d')!;
+ }
+
+ // const { fontString, fontSize, fontFamily } = fontStyle;
+
+ const ctx = this._context;
+
+ const mtc = this.getFontMeasureCache(fontString, content);
+ if (mtc != null) {
+ return mtc;
+ }
+
+ ctx.font = fontString;
+
+ const textMetrics = ctx.measureText(content);
+
+ const { width, fontBoundingBoxAscent, fontBoundingBoxDescent, actualBoundingBoxAscent, actualBoundingBoxDescent } = textMetrics;
+
+ const cache: IMeasureTextCache = {
+ width,
+ fontBoundingBoxAscent,
+ fontBoundingBoxDescent,
+ actualBoundingBoxAscent,
+ actualBoundingBoxDescent,
+ };
+
+ // 兼容不支持textMetrics的情况
+ if (fontBoundingBoxAscent == null || fontBoundingBoxDescent == null || Number.isNaN(fontBoundingBoxAscent) || Number.isNaN(fontBoundingBoxDescent)) {
+ let oneLineTextHeight = this.getTextSizeByDom(DEFAULT_MEASURE_TEXT, fontString)[1];
+
+ if (ctx.textBaseline === 'top') {
+ cache.fontBoundingBoxAscent = cache.actualBoundingBoxAscent = oneLineTextHeight;
+ cache.fontBoundingBoxDescent = cache.actualBoundingBoxDescent = 0;
+ } else if (ctx.textBaseline === 'middle') {
+ cache.fontBoundingBoxDescent = cache.actualBoundingBoxDescent = oneLineTextHeight / 2;
+ cache.fontBoundingBoxAscent = cache.actualBoundingBoxAscent = oneLineTextHeight / 2;
+ } else {
+ cache.fontBoundingBoxDescent = cache.actualBoundingBoxDescent = 0;
+ cache.fontBoundingBoxAscent = cache.actualBoundingBoxAscent = oneLineTextHeight;
+ }
+ }
+
+ this.setFontMeasureCache(fontString, content, cache);
+ return cache;
+ }
+
+ private static _clearMeasureCache(limit: number, values: Map<string, IMeasureTextCache>) {
+ let valueIndex = 0;
+ for (let txtItem of values) {
+ const [txtKey] = txtItem;
+ if (valueIndex > limit) {
+ break;
+ }
+ values.delete(txtKey);
+ valueIndex++;
+ }
+ return true;
+ }
/**
* Vertical Metrics https://glyphsapp.com/learn/vertical-metrics
@@ -234,66 +296,4 @@ export class FontCache {
spo: fontSize,
};
}
-
- static getTextSize(content: string, fontStyle: IDocumentSkeletonFontStyle): IDocumentSkeletonBoundingBox {
- const { fontString, fontSize, fontFamily } = fontStyle;
-
- let bBox = this._getBoundingBoxByFont(fontFamily, fontSize);
- if (!bBox) {
- const measureText = this.getMeasureText(content, fontString);
- bBox = this._calculateBoundingBoxByMeasureText(measureText, fontSize);
- }
- return bBox;
- }
-
- // 获取有值单元格文本大小
- // let measureTextCache = {}, measureTextCacheTimeOut = null;
- static getMeasureText(content: string, fontString: string): IMeasureTextCache {
- if (!this._context) {
- const canvas = document.createElement('canvas');
- this._context = canvas.getContext('2d')!;
- }
-
- // const { fontString, fontSize, fontFamily } = fontStyle;
-
- const ctx = this._context;
-
- const mtc = this.getFontMeasureCache(fontString, content);
- if (mtc != null) {
- return mtc;
- }
-
- ctx.font = fontString;
-
- const textMetrics = ctx.measureText(content);
-
- const { width, fontBoundingBoxAscent, fontBoundingBoxDescent, actualBoundingBoxAscent, actualBoundingBoxDescent } = textMetrics;
-
- const cache: IMeasureTextCache = {
- width,
- fontBoundingBoxAscent,
- fontBoundingBoxDescent,
- actualBoundingBoxAscent,
- actualBoundingBoxDescent,
- };
-
- // 兼容不支持textMetrics的情况
- if (fontBoundingBoxAscent == null || fontBoundingBoxDescent == null || Number.isNaN(fontBoundingBoxAscent) || Number.isNaN(fontBoundingBoxDescent)) {
- let oneLineTextHeight = this.getTextSizeByDom(DEFAULT_MEASURE_TEXT, fontString)[1];
-
- if (ctx.textBaseline === 'top') {
- cache.fontBoundingBoxAscent = cache.actualBoundingBoxAscent = oneLineTextHeight;
- cache.fontBoundingBoxDescent = cache.actualBoundingBoxDescent = 0;
- } else if (ctx.textBaseline === 'middle') {
- cache.fontBoundingBoxDescent = cache.actualBoundingBoxDescent = oneLineTextHeight / 2;
- cache.fontBoundingBoxAscent = cache.actualBoundingBoxAscent = oneLineTextHeight / 2;
- } else {
- cache.fontBoundingBoxDescent = cache.actualBoundingBoxDescent = 0;
- cache.fontBoundingBoxAscent = cache.actualBoundingBoxAscent = oneLineTextHeight;
- }
- }
-
- this.setFontMeasureCache(fontString, content, cache);
- return cache;
- }
}
diff --git a/packages/base-render/src/Basics/PerformanceMonitor.ts b/packages/base-render/src/Basics/PerformanceMonitor.ts
index 88850fee23..1bfddf278e 100644
--- a/packages/base-render/src/Basics/PerformanceMonitor.ts
+++ b/packages/base-render/src/Basics/PerformanceMonitor.ts
@@ -18,31 +18,6 @@ export class PerformanceMonitor {
this._rollingFrameTime = new RollingAverage(frameSampleSize);
}
- /**
- * Samples current frame
- * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
- */
- sampleFrame(timeMs: number = this.Now()) {
- if (!this._enabled) {
- return;
- }
-
- if (this._lastFrameTimeMs != null) {
- let dt = timeMs - this._lastFrameTimeMs;
- this._rollingFrameTime.add(dt);
- }
-
- this._lastFrameTimeMs = timeMs;
- }
-
- Now(): number {
- if (window.performance && window.performance.now) {
- return window.performance.now();
- }
-
- return Date.now();
- }
-
/**
* Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
*/
@@ -91,6 +66,38 @@ export class PerformanceMonitor {
return this._rollingFrameTime.isSaturated();
}
+ /**
+ * Returns true if sampling is enabled
+ */
+ get isEnabled(): boolean {
+ return this._enabled;
+ }
+
+ /**
+ * Samples current frame
+ * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
+ */
+ sampleFrame(timeMs: number = this.Now()) {
+ if (!this._enabled) {
+ return;
+ }
+
+ if (this._lastFrameTimeMs != null) {
+ let dt = timeMs - this._lastFrameTimeMs;
+ this._rollingFrameTime.add(dt);
+ }
+
+ this._lastFrameTimeMs = timeMs;
+ }
+
+ Now(): number {
+ if (window.performance && window.performance.now) {
+ return window.performance.now();
+ }
+
+ return Date.now();
+ }
+
/**
* Enables contributions to the sliding window sample set
*/
@@ -108,13 +115,6 @@ export class PerformanceMonitor {
this._lastFrameTimeMs = null;
}
- /**
- * Returns true if sampling is enabled
- */
- get isEnabled(): boolean {
- return this._enabled;
- }
-
/**
* Resets performance monitor
*/
diff --git a/packages/base-render/src/Basics/Transform.ts b/packages/base-render/src/Basics/Transform.ts
index 85cd3c567a..d4e308ca2c 100644
--- a/packages/base-render/src/Basics/Transform.ts
+++ b/packages/base-render/src/Basics/Transform.ts
@@ -6,10 +6,10 @@ import { Vector2 } from './Vector2';
export const INITIAL_MATRIX: number[] = [1, 0, 0, 1, 0, 0];
export class Transform {
- private _m: number[];
-
dirty = false;
+ private _m: number[];
+
constructor(m = INITIAL_MATRIX) {
this._m = (m && m.slice()) || INITIAL_MATRIX;
}
@@ -322,6 +322,10 @@ export class Transform {
return this;
}
+ clone() {
+ return new Transform([...this._m]);
+ }
+
/**
* Returns a transform matrix starting from an object of the same kind of
* the one returned from qrDecompose, useful also if you want to calculate some
@@ -350,10 +354,6 @@ export class Transform {
return scaleMatrix;
}
- clone() {
- return new Transform([...this._m]);
- }
-
// static createTransformByState(state: positionState) {
// const newTr = new this();
// let { x, y, angle, scaleX, scaleY, skewX, skewY, flipX, flipY } = state;
diff --git a/packages/base-render/src/Basics/Vector2.ts b/packages/base-render/src/Basics/Vector2.ts
index dcb59d97b7..18c3b31833 100644
--- a/packages/base-render/src/Basics/Vector2.ts
+++ b/packages/base-render/src/Basics/Vector2.ts
@@ -19,759 +19,759 @@ export class Vector2 implements IPoint {
public y: number = 0
) {}
- /**
- * Gets a string with the Vector2 coordinates
- * @returns a string with the Vector2 coordinates
- */
- toString(): string {
- return `{X: ${this.x} Y: ${this.y}}`;
- }
+ // Statics
/**
- * Gets class name
- * @returns the string "Vector2"
+ * Gets a new Vector2(0, 0)
+ * @returns a new Vector2
*/
- getClassName(): string {
- return 'Vector2';
+ static Zero(): Vector2 {
+ return new Vector2(0, 0);
}
/**
- * Gets current vector hash code
- * @returns the Vector2 hash code as a number
+ * Gets a new Vector2(1, 1)
+ * @returns a new Vector2
*/
- getHashCode(): number {
- let hash = this.x | 0;
- hash = (hash * 397) ^ (this.y | 0);
- return hash;
+ static One(): Vector2 {
+ return new Vector2(1, 1);
}
- // Operators
-
/**
- * Sets the Vector2 coordinates in the given array or Float32Array from the given index.
- * @param array defines the source array
- * @param index defines the offset in source array
- * @returns the current Vector2
+ * Gets a new Vector2 set from the given index element of the given array
+ * @param array defines the data source
+ * @param offset defines the offset in the data source
+ * @returns a new Vector2
*/
- toArray(array: FloatArray, index: number = 0): Vector2 {
- array[index] = this.x;
- array[index + 1] = this.y;
- return this;
+ static FromArray(array: DeepImmutable<ArrayLike<number>>, offset: number = 0): Vector2 {
+ return new Vector2(array[offset], array[offset + 1]);
}
/**
- * Update the current vector from an array
- * @param array defines the destination array
- * @param index defines the offset in the destination array
- * @returns the current Vector3
+ * Sets "result" from the given index element of the given array
+ * @param array defines the data source
+ * @param offset defines the offset in the data source
+ * @param result defines the target vector
*/
- fromArray(array: FloatArray, index: number = 0): Vector2 {
- Vector2.FromArrayToRef(array, index, this);
- return this;
+ static FromArrayToRef(array: ArrayLike<number>, offset: number, result: Vector2): void {
+ result.x = array[offset];
+ result.y = array[offset + 1];
}
/**
- * Copy the current vector to an array
- * @returns a new array with 2 elements: the Vector2 coordinates.
+ * Gets a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the given four Vector2
+ * @param value1 defines 1st point of control
+ * @param value2 defines 2nd point of control
+ * @param value3 defines 3rd point of control
+ * @param value4 defines 4th point of control
+ * @param amount defines the interpolation factor
+ * @returns a new Vector2
*/
- asArray(): number[] {
- let result = new Array<number>();
- this.toArray(result, 0);
- return result;
- }
+ static CatmullRom(value1: DeepImmutable<Vector2>, value2: DeepImmutable<Vector2>, value3: DeepImmutable<Vector2>, value4: DeepImmutable<Vector2>, amount: number): Vector2 {
+ let squared = amount * amount;
+ let cubed = amount * squared;
- /**
- * Sets the Vector2 coordinates with the given Vector2 coordinates
- * @param source defines the source Vector2
- * @returns the current updated Vector2
- */
- copyFrom(source: DeepImmutable<Vector2>): Vector2 {
- this.x = source.x;
- this.y = source.y;
- return this;
- }
+ let x =
+ 0.5 *
+ (2.0 * value2.x +
+ (-value1.x + value3.x) * amount +
+ (2.0 * value1.x - 5.0 * value2.x + 4.0 * value3.x - value4.x) * squared +
+ (-value1.x + 3.0 * value2.x - 3.0 * value3.x + value4.x) * cubed);
- /**
- * Sets the Vector2 coordinates with the given floats
- * @param x defines the first coordinate
- * @param y defines the second coordinate
- * @returns the current updated Vector2
- */
- copyFromFloats(x: number, y: number): Vector2 {
- this.x = x;
- this.y = y;
- return this;
- }
+ let y =
+ 0.5 *
+ (2.0 * value2.y +
+ (-value1.y + value3.y) * amount +
+ (2.0 * value1.y - 5.0 * value2.y + 4.0 * value3.y - value4.y) * squared +
+ (-value1.y + 3.0 * value2.y - 3.0 * value3.y + value4.y) * cubed);
- /**
- * Sets the Vector2 coordinates with the given floats
- * @param x defines the first coordinate
- * @param y defines the second coordinate
- * @returns the current updated Vector2
- */
- set(x: number, y: number): Vector2 {
- return this.copyFromFloats(x, y);
+ return new Vector2(x, y);
}
/**
- * Add another vector with the current one
- * @param otherVector defines the other vector
- * @returns a new Vector2 set with the addition of the current Vector2 and the given one coordinates
+ * Returns a new Vector2 set with same the coordinates than "value" ones if the vector "value" is in the square defined by "min" and "max".
+ * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
+ * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate
+ * @param value defines the value to clamp
+ * @param min defines the lower limit
+ * @param max defines the upper limit
+ * @returns a new Vector2
*/
- add(otherVector: DeepImmutable<Vector2>): Vector2 {
- return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
- }
+ static Clamp(value: DeepImmutable<Vector2>, min: DeepImmutable<Vector2>, max: DeepImmutable<Vector2>): Vector2 {
+ let x = value.x;
+ x = x > max.x ? max.x : x;
+ x = x < min.x ? min.x : x;
- /**
- * Sets the "result" coordinates with the addition of the current Vector2 and the given one coordinates
- * @param otherVector defines the other vector
- * @param result defines the target vector
- * @returns the unmodified current Vector2
- */
- addToRef(otherVector: DeepImmutable<Vector2>, result: Vector2): Vector2 {
- result.x = this.x + otherVector.x;
- result.y = this.y + otherVector.y;
- return this;
- }
+ let y = value.y;
+ y = y > max.y ? max.y : y;
+ y = y < min.y ? min.y : y;
- addByPoint(x: number, y: number) {
- return new Vector2(this.x + x, this.y + y);
+ return new Vector2(x, y);
}
/**
- * Set the Vector2 coordinates by adding the given Vector2 coordinates
- * @param otherVector defines the other vector
- * @returns the current updated Vector2
+ * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value2", "tangent1", "tangent2"
+ * @param value1 defines the 1st control point
+ * @param tangent1 defines the outgoing tangent
+ * @param value2 defines the 2nd control point
+ * @param tangent2 defines the incoming tangent
+ * @param amount defines the interpolation factor
+ * @returns a new Vector2
*/
- addInPlace(otherVector: DeepImmutable<Vector2>): Vector2 {
- this.x += otherVector.x;
- this.y += otherVector.y;
- return this;
+ static Hermite(value1: DeepImmutable<Vector2>, tangent1: DeepImmutable<Vector2>, value2: DeepImmutable<Vector2>, tangent2: DeepImmutable<Vector2>, amount: number): Vector2 {
+ let squared = amount * amount;
+ let cubed = amount * squared;
+ let part1 = 2.0 * cubed - 3.0 * squared + 1.0;
+ let part2 = -2.0 * cubed + 3.0 * squared;
+ let part3 = cubed - 2.0 * squared + amount;
+ let part4 = cubed - squared;
+
+ let x = value1.x * part1 + value2.x * part2 + tangent1.x * part3 + tangent2.x * part4;
+ let y = value1.y * part1 + value2.y * part2 + tangent1.y * part3 + tangent2.y * part4;
+
+ return new Vector2(x, y);
}
/**
- * Gets a new Vector2 set with the subtracted coordinates of the given one from the current Vector2
- * @param otherVector defines the other vector
- * @returns a new Vector2
+ * Returns a new Vector2 which is the 1st derivative of the Hermite spline defined by the vectors "value1", "value2", "tangent1", "tangent2".
+ * @param value1 defines the first control point
+ * @param tangent1 defines the first tangent
+ * @param value2 defines the second control point
+ * @param tangent2 defines the second tangent
+ * @param time define where the derivative must be done
+ * @returns 1st derivative
*/
- subtract(otherVector: Vector2): Vector2 {
- return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
- }
+ static Hermite1stDerivative(
+ value1: DeepImmutable<Vector2>,
+ tangent1: DeepImmutable<Vector2>,
+ value2: DeepImmutable<Vector2>,
+ tangent2: DeepImmutable<Vector2>,
+ time: number
+ ): Vector2 {
+ let result = Vector2.Zero();
- subtractByPoint(x: number, y: number) {
- return new Vector2(this.x - x, this.y - y);
+ this.Hermite1stDerivativeToRef(value1, tangent1, value2, tangent2, time, result);
+
+ return result;
}
/**
- * Sets the "result" coordinates with the subtraction of the given one from the current Vector2 coordinates.
- * @param otherVector defines the other vector
- * @param result defines the target vector
- * @returns the unmodified current Vector2
+ * Returns a new Vector2 which is the 1st derivative of the Hermite spline defined by the vectors "value1", "value2", "tangent1", "tangent2".
+ * @param value1 defines the first control point
+ * @param tangent1 defines the first tangent
+ * @param value2 defines the second control point
+ * @param tangent2 defines the second tangent
+ * @param time define where the derivative must be done
+ * @param result define where the derivative will be stored
*/
- subtractToRef(otherVector: DeepImmutable<Vector2>, result: Vector2): Vector2 {
- result.x = this.x - otherVector.x;
- result.y = this.y - otherVector.y;
- return this;
+ static Hermite1stDerivativeToRef(
+ value1: DeepImmutable<Vector2>,
+ tangent1: DeepImmutable<Vector2>,
+ value2: DeepImmutable<Vector2>,
+ tangent2: DeepImmutable<Vector2>,
+ time: number,
+ result: Vector2
+ ) {
+ const t2 = time * time;
+
+ result.x = (t2 - time) * 6 * value1.x + (3 * t2 - 4 * time + 1) * tangent1.x + (-t2 + time) * 6 * value2.x + (3 * t2 - 2 * time) * tangent2.x;
+ result.y = (t2 - time) * 6 * value1.y + (3 * t2 - 4 * time + 1) * tangent1.y + (-t2 + time) * 6 * value2.y + (3 * t2 - 2 * time) * tangent2.y;
}
/**
- * Sets the current Vector2 coordinates by subtracting from it the given one coordinates
- * @param otherVector defines the other vector
- * @returns the current updated Vector2
+ * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
+ * @param start defines the start vector
+ * @param end defines the end vector
+ * @param amount defines the interpolation factor
+ * @returns a new Vector2
*/
- subtractInPlace(otherVector: DeepImmutable<Vector2>): Vector2 {
- this.x -= otherVector.x;
- this.y -= otherVector.y;
- return this;
+ static Lerp(start: DeepImmutable<Vector2>, end: DeepImmutable<Vector2>, amount: number): Vector2 {
+ let x = start.x + (end.x - start.x) * amount;
+ let y = start.y + (end.y - start.y) * amount;
+ return new Vector2(x, y);
}
/**
- * Multiplies in place the current Vector2 coordinates by the given ones
- * @param otherVector defines the other vector
- * @returns the current updated Vector2
+ * Gets the dot product of the vector "left" and the vector "right"
+ * @param left defines first vector
+ * @param right defines second vector
+ * @returns the dot product (float)
*/
- multiplyInPlace(otherVector: DeepImmutable<Vector2>): Vector2 {
- this.x *= otherVector.x;
- this.y *= otherVector.y;
- return this;
+ static Dot(left: DeepImmutable<Vector2>, right: DeepImmutable<Vector2>): number {
+ return left.x * right.x + left.y * right.y;
}
/**
- * Returns a new Vector2 set with the multiplication of the current Vector2 and the given one coordinates
- * @param otherVector defines the other vector
+ * Returns a new Vector2 equal to the normalized given vector
+ * @param vector defines the vector to normalize
* @returns a new Vector2
*/
- multiply(otherVector: DeepImmutable<Vector2>): Vector2 {
- return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
+ static Normalize(vector: DeepImmutable<Vector2>): Vector2 {
+ let newVector = Vector2.Zero();
+ this.NormalizeToRef(vector, newVector);
+ return newVector;
}
/**
- * Sets "result" coordinates with the multiplication of the current Vector2 and the given one coordinates
- * @param otherVector defines the other vector
- * @param result defines the target vector
- * @returns the unmodified current Vector2
+ * Normalize a given vector into a second one
+ * @param vector defines the vector to normalize
+ * @param result defines the vector where to store the result
*/
- multiplyToRef(otherVector: DeepImmutable<Vector2>, result: Vector2): Vector2 {
- result.x = this.x * otherVector.x;
- result.y = this.y * otherVector.y;
- return this;
+ static NormalizeToRef(vector: DeepImmutable<Vector2>, result: Vector2) {
+ let len = vector.length();
+
+ if (len === 0) {
+ return;
+ }
+
+ result.x = vector.x / len;
+ result.y = vector.y / len;
}
/**
- * Gets a new Vector2 set with the Vector2 coordinates multiplied by the given floats
- * @param x defines the first coordinate
- * @param y defines the second coordinate
+ * Gets a new Vector2 set with the minimal coordinate values from the "left" and "right" vectors
+ * @param left defines 1st vector
+ * @param right defines 2nd vector
* @returns a new Vector2
*/
- multiplyByFloats(x: number, y: number): Vector2 {
- return new Vector2(this.x * x, this.y * y);
+ static Minimize(left: DeepImmutable<Vector2>, right: DeepImmutable<Vector2>): Vector2 {
+ let x = left.x < right.x ? left.x : right.x;
+ let y = left.y < right.y ? left.y : right.y;
+ return new Vector2(x, y);
}
/**
- * Returns a new Vector2 set with the Vector2 coordinates divided by the given one coordinates
- * @param otherVector defines the other vector
+ * Gets a new Vector2 set with the maximal coordinate values from the "left" and "right" vectors
+ * @param left defines 1st vector
+ * @param right defines 2nd vector
* @returns a new Vector2
*/
- divide(otherVector: Vector2): Vector2 {
- return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
+ static Maximize(left: DeepImmutable<Vector2>, right: DeepImmutable<Vector2>): Vector2 {
+ let x = left.x > right.x ? left.x : right.x;
+ let y = left.y > right.y ? left.y : right.y;
+ return new Vector2(x, y);
}
/**
- * Sets the "result" coordinates with the Vector2 divided by the given one coordinates
- * @param otherVector defines the other vector
+ * Transforms the given vector coordinates by the given transformation Transform and stores the result in the vector "result" coordinates
+ * @param vector defines the vector to transform
+ * @param transformation defines the Transform to apply
* @param result defines the target vector
- * @returns the unmodified current Vector2
*/
- divideToRef(otherVector: DeepImmutable<Vector2>, result: Vector2): Vector2 {
- result.x = this.x / otherVector.x;
- result.y = this.y / otherVector.y;
- return this;
+ static Transform(vector: DeepImmutable<Vector2>, transformation: DeepImmutable<Transform>, ignoreOffset: boolean = false) {
+ const t = transformation;
+ const p = vector;
+
+ if (ignoreOffset) {
+ return new Vector2(t[0] * p.x + t[2] * p.y, t[1] * p.x + t[3] * p.y);
+ }
+ return new Vector2(t[0] * p.x + t[2] * p.y + t[4], t[1] * p.x + t[3] * p.y + t[5]);
}
/**
- * Divides the current Vector2 coordinates by the given ones
- * @param otherVector defines the other vector
- * @returns the current updated Vector2
+ * Determines if a given vector is included in a triangle
+ * @param p defines the vector to test
+ * @param p0 defines 1st triangle point
+ * @param p1 defines 2nd triangle point
+ * @param p2 defines 3rd triangle point
+ * @returns true if the point "p" is in the triangle defined by the vectors "p0", "p1", "p2"
*/
- divideInPlace(otherVector: DeepImmutable<Vector2>): Vector2 {
- return this.divideToRef(otherVector, this);
+ static PointInTriangle(p: DeepImmutable<Vector2>, p0: DeepImmutable<Vector2>, p1: DeepImmutable<Vector2>, p2: DeepImmutable<Vector2>) {
+ let a = (1 / 2) * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
+ let sign = a < 0 ? -1 : 1;
+ let s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
+ let t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
+
+ return s > 0 && t > 0 && s + t < 2 * a * sign;
}
/**
- * Gets a new Vector2 with current Vector2 negated coordinates
- * @returns a new Vector2
+ * Gets the distance between the vectors "value1" and "value2"
+ * @param value1 defines first vector
+ * @param value2 defines second vector
+ * @returns the distance between vectors
*/
- negate(): Vector2 {
- return new Vector2(-this.x, -this.y);
+ static Distance(value1: DeepImmutable<Vector2>, value2: DeepImmutable<Vector2>): number {
+ return Math.sqrt(Vector2.DistanceSquared(value1, value2));
}
/**
- * Negate this vector in place
- * @returns this
+ * Returns the squared distance between the vectors "value1" and "value2"
+ * @param value1 defines first vector
+ * @param value2 defines second vector
+ * @returns the squared distance between vectors
*/
- negateInPlace(): Vector2 {
- this.x *= -1;
- this.y *= -1;
- return this;
+ static DistanceSquared(value1: DeepImmutable<Vector2>, value2: DeepImmutable<Vector2>): number {
+ let x = value1.x - value2.x;
+ let y = value1.y - value2.y;
+ return x * x + y * y;
}
/**
- * Negate the current Vector2 and stores the result in the given vector "result" coordinates
- * @param result defines the Vector3 object where to store the result
- * @returns the current Vector2
+ * Gets a new Vector2 located at the center of the vectors "value1" and "value2"
+ * @param value1 defines first vector
+ * @param value2 defines second vector
+ * @returns a new Vector2
*/
- negateToRef(result: Vector2): Vector2 {
- return result.copyFromFloats(this.x * -1, this.y * -1);
+ static Center(value1: DeepImmutable<Vector2>, value2: DeepImmutable<Vector2>): Vector2 {
+ return Vector2.CenterToRef(value1, value2, Vector2.Zero());
}
/**
- * Multiply the Vector2 coordinates by scale
- * @param scale defines the scaling factor
- * @returns the current updated Vector2
+ * Gets the center of the vectors "value1" and "value2" and stores the result in the vector "ref"
+ * @param value1 defines first vector
+ * @param value2 defines second vector
+ * @param ref defines third vector
+ * @returns ref
*/
- scaleInPlace(scale: number): Vector2 {
- this.x *= scale;
- this.y *= scale;
- return this;
+ static CenterToRef(value1: DeepImmutable<Vector2>, value2: DeepImmutable<Vector2>, ref: DeepImmutable<Vector2>): Vector2 {
+ return ref.copyFromFloats((value1.x + value2.x) / 2, (value1.y + value2.y) / 2);
}
/**
- * Returns a new Vector2 scaled by "scale" from the current Vector2
- * @param scale defines the scaling factor
- * @returns a new Vector2
+ * Gets the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
+ * @param p defines the middle point
+ * @param segA defines one point of the segment
+ * @param segB defines the other point of the segment
+ * @returns the shortest distance
*/
- scale(scale: number): Vector2 {
- let result = new Vector2(0, 0);
- this.scaleToRef(scale, result);
- return result;
+ static DistanceOfPointFromSegment(p: DeepImmutable<Vector2>, segA: DeepImmutable<Vector2>, segB: DeepImmutable<Vector2>): number {
+ let l2 = Vector2.DistanceSquared(segA, segB);
+ if (l2 === 0.0) {
+ return Vector2.Distance(p, segA);
+ }
+ let v = segB.subtract(segA);
+ let t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
+ let proj = segA.add(v.multiplyByFloats(t, t));
+ return Vector2.Distance(p, proj);
+ }
+
+ static create(x: number, y: number) {
+ return new Vector2(x, y);
}
/**
- * Scale the current Vector2 values by a factor to a given Vector2
- * @param scale defines the scale factor
- * @param result defines the Vector2 object where to store the result
- * @returns the unmodified current Vector2
+ * Gets a string with the Vector2 coordinates
+ * @returns a string with the Vector2 coordinates
*/
- scaleToRef(scale: number, result: Vector2): Vector2 {
- result.x = this.x * scale;
- result.y = this.y * scale;
- return this;
+ toString(): string {
+ return `{X: ${this.x} Y: ${this.y}}`;
}
/**
- * Scale the current Vector2 values by a factor and add the result to a given Vector2
- * @param scale defines the scale factor
- * @param result defines the Vector2 object where to store the result
- * @returns the unmodified current Vector2
+ * Gets class name
+ * @returns the string "Vector2"
*/
- scaleAndAddToRef(scale: number, result: Vector2): Vector2 {
- result.x += this.x * scale;
- result.y += this.y * scale;
- return this;
+ getClassName(): string {
+ return 'Vector2';
}
/**
- * Gets a boolean if two vectors are equals
- * @param otherVector defines the other vector
- * @returns true if the given vector coordinates strictly equal the current Vector2 ones
+ * Gets current vector hash code
+ * @returns the Vector2 hash code as a number
*/
- equals(otherVector: DeepImmutable<Vector2>): boolean {
- return otherVector && this.x === otherVector.x && this.y === otherVector.y;
+ getHashCode(): number {
+ let hash = this.x | 0;
+ hash = (hash * 397) ^ (this.y | 0);
+ return hash;
}
+ // Operators
+
/**
- * Gets a new Vector2 from current Vector2 floored values
- * eg (1.2, 2.31) returns (1, 2)
- * @returns a new Vector2
+ * Sets the Vector2 coordinates in the given array or Float32Array from the given index.
+ * @param array defines the source array
+ * @param index defines the offset in source array
+ * @returns the current Vector2
*/
- floor(): Vector2 {
- return new Vector2(Math.floor(this.x), Math.floor(this.y));
+ toArray(array: FloatArray, index: number = 0): Vector2 {
+ array[index] = this.x;
+ array[index + 1] = this.y;
+ return this;
}
/**
- * Gets a new Vector2 from current Vector2 fractional values
- * eg (1.2, 2.31) returns (0.2, 0.31)
- * @returns a new Vector2
+ * Update the current vector from an array
+ * @param array defines the destination array
+ * @param index defines the offset in the destination array
+ * @returns the current Vector3
*/
- fract(): Vector2 {
- return new Vector2(this.x - Math.floor(this.x), this.y - Math.floor(this.y));
+ fromArray(array: FloatArray, index: number = 0): Vector2 {
+ Vector2.FromArrayToRef(array, index, this);
+ return this;
}
/**
- * Rotate the current vector into a given result vector
- * @param angle defines the rotation angle
- * @returns the current vector
+ * Copy the current vector to an array
+ * @returns a new array with 2 elements: the Vector2 coordinates.
*/
- rotate(angle: number) {
- const cos = Math.cos(angle);
- const sin = Math.sin(angle);
- const rx = cos * this.x - sin * this.y;
- const ry = sin * this.x + cos * this.y;
- this.x = rx;
- this.y = ry;
- return this;
+ asArray(): number[] {
+ let result = new Array<number>();
+ this.toArray(result, 0);
+ return result;
}
/**
- * Rotate the current vector into a given result vector
- * @param angle defines the rotation angle
- * @param result defines the result vector where to store the rotated vector
- * @returns the current vector
+ * Sets the Vector2 coordinates with the given Vector2 coordinates
+ * @param source defines the source Vector2
+ * @returns the current updated Vector2
*/
- rotateToRef(angle: number, result: Vector2) {
- const cos = Math.cos(angle);
- const sin = Math.sin(angle);
- result.x = cos * this.x - sin * this.y;
- result.y = sin * this.x + cos * this.y;
-
+ copyFrom(source: DeepImmutable<Vector2>): Vector2 {
+ this.x = source.x;
+ this.y = source.y;
return this;
}
- rotateByPoint(angle: number, originPoint: Vector2 = Vector2.create(0, 0)) {
- const cosA = Math.cos(angle);
- const sinA = Math.sin(angle);
- const rx = originPoint.x + (this.x - originPoint.x) * cosA - (this.y - originPoint.y) * sinA;
- const ry = originPoint.y + (this.x - originPoint.x) * sinA + (this.y - originPoint.y) * cosA;
- this.x = rx;
- this.y = ry;
+ /**
+ * Sets the Vector2 coordinates with the given floats
+ * @param x defines the first coordinate
+ * @param y defines the second coordinate
+ * @returns the current updated Vector2
+ */
+ copyFromFloats(x: number, y: number): Vector2 {
+ this.x = x;
+ this.y = y;
return this;
}
- transformCoordinateOnRotate(angle: number) {
- const hypotenuse = Math.sqrt(this.x ** 2 + this.y ** 2);
- const beta = Math.atan2(this.y, this.x);
- const theta = -angle + beta;
- this.x = hypotenuse * Math.cos(theta);
- this.y = hypotenuse * Math.sin(theta);
- return this;
+ /**
+ * Sets the Vector2 coordinates with the given floats
+ * @param x defines the first coordinate
+ * @param y defines the second coordinate
+ * @returns the current updated Vector2
+ */
+ set(x: number, y: number): Vector2 {
+ return this.copyFromFloats(x, y);
}
- // Properties
-
/**
- * Gets the length of the vector
- * @returns the vector length (float)
+ * Add another vector with the current one
+ * @param otherVector defines the other vector
+ * @returns a new Vector2 set with the addition of the current Vector2 and the given one coordinates
*/
- length(): number {
- return Math.sqrt(this.x * this.x + this.y * this.y);
+ add(otherVector: DeepImmutable<Vector2>): Vector2 {
+ return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
}
/**
- * Gets the vector squared length
- * @returns the vector squared length (float)
+ * Sets the "result" coordinates with the addition of the current Vector2 and the given one coordinates
+ * @param otherVector defines the other vector
+ * @param result defines the target vector
+ * @returns the unmodified current Vector2
*/
- lengthSquared(): number {
- return this.x * this.x + this.y * this.y;
+ addToRef(otherVector: DeepImmutable<Vector2>, result: Vector2): Vector2 {
+ result.x = this.x + otherVector.x;
+ result.y = this.y + otherVector.y;
+ return this;
}
- // Methods
+ addByPoint(x: number, y: number) {
+ return new Vector2(this.x + x, this.y + y);
+ }
/**
- * Normalize the vector
+ * Set the Vector2 coordinates by adding the given Vector2 coordinates
+ * @param otherVector defines the other vector
* @returns the current updated Vector2
*/
- normalize(): Vector2 {
- Vector2.NormalizeToRef(this, this);
+ addInPlace(otherVector: DeepImmutable<Vector2>): Vector2 {
+ this.x += otherVector.x;
+ this.y += otherVector.y;
return this;
}
/**
- * Gets a new Vector2 copied from the Vector2
+ * Gets a new Vector2 set with the subtracted coordinates of the given one from the current Vector2
+ * @param otherVector defines the other vector
* @returns a new Vector2
*/
- clone(): Vector2 {
- return new Vector2(this.x, this.y);
+ subtract(otherVector: Vector2): Vector2 {
+ return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
}
- // Statics
+ subtractByPoint(x: number, y: number) {
+ return new Vector2(this.x - x, this.y - y);
+ }
/**
- * Gets a new Vector2(0, 0)
- * @returns a new Vector2
+ * Sets the "result" coordinates with the subtraction of the given one from the current Vector2 coordinates.
+ * @param otherVector defines the other vector
+ * @param result defines the target vector
+ * @returns the unmodified current Vector2
*/
- static Zero(): Vector2 {
- return new Vector2(0, 0);
+ subtractToRef(otherVector: DeepImmutable<Vector2>, result: Vector2): Vector2 {
+ result.x = this.x - otherVector.x;
+ result.y = this.y - otherVector.y;
+ return this;
}
/**
- * Gets a new Vector2(1, 1)
- * @returns a new Vector2
+ * Sets the current Vector2 coordinates by subtracting from it the given one coordinates
+ * @param otherVector defines the other vector
+ * @returns the current updated Vector2
*/
- static One(): Vector2 {
- return new Vector2(1, 1);
+ subtractInPlace(otherVector: DeepImmutable<Vector2>): Vector2 {
+ this.x -= otherVector.x;
+ this.y -= otherVector.y;
+ return this;
}
/**
- * Gets a new Vector2 set from the given index element of the given array
- * @param array defines the data source
- * @param offset defines the offset in the data source
+ * Multiplies in place the current Vector2 coordinates by the given ones
+ * @param otherVector defines the other vector
+ * @returns the current updated Vector2
+ */
+ multiplyInPlace(otherVector: DeepImmutable<Vector2>): Vector2 {
+ this.x *= otherVector.x;
+ this.y *= otherVector.y;
+ return this;
+ }
+
+ /**
+ * Returns a new Vector2 set with the multiplication of the current Vector2 and the given one coordinates
+ * @param otherVector defines the other vector
* @returns a new Vector2
*/
- static FromArray(array: DeepImmutable<ArrayLike<number>>, offset: number = 0): Vector2 {
- return new Vector2(array[offset], array[offset + 1]);
+ multiply(otherVector: DeepImmutable<Vector2>): Vector2 {
+ return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
}
/**
- * Sets "result" from the given index element of the given array
- * @param array defines the data source
- * @param offset defines the offset in the data source
+ * Sets "result" coordinates with the multiplication of the current Vector2 and the given one coordinates
+ * @param otherVector defines the other vector
* @param result defines the target vector
+ * @returns the unmodified current Vector2
*/
- static FromArrayToRef(array: ArrayLike<number>, offset: number, result: Vector2): void {
- result.x = array[offset];
- result.y = array[offset + 1];
+ multiplyToRef(otherVector: DeepImmutable<Vector2>, result: Vector2): Vector2 {
+ result.x = this.x * otherVector.x;
+ result.y = this.y * otherVector.y;
+ return this;
}
/**
- * Gets a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the given four Vector2
- * @param value1 defines 1st point of control
- * @param value2 defines 2nd point of control
- * @param value3 defines 3rd point of control
- * @param value4 defines 4th point of control
- * @param amount defines the interpolation factor
+ * Gets a new Vector2 set with the Vector2 coordinates multiplied by the given floats
+ * @param x defines the first coordinate
+ * @param y defines the second coordinate
* @returns a new Vector2
*/
- static CatmullRom(value1: DeepImmutable<Vector2>, value2: DeepImmutable<Vector2>, value3: DeepImmutable<Vector2>, value4: DeepImmutable<Vector2>, amount: number): Vector2 {
- let squared = amount * amount;
- let cubed = amount * squared;
-
- let x =
- 0.5 *
- (2.0 * value2.x +
- (-value1.x + value3.x) * amount +
- (2.0 * value1.x - 5.0 * value2.x + 4.0 * value3.x - value4.x) * squared +
- (-value1.x + 3.0 * value2.x - 3.0 * value3.x + value4.x) * cubed);
-
- let y =
- 0.5 *
- (2.0 * value2.y +
- (-value1.y + value3.y) * amount +
- (2.0 * value1.y - 5.0 * value2.y + 4.0 * value3.y - value4.y) * squared +
- (-value1.y + 3.0 * value2.y - 3.0 * value3.y + value4.y) * cubed);
-
- return new Vector2(x, y);
+ multiplyByFloats(x: number, y: number): Vector2 {
+ return new Vector2(this.x * x, this.y * y);
}
/**
- * Returns a new Vector2 set with same the coordinates than "value" ones if the vector "value" is in the square defined by "min" and "max".
- * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
- * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate
- * @param value defines the value to clamp
- * @param min defines the lower limit
- * @param max defines the upper limit
+ * Returns a new Vector2 set with the Vector2 coordinates divided by the given one coordinates
+ * @param otherVector defines the other vector
* @returns a new Vector2
*/
- static Clamp(value: DeepImmutable<Vector2>, min: DeepImmutable<Vector2>, max: DeepImmutable<Vector2>): Vector2 {
- let x = value.x;
- x = x > max.x ? max.x : x;
- x = x < min.x ? min.x : x;
-
- let y = value.y;
- y = y > max.y ? max.y : y;
- y = y < min.y ? min.y : y;
-
- return new Vector2(x, y);
+ divide(otherVector: Vector2): Vector2 {
+ return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
}
/**
- * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value2", "tangent1", "tangent2"
- * @param value1 defines the 1st control point
- * @param tangent1 defines the outgoing tangent
- * @param value2 defines the 2nd control point
- * @param tangent2 defines the incoming tangent
- * @param amount defines the interpolation factor
- * @returns a new Vector2
+ * Sets the "result" coordinates with the Vector2 divided by the given one coordinates
+ * @param otherVector defines the other vector
+ * @param result defines the target vector
+ * @returns the unmodified current Vector2
*/
- static Hermite(value1: DeepImmutable<Vector2>, tangent1: DeepImmutable<Vector2>, value2: DeepImmutable<Vector2>, tangent2: DeepImmutable<Vector2>, amount: number): Vector2 {
- let squared = amount * amount;
- let cubed = amount * squared;
- let part1 = 2.0 * cubed - 3.0 * squared + 1.0;
- let part2 = -2.0 * cubed + 3.0 * squared;
- let part3 = cubed - 2.0 * squared + amount;
- let part4 = cubed - squared;
-
- let x = value1.x * part1 + value2.x * part2 + tangent1.x * part3 + tangent2.x * part4;
- let y = value1.y * part1 + value2.y * part2 + tangent1.y * part3 + tangent2.y * part4;
-
- return new Vector2(x, y);
+ divideToRef(otherVector: DeepImmutable<Vector2>, result: Vector2): Vector2 {
+ result.x = this.x / otherVector.x;
+ result.y = this.y / otherVector.y;
+ return this;
}
/**
- * Returns a new Vector2 which is the 1st derivative of the Hermite spline defined by the vectors "value1", "value2", "tangent1", "tangent2".
- * @param value1 defines the first control point
- * @param tangent1 defines the first tangent
- * @param value2 defines the second control point
- * @param tangent2 defines the second tangent
- * @param time define where the derivative must be done
- * @returns 1st derivative
+ * Divides the current Vector2 coordinates by the given ones
+ * @param otherVector defines the other vector
+ * @returns the current updated Vector2
*/
- static Hermite1stDerivative(
- value1: DeepImmutable<Vector2>,
- tangent1: DeepImmutable<Vector2>,
- value2: DeepImmutable<Vector2>,
- tangent2: DeepImmutable<Vector2>,
- time: number
- ): Vector2 {
- let result = Vector2.Zero();
-
- this.Hermite1stDerivativeToRef(value1, tangent1, value2, tangent2, time, result);
+ divideInPlace(otherVector: DeepImmutable<Vector2>): Vector2 {
+ return this.divideToRef(otherVector, this);
+ }
- return result;
+ /**
+ * Gets a new Vector2 with current Vector2 negated coordinates
+ * @returns a new Vector2
+ */
+ negate(): Vector2 {
+ return new Vector2(-this.x, -this.y);
}
/**
- * Returns a new Vector2 which is the 1st derivative of the Hermite spline defined by the vectors "value1", "value2", "tangent1", "tangent2".
- * @param value1 defines the first control point
- * @param tangent1 defines the first tangent
- * @param value2 defines the second control point
- * @param tangent2 defines the second tangent
- * @param time define where the derivative must be done
- * @param result define where the derivative will be stored
+ * Negate this vector in place
+ * @returns this
*/
- static Hermite1stDerivativeToRef(
- value1: DeepImmutable<Vector2>,
- tangent1: DeepImmutable<Vector2>,
- value2: DeepImmutable<Vector2>,
- tangent2: DeepImmutable<Vector2>,
- time: number,
- result: Vector2
- ) {
- const t2 = time * time;
-
- result.x = (t2 - time) * 6 * value1.x + (3 * t2 - 4 * time + 1) * tangent1.x + (-t2 + time) * 6 * value2.x + (3 * t2 - 2 * time) * tangent2.x;
- result.y = (t2 - time) * 6 * value1.y + (3 * t2 - 4 * time + 1) * tangent1.y + (-t2 + time) * 6 * value2.y + (3 * t2 - 2 * time) * tangent2.y;
+ negateInPlace(): Vector2 {
+ this.x *= -1;
+ this.y *= -1;
+ return this;
}
/**
- * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
- * @param start defines the start vector
- * @param end defines the end vector
- * @param amount defines the interpolation factor
- * @returns a new Vector2
+ * Negate the current Vector2 and stores the result in the given vector "result" coordinates
+ * @param result defines the Vector3 object where to store the result
+ * @returns the current Vector2
*/
- static Lerp(start: DeepImmutable<Vector2>, end: DeepImmutable<Vector2>, amount: number): Vector2 {
- let x = start.x + (end.x - start.x) * amount;
- let y = start.y + (end.y - start.y) * amount;
- return new Vector2(x, y);
+ negateToRef(result: Vector2): Vector2 {
+ return result.copyFromFloats(this.x * -1, this.y * -1);
}
/**
- * Gets the dot product of the vector "left" and the vector "right"
- * @param left defines first vector
- * @param right defines second vector
- * @returns the dot product (float)
+ * Multiply the Vector2 coordinates by scale
+ * @param scale defines the scaling factor
+ * @returns the current updated Vector2
*/
- static Dot(left: DeepImmutable<Vector2>, right: DeepImmutable<Vector2>): number {
- return left.x * right.x + left.y * right.y;
+ scaleInPlace(scale: number): Vector2 {
+ this.x *= scale;
+ this.y *= scale;
+ return this;
}
/**
- * Returns a new Vector2 equal to the normalized given vector
- * @param vector defines the vector to normalize
+ * Returns a new Vector2 scaled by "scale" from the current Vector2
+ * @param scale defines the scaling factor
* @returns a new Vector2
*/
- static Normalize(vector: DeepImmutable<Vector2>): Vector2 {
- let newVector = Vector2.Zero();
- this.NormalizeToRef(vector, newVector);
- return newVector;
+ scale(scale: number): Vector2 {
+ let result = new Vector2(0, 0);
+ this.scaleToRef(scale, result);
+ return result;
}
/**
- * Normalize a given vector into a second one
- * @param vector defines the vector to normalize
- * @param result defines the vector where to store the result
+ * Scale the current Vector2 values by a factor to a given Vector2
+ * @param scale defines the scale factor
+ * @param result defines the Vector2 object where to store the result
+ * @returns the unmodified current Vector2
*/
- static NormalizeToRef(vector: DeepImmutable<Vector2>, result: Vector2) {
- let len = vector.length();
+ scaleToRef(scale: number, result: Vector2): Vector2 {
+ result.x = this.x * scale;
+ result.y = this.y * scale;
+ return this;
+ }
- if (len === 0) {
- return;
- }
+ /**
+ * Scale the current Vector2 values by a factor and add the result to a given Vector2
+ * @param scale defines the scale factor
+ * @param result defines the Vector2 object where to store the result
+ * @returns the unmodified current Vector2
+ */
+ scaleAndAddToRef(scale: number, result: Vector2): Vector2 {
+ result.x += this.x * scale;
+ result.y += this.y * scale;
+ return this;
+ }
- result.x = vector.x / len;
- result.y = vector.y / len;
+ /**
+ * Gets a boolean if two vectors are equals
+ * @param otherVector defines the other vector
+ * @returns true if the given vector coordinates strictly equal the current Vector2 ones
+ */
+ equals(otherVector: DeepImmutable<Vector2>): boolean {
+ return otherVector && this.x === otherVector.x && this.y === otherVector.y;
}
/**
- * Gets a new Vector2 set with the minimal coordinate values from the "left" and "right" vectors
- * @param left defines 1st vector
- * @param right defines 2nd vector
+ * Gets a new Vector2 from current Vector2 floored values
+ * eg (1.2, 2.31) returns (1, 2)
* @returns a new Vector2
*/
- static Minimize(left: DeepImmutable<Vector2>, right: DeepImmutable<Vector2>): Vector2 {
- let x = left.x < right.x ? left.x : right.x;
- let y = left.y < right.y ? left.y : right.y;
- return new Vector2(x, y);
+ floor(): Vector2 {
+ return new Vector2(Math.floor(this.x), Math.floor(this.y));
}
/**
- * Gets a new Vector2 set with the maximal coordinate values from the "left" and "right" vectors
- * @param left defines 1st vector
- * @param right defines 2nd vector
+ * Gets a new Vector2 from current Vector2 fractional values
+ * eg (1.2, 2.31) returns (0.2, 0.31)
* @returns a new Vector2
*/
- static Maximize(left: DeepImmutable<Vector2>, right: DeepImmutable<Vector2>): Vector2 {
- let x = left.x > right.x ? left.x : right.x;
- let y = left.y > right.y ? left.y : right.y;
- return new Vector2(x, y);
+ fract(): Vector2 {
+ return new Vector2(this.x - Math.floor(this.x), this.y - Math.floor(this.y));
}
/**
- * Transforms the given vector coordinates by the given transformation Transform and stores the result in the vector "result" coordinates
- * @param vector defines the vector to transform
- * @param transformation defines the Transform to apply
- * @param result defines the target vector
+ * Rotate the current vector into a given result vector
+ * @param angle defines the rotation angle
+ * @returns the current vector
*/
- static Transform(vector: DeepImmutable<Vector2>, transformation: DeepImmutable<Transform>, ignoreOffset: boolean = false) {
- const t = transformation;
- const p = vector;
-
- if (ignoreOffset) {
- return new Vector2(t[0] * p.x + t[2] * p.y, t[1] * p.x + t[3] * p.y);
- }
- return new Vector2(t[0] * p.x + t[2] * p.y + t[4], t[1] * p.x + t[3] * p.y + t[5]);
+ rotate(angle: number) {
+ const cos = Math.cos(angle);
+ const sin = Math.sin(angle);
+ const rx = cos * this.x - sin * this.y;
+ const ry = sin * this.x + cos * this.y;
+ this.x = rx;
+ this.y = ry;
+ return this;
}
/**
- * Determines if a given vector is included in a triangle
- * @param p defines the vector to test
- * @param p0 defines 1st triangle point
- * @param p1 defines 2nd triangle point
- * @param p2 defines 3rd triangle point
- * @returns true if the point "p" is in the triangle defined by the vectors "p0", "p1", "p2"
+ * Rotate the current vector into a given result vector
+ * @param angle defines the rotation angle
+ * @param result defines the result vector where to store the rotated vector
+ * @returns the current vector
*/
- static PointInTriangle(p: DeepImmutable<Vector2>, p0: DeepImmutable<Vector2>, p1: DeepImmutable<Vector2>, p2: DeepImmutable<Vector2>) {
- let a = (1 / 2) * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
- let sign = a < 0 ? -1 : 1;
- let s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
- let t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
+ rotateToRef(angle: number, result: Vector2) {
+ const cos = Math.cos(angle);
+ const sin = Math.sin(angle);
+ result.x = cos * this.x - sin * this.y;
+ result.y = sin * this.x + cos * this.y;
- return s > 0 && t > 0 && s + t < 2 * a * sign;
+ return this;
}
- /**
- * Gets the distance between the vectors "value1" and "value2"
- * @param value1 defines first vector
- * @param value2 defines second vector
- * @returns the distance between vectors
- */
- static Distance(value1: DeepImmutable<Vector2>, value2: DeepImmutable<Vector2>): number {
- return Math.sqrt(Vector2.DistanceSquared(value1, value2));
+ rotateByPoint(angle: number, originPoint: Vector2 = Vector2.create(0, 0)) {
+ const cosA = Math.cos(angle);
+ const sinA = Math.sin(angle);
+ const rx = originPoint.x + (this.x - originPoint.x) * cosA - (this.y - originPoint.y) * sinA;
+ const ry = originPoint.y + (this.x - originPoint.x) * sinA + (this.y - originPoint.y) * cosA;
+ this.x = rx;
+ this.y = ry;
+ return this;
}
- /**
- * Returns the squared distance between the vectors "value1" and "value2"
- * @param value1 defines first vector
- * @param value2 defines second vector
- * @returns the squared distance between vectors
- */
- static DistanceSquared(value1: DeepImmutable<Vector2>, value2: DeepImmutable<Vector2>): number {
- let x = value1.x - value2.x;
- let y = value1.y - value2.y;
- return x * x + y * y;
+ transformCoordinateOnRotate(angle: number) {
+ const hypotenuse = Math.sqrt(this.x ** 2 + this.y ** 2);
+ const beta = Math.atan2(this.y, this.x);
+ const theta = -angle + beta;
+ this.x = hypotenuse * Math.cos(theta);
+ this.y = hypotenuse * Math.sin(theta);
+ return this;
}
+ // Properties
+
/**
- * Gets a new Vector2 located at the center of the vectors "value1" and "value2"
- * @param value1 defines first vector
- * @param value2 defines second vector
- * @returns a new Vector2
+ * Gets the length of the vector
+ * @returns the vector length (float)
*/
- static Center(value1: DeepImmutable<Vector2>, value2: DeepImmutable<Vector2>): Vector2 {
- return Vector2.CenterToRef(value1, value2, Vector2.Zero());
+ length(): number {
+ return Math.sqrt(this.x * this.x + this.y * this.y);
}
/**
- * Gets the center of the vectors "value1" and "value2" and stores the result in the vector "ref"
- * @param value1 defines first vector
- * @param value2 defines second vector
- * @param ref defines third vector
- * @returns ref
+ * Gets the vector squared length
+ * @returns the vector squared length (float)
*/
- static CenterToRef(value1: DeepImmutable<Vector2>, value2: DeepImmutable<Vector2>, ref: DeepImmutable<Vector2>): Vector2 {
- return ref.copyFromFloats((value1.x + value2.x) / 2, (value1.y + value2.y) / 2);
+ lengthSquared(): number {
+ return this.x * this.x + this.y * this.y;
}
+ // Methods
+
/**
- * Gets the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
- * @param p defines the middle point
- * @param segA defines one point of the segment
- * @param segB defines the other point of the segment
- * @returns the shortest distance
+ * Normalize the vector
+ * @returns the current updated Vector2
*/
- static DistanceOfPointFromSegment(p: DeepImmutable<Vector2>, segA: DeepImmutable<Vector2>, segB: DeepImmutable<Vector2>): number {
- let l2 = Vector2.DistanceSquared(segA, segB);
- if (l2 === 0.0) {
- return Vector2.Distance(p, segA);
- }
- let v = segB.subtract(segA);
- let t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
- let proj = segA.add(v.multiplyByFloats(t, t));
- return Vector2.Distance(p, proj);
+ normalize(): Vector2 {
+ Vector2.NormalizeToRef(this, this);
+ return this;
}
- static create(x: number, y: number) {
- return new Vector2(x, y);
+ /**
+ * Gets a new Vector2 copied from the Vector2
+ * @returns a new Vector2
+ */
+ clone(): Vector2 {
+ return new Vector2(this.x, this.y);
}
}
diff --git a/packages/base-render/src/Canvas.ts b/packages/base-render/src/Canvas.ts
index 83348cd284..0e872ccd40 100644
--- a/packages/base-render/src/Canvas.ts
+++ b/packages/base-render/src/Canvas.ts
@@ -48,6 +48,8 @@ interface ICanvasProps {
* @param {Number} props.pixelRatio
*/
export class Canvas {
+ isCache = false;
+
private _pixelRatio = 1;
private _canvasEle: HTMLCanvasElement;
@@ -58,8 +60,6 @@ export class Canvas {
private _height = 0;
- isCache = false;
-
constructor(props?: ICanvasProps) {
props = props || {};
diff --git a/packages/base-render/src/Component/Component.ts b/packages/base-render/src/Component/Component.ts
index 89bafcf788..cf42a130e0 100644
--- a/packages/base-render/src/Component/Component.ts
+++ b/packages/base-render/src/Component/Component.ts
@@ -6,6 +6,10 @@ import { ComponentExtension } from './Extension';
export class RenderComponent<T, U> extends BaseObject {
private _extensions = new Map<string, ComponentExtension<T, U>>();
+ get extensions() {
+ return this._extensions;
+ }
+
register(...extensions: Array<ComponentExtension<T, U>>) {
for (let extension of extensions) {
extension.parent = this;
@@ -29,10 +33,6 @@ export class RenderComponent<T, U> extends BaseObject {
return this._extensions.get(uKey);
}
- get extensions() {
- return this._extensions;
- }
-
draw(ctx: CanvasRenderingContext2D, bounds?: IBoundRect) {
/* abstract */
}
diff --git a/packages/base-render/src/Component/Docs/Common/TextSelection.ts b/packages/base-render/src/Component/Docs/Common/TextSelection.ts
index 7aec455348..9e243d9022 100644
--- a/packages/base-render/src/Component/Docs/Common/TextSelection.ts
+++ b/packages/base-render/src/Component/Docs/Common/TextSelection.ts
@@ -91,7 +91,156 @@ export class TextSelection {
span: NodePositionStateType.NORMAL,
};
- constructor(private _scene: Scene, public startNodePosition?: Nullable<INodePosition>, public endNodePosition?: Nullable<INodePosition>, public segmentId?: string) { }
+ constructor(private _scene: Scene, public startNodePosition?: Nullable<INodePosition>, public endNodePosition?: Nullable<INodePosition>, public segmentId?: string) {}
+
+ getRange() {
+ const cursorList = this._rangeList;
+
+ const firstCursor = cursorList[0];
+
+ const lastCursor = cursorList[cursorList.length - 1];
+
+ let isCollapse = cursorList.length === 1 && firstCursor.isCollapse;
+
+ return {
+ cursorStart: firstCursor.cursorStart,
+ cursorEnd: lastCursor.cursorEnd,
+ isStartBack: firstCursor.isStartBack,
+ isEndBack: lastCursor.isEndBack,
+ isCollapse,
+ };
+ }
+
+ getRangeList() {
+ return this._rangeList;
+ }
+
+ getAnchor() {
+ return this._anchorShape;
+ }
+
+ activeStatic() {
+ this._anchorShape?.setProps({
+ stroke: getColor(COLORS.black, 1),
+ });
+ }
+
+ deactivateStatic() {
+ this._anchorShape?.setProps({
+ stroke: getColor(COLORS.black, 0),
+ });
+ }
+
+ isActive() {
+ return this._current === true;
+ }
+
+ activate() {
+ this._current = true;
+ }
+
+ deactivate() {
+ this._current = false;
+ }
+
+ isEmpty() {
+ return this.startNodePosition == null && this.endNodePosition == null;
+ }
+
+ isCollapsed() {
+ if (this.startNodePosition != null && this.endNodePosition == null) {
+ return true;
+ }
+
+ if (this.isSamePosition()) {
+ return true;
+ }
+
+ return false;
+ }
+
+ isRange() {
+ const start = this.startNodePosition;
+
+ const end = this.endNodePosition;
+
+ if (start == null || end == null) {
+ return false;
+ }
+
+ if (this.isSamePosition()) {
+ return false;
+ }
+
+ return true;
+ }
+
+ dispose() {
+ this._rangeShape?.dispose();
+ this._rangeShape = null;
+ this._anchorShape?.dispose();
+ this._anchorShape = null;
+ }
+
+ isIntersection(textSelection: TextSelection) {
+ const activeRange = this.getRange();
+
+ const compareRange = textSelection.getRange();
+
+ const activeStart = this._getCursorPosition(activeRange.cursorStart, activeRange.isStartBack);
+
+ const activeEnd = this._getCursorPosition(activeRange.cursorEnd, activeRange.isEndBack);
+
+ const compareStart = this._getCursorPosition(compareRange.cursorStart, compareRange.isStartBack);
+
+ const compareEnd = this._getCursorPosition(compareRange.cursorEnd, compareRange.isEndBack);
+
+ if (activeStart > compareEnd || activeEnd < compareStart) {
+ return false;
+ }
+
+ return true;
+ }
+
+ refresh(documents: Documents) {
+ const start = this.startNodePosition;
+
+ const end = this.endNodePosition;
+
+ this._anchorShape?.hide();
+ this._rangeShape?.hide();
+
+ if (this.isEmpty()) {
+ return;
+ }
+
+ if (this.isCollapsed()) {
+ const data = this._getRangePointData(start!, start!, documents);
+ const { pointGroup, cursorList } = data;
+ this._setRangeList(cursorList);
+ pointGroup.length > 0 && this._createAndUpdateAnchor(pointGroup, documents.left, documents.top);
+ return;
+ }
+
+ const data = this._getRangePointData(start!, end!, documents);
+ const { pointGroup, cursorList } = data;
+ this._setRangeList(cursorList);
+ pointGroup.length > 0 && this._createAndUpdateRange(pointGroup, documents.left, documents.top);
+ }
+
+ getStart() {
+ if (this.startNodePosition == null) {
+ return this.endNodePosition;
+ }
+
+ if (this.endNodePosition == null) {
+ return this.startNodePosition;
+ }
+
+ const { start } = this._compareNodePosition(this.startNodePosition, this.endNodePosition);
+
+ return start;
+ }
private _resetCurrentNodePositionState() {
this._currentStartState = {
@@ -613,153 +762,4 @@ export class TextSelection {
private _getCursorPosition(index: number, isBack: boolean) {
return index - (isBack === true ? 1 : 0);
}
-
- getRange() {
- const cursorList = this._rangeList;
-
- const firstCursor = cursorList[0];
-
- const lastCursor = cursorList[cursorList.length - 1];
-
- let isCollapse = cursorList.length === 1 && firstCursor.isCollapse;
-
- return {
- cursorStart: firstCursor.cursorStart,
- cursorEnd: lastCursor.cursorEnd,
- isStartBack: firstCursor.isStartBack,
- isEndBack: lastCursor.isEndBack,
- isCollapse,
- };
- }
-
- getRangeList() {
- return this._rangeList;
- }
-
- getAnchor() {
- return this._anchorShape;
- }
-
- activeStatic() {
- this._anchorShape?.setProps({
- stroke: getColor(COLORS.black, 1),
- });
- }
-
- deactivateStatic() {
- this._anchorShape?.setProps({
- stroke: getColor(COLORS.black, 0),
- });
- }
-
- isActive() {
- return this._current === true;
- }
-
- activate() {
- this._current = true;
- }
-
- deactivate() {
- this._current = false;
- }
-
- isEmpty() {
- return this.startNodePosition == null && this.endNodePosition == null;
- }
-
- isCollapsed() {
- if (this.startNodePosition != null && this.endNodePosition == null) {
- return true;
- }
-
- if (this.isSamePosition()) {
- return true;
- }
-
- return false;
- }
-
- isRange() {
- const start = this.startNodePosition;
-
- const end = this.endNodePosition;
-
- if (start == null || end == null) {
- return false;
- }
-
- if (this.isSamePosition()) {
- return false;
- }
-
- return true;
- }
-
- dispose() {
- this._rangeShape?.dispose();
- this._rangeShape = null;
- this._anchorShape?.dispose();
- this._anchorShape = null;
- }
-
- isIntersection(textSelection: TextSelection) {
- const activeRange = this.getRange();
-
- const compareRange = textSelection.getRange();
-
- const activeStart = this._getCursorPosition(activeRange.cursorStart, activeRange.isStartBack);
-
- const activeEnd = this._getCursorPosition(activeRange.cursorEnd, activeRange.isEndBack);
-
- const compareStart = this._getCursorPosition(compareRange.cursorStart, compareRange.isStartBack);
-
- const compareEnd = this._getCursorPosition(compareRange.cursorEnd, compareRange.isEndBack);
-
- if (activeStart > compareEnd || activeEnd < compareStart) {
- return false;
- }
-
- return true;
- }
-
- refresh(documents: Documents) {
- const start = this.startNodePosition;
-
- const end = this.endNodePosition;
-
- this._anchorShape?.hide();
- this._rangeShape?.hide();
-
- if (this.isEmpty()) {
- return;
- }
-
- if (this.isCollapsed()) {
- const data = this._getRangePointData(start!, start!, documents);
- const { pointGroup, cursorList } = data;
- this._setRangeList(cursorList);
- pointGroup.length > 0 && this._createAndUpdateAnchor(pointGroup, documents.left, documents.top);
- return;
- }
-
- const data = this._getRangePointData(start!, end!, documents);
- const { pointGroup, cursorList } = data;
- this._setRangeList(cursorList);
- pointGroup.length > 0 && this._createAndUpdateRange(pointGroup, documents.left, documents.top);
- }
-
- getStart() {
- if (this.startNodePosition == null) {
- return this.endNodePosition;
- }
-
- if (this.endNodePosition == null) {
- return this.startNodePosition;
- }
-
- const { start } = this._compareNodePosition(this.startNodePosition, this.endNodePosition);
-
- return start;
- }
}
diff --git a/packages/base-render/src/Component/Docs/DocComponent.ts b/packages/base-render/src/Component/Docs/DocComponent.ts
index d115a083ec..91a8a58438 100644
--- a/packages/base-render/src/Component/Docs/DocComponent.ts
+++ b/packages/base-render/src/Component/Docs/DocComponent.ts
@@ -11,14 +11,6 @@ import { RENDER_CLASS_TYPE } from '../../Basics/Const';
export class DocComponent extends RenderComponent<IDocumentSkeletonSpan | IDocumentSkeletonLine, DOCS_EXTENSION_TYPE> {
protected _cacheCanvas: Canvas;
- getSkeleton() {
- return this._skeleton;
- }
-
- setSkeleton(skeleton: DocumentSkeleton) {
- this._skeleton = skeleton;
- }
-
constructor(oKey: string, private _skeleton?: DocumentSkeleton, private _allowCache: boolean = false) {
super(oKey);
if (this._allowCache) {
@@ -32,6 +24,14 @@ export class DocComponent extends RenderComponent<IDocumentSkeletonSpan | IDocum
});
}
+ getSkeleton() {
+ return this._skeleton;
+ }
+
+ setSkeleton(skeleton: DocumentSkeleton) {
+ this._skeleton = skeleton;
+ }
+
render(mainCtx: CanvasRenderingContext2D, bounds?: IBoundRect) {
if (!this.visible) {
this.makeDirty(false);
@@ -54,12 +54,6 @@ export class DocComponent extends RenderComponent<IDocumentSkeletonSpan | IDocum
// console.log('mainCtx', mainCtx, this.width, this.height);
}
- protected _getBounding(bounds?: IBoundRect) {}
-
- protected _draw(ctx: CanvasRenderingContext2D, bounds?: IBoundRect) {
- /* abstract */
- }
-
getParentScale() {
if (!this.parent) {
return { scaleX: 1, scaleY: 1 };
@@ -76,4 +70,10 @@ export class DocComponent extends RenderComponent<IDocumentSkeletonSpan | IDocum
scaleY,
};
}
+
+ protected _getBounding(bounds?: IBoundRect) {}
+
+ protected _draw(ctx: CanvasRenderingContext2D, bounds?: IBoundRect) {
+ /* abstract */
+ }
}
diff --git a/packages/base-render/src/Component/Docs/DocSkeleton.ts b/packages/base-render/src/Component/Docs/DocSkeleton.ts
index 7d5591638f..0e96078368 100644
--- a/packages/base-render/src/Component/Docs/DocSkeleton.ts
+++ b/packages/base-render/src/Component/Docs/DocSkeleton.ts
@@ -46,19 +46,23 @@ interface IDrawingUpdateConfig {
}
export class DocumentSkeleton extends Skeleton {
+ onRecalculateChangeObservable = new Observable<IDocumentSkeletonCached>();
+
private _documentData: IDocumentData;
private _skeletonData: IDocumentSkeletonCached;
private _renderedBlockIdMap = new Map<string, boolean>();
- onRecalculateChangeObservable = new Observable<IDocumentSkeletonCached>();
-
constructor(documentData: IDocumentData, context: ContextBase) {
super(context);
this._documentData = documentData;
}
+ static create(documentData: IDocumentData, context: ContextBase) {
+ return new DocumentSkeleton(documentData, context);
+ }
+
updateDrawing(id: string, config: IDrawingUpdateConfig) {
const drawings = this._documentData.drawings;
if (!drawings) {
@@ -379,8 +383,4 @@ export class DocumentSkeleton extends Skeleton {
blockAnchor: new Map(),
};
}
-
- static create(documentData: IDocumentData, context: ContextBase) {
- return new DocumentSkeleton(documentData, context);
- }
}
diff --git a/packages/base-render/src/Component/Docs/Document.Editor.ts b/packages/base-render/src/Component/Docs/Document.Editor.ts
index 1c2c810c42..d10654c1ec 100644
--- a/packages/base-render/src/Component/Docs/Document.Editor.ts
+++ b/packages/base-render/src/Component/Docs/Document.Editor.ts
@@ -21,6 +21,16 @@ interface INodeInfo {
}
export class DocsEditor {
+ onKeydownObservable = new Observable<IEditorInputConfig>();
+
+ onInputObservable = new Observable<IEditorInputConfig>();
+
+ onCompositionstartObservable = new Observable<IEditorInputConfig>();
+
+ onCompositionupdateObservable = new Observable<IEditorInputConfig>();
+
+ onCompositionendObservable = new Observable<IEditorInputConfig>();
+
private _container: HTMLDivElement;
private _inputParent: HTMLDivElement;
@@ -57,15 +67,7 @@ export class DocsEditor {
}
>();
- onKeydownObservable = new Observable<IEditorInputConfig>();
-
- onInputObservable = new Observable<IEditorInputConfig>();
-
- onCompositionstartObservable = new Observable<IEditorInputConfig>();
-
- onCompositionupdateObservable = new Observable<IEditorInputConfig>();
-
- onCompositionendObservable = new Observable<IEditorInputConfig>();
+ private _isIMEInputApply = false;
constructor(private _documents?: Documents) {
this._initialDom();
@@ -77,6 +79,87 @@ export class DocsEditor {
}
}
+ set activeViewport(viewport: Nullable<Viewport>) {
+ this._attachScrollEvent(viewport);
+ this._activeViewport = viewport;
+ }
+
+ static create(documents?: Documents) {
+ return new DocsEditor(documents);
+ }
+
+ getActiveTextSelection() {
+ const list = this._textSelectionList;
+ for (let textSelection of list) {
+ if (textSelection.isActive()) {
+ return textSelection;
+ }
+ }
+ }
+
+ getTextSelectionList() {
+ return this._textSelectionList;
+ }
+
+ add(textSelection: TextSelection) {
+ this._addTextSelection(textSelection);
+ }
+
+ remain() {
+ const activeSelection = this.getActiveTextSelection();
+ if (activeSelection == null) {
+ return;
+ }
+ const index = this._textSelectionList.indexOf(activeSelection);
+
+ return this._textSelectionList.splice(index, 1)[0];
+ }
+
+ sync() {
+ this._syncDomToSelection();
+ }
+
+ active(x: number, y: number) {
+ this._container.style.left = `${x}px`;
+ this._container.style.top = `${y}px`;
+
+ this._cursor.style.animation = 'univer_cursor_blinkStyle 1s steps(1) infinite';
+ this._cursor.style.display = 'revert';
+
+ setTimeout(() => {
+ this._input.focus();
+ }, 0);
+ }
+
+ deactivate() {
+ this._container.style.left = `0px`;
+ this._container.style.top = `0px`;
+
+ this._cursor.style.animation = '';
+ this._cursor.style.display = 'none';
+
+ this._input.blur();
+ }
+
+ changeDocuments(documents: Documents) {
+ if (this._documents) {
+ this._detachEvent(this._documents);
+ }
+
+ this._documents = documents;
+ this._skeletonObserver = documents.getSkeleton()?.onRecalculateChangeObservable.add((data: IDocumentSkeletonCached) => {
+ this._deleteAllTextSelection();
+ });
+ this._attachSelectionEvent(this._documents);
+ }
+
+ dispose() {
+ if (this._documents) {
+ this._detachEvent(this._documents);
+ }
+ this._container.remove();
+ }
+
private _initialDom() {
const container = document.createElement('div');
@@ -421,8 +504,6 @@ export class DocsEditor {
});
}
- private _isIMEInputApply = false;
-
private _attachInputEvent() {
this._input.addEventListener('keydown', (e) => {
if (this._isIMEInputApply) {
@@ -628,85 +709,4 @@ export class DocsEditor {
activeSelection?.refresh(this._documents);
}
-
- getActiveTextSelection() {
- const list = this._textSelectionList;
- for (let textSelection of list) {
- if (textSelection.isActive()) {
- return textSelection;
- }
- }
- }
-
- getTextSelectionList() {
- return this._textSelectionList;
- }
-
- add(textSelection: TextSelection) {
- this._addTextSelection(textSelection);
- }
-
- remain() {
- const activeSelection = this.getActiveTextSelection();
- if (activeSelection == null) {
- return;
- }
- const index = this._textSelectionList.indexOf(activeSelection);
-
- return this._textSelectionList.splice(index, 1)[0];
- }
-
- sync() {
- this._syncDomToSelection();
- }
-
- active(x: number, y: number) {
- this._container.style.left = `${x}px`;
- this._container.style.top = `${y}px`;
-
- this._cursor.style.animation = 'univer_cursor_blinkStyle 1s steps(1) infinite';
- this._cursor.style.display = 'revert';
-
- setTimeout(() => {
- this._input.focus();
- }, 0);
- }
-
- deactivate() {
- this._container.style.left = `0px`;
- this._container.style.top = `0px`;
-
- this._cursor.style.animation = '';
- this._cursor.style.display = 'none';
-
- this._input.blur();
- }
-
- changeDocuments(documents: Documents) {
- if (this._documents) {
- this._detachEvent(this._documents);
- }
-
- this._documents = documents;
- this._skeletonObserver = documents.getSkeleton()?.onRecalculateChangeObservable.add((data: IDocumentSkeletonCached) => {
- this._deleteAllTextSelection();
- });
- this._attachSelectionEvent(this._documents);
- }
-
- dispose() {
- if (this._documents) {
- this._detachEvent(this._documents);
- }
- this._container.remove();
- }
-
- set activeViewport(viewport: Nullable<Viewport>) {
- this._attachScrollEvent(viewport);
- this._activeViewport = viewport;
- }
-
- static create(documents?: Documents) {
- return new DocsEditor(documents);
- }
}
diff --git a/packages/base-render/src/Component/Docs/Document.ts b/packages/base-render/src/Component/Docs/Document.ts
index 276c407ba0..4ef2318d21 100644
--- a/packages/base-render/src/Component/Docs/Document.ts
+++ b/packages/base-render/src/Component/Docs/Document.ts
@@ -29,18 +29,6 @@ export interface IPageRenderConfig {
}
export class Documents extends DocComponent {
- private _drawLiquid: Liquid;
-
- private _findLiquid: Liquid;
-
- private _hasEditor = false;
-
- private _editor: DocsEditor;
-
- private _skeletonObserver: Nullable<Observer<IDocumentSkeletonCached>>;
-
- // private _textAngleRotateOffset: number = 0;
-
pageWidth: number;
pageHeight: number;
@@ -55,6 +43,18 @@ export class Documents extends DocComponent {
onPageRenderObservable = new Observable<IPageRenderConfig>();
+ private _drawLiquid: Liquid;
+
+ private _findLiquid: Liquid;
+
+ private _hasEditor = false;
+
+ private _editor: DocsEditor;
+
+ private _skeletonObserver: Nullable<Observer<IDocumentSkeletonCached>>;
+
+ // private _textAngleRotateOffset: number = 0;
+
constructor(oKey: string, documentSkeleton?: DocumentSkeleton, config?: IDocumentsConfig) {
super(oKey, documentSkeleton, config?.allowCache);
@@ -85,108 +85,12 @@ export class Documents extends DocComponent {
this.makeDirty(true);
}
- protected _draw(ctx: CanvasRenderingContext2D, bounds?: IBoundRect) {
- this.draw(ctx, bounds);
- }
-
- private _horizontalHandler(pageWidth: number, pagePaddingLeft: number, pagePaddingRight: number, horizontalAlign: HorizontalAlign) {
- let offsetLeft = 0;
- if (horizontalAlign === HorizontalAlign.CENTER) {
- offsetLeft = (this.width - pageWidth) / 2;
- } else if (horizontalAlign === HorizontalAlign.RIGHT) {
- offsetLeft = this.width - pageWidth - pagePaddingRight;
- } else {
- offsetLeft = pagePaddingLeft;
- }
-
- return offsetLeft;
- }
-
- private _verticalHandler(pageHeight: number, pagePaddingTop: number, pagePaddingBottom: number, verticalAlign: VerticalAlign) {
- let offsetTop = 0;
- if (verticalAlign === VerticalAlign.MIDDLE) {
- offsetTop = (this.height - pageHeight) / 2;
- } else if (verticalAlign === VerticalAlign.BOTTOM) {
- offsetTop = this.height - pageHeight - pagePaddingBottom;
- } else {
- offsetTop = pagePaddingTop;
- }
- return offsetTop;
- }
-
- private _startRotation(ctx: CanvasRenderingContext2D, textAngle: number) {
- ctx.rotate(textAngle || 0);
- }
-
- private _resetRotation(ctx: CanvasRenderingContext2D, textAngle: number) {
- ctx.rotate(-textAngle || 0);
- }
-
- private _initialDefaultExtension() {
- DocumentsSpanAndLineExtensionRegistry.getData().forEach((extension) => {
- this.register(extension);
- });
- }
-
- private _addSkeletonChangeObserver(skeleton?: DocumentSkeleton) {
- if (!skeleton) {
- return;
- }
-
- this._skeletonObserver = skeleton.onRecalculateChangeObservable.add((data) => {
- const pages = data.pages;
- let width = 0;
- let height = 0;
- for (let i = 0, len = pages.length; i < len; i++) {
- const page = pages[i];
- const { pageWidth, pageHeight } = page;
- if (this.pageLayoutType === PageLayoutType.VERTICAL) {
- height += pageHeight;
- if (i !== len - 1) {
- height += this.pageMarginTop;
- }
- width = Math.max(width, pageWidth);
- } else if (this.pageLayoutType === PageLayoutType.HORIZONTAL) {
- width += pageWidth;
- if (i !== len - 1) {
- width += this.pageMarginLeft;
- }
- height = Math.max(height, pageHeight);
- }
- }
-
- this.resize(width, height);
- this.calculatePagePosition();
- });
- }
-
- private _disposeSkeletonChangeObserver(skeleton?: DocumentSkeleton) {
- if (!skeleton) {
- return;
- }
- skeleton.onRecalculateChangeObservable.remove(this._skeletonObserver);
+ get hasEditor() {
+ return this._hasEditor;
}
- private _getPageBoundingBox(page: IDocumentSkeletonPage) {
- const { pageWidth, pageHeight } = page;
- let { x: startX, y: startY } = this._findLiquid;
-
- let endX = -1;
- let endY = -1;
- if (this.pageLayoutType === PageLayoutType.VERTICAL) {
- endX = pageWidth;
- endY = startY + pageHeight;
- } else if (this.pageLayoutType === PageLayoutType.HORIZONTAL) {
- endX = startX + pageWidth;
- endY = pageHeight;
- }
-
- return {
- startX,
- startY,
- endX,
- endY,
- };
+ static create(oKey: string, documentSkeleton?: DocumentSkeleton, config?: IDocumentsConfig) {
+ return new Documents(oKey, documentSkeleton, config);
}
calculatePagePosition() {
@@ -281,10 +185,6 @@ export class Documents extends DocComponent {
return this._editor.sync();
}
- get hasEditor() {
- return this._hasEditor;
- }
-
draw(ctx: CanvasRenderingContext2D, bounds?: IBoundRect) {
const documentSkeleton = this.getSkeleton();
if (!documentSkeleton) {
@@ -731,11 +631,111 @@ export class Documents extends DocComponent {
return false;
}
- private _translatePage(page: IDocumentSkeletonPage) {
- this._findLiquid.translatePage(page, this.pageLayoutType, this.pageMarginLeft, this.pageMarginTop);
+ protected _draw(ctx: CanvasRenderingContext2D, bounds?: IBoundRect) {
+ this.draw(ctx, bounds);
}
- static create(oKey: string, documentSkeleton?: DocumentSkeleton, config?: IDocumentsConfig) {
- return new Documents(oKey, documentSkeleton, config);
+ private _horizontalHandler(pageWidth: number, pagePaddingLeft: number, pagePaddingRight: number, horizontalAlign: HorizontalAlign) {
+ let offsetLeft = 0;
+ if (horizontalAlign === HorizontalAlign.CENTER) {
+ offsetLeft = (this.width - pageWidth) / 2;
+ } else if (horizontalAlign === HorizontalAlign.RIGHT) {
+ offsetLeft = this.width - pageWidth - pagePaddingRight;
+ } else {
+ offsetLeft = pagePaddingLeft;
+ }
+
+ return offsetLeft;
+ }
+
+ private _verticalHandler(pageHeight: number, pagePaddingTop: number, pagePaddingBottom: number, verticalAlign: VerticalAlign) {
+ let offsetTop = 0;
+ if (verticalAlign === VerticalAlign.MIDDLE) {
+ offsetTop = (this.height - pageHeight) / 2;
+ } else if (verticalAlign === VerticalAlign.BOTTOM) {
+ offsetTop = this.height - pageHeight - pagePaddingBottom;
+ } else {
+ offsetTop = pagePaddingTop;
+ }
+ return offsetTop;
+ }
+
+ private _startRotation(ctx: CanvasRenderingContext2D, textAngle: number) {
+ ctx.rotate(textAngle || 0);
+ }
+
+ private _resetRotation(ctx: CanvasRenderingContext2D, textAngle: number) {
+ ctx.rotate(-textAngle || 0);
+ }
+
+ private _initialDefaultExtension() {
+ DocumentsSpanAndLineExtensionRegistry.getData().forEach((extension) => {
+ this.register(extension);
+ });
+ }
+
+ private _addSkeletonChangeObserver(skeleton?: DocumentSkeleton) {
+ if (!skeleton) {
+ return;
+ }
+
+ this._skeletonObserver = skeleton.onRecalculateChangeObservable.add((data) => {
+ const pages = data.pages;
+ let width = 0;
+ let height = 0;
+ for (let i = 0, len = pages.length; i < len; i++) {
+ const page = pages[i];
+ const { pageWidth, pageHeight } = page;
+ if (this.pageLayoutType === PageLayoutType.VERTICAL) {
+ height += pageHeight;
+ if (i !== len - 1) {
+ height += this.pageMarginTop;
+ }
+ width = Math.max(width, pageWidth);
+ } else if (this.pageLayoutType === PageLayoutType.HORIZONTAL) {
+ width += pageWidth;
+ if (i !== len - 1) {
+ width += this.pageMarginLeft;
+ }
+ height = Math.max(height, pageHeight);
+ }
+ }
+
+ this.resize(width, height);
+ this.calculatePagePosition();
+ });
+ }
+
+ private _disposeSkeletonChangeObserver(skeleton?: DocumentSkeleton) {
+ if (!skeleton) {
+ return;
+ }
+ skeleton.onRecalculateChangeObservable.remove(this._skeletonObserver);
+ }
+
+ private _getPageBoundingBox(page: IDocumentSkeletonPage) {
+ const { pageWidth, pageHeight } = page;
+ let { x: startX, y: startY } = this._findLiquid;
+
+ let endX = -1;
+ let endY = -1;
+ if (this.pageLayoutType === PageLayoutType.VERTICAL) {
+ endX = pageWidth;
+ endY = startY + pageHeight;
+ } else if (this.pageLayoutType === PageLayoutType.HORIZONTAL) {
+ endX = startX + pageWidth;
+ endY = pageHeight;
+ }
+
+ return {
+ startX,
+ startY,
+ endX,
+ endY,
+ };
+ }
+
+ private _translatePage(page: IDocumentSkeletonPage) {
+ this._findLiquid.translatePage(page, this.pageLayoutType, this.pageMarginLeft, this.pageMarginTop);
}
}
diff --git a/packages/base-render/src/Component/Sheets/ColumnTitle.ts b/packages/base-render/src/Component/Sheets/ColumnTitle.ts
index 53ac1ab3f0..195fa43054 100644
--- a/packages/base-render/src/Component/Sheets/ColumnTitle.ts
+++ b/packages/base-render/src/Component/Sheets/ColumnTitle.ts
@@ -21,13 +21,6 @@ export class SpreadsheetColumnTitle extends SpreadsheetTitle {
return this._columnTitleLayoutExtension;
}
- private _initialDefaultExtension() {
- SheetColumnTitleExtensionRegistry.getData().forEach((extension) => {
- this.register(extension);
- });
- this._columnTitleLayoutExtension = this.getExtensionByKey('DefaultColumnTitleLayoutExtension') as ColumnTitleLayout;
- }
-
draw(ctx: CanvasRenderingContext2D, bounds?: IBoundRect) {
const spreadsheetSkeleton = this.getSkeleton();
if (!spreadsheetSkeleton) {
@@ -61,4 +54,11 @@ export class SpreadsheetColumnTitle extends SpreadsheetTitle {
}
return false;
}
+
+ private _initialDefaultExtension() {
+ SheetColumnTitleExtensionRegistry.getData().forEach((extension) => {
+ this.register(extension);
+ });
+ this._columnTitleLayoutExtension = this.getExtensionByKey('DefaultColumnTitleLayoutExtension') as ColumnTitleLayout;
+ }
}
diff --git a/packages/base-render/src/Component/Sheets/Extensions/Font.ts b/packages/base-render/src/Component/Sheets/Extensions/Font.ts
index 1c9d5adc08..27e18b0e66 100644
--- a/packages/base-render/src/Component/Sheets/Extensions/Font.ts
+++ b/packages/base-render/src/Component/Sheets/Extensions/Font.ts
@@ -12,13 +12,13 @@ export class Font extends SheetExtension {
zIndex = 40;
+ changeFontColor: ObjectMatrix<IColorStyle>;
+
getDocuments() {
const parent = this.parent as Spreadsheet;
return parent.getDocuments();
}
- changeFontColor: ObjectMatrix<IColorStyle>;
-
setChangeFontColor(r: number, c: number, color: IColorStyle) {
this.changeFontColor.setValue(r, c, color);
}
diff --git a/packages/base-render/src/Component/Sheets/Selection/SelectionControl.ts b/packages/base-render/src/Component/Sheets/Selection/SelectionControl.ts
index 769ff1a643..acf0cafb53 100644
--- a/packages/base-render/src/Component/Sheets/Selection/SelectionControl.ts
+++ b/packages/base-render/src/Component/Sheets/Selection/SelectionControl.ts
@@ -73,6 +73,160 @@ export class SelectionControl {
this._initialize();
}
+ get zIndex() {
+ return this._zIndex;
+ }
+
+ get leftControl() {
+ return this._leftControl;
+ }
+
+ get rightControl() {
+ return this._rightControl;
+ }
+
+ get topControl() {
+ return this._topControl;
+ }
+
+ get bottomControl() {
+ return this._bottomControl;
+ }
+
+ get fillControl() {
+ return this._fillControl;
+ }
+
+ get backgroundControlTop() {
+ return this._backgroundControlTop;
+ }
+
+ get backgroundControlBottom() {
+ return this._backgroundControlBottom;
+ }
+
+ get backgroundControlMiddleLeft() {
+ return this._backgroundControlMiddleLeft;
+ }
+
+ get backgroundControlMiddleRight() {
+ return this._backgroundControlMiddleRight;
+ }
+
+ get selectionShape() {
+ return this._selectionShape;
+ }
+
+ get model() {
+ return this._selectionModel;
+ }
+
+ static create(scene: Scene, zIndex: number) {
+ return new this(scene, zIndex);
+ }
+
+ static fromJson(scene: Scene, zIndex: number, newSelectionRange: ISelection) {
+ const control = SelectionControl.create(scene, zIndex);
+ control.update(newSelectionRange);
+ return control;
+ }
+
+ /**
+ * just handle the view
+ *
+ * inner update
+ */
+ _updateControl() {
+ const { startX, startY, endX, endY } = this._selectionModel;
+
+ this.leftControl.resize(undefined, endY - startY);
+ this.rightControl.transformByState({
+ height: endY - startY,
+ left: endX - startX - DEFAULT_SELECTION_CONFIG.strokeWidth / 2,
+ });
+ this.topControl.resize(endX - startX + DEFAULT_SELECTION_CONFIG.strokeWidth);
+ this.bottomControl.transformByState({
+ width: endX - startX + DEFAULT_SELECTION_CONFIG.strokeWidth,
+ top: endY - startY - DEFAULT_SELECTION_CONFIG.strokeWidth / 2,
+ });
+
+ this.fillControl.translate(endX - startX - DEFAULT_SELECTION_CONFIG.fillSideLength / 2, endY - startY - DEFAULT_SELECTION_CONFIG.fillSideLength / 2);
+
+ this._updateBackgroundControl();
+
+ this.selectionShape.show();
+ this.selectionShape.translate(startX, startY);
+
+ this.selectionShape.makeDirty(true);
+ }
+
+ update(newSelectionRange: ISelection, highlight: Nullable<ICellInfo>) {
+ this._selectionModel.setValue(newSelectionRange, highlight);
+ this._updateControl();
+ }
+
+ clearHighlight() {
+ this._selectionModel.clearCurrentCell();
+ this._updateControl();
+ }
+
+ getScene() {
+ return this._scene;
+ }
+
+ dispose() {
+ this._leftControl?.dispose();
+ this._rightControl?.dispose();
+ this._topControl?.dispose();
+ this._bottomControl?.dispose();
+ this._backgroundControlTop?.dispose();
+ this._backgroundControlMiddleLeft?.dispose();
+ this._backgroundControlMiddleRight?.dispose();
+ this._backgroundControlBottom?.dispose();
+ this._fillControl?.dispose();
+ this._selectionShape?.dispose();
+ }
+
+ /**
+ * Get the cell information of the current selection, considering the case of merging cells
+ */
+ getCurrentCellInfo(): Nullable<ISelection> {
+ const currentCell = this.model.currentCell;
+
+ if (currentCell) {
+ let currentRangeData;
+
+ if (currentCell.isMerged) {
+ const mergeInfo = currentCell.mergeInfo;
+
+ currentRangeData = {
+ startRow: mergeInfo.startRow,
+ endRow: mergeInfo.endRow,
+ startColumn: mergeInfo.startColumn,
+ endColumn: mergeInfo.endColumn,
+ startX: mergeInfo.startX,
+ endX: mergeInfo.endX,
+ startY: mergeInfo.startY,
+ endY: mergeInfo.endY,
+ };
+ } else {
+ const { row, column, startX, endX, startY, endY } = currentCell;
+ currentRangeData = {
+ startRow: row,
+ endRow: row,
+ startColumn: column,
+ endColumn: column,
+ startX,
+ endX,
+ startY,
+ endY,
+ };
+ }
+
+ return currentRangeData;
+ }
+ }
+
private _initialize() {
this._selectionModel = new SelectionModel(SELECTION_TYPE.NORMAL);
const zIndex = this._zIndex;
@@ -153,39 +307,6 @@ export class SelectionControl {
scene.addObject(this._selectionShape);
}
- get zIndex() {
- return this._zIndex;
- }
-
- /**
- * just handle the view
- *
- * inner update
- */
- _updateControl() {
- const { startX, startY, endX, endY } = this._selectionModel;
-
- this.leftControl.resize(undefined, endY - startY);
- this.rightControl.transformByState({
- height: endY - startY,
- left: endX - startX - DEFAULT_SELECTION_CONFIG.strokeWidth / 2,
- });
- this.topControl.resize(endX - startX + DEFAULT_SELECTION_CONFIG.strokeWidth);
- this.bottomControl.transformByState({
- width: endX - startX + DEFAULT_SELECTION_CONFIG.strokeWidth,
- top: endY - startY - DEFAULT_SELECTION_CONFIG.strokeWidth / 2,
- });
-
- this.fillControl.translate(endX - startX - DEFAULT_SELECTION_CONFIG.fillSideLength / 2, endY - startY - DEFAULT_SELECTION_CONFIG.fillSideLength / 2);
-
- this._updateBackgroundControl();
-
- this.selectionShape.show();
- this.selectionShape.translate(startX, startY);
-
- this.selectionShape.makeDirty(true);
- }
-
private _updateBackgroundControl() {
const {
startColumn,
@@ -261,125 +382,4 @@ export class SelectionControl {
}
this._backgroundControlBottom.transformByState(middleBottomConfig);
}
-
- update(newSelectionRange: ISelection, highlight: Nullable<ICellInfo>) {
- this._selectionModel.setValue(newSelectionRange, highlight);
- this._updateControl();
- }
-
- clearHighlight() {
- this._selectionModel.clearCurrentCell();
- this._updateControl();
- }
-
- getScene() {
- return this._scene;
- }
-
- dispose() {
- this._leftControl?.dispose();
- this._rightControl?.dispose();
- this._topControl?.dispose();
- this._bottomControl?.dispose();
- this._backgroundControlTop?.dispose();
- this._backgroundControlMiddleLeft?.dispose();
- this._backgroundControlMiddleRight?.dispose();
- this._backgroundControlBottom?.dispose();
- this._fillControl?.dispose();
- this._selectionShape?.dispose();
- }
-
- get leftControl() {
- return this._leftControl;
- }
-
- get rightControl() {
- return this._rightControl;
- }
-
- get topControl() {
- return this._topControl;
- }
-
- get bottomControl() {
- return this._bottomControl;
- }
-
- get fillControl() {
- return this._fillControl;
- }
-
- get backgroundControlTop() {
- return this._backgroundControlTop;
- }
-
- get backgroundControlBottom() {
- return this._backgroundControlBottom;
- }
-
- get backgroundControlMiddleLeft() {
- return this._backgroundControlMiddleLeft;
- }
-
- get backgroundControlMiddleRight() {
- return this._backgroundControlMiddleRight;
- }
-
- get selectionShape() {
- return this._selectionShape;
- }
-
- get model() {
- return this._selectionModel;
- }
-
- /**
- * Get the cell information of the current selection, considering the case of merging cells
- */
- getCurrentCellInfo(): Nullable<ISelection> {
- const currentCell = this.model.currentCell;
-
- if (currentCell) {
- let currentRangeData;
-
- if (currentCell.isMerged) {
- const mergeInfo = currentCell.mergeInfo;
-
- currentRangeData = {
- startRow: mergeInfo.startRow,
- endRow: mergeInfo.endRow,
- startColumn: mergeInfo.startColumn,
- endColumn: mergeInfo.endColumn,
- startX: mergeInfo.startX,
- endX: mergeInfo.endX,
- startY: mergeInfo.startY,
- endY: mergeInfo.endY,
- };
- } else {
- const { row, column, startX, endX, startY, endY } = currentCell;
- currentRangeData = {
- startRow: row,
- endRow: row,
- startColumn: column,
- endColumn: column,
- startX,
- endX,
- startY,
- endY,
- };
- }
-
- return currentRangeData;
- }
- }
-
- static create(scene: Scene, zIndex: number) {
- return new this(scene, zIndex);
- }
-
- static fromJson(scene: Scene, zIndex: number, newSelectionRange: ISelection) {
- const control = SelectionControl.create(scene, zIndex);
- control.update(newSelectionRange);
- return control;
- }
}
diff --git a/packages/base-render/src/Component/Sheets/Selection/SelectionManager.ts b/packages/base-render/src/Component/Sheets/Selection/SelectionManager.ts
index a6b60df855..94fbee07b7 100644
--- a/packages/base-render/src/Component/Sheets/Selection/SelectionManager.ts
+++ b/packages/base-render/src/Component/Sheets/Selection/SelectionManager.ts
@@ -14,6 +14,8 @@ import { Scene } from '../../../Scene';
* SelectionManager 维护model数据list,action也是修改这一层数据,obs监听到数据变动后,自动刷新(control仍然可以持有数据)
*/
export class SelectionManager {
+ hasSelection: boolean = false;
+
private _moveObserver: Nullable<Observer<IPointerEvent | IMouseEvent>>;
private _upObserver: Nullable<Observer<IPointerEvent | IMouseEvent>>;
@@ -32,12 +34,14 @@ export class SelectionManager {
private _cancelUpObserver: Nullable<Observer<IPointerEvent | IMouseEvent>>;
- hasSelection: boolean = false;
-
constructor(private _spreadsheet: Spreadsheet) {
this._mainEventInitial();
}
+ static create(spreadsheet: Spreadsheet) {
+ return new SelectionManager(spreadsheet);
+ }
+
/**
* add a selection
* @param selectionRange
@@ -411,8 +415,4 @@ export class SelectionManager {
state.stopPropagation();
});
}
-
- static create(spreadsheet: Spreadsheet) {
- return new SelectionManager(spreadsheet);
- }
}
diff --git a/packages/base-render/src/Component/Sheets/Selection/SelectionModel.ts b/packages/base-render/src/Component/Sheets/Selection/SelectionModel.ts
index 579d67de3f..2c3dae8ff7 100644
--- a/packages/base-render/src/Component/Sheets/Selection/SelectionModel.ts
+++ b/packages/base-render/src/Component/Sheets/Selection/SelectionModel.ts
@@ -26,32 +26,6 @@ export class SelectionModel implements ISelection {
this._type = type;
}
- isEqual(selectionRange: ISelection) {
- const { startColumn, startRow, endColumn, endRow, type } = this;
- const { startColumn: newStartColumn, startRow: newStartRow, endColumn: newEndColumn, endRow: newEndRow } = selectionRange;
- // if (type !== newType) {
- // return false;
- // }
- if (startColumn === newStartColumn && startRow === newStartRow && endColumn === newEndColumn && endRow === newEndRow) {
- return true;
- }
- return false;
- }
-
- isInclude(selectionRange: ISelection) {
- const { startColumn, startRow, endColumn, endRow, type } = this;
- const { startColumn: newStartColumn, startRow: newStartRow, endColumn: newEndColumn, endRow: newEndRow } = selectionRange;
-
- // if (type !== newType) {
- // return false;
- // }
-
- if (!(newEndColumn < startColumn || newStartColumn > endColumn || newStartRow > endRow || newEndRow < startRow)) {
- return true;
- }
- return false;
- }
-
get startColumn() {
return this._startColumn;
}
@@ -92,6 +66,32 @@ export class SelectionModel implements ISelection {
return this._currentCell;
}
+ isEqual(selectionRange: ISelection) {
+ const { startColumn, startRow, endColumn, endRow, type } = this;
+ const { startColumn: newStartColumn, startRow: newStartRow, endColumn: newEndColumn, endRow: newEndRow } = selectionRange;
+ // if (type !== newType) {
+ // return false;
+ // }
+ if (startColumn === newStartColumn && startRow === newStartRow && endColumn === newEndColumn && endRow === newEndRow) {
+ return true;
+ }
+ return false;
+ }
+
+ isInclude(selectionRange: ISelection) {
+ const { startColumn, startRow, endColumn, endRow, type } = this;
+ const { startColumn: newStartColumn, startRow: newStartRow, endColumn: newEndColumn, endRow: newEndRow } = selectionRange;
+
+ // if (type !== newType) {
+ // return false;
+ // }
+
+ if (!(newEndColumn < startColumn || newStartColumn > endColumn || newStartRow > endRow || newEndRow < startRow)) {
+ return true;
+ }
+ return false;
+ }
+
highlightToSelection() {
return makeCellToSelection(this._currentCell);
}
diff --git a/packages/base-render/src/Component/Sheets/SheetSkeleton.ts b/packages/base-render/src/Component/Sheets/SheetSkeleton.ts
index 5896083216..886ba0644d 100644
--- a/packages/base-render/src/Component/Sheets/SheetSkeleton.ts
+++ b/packages/base-render/src/Component/Sheets/SheetSkeleton.ts
@@ -110,18 +110,6 @@ export class SpreadsheetSkeleton extends Skeleton {
this.updateDataMerge();
}
- getWorksheetConfig() {
- return this._config;
- }
-
- getCellData() {
- return this._cellData;
- }
-
- getsStyles() {
- return this._styles;
- }
-
get rowHeightAccumulation() {
return this._rowHeightAccumulation;
}
@@ -166,6 +154,26 @@ export class SpreadsheetSkeleton extends Skeleton {
return this._showGridlines;
}
+ get dataMergeCacheAll() {
+ return this._dataMergeCacheAll;
+ }
+
+ static create(config: IWorksheetConfig, cellData: ObjectMatrix<ICellData>, styles: Styles, context: SheetContext) {
+ return new SpreadsheetSkeleton(config, cellData, styles, context);
+ }
+
+ getWorksheetConfig() {
+ return this._config;
+ }
+
+ getCellData() {
+ return this._cellData;
+ }
+
+ getsStyles() {
+ return this._styles;
+ }
+
setOverflowCache(value: ObjectMatrix<IRangeData>) {
this._overflowCache = value;
}
@@ -293,8 +301,90 @@ export class SpreadsheetSkeleton extends Skeleton {
return this._rowHeightAccumulation.length;
}
- get dataMergeCacheAll() {
- return this._dataMergeCacheAll;
+ getOverflowPosition(contentSize: { width: number; height: number }, horizontalAlign: HorizontalAlign, row: number, column: number, columnCount: number) {
+ const { width: contentWidth, height: contentHeight } = contentSize;
+
+ let startColumn = column;
+ let endColumn = column;
+
+ // console.log('documentSkeleton', cell?.v, column, endColumn, row, column, columnCount, contentWidth);
+
+ if (horizontalAlign === HorizontalAlign.CENTER) {
+ startColumn = this._getOverflowBound(row, column, 0, contentWidth / 2);
+ endColumn = this._getOverflowBound(row, column, columnCount - 1, contentWidth / 2);
+ } else if (horizontalAlign === HorizontalAlign.RIGHT) {
+ startColumn = this._getOverflowBound(row, column, 0, contentWidth);
+ } else {
+ endColumn = this._getOverflowBound(row, column, columnCount - 1, contentWidth);
+ }
+
+ return {
+ startColumn,
+ endColumn,
+ };
+ }
+
+ /**
+ *
+ * @param rowHeightAccumulation Row layout information
+ * @param columnWidthAccumulation Column layout information
+ * @param bounds The range of the visible area of the canvas
+ * @returns The range cell index of the canvas visible area
+ */
+ protected _getBounding(rowHeightAccumulation: number[], columnWidthAccumulation: number[], bounds?: IBoundRect) {
+ const rhaLength = rowHeightAccumulation.length;
+ const cwaLength = columnWidthAccumulation.length;
+
+ if (!bounds) {
+ return {
+ startRow: 0,
+ endRow: rhaLength - 1,
+ startColumn: 0,
+ endColumn: cwaLength - 1,
+ };
+ }
+
+ let dataset_row_st = -1;
+ let dataset_row_ed = -1;
+ let dataset_col_st = -1;
+ let dataset_col_ed = -1;
+
+ dataset_row_st = searchArray(rowHeightAccumulation, bounds.tl.y - this.columnTitleHeight);
+ dataset_row_ed = searchArray(rowHeightAccumulation, bounds.bl.y - this.columnTitleHeight);
+
+ if (dataset_row_st === -1) {
+ dataset_row_st = 0;
+ }
+
+ if (dataset_row_ed === -1) {
+ dataset_row_ed = rhaLength - 1;
+ }
+
+ if (dataset_row_ed >= rhaLength) {
+ dataset_row_ed = rhaLength - 1;
+ }
+
+ dataset_col_st = searchArray(columnWidthAccumulation, bounds.tl.x - this.rowTitleWidth);
+ dataset_col_ed = searchArray(columnWidthAccumulation, bounds.tr.x - this.rowTitleWidth);
+
+ if (dataset_col_st === -1) {
+ dataset_col_st = 0;
+ }
+
+ if (dataset_col_ed === -1) {
+ dataset_col_ed = cwaLength - 1;
+ }
+
+ if (dataset_col_ed >= cwaLength) {
+ dataset_col_ed = cwaLength - 1;
+ }
+
+ return {
+ startRow: dataset_row_st - 1,
+ endRow: dataset_row_ed + 1,
+ startColumn: dataset_col_st - 1,
+ endColumn: dataset_col_ed + 1,
+ };
}
private _generateRowMatrixCache(rowCount: number, rowData: ObjectArrayType<Partial<IRowData>>, defaultRowHeight: number) {
@@ -369,69 +459,6 @@ export class SpreadsheetSkeleton extends Skeleton {
};
}
- /**
- *
- * @param rowHeightAccumulation Row layout information
- * @param columnWidthAccumulation Column layout information
- * @param bounds The range of the visible area of the canvas
- * @returns The range cell index of the canvas visible area
- */
- protected _getBounding(rowHeightAccumulation: number[], columnWidthAccumulation: number[], bounds?: IBoundRect) {
- const rhaLength = rowHeightAccumulation.length;
- const cwaLength = columnWidthAccumulation.length;
-
- if (!bounds) {
- return {
- startRow: 0,
- endRow: rhaLength - 1,
- startColumn: 0,
- endColumn: cwaLength - 1,
- };
- }
-
- let dataset_row_st = -1;
- let dataset_row_ed = -1;
- let dataset_col_st = -1;
- let dataset_col_ed = -1;
-
- dataset_row_st = searchArray(rowHeightAccumulation, bounds.tl.y - this.columnTitleHeight);
- dataset_row_ed = searchArray(rowHeightAccumulation, bounds.bl.y - this.columnTitleHeight);
-
- if (dataset_row_st === -1) {
- dataset_row_st = 0;
- }
-
- if (dataset_row_ed === -1) {
- dataset_row_ed = rhaLength - 1;
- }
-
- if (dataset_row_ed >= rhaLength) {
- dataset_row_ed = rhaLength - 1;
- }
-
- dataset_col_st = searchArray(columnWidthAccumulation, bounds.tl.x - this.rowTitleWidth);
- dataset_col_ed = searchArray(columnWidthAccumulation, bounds.tr.x - this.rowTitleWidth);
-
- if (dataset_col_st === -1) {
- dataset_col_st = 0;
- }
-
- if (dataset_col_ed === -1) {
- dataset_col_ed = cwaLength - 1;
- }
-
- if (dataset_col_ed >= cwaLength) {
- dataset_col_ed = cwaLength - 1;
- }
-
- return {
- startRow: dataset_row_st - 1,
- endRow: dataset_row_ed + 1,
- startColumn: dataset_col_st - 1,
- endColumn: dataset_col_ed + 1,
- };
- }
-
// private _calculateOverflowCache() {
// const { font: fontList } = this.stylesCache;
// // const mergeRangeCache = this._getMergeRangeCache();
@@ -484,29 +511,6 @@ export class SpreadsheetSkeleton extends Skeleton {
// return overflowCache;
// }
- getOverflowPosition(contentSize: { width: number; height: number }, horizontalAlign: HorizontalAlign, row: number, column: number, columnCount: number) {
- const { width: contentWidth, height: contentHeight } = contentSize;
-
- let startColumn = column;
- let endColumn = column;
-
- // console.log('documentSkeleton', cell?.v, column, endColumn, row, column, columnCount, contentWidth);
-
- if (horizontalAlign === HorizontalAlign.CENTER) {
- startColumn = this._getOverflowBound(row, column, 0, contentWidth / 2);
- endColumn = this._getOverflowBound(row, column, columnCount - 1, contentWidth / 2);
- } else if (horizontalAlign === HorizontalAlign.RIGHT) {
- startColumn = this._getOverflowBound(row, column, 0, contentWidth);
- } else {
- endColumn = this._getOverflowBound(row, column, columnCount - 1, contentWidth);
- }
-
- return {
- startColumn,
- endColumn,
- };
- }
-
private _getOverflowBound(row: number, startColumn: number, endColumn: number, contentWidth: number) {
let cumWidth = 0;
if (startColumn > endColumn) {
@@ -989,8 +993,4 @@ export class SpreadsheetSkeleton extends Skeleton {
}
return cacheDataMerge;
}
-
- static create(config: IWorksheetConfig, cellData: ObjectMatrix<ICellData>, styles: Styles, context: SheetContext) {
- return new SpreadsheetSkeleton(config, cellData, styles, context);
- }
}
diff --git a/packages/base-render/src/Component/Sheets/Spreadsheet.ts b/packages/base-render/src/Component/Sheets/Spreadsheet.ts
index f61eb446b1..4ef8ad5122 100644
--- a/packages/base-render/src/Component/Sheets/Spreadsheet.ts
+++ b/packages/base-render/src/Component/Sheets/Spreadsheet.ts
@@ -91,10 +91,6 @@ export class Spreadsheet extends SheetComponent {
return this._documents;
}
- protected _draw(ctx: CanvasRenderingContext2D, bounds?: IBoundRect) {
- this.draw(ctx, bounds);
- }
-
draw(ctx: CanvasRenderingContext2D, bounds?: IBoundRect) {
// const { parent = { scaleX: 1, scaleY: 1 } } = this;
// const mergeData = this.getMergeData();
@@ -375,37 +371,55 @@ export class Spreadsheet extends SheetComponent {
this._hasSelection = false;
}
- private _getAncestorSize() {
- const parent = this._getAncestorParent();
- if (!parent) {
+ getDocsSkeletonPageSize(documentSkeleton: DocumentSkeleton, angle: number = 0) {
+ const skeletonData = documentSkeleton?.getSkeletonData();
+
+ if (!skeletonData) {
return;
}
+ const { pages } = skeletonData;
+ const lastPage = pages[pages.length - 1];
- if (parent.classType === RENDER_CLASS_TYPE.ENGINE) {
- const mainCanvas = (parent as Engine).getCanvas();
- return {
- width: mainCanvas.getWidth(),
- height: mainCanvas.getHeight(),
- };
- }
- if (parent.classType === RENDER_CLASS_TYPE.SCENE_VIEWER) {
- return {
- width: parent.width,
- height: parent.height,
- };
+ if (angle === 0) {
+ const { width, height } = lastPage;
+ return { width, height };
}
- }
- private _getAncestorParent(): Nullable<Engine | SceneViewer> {
- let parent: any = this.parent;
- while (parent) {
- if (parent.classType === RENDER_CLASS_TYPE.ENGINE || parent.classType === RENDER_CLASS_TYPE.SCENE_VIEWER) {
- return parent;
+ let allRotatedWidth = 0;
+ let allRotatedHeight = 0;
+
+ const orientation = getRotateOrientation(angle);
+ const widthArray: Array<{ rotatedWidth: number; spaceWidth: number }> = [];
+ columnIterator([lastPage], (column: IDocumentSkeletonColumn) => {
+ const { lines, width: columnWidth, spaceWidth } = column;
+
+ const { rotatedHeight, rotatedWidth } = getRotateOffsetAndFarthestHypotenuse(lines, columnWidth, angle);
+ allRotatedHeight += rotatedHeight;
+
+ widthArray.push({ rotatedWidth, spaceWidth });
+ });
+
+ const tanTheta = Math.tan(angle);
+ const sinTheta = Math.sin(angle);
+
+ const widthCount = widthArray.length;
+ for (let i = 0; i < widthCount; i++) {
+ const { rotatedWidth, spaceWidth } = widthArray[i];
+
+ if (i === 0) {
+ allRotatedWidth += rotatedWidth;
+ }
+
+ if ((orientation === ORIENTATION_TYPE.UP && i === 0) || (orientation === ORIENTATION_TYPE.DOWN && i === widthCount - 1)) {
+ allRotatedWidth += (rotatedWidth + spaceWidth / sinTheta) / tanTheta;
}
- parent = parent?.getParent && parent?.getParent();
}
- }
+ return {
+ width: allRotatedWidth,
+ height: allRotatedHeight,
+ };
+ }
// scaleCacheCanvas() {
// let scaleX = this.getParent()?.ancestorScaleX || 1;
// let scaleY = this.getParent()?.ancestorScaleX || 1;
@@ -438,6 +452,41 @@ export class Spreadsheet extends SheetComponent {
ctx.restore();
}
+ protected _draw(ctx: CanvasRenderingContext2D, bounds?: IBoundRect) {
+ this.draw(ctx, bounds);
+ }
+
+ private _getAncestorSize() {
+ const parent = this._getAncestorParent();
+ if (!parent) {
+ return;
+ }
+
+ if (parent.classType === RENDER_CLASS_TYPE.ENGINE) {
+ const mainCanvas = (parent as Engine).getCanvas();
+ return {
+ width: mainCanvas.getWidth(),
+ height: mainCanvas.getHeight(),
+ };
+ }
+ if (parent.classType === RENDER_CLASS_TYPE.SCENE_VIEWER) {
+ return {
+ width: parent.width,
+ height: parent.height,
+ };
+ }
+ }
+
+ private _getAncestorParent(): Nullable<Engine | SceneViewer> {
+ let parent: any = this.parent;
+ while (parent) {
+ if (parent.classType === RENDER_CLASS_TYPE.ENGINE || parent.classType === RENDER_CLASS_TYPE.SCENE_VIEWER) {
+ return parent;
+ }
+ parent = parent?.getParent && parent?.getParent();
+ }
+ }
+
private _initialDefaultExtension() {
SpreadsheetExtensionRegistry.getData()
.sort(sortRules)
@@ -517,56 +566,6 @@ export class Spreadsheet extends SheetComponent {
// return horizontalAlign;
// }
- getDocsSkeletonPageSize(documentSkeleton: DocumentSkeleton, angle: number = 0) {
- const skeletonData = documentSkeleton?.getSkeletonData();
-
- if (!skeletonData) {
- return;
- }
- const { pages } = skeletonData;
- const lastPage = pages[pages.length - 1];
-
- if (angle === 0) {
- const { width, height } = lastPage;
- return { width, height };
- }
-
- let allRotatedWidth = 0;
- let allRotatedHeight = 0;
-
- const orientation = getRotateOrientation(angle);
- const widthArray: Array<{ rotatedWidth: number; spaceWidth: number }> = [];
- columnIterator([lastPage], (column: IDocumentSkeletonColumn) => {
- const { lines, width: columnWidth, spaceWidth } = column;
-
- const { rotatedHeight, rotatedWidth } = getRotateOffsetAndFarthestHypotenuse(lines, columnWidth, angle);
- allRotatedHeight += rotatedHeight;
-
- widthArray.push({ rotatedWidth, spaceWidth });
- });
-
- const tanTheta = Math.tan(angle);
- const sinTheta = Math.sin(angle);
-
- const widthCount = widthArray.length;
- for (let i = 0; i < widthCount; i++) {
- const { rotatedWidth, spaceWidth } = widthArray[i];
-
- if (i === 0) {
- allRotatedWidth += rotatedWidth;
- }
-
- if ((orientation === ORIENTATION_TYPE.UP && i === 0) || (orientation === ORIENTATION_TYPE.DOWN && i === widthCount - 1)) {
- allRotatedWidth += (rotatedWidth + spaceWidth / sinTheta) / tanTheta;
- }
- }
-
- return {
- width: allRotatedWidth,
- height: allRotatedHeight,
- };
- }
-
private _calculateOverflow() {
const overflowCache = new ObjectMatrix<IRangeData>();
const spreadsheetSkeleton = this.getSkeleton();
diff --git a/packages/base-render/src/Component/Skeleton.ts b/packages/base-render/src/Component/Skeleton.ts
index f502aeef69..110e561f81 100644
--- a/packages/base-render/src/Component/Skeleton.ts
+++ b/packages/base-render/src/Component/Skeleton.ts
@@ -9,13 +9,25 @@ export class Skeleton {
private _dirty = true;
+ constructor(context: ContextBase) {
+ this._context = context;
+ this._localeInitial();
+ }
+
get dirty() {
return this._dirty;
}
- constructor(context: ContextBase) {
- this._context = context;
- this._localeInitial();
+ getFontLocale() {
+ return this._fontLocale;
+ }
+
+ getContext() {
+ return this._context;
+ }
+
+ makeDirty(state: boolean) {
+ this._dirty = state;
}
private _localeInitial() {
@@ -33,16 +45,4 @@ export class Skeleton {
}
this._fontLocale = renderFont as IFontLocale;
}
-
- getFontLocale() {
- return this._fontLocale;
- }
-
- getContext() {
- return this._context;
- }
-
- makeDirty(state: boolean) {
- this._dirty = state;
- }
}
diff --git a/packages/base-render/src/Component/Slides/Slide.ts b/packages/base-render/src/Component/Slides/Slide.ts
index 82f298855e..ed5387b6da 100644
--- a/packages/base-render/src/Component/Slides/Slide.ts
+++ b/packages/base-render/src/Component/Slides/Slide.ts
@@ -16,10 +16,10 @@ const arrowPath =
'M512 1024C229.248 1024 0 794.752 0 512S229.248 0 512 0s512 229.248 512 512-229.248 512-512 512z m200.746667-478.506667l1.749333-1.664 30.165333-30.165333-330.496-330.581333a42.837333 42.837333 0 0 0-60.288 0 42.538667 42.538667 0 0 0 0 60.330666l270.08 270.165334-270.08 269.952a42.496 42.496 0 0 0 0 60.288c16.64 16.64 43.861333 16.469333 60.288 0.042666l298.581334-298.368z';
export class Slide extends SceneViewer {
- private _navigationEnabled = false;
-
onSlideChangePageByNavigationObservable = new Observable<Nullable<string>>();
+ private _navigationEnabled = false;
+
activeFirstPage() {
const scenes = this.getSubScenes();
const firstKey = scenes.keys().next().value;
diff --git a/packages/base-render/src/Engine.ts b/packages/base-render/src/Engine.ts
index 00d6d8d6d3..42ef6856c2 100644
--- a/packages/base-render/src/Engine.ts
+++ b/packages/base-render/src/Engine.ts
@@ -13,6 +13,22 @@ import { Scene } from './Scene';
import { RENDER_CLASS_TYPE } from './Basics/Const';
export class Engine {
+ onInputChangedObservable = new Observable<IEvent>();
+
+ renderEvenInBackground = true;
+
+ /**
+ * Observable raised when the engine begins a new frame
+ */
+ onBeginFrameObservable = new Observable<Engine>();
+
+ /**
+ * Observable raised when the engine ends the current frame
+ */
+ onEndFrameObservable = new Observable<Engine>();
+
+ onTransformChangeObservable = new Observable<ITransformChangeState>();
+
private _container: HTMLElement;
private _canvas: Canvas = new Canvas();
@@ -27,10 +43,6 @@ export class Engine {
private _activeRenderLoops = new Array<() => void>();
- onInputChangedObservable = new Observable<IEvent>();
-
- renderEvenInBackground = true;
-
private _renderFunction: any;
private _requestNewFrameHandler: number;
@@ -56,17 +68,11 @@ export class Engine {
private _pointerWheelEvent: (evt: any) => void;
- /**
- * Observable raised when the engine begins a new frame
- */
- onBeginFrameObservable = new Observable<Engine>();
+ private __pointer: { [deviceSlot: number]: number } = {};
- /**
- * Observable raised when the engine ends the current frame
- */
- onEndFrameObservable = new Observable<Engine>();
+ private __mouseId = -1;
- onTransformChangeObservable = new Observable<ITransformChangeState>();
+ private __isUsingFirefox = navigator.userAgent.indexOf('Firefox') !== -1;
constructor(elemWidth: number = 100, elemHeight: number = 100) {
this._canvasEle = this._canvas.getCanvasEle();
@@ -87,6 +93,21 @@ export class Engine {
return RENDER_CLASS_TYPE.ENGINE;
}
+ get activeScene() {
+ return this._activeScene;
+ }
+
+ get requestNewFrameHandler() {
+ return this._requestNewFrameHandler;
+ }
+
+ /**
+ * Gets the current frame id
+ */
+ get frameId(): number {
+ return this._frameId;
+ }
+
getCanvas() {
return this._canvas;
}
@@ -125,10 +146,6 @@ export class Engine {
return this._activeScene != null;
}
- get activeScene() {
- return this._activeScene;
- }
-
setContainer(elem: HTMLElement) {
this._container = elem;
this._container.appendChild(this._canvasEle);
@@ -209,32 +226,6 @@ export class Engine {
}
}
- get requestNewFrameHandler() {
- return this._requestNewFrameHandler;
- }
-
- /** @hidden */
- private _renderLoop(): void {
- let shouldRender = true;
- if (!this.renderEvenInBackground) {
- shouldRender = false;
- }
-
- if (shouldRender) {
- // Start new frame
- this.beginFrame();
- this._renderFrame();
- // Present
- this.endFrame();
- }
-
- if (this._activeRenderLoops.length > 0) {
- this._requestNewFrameHandler = requestNewFrame(this._renderFunction);
- } else {
- this._renderingQueueLaunched = false;
- }
- }
-
/**
* Begin a new frame
*/
@@ -261,13 +252,6 @@ export class Engine {
return this._fps;
}
- /**
- * Gets the current frame id
- */
- get frameId(): number {
- return this._frameId;
- }
-
/**
* Gets the time spent between current and previous frame
* @returns a number representing the delta time in ms
@@ -276,12 +260,6 @@ export class Engine {
return this._deltaTime;
}
- private _measureFps(): void {
- this._performanceMonitor.sampleFrame();
- this._fps = this._performanceMonitor.averageFPS;
- this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
- }
-
_renderFrame() {
for (let index = 0; index < this._activeRenderLoops.length; index++) {
let renderFunction = this._activeRenderLoops[index];
@@ -290,6 +268,34 @@ export class Engine {
}
}
+ /** @hidden */
+ private _renderLoop(): void {
+ let shouldRender = true;
+ if (!this.renderEvenInBackground) {
+ shouldRender = false;
+ }
+
+ if (shouldRender) {
+ // Start new frame
+ this.beginFrame();
+ this._renderFrame();
+ // Present
+ this.endFrame();
+ }
+
+ if (this._activeRenderLoops.length > 0) {
+ this._requestNewFrameHandler = requestNewFrame(this._renderFunction);
+ } else {
+ this._renderingQueueLaunched = false;
+ }
+ }
+
+ private _measureFps(): void {
+ this._performanceMonitor.sampleFrame();
+ this._fps = this._performanceMonitor.averageFPS;
+ this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
+ }
+
private _handleKeyboardAction() {
const keyboardDownEvent = (evt: any) => {
let deviceEvent = evt as IKeyboardEvent;
@@ -315,12 +321,6 @@ export class Engine {
this._canvasEle.addEventListener('keyup', keyboardUpEvent);
}
- private __pointer: { [deviceSlot: number]: number } = {};
-
- private __mouseId = -1;
-
- private __isUsingFirefox = navigator.userAgent.indexOf('Firefox') !== -1;
-
private _handlePointerAction() {
const eventPrefix = getPointerPrefix();
diff --git a/packages/base-render/src/Group.ts b/packages/base-render/src/Group.ts
index a03720b212..310b7d27d9 100644
--- a/packages/base-render/src/Group.ts
+++ b/packages/base-render/src/Group.ts
@@ -13,14 +13,14 @@ export class Group extends BaseObject {
this.addObjects(...objects);
}
- set cursor(val: CURSOR_TYPE) {
- this.setCursor(val);
- }
-
get classType() {
return RENDER_CLASS_TYPE.GROUP;
}
+ set cursor(val: CURSOR_TYPE) {
+ this.setCursor(val);
+ }
+
addObjects(...objects: BaseObject[]) {
for (const object of objects) {
this.addObject(object);
@@ -122,10 +122,6 @@ export class Group extends BaseObject {
return this;
}
- private _transformBounds(bounds?: IBoundRect) {
- return bounds;
- }
-
// 判断自己scope下的所有对象是否有被选中的
isHit(coord: Vector2) {
return true;
@@ -140,4 +136,8 @@ export class Group extends BaseObject {
});
super.dispose();
}
+
+ private _transformBounds(bounds?: IBoundRect) {
+ return bounds;
+ }
}
diff --git a/packages/base-render/src/Layer.ts b/packages/base-render/src/Layer.ts
index 5e42f6370b..32d10b3c7a 100644
--- a/packages/base-render/src/Layer.ts
+++ b/packages/base-render/src/Layer.ts
@@ -11,10 +11,6 @@ export class Layer {
this.addObjects(objects);
}
- static create(scene: Scene, objects: BaseObject[] = [], zIndex: number = 1000) {
- return new this(scene, objects, zIndex);
- }
-
get scene() {
return this._scene;
}
@@ -23,6 +19,10 @@ export class Layer {
return this._zIndex;
}
+ static create(scene: Scene, objects: BaseObject[] = [], zIndex: number = 1000) {
+ return new this(scene, objects, zIndex);
+ }
+
getObjectsByOrder() {
const objects: BaseObject[] = [];
this._objects.sort(sortRules);
diff --git a/packages/base-render/src/Scene.Transformer.ts b/packages/base-render/src/Scene.Transformer.ts
index fa3cf1af58..80b3cf463d 100644
--- a/packages/base-render/src/Scene.Transformer.ts
+++ b/packages/base-render/src/Scene.Transformer.ts
@@ -161,6 +161,16 @@ export class Transformer implements ITransformerConfig {
shouldOverdrawWholeArea?: boolean;
+ onChangeStartObservable = new Observable<IChangeObserverConfig>();
+
+ onChangingObservable = new Observable<IChangeObserverConfig>();
+
+ onChangeEndObservable = new Observable<IChangeObserverConfig>();
+
+ onClearControlObservable = new Observable<null>();
+
+ onCreateControlObservable = new Observable<Group>();
+
private _startOffsetX: number;
private _startOffsetY: number;
@@ -179,18 +189,89 @@ export class Transformer implements ITransformerConfig {
private _selectedObjectMap = new Map<string, BaseObject>();
- onChangeStartObservable = new Observable<IChangeObserverConfig>();
+ constructor(private _scene: Scene, config?: ITransformerConfig) {
+ this._initialProps(config);
+ }
- onChangingObservable = new Observable<IChangeObserverConfig>();
+ getScene() {
+ return this._scene;
+ }
- onChangeEndObservable = new Observable<IChangeObserverConfig>();
+ attachTo(applyObject: BaseObject) {
+ if (!applyObject.isTransformer) {
+ return;
+ }
- onClearControlObservable = new Observable<null>();
+ if (this.hoverEnabled) {
+ this.hoverEnterFunc && applyObject.onPointerEnterObserver.add(this.hoverEnterFunc);
+ this.hoverLeaveFunc && applyObject.onPointerLeaveObserver.add(this.hoverLeaveFunc);
+ }
- onCreateControlObservable = new Observable<Group>();
+ applyObject.onPointerDownObserver.add((evt: IPointerEvent | IMouseEvent, state) => {
+ const { offsetX: evtOffsetX, offsetY: evtOffsetY } = evt;
+ this._startOffsetX = evtOffsetX;
+ this._startOffsetY = evtOffsetY;
- constructor(private _scene: Scene, config?: ITransformerConfig) {
- this._initialProps(config);
+ const scene = this._getTopScene();
+
+ if (!scene) {
+ return;
+ }
+
+ this._addCancelObserver(scene);
+
+ scene.disableEvent();
+
+ const scrollTimer = ScrollTimer.create(scene);
+ scrollTimer.startScroll(evtOffsetX, evtOffsetY);
+
+ const { scrollX, scrollY } = getCurrentScrollXY(scrollTimer);
+
+ this._viewportScrollX = scrollX;
+ this._viewportScrollY = scrollY;
+
+ this._updateActiveObjectList(applyObject, evt);
+
+ this._moveObserver = scene.onPointerMoveObserver.add((moveEvt: IPointerEvent | IMouseEvent) => {
+ const { offsetX: moveOffsetX, offsetY: moveOffsetY } = moveEvt;
+ this._moving(moveOffsetX, moveOffsetY, scrollTimer);
+ this._hiddenControl();
+ scrollTimer.scrolling(moveOffsetX, moveOffsetY, () => {
+ this._moving(moveOffsetX, moveOffsetY, scrollTimer);
+ });
+ });
+
+ this._upObserver = scene.onPointerUpObserver.add((upEvt: IPointerEvent | IMouseEvent) => {
+ scene.onPointerMoveObserver.remove(this._moveObserver);
+ scene.onPointerUpObserver.remove(this._upObserver);
+ scene.enableEvent();
+ this._updateControl();
+ scrollTimer.stopScroll();
+
+ this.onChangeEndObservable.notifyObservers({
+ objects: this._selectedObjectMap,
+ type: MoveObserverType.MOVE_END,
+ });
+ });
+
+ state.stopPropagation();
+ });
+
+ return applyObject;
+ }
+
+ dispose() {
+ this._moveObserver = null;
+ this._upObserver = null;
+ this._transformerControlMap.forEach((control) => {
+ control.dispose();
+ });
+ this._selectedObjectMap.forEach((control) => {
+ control.dispose();
+ });
+ this.onChangeStartObservable.clear();
+ this.onChangingObservable.clear();
+ this.onChangeEndObservable.clear();
}
private _initialProps(props?: ITransformerConfig) {
@@ -694,10 +775,6 @@ export class Transformer implements ITransformerConfig {
return transformerControl;
}
- getScene() {
- return this._scene;
- }
-
private _getTopScene() {
const currentScene = this.getScene();
return currentScene.getEngine()?.activeScene;
@@ -747,81 +824,4 @@ export class Transformer implements ITransformerConfig {
scene.onPointerDownObserver.remove(this._cancelFocusObserver);
});
}
-
- attachTo(applyObject: BaseObject) {
- if (!applyObject.isTransformer) {
- return;
- }
-
- if (this.hoverEnabled) {
- this.hoverEnterFunc && applyObject.onPointerEnterObserver.add(this.hoverEnterFunc);
- this.hoverLeaveFunc && applyObject.onPointerLeaveObserver.add(this.hoverLeaveFunc);
- }
-
- applyObject.onPointerDownObserver.add((evt: IPointerEvent | IMouseEvent, state) => {
- const { offsetX: evtOffsetX, offsetY: evtOffsetY } = evt;
- this._startOffsetX = evtOffsetX;
- this._startOffsetY = evtOffsetY;
-
- const scene = this._getTopScene();
-
- if (!scene) {
- return;
- }
-
- this._addCancelObserver(scene);
-
- scene.disableEvent();
-
- const scrollTimer = ScrollTimer.create(scene);
- scrollTimer.startScroll(evtOffsetX, evtOffsetY);
-
- const { scrollX, scrollY } = getCurrentScrollXY(scrollTimer);
-
- this._viewportScrollX = scrollX;
- this._viewportScrollY = scrollY;
-
- this._updateActiveObjectList(applyObject, evt);
-
- this._moveObserver = scene.onPointerMoveObserver.add((moveEvt: IPointerEvent | IMouseEvent) => {
- const { offsetX: moveOffsetX, offsetY: moveOffsetY } = moveEvt;
- this._moving(moveOffsetX, moveOffsetY, scrollTimer);
- this._hiddenControl();
- scrollTimer.scrolling(moveOffsetX, moveOffsetY, () => {
- this._moving(moveOffsetX, moveOffsetY, scrollTimer);
- });
- });
-
- this._upObserver = scene.onPointerUpObserver.add((upEvt: IPointerEvent | IMouseEvent) => {
- scene.onPointerMoveObserver.remove(this._moveObserver);
- scene.onPointerUpObserver.remove(this._upObserver);
- scene.enableEvent();
- this._updateControl();
- scrollTimer.stopScroll();
-
- this.onChangeEndObservable.notifyObservers({
- objects: this._selectedObjectMap,
- type: MoveObserverType.MOVE_END,
- });
- });
-
- state.stopPropagation();
- });
-
- return applyObject;
- }
-
- dispose() {
- this._moveObserver = null;
- this._upObserver = null;
- this._transformerControlMap.forEach((control) => {
- control.dispose();
- });
- this._selectedObjectMap.forEach((control) => {
- control.dispose();
- });
- this.onChangeStartObservable.clear();
- this.onChangingObservable.clear();
- this.onChangeEndObservable.clear();
- }
}
diff --git a/packages/base-render/src/Scene.inputManager.ts b/packages/base-render/src/Scene.inputManager.ts
index 3c6e068a9e..5a4479dd19 100644
--- a/packages/base-render/src/Scene.inputManager.ts
+++ b/packages/base-render/src/Scene.inputManager.ts
@@ -57,27 +57,6 @@ export class InputManager {
this._scene = scene;
}
- private _getCurrentObject(offsetX: number, offsetY: number) {
- return this._scene?.pick(Vector2.FromArray([offsetX, offsetY]));
- }
-
- private _checkDirectSceneEventTrigger(isTrigger: boolean, currentObject: Nullable<Scene | BaseObject>) {
- let notObject = false;
- if (currentObject == null) {
- notObject = true;
- }
-
- let isNotInSceneViewer = true;
- if (currentObject && currentObject.classType === RENDER_CLASS_TYPE.BASE_OBJECT) {
- const scene = (currentObject as BaseObject).getScene() as Scene;
- if (scene) {
- const parent = scene.getParent();
- isNotInSceneViewer = parent.classType !== RENDER_CLASS_TYPE.SCENE_VIEWER;
- }
- }
- return (!this._scene.evented && isTrigger && isNotInSceneViewer) || notObject;
- }
-
// 处理事件,比如mouseleave,mouseenter的触发。
mouseLeaveEnterHandler(o: Nullable<BaseObject | Scene>, evt: IMouseEvent) {
if (o === null || o === undefined) {
@@ -245,6 +224,27 @@ export class InputManager {
this._alreadyAttached = false;
}
+ private _getCurrentObject(offsetX: number, offsetY: number) {
+ return this._scene?.pick(Vector2.FromArray([offsetX, offsetY]));
+ }
+
+ private _checkDirectSceneEventTrigger(isTrigger: boolean, currentObject: Nullable<Scene | BaseObject>) {
+ let notObject = false;
+ if (currentObject == null) {
+ notObject = true;
+ }
+
+ let isNotInSceneViewer = true;
+ if (currentObject && currentObject.classType === RENDER_CLASS_TYPE.BASE_OBJECT) {
+ const scene = (currentObject as BaseObject).getScene() as Scene;
+ if (scene) {
+ const parent = scene.getParent();
+ isNotInSceneViewer = parent.classType !== RENDER_CLASS_TYPE.SCENE_VIEWER;
+ }
+ }
+ return (!this._scene.evented && isTrigger && isNotInSceneViewer) || notObject;
+ }
+
/**
* @hidden
* @returns Boolean if delta for pointer exceeds drag movement threshold
diff --git a/packages/base-render/src/Scene.ts b/packages/base-render/src/Scene.ts
index 86067db9e2..69709dc7c0 100644
--- a/packages/base-render/src/Scene.ts
+++ b/packages/base-render/src/Scene.ts
@@ -26,6 +26,32 @@ import { SceneViewer } from './SceneViewer';
import { Transformer, ITransformerConfig } from './Scene.Transformer';
export class Scene {
+ // onPointerMove: (evt: IPointerEvent | IMouseEvent) => void;
+
+ // onPointerDown: (evt: IPointerEvent | IMouseEvent) => void;
+
+ // onPointerUp: (evt: IPointerEvent | IMouseEvent) => void;
+
+ // onDblclick: (evt: IPointerEvent | IMouseEvent) => void;
+
+ // onMouseWheel: (evt: IWheelEvent) => void;
+
+ onPointerDownObserver = new Observable<IPointerEvent | IMouseEvent>();
+
+ onPointerMoveObserver = new Observable<IPointerEvent | IMouseEvent>();
+
+ onPointerUpObserver = new Observable<IPointerEvent | IMouseEvent>();
+
+ onDblclickObserver = new Observable<IPointerEvent | IMouseEvent>();
+
+ onMouseWheelObserver = new Observable<IWheelEvent>();
+
+ onKeyDownObservable = new Observable<IKeyboardEvent>();
+
+ onKeyUpObservable = new Observable<IKeyboardEvent>();
+
+ onTransformChangeObservable = new Observable<ITransformChangeState>();
+
// private _ObjectsForward = new Array<BaseObject>();
// private _ObjectsBack = new Array<BaseObject>();
@@ -95,70 +121,6 @@ export class Scene {
// }, 500);
}
- attachControl(hasDown: boolean = true, hasUp: boolean = true, hasMove: boolean = true, hasWheel: boolean = true) {
- if (!(this._parent.classType === RENDER_CLASS_TYPE.ENGINE)) {
- // 只绑定直接与engine挂载的scene来统一管理事件
- return;
- }
-
- this._inputManager?.attachControl(hasDown, hasUp, hasMove, hasWheel);
- return this;
- }
-
- detachControl() {
- this._inputManager?.detachControl();
- return this;
- }
-
- makeDirty(state: boolean = true) {
- this._viewports.forEach((vp) => {
- vp.makeDirty(state);
- });
- if (this._parent.classType === RENDER_CLASS_TYPE.SCENE_VIEWER) {
- (this._parent as SceneViewer)?.makeDirty(state);
- }
- return this;
- }
-
- makeDirtyNoParent(state: boolean = true) {
- this._viewports.forEach((vp) => {
- vp.makeDirty(state);
- });
- return this;
- }
-
- isDirty(): boolean {
- for (let i = 0; i < this._viewports.length; i++) {
- const vp = this._viewports[i];
- if (vp.isDirty() === true) {
- return true;
- }
- }
- return false;
- }
-
- get cursor() {
- return this._cursor;
- }
-
- set cursor(val: CURSOR_TYPE) {
- this.setCursor(val);
- }
-
- resetCursor() {
- this.setCursor(CURSOR_TYPE.DEFAULT);
- }
-
- setCursor(val: CURSOR_TYPE) {
- this._cursor = val;
- const engine = this.getEngine();
- if (!engine) {
- return;
- }
- const canvasEl = engine.getCanvas().getCanvasEle();
- canvasEl.style.cursor = val;
- }
-
get classType() {
return RENDER_CLASS_TYPE.SCENE;
}
@@ -167,10 +129,6 @@ export class Scene {
return this._transform;
}
- set transform(trans: Transform) {
- this._transform = trans;
- }
-
get width() {
return this._width;
}
@@ -205,6 +163,26 @@ export class Scene {
return this._scaleY * pScale;
}
+ get cursor() {
+ return this._cursor;
+ }
+
+ get sceneKey() {
+ return this._sceneKey;
+ }
+
+ get evented() {
+ return this._evented;
+ }
+
+ set transform(trans: Transform) {
+ this._transform = trans;
+ }
+
+ set cursor(val: CURSOR_TYPE) {
+ this.setCursor(val);
+ }
+
private set width(num: number) {
this._width = num;
}
@@ -221,6 +199,62 @@ export class Scene {
this._scaleY = scaleY;
}
+ attachControl(hasDown: boolean = true, hasUp: boolean = true, hasMove: boolean = true, hasWheel: boolean = true) {
+ if (!(this._parent.classType === RENDER_CLASS_TYPE.ENGINE)) {
+ // 只绑定直接与engine挂载的scene来统一管理事件
+ return;
+ }
+
+ this._inputManager?.attachControl(hasDown, hasUp, hasMove, hasWheel);
+ return this;
+ }
+
+ detachControl() {
+ this._inputManager?.detachControl();
+ return this;
+ }
+
+ makeDirty(state: boolean = true) {
+ this._viewports.forEach((vp) => {
+ vp.makeDirty(state);
+ });
+ if (this._parent.classType === RENDER_CLASS_TYPE.SCENE_VIEWER) {
+ (this._parent as SceneViewer)?.makeDirty(state);
+ }
+ return this;
+ }
+
+ makeDirtyNoParent(state: boolean = true) {
+ this._viewports.forEach((vp) => {
+ vp.makeDirty(state);
+ });
+ return this;
+ }
+
+ isDirty(): boolean {
+ for (let i = 0; i < this._viewports.length; i++) {
+ const vp = this._viewports[i];
+ if (vp.isDirty() === true) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ resetCursor() {
+ this.setCursor(CURSOR_TYPE.DEFAULT);
+ }
+
+ setCursor(val: CURSOR_TYPE) {
+ this._cursor = val;
+ const engine = this.getEngine();
+ if (!engine) {
+ return;
+ }
+ const canvasEl = engine.getCanvas().getCanvasEle();
+ canvasEl.style.cursor = val;
+ }
+
resize(width?: number, height?: number) {
const preWidth = this.width;
if (width !== undefined) {
@@ -346,12 +380,6 @@ export class Scene {
return this._createDefaultLayer(zIndex);
}
- private _createDefaultLayer(zIndex: number = 1) {
- const defaultLayer = Layer.create(this, [], zIndex);
- this.addLayer(defaultLayer);
- return defaultLayer;
- }
-
getLayerMaxZIndex(): number {
let maxIndex = Number.MIN_VALUE;
for (let i = 0; i < this._layers.length; i++) {
@@ -518,17 +546,6 @@ export class Scene {
changeObjectOrder() {}
- get sceneKey() {
- return this._sceneKey;
- }
-
- async requestRender(parentCtx?: CanvasRenderingContext2D) {
- return new Promise((resolve, reject) => {
- this.render(parentCtx);
- requestNewFrame(resolve);
- });
- }
-
renderObjects(ctx: CanvasRenderingContext2D, bounds?: IBoundRect) {
this.getAllObjectsByOrder().forEach((o) => {
o.render(ctx, bounds);
@@ -544,25 +561,6 @@ export class Scene {
this.getViewports()?.forEach((vp: Viewport) => vp.render(parentCtx));
}
- private _resetViewportSize() {
- this.getViewports().forEach((vp: Viewport) => {
- vp.resetSize();
- });
- }
-
- private _setTransForm() {
- const composeResult = Transform.create().composeMatrix({
- scaleX: this.scaleX,
- scaleY: this.scaleY,
- });
-
- this.transform = composeResult;
- this.getViewports().forEach((vp: Viewport) => {
- vp.resizeScrollBar();
- });
- this.makeDirty(true);
- }
-
enableEvent() {
this._evented = true;
}
@@ -571,8 +569,11 @@ export class Scene {
this._evented = false;
}
- get evented() {
- return this._evented;
+ async requestRender(parentCtx?: CanvasRenderingContext2D) {
+ return new Promise((resolve, reject) => {
+ this.render(parentCtx);
+ requestNewFrame(resolve);
+ });
}
openTransformer(config?: ITransformerConfig) {
@@ -749,44 +750,6 @@ export class Scene {
return isPickedObject;
}
- private _getGroupCumLeftRight(object: BaseObject) {
- let parent: any = object.parent;
- let cumLeft = 0;
- let cumTop = 0;
- while (parent.classType === RENDER_CLASS_TYPE.GROUP) {
- const { left, top } = parent;
- cumLeft += left;
- cumTop += top;
-
- parent = parent.parent;
- }
- return { cumLeft, cumTop };
- }
-
- // onPointerMove: (evt: IPointerEvent | IMouseEvent) => void;
-
- // onPointerDown: (evt: IPointerEvent | IMouseEvent) => void;
-
- // onPointerUp: (evt: IPointerEvent | IMouseEvent) => void;
-
- // onDblclick: (evt: IPointerEvent | IMouseEvent) => void;
-
- // onMouseWheel: (evt: IWheelEvent) => void;
-
- onPointerDownObserver = new Observable<IPointerEvent | IMouseEvent>();
-
- onPointerMoveObserver = new Observable<IPointerEvent | IMouseEvent>();
-
- onPointerUpObserver = new Observable<IPointerEvent | IMouseEvent>();
-
- onDblclickObserver = new Observable<IPointerEvent | IMouseEvent>();
-
- onMouseWheelObserver = new Observable<IWheelEvent>();
-
- onKeyDownObservable = new Observable<IKeyboardEvent>();
-
- onKeyUpObservable = new Observable<IKeyboardEvent>();
-
on(eventType: EVENT_TYPE, func: (evt: unknown, state: EventState) => void) {
const observable = this[`on${eventType}Observer`] as Observable<unknown>;
const observer = observable.add(func.bind(this));
@@ -894,5 +857,42 @@ export class Scene {
return true;
}
- onTransformChangeObservable = new Observable<ITransformChangeState>();
+ private _createDefaultLayer(zIndex: number = 1) {
+ const defaultLayer = Layer.create(this, [], zIndex);
+ this.addLayer(defaultLayer);
+ return defaultLayer;
+ }
+
+ private _resetViewportSize() {
+ this.getViewports().forEach((vp: Viewport) => {
+ vp.resetSize();
+ });
+ }
+
+ private _setTransForm() {
+ const composeResult = Transform.create().composeMatrix({
+ scaleX: this.scaleX,
+ scaleY: this.scaleY,
+ });
+
+ this.transform = composeResult;
+ this.getViewports().forEach((vp: Viewport) => {
+ vp.resizeScrollBar();
+ });
+ this.makeDirty(true);
+ }
+
+ private _getGroupCumLeftRight(object: BaseObject) {
+ let parent: any = object.parent;
+ let cumLeft = 0;
+ let cumTop = 0;
+ while (parent.classType === RENDER_CLASS_TYPE.GROUP) {
+ const { left, top } = parent;
+ cumLeft += left;
+ cumTop += top;
+
+ parent = parent.parent;
+ }
+ return { cumLeft, cumTop };
+ }
}
diff --git a/packages/base-render/src/SceneViewer.ts b/packages/base-render/src/SceneViewer.ts
index 6dab939339..0cad116510 100644
--- a/packages/base-render/src/SceneViewer.ts
+++ b/packages/base-render/src/SceneViewer.ts
@@ -113,6 +113,14 @@ export class SceneViewer extends BaseObject {
return this._activeSubScene?.pick(tCoord);
}
+ dispose() {
+ super.dispose();
+
+ this._subScenes.forEach((scene) => {
+ scene.dispose();
+ });
+ }
+
private _initialProps(props?: IObjectFullState) {
if (!props) {
return;
@@ -140,12 +148,4 @@ export class SceneViewer extends BaseObject {
this.makeDirty(true);
}
-
- dispose() {
- super.dispose();
-
- this._subScenes.forEach((scene) => {
- scene.dispose();
- });
- }
}
diff --git a/packages/base-render/src/ScrollTimer.ts b/packages/base-render/src/ScrollTimer.ts
index 23f12758b0..94f42ec786 100644
--- a/packages/base-render/src/ScrollTimer.ts
+++ b/packages/base-render/src/ScrollTimer.ts
@@ -30,6 +30,10 @@ export class ScrollTimer {
}
}
+ static create(scene: Scene, padding?: IPaddingData) {
+ return new ScrollTimer(scene, padding);
+ }
+
startScroll(offsetX: number, offsetY: number) {
this._offsetX = offsetX;
this._offsetY = offsetY;
@@ -97,6 +101,16 @@ export class ScrollTimer {
cancelRequestFrame(this._requestNewFrameNumber);
}
+ getViewportByCoord(scene?: Scene) {
+ // return scene?.getActiveViewportByCoord(Vector2.FromArray([this._offsetX, this._offsetY]));
+
+ return scene?.getActiveViewportByRelativeCoord(Vector2.FromArray([this._offsetX, this._offsetY]));
+ }
+
+ getScene() {
+ return this._scene;
+ }
+
private _runRenderLoop() {
this._scroll(this._viewport);
this._scrollFunction && this._scrollFunction(this._scrollX, this._scrollY);
@@ -112,18 +126,4 @@ export class ScrollTimer {
parent = parent?.getParent && parent?.getParent();
}
}
-
- getViewportByCoord(scene?: Scene) {
- // return scene?.getActiveViewportByCoord(Vector2.FromArray([this._offsetX, this._offsetY]));
-
- return scene?.getActiveViewportByRelativeCoord(Vector2.FromArray([this._offsetX, this._offsetY]));
- }
-
- getScene() {
- return this._scene;
- }
-
- static create(scene: Scene, padding?: IPaddingData) {
- return new ScrollTimer(scene, padding);
- }
}
diff --git a/packages/base-render/src/Shape/Circle.ts b/packages/base-render/src/Shape/Circle.ts
index 60f09d3407..00b7a0a5ab 100644
--- a/packages/base-render/src/Shape/Circle.ts
+++ b/packages/base-render/src/Shape/Circle.ts
@@ -13,10 +13,6 @@ export const CIRCLE_OBJECT_ARRAY = ['radius'];
export class Circle extends Shape<ICircleProps> {
private _radius: number;
- get radius() {
- return this._radius;
- }
-
constructor(key?: string, props?: ICircleProps) {
super(key, props);
this._radius = props?.radius || 10;
@@ -35,15 +31,8 @@ export class Circle extends Shape<ICircleProps> {
});
}
- private _setFixBoundingBox() {
- this.transformByState({
- width: this._radius * 2,
- height: this._radius * 2,
- });
- }
-
- protected _draw(ctx: CanvasRenderingContext2D) {
- Circle.drawWith(ctx, this);
+ get radius() {
+ return this._radius;
}
static drawWith(ctx: CanvasRenderingContext2D, props: ICircleProps | Circle) {
@@ -76,4 +65,15 @@ export class Circle extends Shape<ICircleProps> {
...props,
};
}
+
+ protected _draw(ctx: CanvasRenderingContext2D) {
+ Circle.drawWith(ctx, this);
+ }
+
+ private _setFixBoundingBox() {
+ this.transformByState({
+ width: this._radius * 2,
+ height: this._radius * 2,
+ });
+ }
}
diff --git a/packages/base-render/src/Shape/Path.ts b/packages/base-render/src/Shape/Path.ts
index 66bd320761..8756bb02f1 100644
--- a/packages/base-render/src/Shape/Path.ts
+++ b/packages/base-render/src/Shape/Path.ts
@@ -37,10 +37,6 @@ export class Path extends Shape<IPathProps> {
private _reCalculateCache: boolean = true;
- get dataArray() {
- return this._dataArray;
- }
-
constructor(key?: string, props?: IPathProps) {
super(key, props);
if (props?.data) {
@@ -109,8 +105,8 @@ export class Path extends Shape<IPathProps> {
});
}
- protected _draw(ctx: CanvasRenderingContext2D) {
- Path.drawWith(ctx, this);
+ get dataArray() {
+ return this._dataArray;
}
static drawWith(ctx: CanvasRenderingContext2D, props: IPathProps | Path) {
@@ -171,223 +167,6 @@ export class Path extends Shape<IPathProps> {
this._renderPaintInOrder(ctx, props);
}
- private _setFixBoundingBox() {
- const { left, top, width, height } = this._getSelfRect();
-
- // this.left = (this.left as number) - left;
- // this.top = (this.top as number) - top;
- const fixScaleX = (this.width as number) / width;
- const fixScaleY = (this.height as number) / height;
-
- this.left = (this.left as number) - left * fixScaleX;
- this.top = (this.top as number) - top * fixScaleY;
- this.scaleX = fixScaleX;
- this.scaleY = fixScaleY;
- this.width = width;
- this.height = height;
-
- this._setTransForm();
- }
-
- toJson() {
- const props: IKeyValue = {};
- PATH_OBJECT_ARRAY.forEach((key) => {
- if (this[key]) {
- props[key] = this[key];
- }
- });
- return {
- ...super.toJson(),
- ...props,
- };
- }
-
- getState() {
- const { left, top, width, height } = this.getRect();
- return {
- left,
- top,
- width,
- height,
- scaleX: this.scaleX,
- scaleY: this.scaleY,
- angle: this.angle,
- skewX: this.skewX,
- skewY: this.skewY,
- flipX: this.flipX,
- flipY: this.flipY,
- };
- }
-
- getRect() {
- const { left, top, width, height } = this._getSelfRect();
- return {
- left: left * this.scaleX + this.left,
- top: top * this.scaleY + this.top,
- width: width * this.scaleX,
- height: height * this.scaleY,
- };
- }
-
- private _getSelfRect() {
- if (!this._reCalculateCache) {
- return this._selfRectCache;
- }
- let points: number[] = [];
- this.dataArray.forEach((data) => {
- if (data.command === 'A') {
- // Approximates by breaking curve into line segments
- let start = data.points[4];
- // 4 = theta
- let dTheta = data.points[5];
- // 5 = dTheta
- let end = data.points[4] + dTheta;
- let inc = Math.PI / 180.0;
- // 1 degree resolution
- if (Math.abs(start - end) < inc) {
- inc = Math.abs(start - end);
- }
- if (dTheta < 0) {
- // clockwise
- for (let t = start - inc; t > end; t -= inc) {
- const point = Path.getPointOnEllipticalArc(data.points[0], data.points[1], data.points[2], data.points[3], t, 0);
- points.push(point.x, point.y);
- }
- } else {
- // counter-clockwise
- for (let t = start + inc; t < end; t += inc) {
- const point = Path.getPointOnEllipticalArc(data.points[0], data.points[1], data.points[2], data.points[3], t, 0);
- points.push(point.x, point.y);
- }
- }
- } else if (data.command === 'C') {
- // Approximates by breaking curve into 100 line segments
- for (let t = 0.0; t <= 1; t += 0.01) {
- const point = Path.getPointOnCubicBezier(
- t,
- data.start.x,
- data.start.y,
- data.points[0],
- data.points[1],
- data.points[2],
- data.points[3],
- data.points[4],
- data.points[5]
- );
- points.push(point.x, point.y);
- }
- } else {
- // TODO: how can we calculate bezier curves better?
- points = points.concat(data.points);
- }
- });
- let minX = points[0];
- let maxX = points[0];
- let minY = points[1];
- let maxY = points[1];
- let x;
- let y;
- for (let i = 0; i < points.length / 2; i++) {
- x = points[i * 2];
- y = points[i * 2 + 1];
-
- // skip bad values
- if (!isNaN(x)) {
- minX = Math.min(minX, x);
- maxX = Math.max(maxX, x);
- }
- if (!isNaN(y)) {
- minY = Math.min(minY, y);
- maxY = Math.max(maxY, y);
- }
- }
-
- const cache = {
- left: minX,
- top: minY,
- width: maxX - minX,
- height: maxY - minY,
- };
-
- this._selfRectCache = cache;
-
- return cache;
- }
-
- /**
- * Return length of the path.
- * @method
- * @returns {Number} length
- * @example
- * var length = path.getLength();
- */
- getLength() {
- return this.pathLength;
- }
-
- /**
- * Get point on path at specific length of the path
- * @method
- * @param {Number} length length
- * @returns {Object} point {x,y} point
- * @example
- * var point = path.getPointAtLength(10);
- */
- getPointAtLength(length: number) {
- let point;
- let i = 0;
- let ii = this.dataArray.length;
-
- if (!ii) {
- return null;
- }
-
- while (i < ii && length > this.dataArray[i].pathLength) {
- length -= this.dataArray[i].pathLength;
- ++i;
- }
-
- if (i === ii) {
- point = this.dataArray[i - 1].points.slice(-2);
- return {
- x: point[0],
- y: point[1],
- };
- }
-
- if (length < 0.01) {
- point = this.dataArray[i].points.slice(0, 2);
- return {
- x: point[0],
- y: point[1],
- };
- }
-
- let cp = this.dataArray[i];
- let p = cp.points;
- switch (cp.command) {
- case 'L':
- return Path.getPointOnLine(length, cp.start.x, cp.start.y, p[0], p[1]);
- case 'C':
- return Path.getPointOnCubicBezier(length / cp.pathLength, cp.start.x, cp.start.y, p[0], p[1], p[2], p[3], p[4], p[5]);
- case 'Q':
- return Path.getPointOnQuadraticBezier(length / cp.pathLength, cp.start.x, cp.start.y, p[0], p[1], p[2], p[3]);
- case 'A': {
- let cx = p[0];
- let cy = p[1];
- let rx = p[2];
- let ry = p[3];
- let theta = p[4];
- let dTheta = p[5];
- let psi = p[6];
- theta += (dTheta * length) / cp.pathLength;
- return Path.getPointOnEllipticalArc(cx, cy, rx, ry, theta, psi);
- }
- }
-
- return null;
- }
-
static getLineLength(x1: number, y1: number, x2: number, y2: number) {
return Math.sqrt((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1));
}
@@ -932,4 +711,225 @@ export class Path extends Shape<IPathProps> {
}
return [cx, cy, rx, ry, theta, dTheta, psi, fs];
}
+
+ toJson() {
+ const props: IKeyValue = {};
+ PATH_OBJECT_ARRAY.forEach((key) => {
+ if (this[key]) {
+ props[key] = this[key];
+ }
+ });
+ return {
+ ...super.toJson(),
+ ...props,
+ };
+ }
+
+ getState() {
+ const { left, top, width, height } = this.getRect();
+ return {
+ left,
+ top,
+ width,
+ height,
+ scaleX: this.scaleX,
+ scaleY: this.scaleY,
+ angle: this.angle,
+ skewX: this.skewX,
+ skewY: this.skewY,
+ flipX: this.flipX,
+ flipY: this.flipY,
+ };
+ }
+
+ getRect() {
+ const { left, top, width, height } = this._getSelfRect();
+ return {
+ left: left * this.scaleX + this.left,
+ top: top * this.scaleY + this.top,
+ width: width * this.scaleX,
+ height: height * this.scaleY,
+ };
+ }
+
+ /**
+ * Return length of the path.
+ * @method
+ * @returns {Number} length
+ * @example
+ * var length = path.getLength();
+ */
+ getLength() {
+ return this.pathLength;
+ }
+
+ /**
+ * Get point on path at specific length of the path
+ * @method
+ * @param {Number} length length
+ * @returns {Object} point {x,y} point
+ * @example
+ * var point = path.getPointAtLength(10);
+ */
+ getPointAtLength(length: number) {
+ let point;
+ let i = 0;
+ let ii = this.dataArray.length;
+
+ if (!ii) {
+ return null;
+ }
+
+ while (i < ii && length > this.dataArray[i].pathLength) {
+ length -= this.dataArray[i].pathLength;
+ ++i;
+ }
+
+ if (i === ii) {
+ point = this.dataArray[i - 1].points.slice(-2);
+ return {
+ x: point[0],
+ y: point[1],
+ };
+ }
+
+ if (length < 0.01) {
+ point = this.dataArray[i].points.slice(0, 2);
+ return {
+ x: point[0],
+ y: point[1],
+ };
+ }
+
+ let cp = this.dataArray[i];
+ let p = cp.points;
+ switch (cp.command) {
+ case 'L':
+ return Path.getPointOnLine(length, cp.start.x, cp.start.y, p[0], p[1]);
+ case 'C':
+ return Path.getPointOnCubicBezier(length / cp.pathLength, cp.start.x, cp.start.y, p[0], p[1], p[2], p[3], p[4], p[5]);
+ case 'Q':
+ return Path.getPointOnQuadraticBezier(length / cp.pathLength, cp.start.x, cp.start.y, p[0], p[1], p[2], p[3]);
+ case 'A': {
+ let cx = p[0];
+ let cy = p[1];
+ let rx = p[2];
+ let ry = p[3];
+ let theta = p[4];
+ let dTheta = p[5];
+ let psi = p[6];
+ theta += (dTheta * length) / cp.pathLength;
+ return Path.getPointOnEllipticalArc(cx, cy, rx, ry, theta, psi);
+ }
+ }
+
+ return null;
+ }
+
+ protected _draw(ctx: CanvasRenderingContext2D) {
+ Path.drawWith(ctx, this);
+ }
+
+ private _setFixBoundingBox() {
+ const { left, top, width, height } = this._getSelfRect();
+
+ // this.left = (this.left as number) - left;
+ // this.top = (this.top as number) - top;
+ const fixScaleX = (this.width as number) / width;
+ const fixScaleY = (this.height as number) / height;
+
+ this.left = (this.left as number) - left * fixScaleX;
+ this.top = (this.top as number) - top * fixScaleY;
+ this.scaleX = fixScaleX;
+ this.scaleY = fixScaleY;
+ this.width = width;
+ this.height = height;
+
+ this._setTransForm();
+ }
+
+ private _getSelfRect() {
+ if (!this._reCalculateCache) {
+ return this._selfRectCache;
+ }
+ let points: number[] = [];
+ this.dataArray.forEach((data) => {
+ if (data.command === 'A') {
+ // Approximates by breaking curve into line segments
+ let start = data.points[4];
+ // 4 = theta
+ let dTheta = data.points[5];
+ // 5 = dTheta
+ let end = data.points[4] + dTheta;
+ let inc = Math.PI / 180.0;
+ // 1 degree resolution
+ if (Math.abs(start - end) < inc) {
+ inc = Math.abs(start - end);
+ }
+ if (dTheta < 0) {
+ // clockwise
+ for (let t = start - inc; t > end; t -= inc) {
+ const point = Path.getPointOnEllipticalArc(data.points[0], data.points[1], data.points[2], data.points[3], t, 0);
+ points.push(point.x, point.y);
+ }
+ } else {
+ // counter-clockwise
+ for (let t = start + inc; t < end; t += inc) {
+ const point = Path.getPointOnEllipticalArc(data.points[0], data.points[1], data.points[2], data.points[3], t, 0);
+ points.push(point.x, point.y);
+ }
+ }
+ } else if (data.command === 'C') {
+ // Approximates by breaking curve into 100 line segments
+ for (let t = 0.0; t <= 1; t += 0.01) {
+ const point = Path.getPointOnCubicBezier(
+ t,
+ data.start.x,
+ data.start.y,
+ data.points[0],
+ data.points[1],
+ data.points[2],
+ data.points[3],
+ data.points[4],
+ data.points[5]
+ );
+ points.push(point.x, point.y);
+ }
+ } else {
+ // TODO: how can we calculate bezier curves better?
+ points = points.concat(data.points);
+ }
+ });
+ let minX = points[0];
+ let maxX = points[0];
+ let minY = points[1];
+ let maxY = points[1];
+ let x;
+ let y;
+ for (let i = 0; i < points.length / 2; i++) {
+ x = points[i * 2];
+ y = points[i * 2 + 1];
+
+ // skip bad values
+ if (!isNaN(x)) {
+ minX = Math.min(minX, x);
+ maxX = Math.max(maxX, x);
+ }
+ if (!isNaN(y)) {
+ minY = Math.min(minY, y);
+ maxY = Math.max(maxY, y);
+ }
+ }
+
+ const cache = {
+ left: minX,
+ top: minY,
+ width: maxX - minX,
+ height: maxY - minY,
+ };
+
+ this._selfRectCache = cache;
+
+ return cache;
+ }
}
diff --git a/packages/base-render/src/Shape/Picture.ts b/packages/base-render/src/Shape/Picture.ts
index 73a6948b5e..39d5f474cd 100644
--- a/packages/base-render/src/Shape/Picture.ts
+++ b/packages/base-render/src/Shape/Picture.ts
@@ -10,38 +10,10 @@ export interface IPictureProps extends IShapeProps {
}
export class Picture extends Shape<IPictureProps> {
- static drawWith(ctx: CanvasRenderingContext2D, picture: Picture) {
- if (picture._native.complete) {
- const { width, height } = picture;
- try {
- ctx.drawImage(picture._native, 0, 0, width, height);
- } catch (error) {
- console.error(error);
- }
- }
- }
-
- static create(id: string, url: string, callback?: () => void): Picture {
- return new Picture(id, { url, success: callback });
- }
-
protected _props: IPictureProps;
protected _native: HTMLImageElement;
- protected _draw(ctx: CanvasRenderingContext2D) {
- Picture.drawWith(ctx, this);
- }
-
- protected _init(): void {
- if (this._props.autoWidth) {
- this.resize(this._native.width);
- }
- if (this._props.autoHeight) {
- this.resize(undefined, this._native.height);
- }
- }
-
constructor(id: string, config: IPictureProps) {
super(id, config);
this._props = {
@@ -72,4 +44,32 @@ export class Picture extends Shape<IPictureProps> {
};
}
}
+
+ static drawWith(ctx: CanvasRenderingContext2D, picture: Picture) {
+ if (picture._native.complete) {
+ const { width, height } = picture;
+ try {
+ ctx.drawImage(picture._native, 0, 0, width, height);
+ } catch (error) {
+ console.error(error);
+ }
+ }
+ }
+
+ static create(id: string, url: string, callback?: () => void): Picture {
+ return new Picture(id, { url, success: callback });
+ }
+
+ protected _draw(ctx: CanvasRenderingContext2D) {
+ Picture.drawWith(ctx, this);
+ }
+
+ protected _init(): void {
+ if (this._props.autoWidth) {
+ this.resize(this._native.width);
+ }
+ if (this._props.autoHeight) {
+ this.resize(undefined, this._native.height);
+ }
+ }
}
diff --git a/packages/base-render/src/Shape/Rect.ts b/packages/base-render/src/Shape/Rect.ts
index 2873a209f2..ffc44e4a98 100644
--- a/packages/base-render/src/Shape/Rect.ts
+++ b/packages/base-render/src/Shape/Rect.ts
@@ -12,10 +12,6 @@ export const RECT_OBJECT_ARRAY = ['radius'];
export class Rect extends Shape<IRectProps> {
private _radius: number;
- get radius() {
- return this._radius;
- }
-
constructor(key?: string, props?: IRectProps) {
super(key, props);
if (props?.radius) {
@@ -23,8 +19,8 @@ export class Rect extends Shape<IRectProps> {
}
}
- protected _draw(ctx: CanvasRenderingContext2D) {
- Rect.drawWith(ctx, this);
+ get radius() {
+ return this._radius;
}
static drawWith(ctx: CanvasRenderingContext2D, props: IRectProps | Rect) {
@@ -76,4 +72,8 @@ export class Rect extends Shape<IRectProps> {
...props,
};
}
+
+ protected _draw(ctx: CanvasRenderingContext2D) {
+ Rect.drawWith(ctx, this);
+ }
}
diff --git a/packages/base-render/src/Shape/RegularPolygon.ts b/packages/base-render/src/Shape/RegularPolygon.ts
index 26f30c498d..154c58fb30 100644
--- a/packages/base-render/src/Shape/RegularPolygon.ts
+++ b/packages/base-render/src/Shape/RegularPolygon.ts
@@ -14,10 +14,6 @@ export const REGULAR_POLYGON_OBJECT_ARRAY = ['pointsGroup'];
export class RegularPolygon extends Shape<IRegularPolygonProps> {
private _pointsGroup: IPoint[][];
- get pointsGroup() {
- return this._pointsGroup;
- }
-
constructor(key?: string, props?: IRegularPolygonProps) {
super(key, props);
this._pointsGroup = props?.pointsGroup || [[]];
@@ -30,8 +26,8 @@ export class RegularPolygon extends Shape<IRegularPolygonProps> {
});
}
- protected _draw(ctx: CanvasRenderingContext2D) {
- RegularPolygon.drawWith(ctx, this);
+ get pointsGroup() {
+ return this._pointsGroup;
}
static drawWith(ctx: CanvasRenderingContext2D, props: IRegularPolygonProps | RegularPolygon) {
@@ -133,6 +129,10 @@ export class RegularPolygon extends Shape<IRegularPolygonProps> {
};
}
+ protected _draw(ctx: CanvasRenderingContext2D) {
+ RegularPolygon.drawWith(ctx, this);
+ }
+
private _setFixBoundingBox() {
const { width, height, left, top } = this._getSelfRect();
this.left = (this.left as number) + left;
diff --git a/packages/base-render/src/Shape/RichText.ts b/packages/base-render/src/Shape/RichText.ts
index bdb43fbaf8..b4081bf388 100644
--- a/packages/base-render/src/Shape/RichText.ts
+++ b/packages/base-render/src/Shape/RichText.ts
@@ -65,10 +65,6 @@ export class RichText extends BaseObject {
private _cl?: IColorStyle;
- get documentData() {
- return this._documentData;
- }
-
constructor(context: ContextBase, key?: string, props?: IRichTextProps) {
super(key);
if (props?.richText) {
@@ -119,6 +115,10 @@ export class RichText extends BaseObject {
});
}
+ get documentData() {
+ return this._documentData;
+ }
+
getDocsSkeletonPageSize() {
const skeletonData = this._documentSkeleton?.getSkeletonData();
@@ -132,6 +132,86 @@ export class RichText extends BaseObject {
return { width, height };
}
+ setProps(props?: IRichTextProps) {
+ if (!props) {
+ return;
+ }
+
+ const themeKeys = Object.keys(props);
+ if (themeKeys.length === 0) {
+ return;
+ }
+ themeKeys.forEach((key) => {
+ if (props[key] === undefined) {
+ return true;
+ }
+
+ if (RICHTEXT_OBJECT_ARRAY.indexOf(key) === -1) {
+ this[`_${key}`] = props[key];
+ }
+ });
+ this.makeDirty(true);
+ return this;
+ }
+
+ render(mainCtx: CanvasRenderingContext2D, bounds?: IBoundRect) {
+ if (!this.visible) {
+ this.makeDirty(false);
+ return this;
+ }
+
+ // Temporarily ignore the on-demand display of elements within a group:this.isInGroup
+ if (this.isRender()) {
+ const { minX, maxX, minY, maxY } = transformBoundingCoord(this, bounds!);
+
+ if (this.width + this.strokeWidth < minX || maxX < 0 || this.height + this.strokeWidth < minY || maxY < 0) {
+ // console.warn('ignore object', this);
+ return this;
+ }
+ }
+
+ const m = this.transform.getMatrix();
+ mainCtx.save();
+ mainCtx.transform(m[0], m[1], m[2], m[3], m[4], m[5]);
+ if (this._allowCache) {
+ if (this.isDirty()) {
+ const ctx = this._cacheCanvas.getContext();
+ this._cacheCanvas.clear();
+ ctx.save();
+ ctx.translate(this.strokeWidth / 2, this.strokeWidth / 2); // 边框会按照宽度画在边界上,分别占据内外二分之一
+ this._draw(ctx);
+ ctx.restore();
+ }
+ this._applyCache(mainCtx);
+ } else {
+ this._draw(mainCtx);
+ }
+ mainCtx.restore();
+ this.makeDirty(false);
+ return this;
+ }
+
+ getContext() {
+ return this._context;
+ }
+
+ toJson() {
+ const props: IKeyValue = {};
+ RICHTEXT_OBJECT_ARRAY.forEach((key) => {
+ if (this[key]) {
+ props[key] = this[key];
+ }
+ });
+ return {
+ ...super.toJson(),
+ ...props,
+ };
+ }
+
+ protected _draw(ctx: CanvasRenderingContext2D) {
+ this._documents.render(ctx);
+ }
+
private convertToDocumentData(text: string) {
const contentLength = text.length;
const documentData: IDocumentData = {
@@ -201,69 +281,6 @@ export class RichText extends BaseObject {
this.makeDirty(true);
}
- setProps(props?: IRichTextProps) {
- if (!props) {
- return;
- }
-
- const themeKeys = Object.keys(props);
- if (themeKeys.length === 0) {
- return;
- }
- themeKeys.forEach((key) => {
- if (props[key] === undefined) {
- return true;
- }
-
- if (RICHTEXT_OBJECT_ARRAY.indexOf(key) === -1) {
- this[`_${key}`] = props[key];
- }
- });
- this.makeDirty(true);
- return this;
- }
-
- protected _draw(ctx: CanvasRenderingContext2D) {
- this._documents.render(ctx);
- }
-
- render(mainCtx: CanvasRenderingContext2D, bounds?: IBoundRect) {
- if (!this.visible) {
- this.makeDirty(false);
- return this;
- }
-
- // Temporarily ignore the on-demand display of elements within a group:this.isInGroup
- if (this.isRender()) {
- const { minX, maxX, minY, maxY } = transformBoundingCoord(this, bounds!);
-
- if (this.width + this.strokeWidth < minX || maxX < 0 || this.height + this.strokeWidth < minY || maxY < 0) {
- // console.warn('ignore object', this);
- return this;
- }
- }
-
- const m = this.transform.getMatrix();
- mainCtx.save();
- mainCtx.transform(m[0], m[1], m[2], m[3], m[4], m[5]);
- if (this._allowCache) {
- if (this.isDirty()) {
- const ctx = this._cacheCanvas.getContext();
- this._cacheCanvas.clear();
- ctx.save();
- ctx.translate(this.strokeWidth / 2, this.strokeWidth / 2); // 边框会按照宽度画在边界上,分别占据内外二分之一
- this._draw(ctx);
- ctx.restore();
- }
- this._applyCache(mainCtx);
- } else {
- this._draw(mainCtx);
- }
- mainCtx.restore();
- this.makeDirty(false);
- return this;
- }
-
private _applyCache(ctx?: CanvasRenderingContext2D) {
if (!ctx || !this._cacheCanvas) {
return;
@@ -283,21 +300,4 @@ export class RichText extends BaseObject {
this.height + this.strokeWidth
);
}
-
- getContext() {
- return this._context;
- }
-
- toJson() {
- const props: IKeyValue = {};
- RICHTEXT_OBJECT_ARRAY.forEach((key) => {
- if (this[key]) {
- props[key] = this[key];
- }
- });
- return {
- ...super.toJson(),
- ...props,
- };
- }
}
diff --git a/packages/base-render/src/Shape/ScrollBar.ts b/packages/base-render/src/Shape/ScrollBar.ts
index a1fa86219e..b9386bf282 100644
--- a/packages/base-render/src/Shape/ScrollBar.ts
+++ b/packages/base-render/src/Shape/ScrollBar.ts
@@ -77,6 +77,14 @@ export class ScrollBar {
private _mainScene?: Scene;
+ private _lastX: number;
+
+ private _lastY: number;
+
+ private _isHorizonMove = false;
+
+ private _isVerticalMove = false;
+
constructor(view: Viewport, props?: IScrollBarProps) {
if (!view) {
console.warn('Missing viewport');
@@ -109,6 +117,32 @@ export class ScrollBar {
return this._verticalThumbHeight;
}
+ get ratioScrollX(): number {
+ if (this._horizontalThumbWidth === undefined || this._horizontalBarWidth === undefined) {
+ return 1;
+ }
+ return (this._horizontalThumbWidth - this._horizontalMinusMiniThumb) / this._horizontalBarWidth;
+ }
+
+ get ratioScrollY(): number {
+ if (this._verticalThumbHeight === undefined || this._verticalBarHeight === undefined) {
+ return 1;
+ }
+ return (this._verticalThumbHeight - this._verticalMinusMiniThumb) / this._verticalBarHeight;
+ }
+
+ get barSize() {
+ return this._barSize;
+ }
+
+ get barBorder() {
+ return this._barBorder;
+ }
+
+ static attachTo(view: Viewport, props?: IScrollBarProps) {
+ return new ScrollBar(view, props);
+ }
+
setProps(props?: IScrollBarProps) {
if (!props) {
return;
@@ -126,6 +160,156 @@ export class ScrollBar {
});
}
+ render(ctx: CanvasRenderingContext2D, left: number = 0, top: number = 0) {
+ let { scrollX, scrollY } = this._view;
+ ctx.save();
+ const transform = new Transform([1, 0, 0, 1, left, top]);
+ const m = transform.getMatrix();
+ ctx.transform(m[0], m[1], m[2], m[3], m[4], m[5]);
+ this._horizonBarRect.render(ctx);
+ this._horizonThumbRect.translate(scrollX).render(ctx);
+ this._verticalBarRect.render(ctx);
+ this._verticalThumbRect.translate(undefined, scrollY).render(ctx);
+ this._placeholderBarRect.render(ctx);
+ ctx.restore();
+ }
+
+ resize(parentWidth: number = 0, parentHeight: number = 0, contentWidth: number = 0, contentHeight: number = 0) {
+ if (parentWidth === 0 && parentWidth === 0) {
+ return;
+ }
+ // ratioScrollY = 内容可视区高度/内容实际区高度= 滑动条的高度/滑道高度=滚动条的顶部距离/实际内容区域顶部距离;
+ if (this._enableHorizontal) {
+ this._horizontalMinusMiniThumb = 0;
+ this._horizontalBarWidth = parentWidth - this._barSize;
+ this._horizontalThumbWidth = ((this._horizontalBarWidth * (this._horizontalBarWidth - this._barBorder)) / contentWidth) * this._thumbLengthRatio;
+
+ // this._horizontalThumbWidth = this._horizontalThumbWidth < MINI_THUMB_SIZE ? MINI_THUMB_SIZE : this._horizontalThumbWidth;
+ if (this._horizontalThumbWidth < MINI_THUMB_SIZE) {
+ this._horizontalMinusMiniThumb = MINI_THUMB_SIZE - this._horizontalThumbWidth;
+ this._horizontalThumbWidth = MINI_THUMB_SIZE;
+ }
+
+ this._horizonBarRect?.transformByState({
+ left: 0,
+ top: parentHeight - this._barSize,
+ width: this._horizontalBarWidth,
+ height: this._barSize - this._barBorder,
+ });
+
+ if (this._horizontalThumbWidth >= parentWidth) {
+ this._horizonThumbRect?.setProps({
+ visible: false,
+ });
+ } else {
+ if (!this._horizonThumbRect?.visible) {
+ this._horizonThumbRect?.setProps({
+ visible: true,
+ });
+ }
+
+ this._horizonThumbRect?.transformByState({
+ left: this._view.scrollX,
+ top: parentHeight - this._barSize + this._thumbMargin,
+ width: this._horizontalThumbWidth,
+ height: this._barSize - this._thumbMargin * 2,
+ });
+ }
+ }
+
+ if (this._enableVertical) {
+ this._verticalMinusMiniThumb = 0;
+ this._verticalBarHeight = parentHeight - this._barSize;
+ this._verticalThumbHeight = ((this._verticalBarHeight * (this._verticalBarHeight - this._barBorder)) / contentHeight) * this._thumbLengthRatio;
+ // this._verticalThumbHeight = this._verticalThumbHeight < MINI_THUMB_SIZE ? MINI_THUMB_SIZE : this._verticalThumbHeight;
+ if (this._verticalThumbHeight < MINI_THUMB_SIZE) {
+ this._verticalMinusMiniThumb = MINI_THUMB_SIZE - this._verticalThumbHeight;
+ this._verticalThumbHeight = MINI_THUMB_SIZE;
+ }
+
+ this._verticalBarRect?.transformByState({
+ left: parentWidth - this._barSize,
+ top: 0,
+ width: this._barSize - this._barBorder,
+ height: this._verticalBarHeight,
+ });
+
+ if (this._verticalThumbHeight >= parentHeight) {
+ this._verticalThumbRect?.setProps({
+ visible: false,
+ });
+ } else {
+ if (!this._verticalThumbRect?.visible) {
+ this._verticalThumbRect?.setProps({
+ visible: true,
+ });
+ }
+
+ this._verticalThumbRect?.transformByState({
+ left: parentWidth - this._barSize + this._thumbMargin,
+ top: this._view.scrollY,
+ width: this._barSize - this._thumbMargin * 2,
+ height: this._verticalThumbHeight,
+ });
+ }
+ }
+
+ if (this._enableHorizontal && this._enableVertical) {
+ this._placeholderBarRect?.transformByState({
+ left: parentWidth - this._barSize,
+ top: parentHeight - this._barSize,
+ width: this._barSize - this._barBorder,
+ height: this._barSize - this._barBorder,
+ });
+ }
+ }
+
+ makeDirty(state: boolean) {
+ this._horizonBarRect?.makeDirty(state);
+ this._horizonThumbRect?.makeDirty(state);
+ this._verticalBarRect?.makeDirty(state);
+ this._verticalThumbRect?.makeDirty(state);
+ this._placeholderBarRect?.makeDirty(state);
+
+ this.makeViewDirty(state);
+ }
+
+ makeViewDirty(state: boolean) {
+ this._view.makeDirty(state);
+ const parent = this._view.scene.getParent();
+ if (parent.classType === RENDER_CLASS_TYPE.SCENE_VIEWER) {
+ (parent as SceneViewer).makeDirty(true);
+ }
+ }
+
+ pick(coord: Vector2) {
+ if (this._horizonThumbRect?.isHit(coord)) {
+ return this._horizonThumbRect;
+ }
+
+ if (this._verticalThumbRect?.isHit(coord)) {
+ return this._verticalThumbRect;
+ }
+
+ if (this._horizonBarRect?.isHit(coord)) {
+ return this._horizonBarRect;
+ }
+
+ if (this._verticalBarRect?.isHit(coord)) {
+ return this._verticalBarRect;
+ }
+
+ return null;
+ }
+
+ dispose() {
+ this._horizonBarRect.dispose();
+ this._horizonThumbRect.dispose();
+ this._verticalBarRect.dispose();
+ this._verticalThumbRect.dispose();
+ this._placeholderBarRect.dispose();
+ }
+
private _initialScrollRect() {
if (this._enableHorizontal) {
this._horizonBarRect = new Rect('__horizonBarRect__', {
@@ -164,14 +348,6 @@ export class ScrollBar {
this.__initialEvent();
}
- private _lastX: number;
-
- private _lastY: number;
-
- private _isHorizonMove = false;
-
- private _isVerticalMove = false;
-
private __initialEvent() {
const mainScene = this._mainScene || this._view.scene;
const hoverFunc = (color: string, object: Rect) => (evt: unknown, state: EventState) => {
@@ -290,180 +466,4 @@ export class ScrollBar {
});
}
}
-
- render(ctx: CanvasRenderingContext2D, left: number = 0, top: number = 0) {
- let { scrollX, scrollY } = this._view;
- ctx.save();
- const transform = new Transform([1, 0, 0, 1, left, top]);
- const m = transform.getMatrix();
- ctx.transform(m[0], m[1], m[2], m[3], m[4], m[5]);
- this._horizonBarRect.render(ctx);
- this._horizonThumbRect.translate(scrollX).render(ctx);
- this._verticalBarRect.render(ctx);
- this._verticalThumbRect.translate(undefined, scrollY).render(ctx);
- this._placeholderBarRect.render(ctx);
- ctx.restore();
- }
-
- resize(parentWidth: number = 0, parentHeight: number = 0, contentWidth: number = 0, contentHeight: number = 0) {
- if (parentWidth === 0 && parentWidth === 0) {
- return;
- }
- // ratioScrollY = 内容可视区高度/内容实际区高度= 滑动条的高度/滑道高度=滚动条的顶部距离/实际内容区域顶部距离;
- if (this._enableHorizontal) {
- this._horizontalMinusMiniThumb = 0;
- this._horizontalBarWidth = parentWidth - this._barSize;
- this._horizontalThumbWidth = ((this._horizontalBarWidth * (this._horizontalBarWidth - this._barBorder)) / contentWidth) * this._thumbLengthRatio;
-
- // this._horizontalThumbWidth = this._horizontalThumbWidth < MINI_THUMB_SIZE ? MINI_THUMB_SIZE : this._horizontalThumbWidth;
- if (this._horizontalThumbWidth < MINI_THUMB_SIZE) {
- this._horizontalMinusMiniThumb = MINI_THUMB_SIZE - this._horizontalThumbWidth;
- this._horizontalThumbWidth = MINI_THUMB_SIZE;
- }
-
- this._horizonBarRect?.transformByState({
- left: 0,
- top: parentHeight - this._barSize,
- width: this._horizontalBarWidth,
- height: this._barSize - this._barBorder,
- });
-
- if (this._horizontalThumbWidth >= parentWidth) {
- this._horizonThumbRect?.setProps({
- visible: false,
- });
- } else {
- if (!this._horizonThumbRect?.visible) {
- this._horizonThumbRect?.setProps({
- visible: true,
- });
- }
-
- this._horizonThumbRect?.transformByState({
- left: this._view.scrollX,
- top: parentHeight - this._barSize + this._thumbMargin,
- width: this._horizontalThumbWidth,
- height: this._barSize - this._thumbMargin * 2,
- });
- }
- }
-
- if (this._enableVertical) {
- this._verticalMinusMiniThumb = 0;
- this._verticalBarHeight = parentHeight - this._barSize;
- this._verticalThumbHeight = ((this._verticalBarHeight * (this._verticalBarHeight - this._barBorder)) / contentHeight) * this._thumbLengthRatio;
- // this._verticalThumbHeight = this._verticalThumbHeight < MINI_THUMB_SIZE ? MINI_THUMB_SIZE : this._verticalThumbHeight;
- if (this._verticalThumbHeight < MINI_THUMB_SIZE) {
- this._verticalMinusMiniThumb = MINI_THUMB_SIZE - this._verticalThumbHeight;
- this._verticalThumbHeight = MINI_THUMB_SIZE;
- }
-
- this._verticalBarRect?.transformByState({
- left: parentWidth - this._barSize,
- top: 0,
- width: this._barSize - this._barBorder,
- height: this._verticalBarHeight,
- });
-
- if (this._verticalThumbHeight >= parentHeight) {
- this._verticalThumbRect?.setProps({
- visible: false,
- });
- } else {
- if (!this._verticalThumbRect?.visible) {
- this._verticalThumbRect?.setProps({
- visible: true,
- });
- }
-
- this._verticalThumbRect?.transformByState({
- left: parentWidth - this._barSize + this._thumbMargin,
- top: this._view.scrollY,
- width: this._barSize - this._thumbMargin * 2,
- height: this._verticalThumbHeight,
- });
- }
- }
-
- if (this._enableHorizontal && this._enableVertical) {
- this._placeholderBarRect?.transformByState({
- left: parentWidth - this._barSize,
- top: parentHeight - this._barSize,
- width: this._barSize - this._barBorder,
- height: this._barSize - this._barBorder,
- });
- }
- }
-
- get ratioScrollX(): number {
- if (this._horizontalThumbWidth === undefined || this._horizontalBarWidth === undefined) {
- return 1;
- }
- return (this._horizontalThumbWidth - this._horizontalMinusMiniThumb) / this._horizontalBarWidth;
- }
-
- get ratioScrollY(): number {
- if (this._verticalThumbHeight === undefined || this._verticalBarHeight === undefined) {
- return 1;
- }
- return (this._verticalThumbHeight - this._verticalMinusMiniThumb) / this._verticalBarHeight;
- }
-
- get barSize() {
- return this._barSize;
- }
-
- get barBorder() {
- return this._barBorder;
- }
-
- makeDirty(state: boolean) {
- this._horizonBarRect?.makeDirty(state);
- this._horizonThumbRect?.makeDirty(state);
- this._verticalBarRect?.makeDirty(state);
- this._verticalThumbRect?.makeDirty(state);
- this._placeholderBarRect?.makeDirty(state);
-
- this.makeViewDirty(state);
- }
-
- makeViewDirty(state: boolean) {
- this._view.makeDirty(state);
- const parent = this._view.scene.getParent();
- if (parent.classType === RENDER_CLASS_TYPE.SCENE_VIEWER) {
- (parent as SceneViewer).makeDirty(true);
- }
- }
-
- pick(coord: Vector2) {
- if (this._horizonThumbRect?.isHit(coord)) {
- return this._horizonThumbRect;
- }
-
- if (this._verticalThumbRect?.isHit(coord)) {
- return this._verticalThumbRect;
- }
-
- if (this._horizonBarRect?.isHit(coord)) {
- return this._horizonBarRect;
- }
-
- if (this._verticalBarRect?.isHit(coord)) {
- return this._verticalBarRect;
- }
-
- return null;
- }
-
- dispose() {
- this._horizonBarRect.dispose();
- this._horizonThumbRect.dispose();
- this._verticalBarRect.dispose();
- this._verticalThumbRect.dispose();
- this._placeholderBarRect.dispose();
- }
-
- static attachTo(view: Viewport, props?: IScrollBarProps) {
- return new ScrollBar(view, props);
- }
}
diff --git a/packages/base-render/src/Shape/Shape.ts b/packages/base-render/src/Shape/Shape.ts
index 724fc6ac8a..e446e70cd2 100644
--- a/packages/base-render/src/Shape/Shape.ts
+++ b/packages/base-render/src/Shape/Shape.ts
@@ -71,6 +71,8 @@ export const SHAPE_OBJECT_ARRAY = [
];
export abstract class Shape<T> extends BaseObject {
+ protected _cacheCanvas: Canvas;
+
private _hoverCursor: Nullable<string>;
private _moveCursor: string | null = null;
@@ -119,6 +121,20 @@ export abstract class Shape<T> extends BaseObject {
private _strokeMiterLimit: number;
+ private _type: SHAPE_TYPE;
+
+ constructor(key?: string, props?: T) {
+ super(key);
+
+ if (this._allowCache) {
+ this._cacheCanvas = new Canvas();
+ this.onTransformChangeObservable.add(() => {
+ this.resizeCacheCanvas();
+ });
+ }
+ this._initialProps(props);
+ }
+
get hoverCursor() {
return this._hoverCursor;
}
@@ -215,22 +231,90 @@ export abstract class Shape<T> extends BaseObject {
return this._strokeMiterLimit;
}
- private _type: SHAPE_TYPE;
+ static drawWith(ctx: CanvasRenderingContext2D, props: IShapeProps) {
+ /** abstract */
+ }
- protected _cacheCanvas: Canvas;
+ protected static _renderPaintInOrder(ctx: CanvasRenderingContext2D, props: IShapeProps) {
+ if (props.paintFirst === 'stroke') {
+ this._renderStroke(ctx, props);
+ this._renderFill(ctx, props);
+ } else {
+ this._renderFill(ctx, props);
+ this._renderStroke(ctx, props);
+ }
+ }
- constructor(key?: string, props?: T) {
- super(key);
+ /**
+ * @private
+ * @param {CanvasRenderingContext2D} ctx SheetContext to render on
+ */
+ private static _renderFill(ctx: CanvasRenderingContext2D, props: IShapeProps) {
+ if (!props.fill) {
+ return;
+ }
- if (this._allowCache) {
- this._cacheCanvas = new Canvas();
- this.onTransformChangeObservable.add(() => {
- this.resizeCacheCanvas();
- });
+ ctx.save();
+ this.__setFillStyles(ctx, props);
+ if (props.fillRule === 'evenodd') {
+ ctx.fill('evenodd');
+ } else {
+ ctx.fill();
}
- this._initialProps(props);
+ ctx.restore();
+ }
+
+ /**
+ * @private
+ * @param {CanvasRenderingContext2D} ctx SheetContext to render on
+ */
+ private static _renderStroke(ctx: CanvasRenderingContext2D, props: IShapeProps) {
+ let { stroke, strokeWidth, shadowEnabled, shadowForStrokeEnabled, strokeScaleEnabled, scaleX, scaleY, parent } = props;
+ if (!stroke || strokeWidth === 0) {
+ return;
+ }
+
+ if (shadowEnabled && !shadowForStrokeEnabled) {
+ this.__removeShadow(ctx);
+ }
+
+ ctx.save();
+ if (strokeScaleEnabled && parent) {
+ let scaling = this.__getObjectScaling();
+ ctx.scale(1 / scaling.scaleX, 1 / scaling.scaleY);
+ } else if (strokeScaleEnabled) {
+ scaleX = scaleX ?? 1;
+ scaleY = scaleY ?? 1;
+ ctx.scale(1 / scaleX, 1 / scaleY);
+ }
+ this.__setLineDash(ctx);
+ this.__setStrokeStyles(ctx, props);
+ ctx.stroke();
+ ctx.restore();
}
+ private static __getObjectScaling() {
+ return { scaleX: 1, scaleY: 1 };
+ }
+
+ private static __removeShadow(ctx: CanvasRenderingContext2D) {}
+
+ private static __setFillStyles(ctx: CanvasRenderingContext2D, props: IShapeProps) {
+ ctx.fillStyle = props.fill!;
+ }
+
+ private static __setStrokeStyles(ctx: CanvasRenderingContext2D, props: IShapeProps) {
+ const { strokeWidth, strokeLineCap, strokeDashOffset, strokeLineJoin, strokeMiterLimit, stroke } = props;
+ ctx.lineWidth = strokeWidth!;
+ ctx.lineCap = strokeLineCap!;
+ ctx.lineDashOffset = strokeDashOffset!;
+ ctx.lineJoin = strokeLineJoin!;
+ ctx.miterLimit = strokeMiterLimit!;
+ ctx.strokeStyle = stroke!;
+ }
+
+ private static __setLineDash(ctx: CanvasRenderingContext2D) {}
+
render(mainCtx: CanvasRenderingContext2D, bounds?: IBoundRect) {
if (!this.visible) {
this.makeDirty(false);
@@ -268,42 +352,6 @@ export abstract class Shape<T> extends BaseObject {
return this;
}
- protected _draw(ctx: CanvasRenderingContext2D) {
- /** abstract */
- }
-
- private _initialProps(props?: T) {
- if (!props) {
- return;
- }
-
- const themeKeys = Object.keys(props);
- if (themeKeys.length === 0) {
- return;
- }
-
- const transformState: IObjectFullState = {};
- let hasTransformState = false;
- themeKeys.forEach((key) => {
- if (props[key] === undefined) {
- return true;
- }
-
- if (BASE_OBJECT_ARRAY.indexOf(key) > -1) {
- transformState[key] = props[key];
- hasTransformState = true;
- } else {
- this[`_${key}`] = props[key];
- }
- });
-
- if (hasTransformState) {
- this.transformByState(transformState);
- }
-
- this.makeDirty(true);
- }
-
setProps(props?: IShapeProps) {
if (!props) {
return;
@@ -339,6 +387,19 @@ export abstract class Shape<T> extends BaseObject {
this.makeDirty(true);
}
+ toJson() {
+ const props: IKeyValue = {};
+ SHAPE_OBJECT_ARRAY.forEach((key) => {
+ if (this[key]) {
+ props[key] = this[key];
+ }
+ });
+ return {
+ ...super.toJson(),
+ ...props,
+ };
+ }
+
protected _applyCache(ctx?: CanvasRenderingContext2D) {
if (!ctx || !this._cacheCanvas) {
return;
@@ -359,100 +420,39 @@ export abstract class Shape<T> extends BaseObject {
);
}
- protected static _renderPaintInOrder(ctx: CanvasRenderingContext2D, props: IShapeProps) {
- if (props.paintFirst === 'stroke') {
- this._renderStroke(ctx, props);
- this._renderFill(ctx, props);
- } else {
- this._renderFill(ctx, props);
- this._renderStroke(ctx, props);
- }
+ protected _draw(ctx: CanvasRenderingContext2D) {
+ /** abstract */
}
- /**
- * @private
- * @param {CanvasRenderingContext2D} ctx SheetContext to render on
- */
- private static _renderFill(ctx: CanvasRenderingContext2D, props: IShapeProps) {
- if (!props.fill) {
+ private _initialProps(props?: T) {
+ if (!props) {
return;
}
- ctx.save();
- this.__setFillStyles(ctx, props);
- if (props.fillRule === 'evenodd') {
- ctx.fill('evenodd');
- } else {
- ctx.fill();
- }
- ctx.restore();
- }
-
- /**
- * @private
- * @param {CanvasRenderingContext2D} ctx SheetContext to render on
- */
- private static _renderStroke(ctx: CanvasRenderingContext2D, props: IShapeProps) {
- let { stroke, strokeWidth, shadowEnabled, shadowForStrokeEnabled, strokeScaleEnabled, scaleX, scaleY, parent } = props;
- if (!stroke || strokeWidth === 0) {
+ const themeKeys = Object.keys(props);
+ if (themeKeys.length === 0) {
return;
}
- if (shadowEnabled && !shadowForStrokeEnabled) {
- this.__removeShadow(ctx);
- }
-
- ctx.save();
- if (strokeScaleEnabled && parent) {
- let scaling = this.__getObjectScaling();
- ctx.scale(1 / scaling.scaleX, 1 / scaling.scaleY);
- } else if (strokeScaleEnabled) {
- scaleX = scaleX ?? 1;
- scaleY = scaleY ?? 1;
- ctx.scale(1 / scaleX, 1 / scaleY);
- }
- this.__setLineDash(ctx);
- this.__setStrokeStyles(ctx, props);
- ctx.stroke();
- ctx.restore();
- }
-
- private static __getObjectScaling() {
- return { scaleX: 1, scaleY: 1 };
- }
-
- private static __removeShadow(ctx: CanvasRenderingContext2D) {}
-
- private static __setFillStyles(ctx: CanvasRenderingContext2D, props: IShapeProps) {
- ctx.fillStyle = props.fill!;
- }
-
- private static __setStrokeStyles(ctx: CanvasRenderingContext2D, props: IShapeProps) {
- const { strokeWidth, strokeLineCap, strokeDashOffset, strokeLineJoin, strokeMiterLimit, stroke } = props;
- ctx.lineWidth = strokeWidth!;
- ctx.lineCap = strokeLineCap!;
- ctx.lineDashOffset = strokeDashOffset!;
- ctx.lineJoin = strokeLineJoin!;
- ctx.miterLimit = strokeMiterLimit!;
- ctx.strokeStyle = stroke!;
- }
-
- private static __setLineDash(ctx: CanvasRenderingContext2D) {}
-
- static drawWith(ctx: CanvasRenderingContext2D, props: IShapeProps) {
- /** abstract */
- }
+ const transformState: IObjectFullState = {};
+ let hasTransformState = false;
+ themeKeys.forEach((key) => {
+ if (props[key] === undefined) {
+ return true;
+ }
- toJson() {
- const props: IKeyValue = {};
- SHAPE_OBJECT_ARRAY.forEach((key) => {
- if (this[key]) {
- props[key] = this[key];
+ if (BASE_OBJECT_ARRAY.indexOf(key) > -1) {
+ transformState[key] = props[key];
+ hasTransformState = true;
+ } else {
+ this[`_${key}`] = props[key];
}
});
- return {
- ...super.toJson(),
- ...props,
- };
+
+ if (hasTransformState) {
+ this.transformByState(transformState);
+ }
+
+ this.makeDirty(true);
}
}
diff --git a/packages/base-render/src/Viewport.ts b/packages/base-render/src/Viewport.ts
index 61e9111c09..0bef82d80b 100644
--- a/packages/base-render/src/Viewport.ts
+++ b/packages/base-render/src/Viewport.ts
@@ -55,6 +55,22 @@ enum SCROLL_TYPE {
}
export class Viewport {
+ scrollX: number = 0;
+
+ scrollY: number = 0;
+
+ actualScrollX: number;
+
+ actualScrollY: number;
+
+ onMouseWheelObserver = new Observable<IWheelEvent>();
+
+ onScrollAfterObserver = new Observable<IScrollObserverParam>();
+
+ onScrollBeforeObserver = new Observable<IScrollObserverParam>();
+
+ onScrollStopObserver = new Observable<IScrollObserverParam>();
+
private _viewPortKey: string;
private _dirty: boolean = true;
@@ -97,20 +113,12 @@ export class Viewport {
private _scrollStopNum: number;
- scrollX: number = 0;
-
- scrollY: number = 0;
-
private _preScrollX: Nullable<number> = 0;
private _preScrollY: Nullable<number> = 0;
private _renderClipState = true;
- actualScrollX: number;
-
- actualScrollY: number;
-
constructor(viewPortKey: string, scene: Scene, props?: IViewProps) {
this._viewPortKey = viewPortKey;
@@ -153,18 +161,10 @@ export class Viewport {
return this._width;
}
- set width(w: Nullable<number>) {
- this._width = w;
- }
-
get height() {
return this._height;
}
- set height(h: Nullable<number>) {
- this._height = h;
- }
-
get viewPortKey() {
return this._viewPortKey;
}
@@ -189,33 +189,41 @@ export class Viewport {
return this._top;
}
+ get left(): number {
+ return this._left;
+ }
+
+ get bottom(): number {
+ return this._bottom;
+ }
+
+ get right(): number {
+ return this._right;
+ }
+
+ set width(w: Nullable<number>) {
+ this._width = w;
+ }
+
+ set height(h: Nullable<number>) {
+ this._height = h;
+ }
+
private set top(num: number | string) {
this._topOrigin = num;
this._top = toPx(num, this._scene?.getParent()?.height);
}
- get left(): number {
- return this._left;
- }
-
private set left(num: number | string) {
this._leftOrigin = num;
this._left = toPx(num, this.scene.getParent()?.width);
}
- get bottom(): number {
- return this._bottom;
- }
-
private set bottom(num: number | string) {
this._bottomOrigin = num;
this._bottom = toPx(num, this.scene.getParent()?.height);
}
- get right(): number {
- return this._right;
- }
-
private set right(num: number | string) {
this._rightOrigin = num;
this._right = toPx(num, this.scene.getParent()?.width);
@@ -252,46 +260,6 @@ export class Viewport {
this._resizeCacheCanvasAndScrollBar();
}
- private _resizeCacheCanvasAndScrollBar(forceCalculate = false) {
- const { width, height } = this._getViewPortSize(forceCalculate);
-
- this.width = width;
- this.height = height;
-
- const contentWidth = this._scene.width * this._scene.scaleX;
- const contentHeight = this._scene.height * this._scene.scaleY;
-
- this._scrollBar?.resize(width, height, contentWidth, contentHeight);
- this.makeDirty(true);
- }
-
- private _getViewPortSize(forceCalculate = false) {
- const parent = this._scene?.getParent();
- let width;
- let height;
-
- if (!forceCalculate && this._widthOrigin !== undefined) {
- width = this._widthOrigin!;
- } else {
- const referenceWidth = parent.width;
- let containerWidth = parent.classType === RENDER_CLASS_TYPE.SCENE_VIEWER ? referenceWidth * (parent as SceneViewer).scaleX : referenceWidth;
- width = containerWidth - (this._left + this._right);
- }
-
- if (!forceCalculate && this._heightOrigin !== undefined) {
- height = this._heightOrigin!;
- } else {
- const referenceHeight = parent.height;
- let containerHeight = parent.classType === RENDER_CLASS_TYPE.SCENE_VIEWER ? referenceHeight * (parent as SceneViewer).scaleY : referenceHeight;
- height = containerHeight - (this._top + this._bottom);
- }
-
- return {
- width,
- height,
- };
- }
-
makeDirty(state: boolean = true) {
this._dirty = state;
}
@@ -308,129 +276,6 @@ export class Viewport {
return this._scroll(SCROLL_TYPE.scrollBy, pos);
}
- private _getApplyCanvasState() {
- return this._allowCache && this._renderClipState;
- }
-
- private _scrollRendered() {
- this._preScrollX = this.scrollX;
- this._preScrollY = this.scrollY;
- }
-
- private _limitedScroll() {
- if (!this._scrollBar) {
- return;
- }
-
- const limitX = this._scrollBar?.limitX || Infinity;
- const limitY = this._scrollBar?.limitY || Infinity;
-
- let isLimitedX = true;
- let isLimitedY = true;
-
- if (this.scrollX < 0) {
- this.scrollX = 0;
- } else if (this.scrollX > limitX) {
- this.scrollX = limitX;
- } else {
- isLimitedX = false;
- }
-
- if (this.scrollY < 0) {
- this.scrollY = 0;
- } else if (this.scrollY > limitY) {
- this.scrollY = limitY;
- } else {
- isLimitedY = false;
- }
-
- return {
- isLimitedX,
- isLimitedY,
- };
- }
-
- private _triggerScrollStop(
- scroll: {
- x: number;
- y: number;
- },
- x?: number,
- y?: number
- ) {
- window.clearTimeout(this._scrollStopNum);
- this._scrollStopNum = window.setTimeout(() => {
- this.onScrollStopObserver.notifyObservers({
- viewport: this,
- scrollX: this.scrollX,
- scrollY: this.scrollY,
- x,
- y,
- actualScrollX: scroll.x,
- actualScrollY: scroll.y,
- limitX: this._scrollBar?.limitX,
- limitY: this._scrollBar?.limitY,
- });
- }, 0);
- }
-
- private _scroll(scrollType: SCROLL_TYPE, pos: IScrollBarPosition) {
- const { x, y } = pos;
- if (x !== undefined) {
- if (scrollType === SCROLL_TYPE.scrollBy) {
- this.scrollX += x;
- } else {
- this.scrollX = x;
- }
- }
-
- if (y !== undefined) {
- if (scrollType === SCROLL_TYPE.scrollBy) {
- this.scrollY += y;
- } else {
- this.scrollY = y;
- }
- }
-
- const limited = this._limitedScroll(); // 限制滚动范围
-
- this.onScrollBeforeObserver.notifyObservers({
- viewport: this,
- scrollX: this.scrollX,
- scrollY: this.scrollY,
- x,
- y,
- limitX: this._scrollBar?.limitX,
- limitY: this._scrollBar?.limitY,
- });
-
- if (this._scrollBar) {
- this._scrollBar.makeDirty(true);
- } else {
- this.makeDirty(true);
- }
-
- const scroll = this.transformScroll();
- this.actualScrollX = scroll.x;
- this.actualScrollY = scroll.y;
-
- this.onScrollAfterObserver.notifyObservers({
- viewport: this,
- scrollX: this.scrollX,
- scrollY: this.scrollY,
- x,
- y,
- actualScrollX: scroll.x,
- actualScrollY: scroll.y,
- limitX: this._scrollBar?.limitX,
- limitY: this._scrollBar?.limitY,
- });
-
- this._triggerScrollStop(scroll, x, y);
-
- return limited;
- }
-
getBarScroll(actualX: number, actualY: number) {
let x = actualX;
let y = actualY;
@@ -575,42 +420,6 @@ export class Viewport {
return this._calViewportRelativeBounding();
}
- private _calViewportRelativeBounding() {
- let ratioScrollX = this._scrollBar?.ratioScrollX ?? 1;
- let ratioScrollY = this._scrollBar?.ratioScrollY ?? 1;
- let xFrom: number = this.left;
- let xTo: number = (this.width || 0) + this.left;
- let yFrom: number = this.top;
- let yTo: number = (this.height || 0) + this.top;
-
- let differenceX = 0;
- let differenceY = 0;
-
- if (this._preScrollX != null) {
- differenceX = (this._preScrollX - this.scrollX) / ratioScrollX;
- }
-
- if (this._preScrollY != null) {
- differenceY = (this._preScrollY - this.scrollY) / ratioScrollY;
- }
-
- const bounding: IBoundRect = {
- tl: Vector2.FromArray([xFrom, yFrom]),
- tr: Vector2.FromArray([xTo, yFrom]),
- bl: Vector2.FromArray([xFrom, yTo]),
- br: Vector2.FromArray([xTo, yTo]),
- dx: differenceX,
- dy: differenceY,
- };
-
- bounding.tl = this.getRelativeVector(bounding.tl);
- bounding.tr = this.getRelativeVector(bounding.tr);
- bounding.bl = this.getRelativeVector(bounding.bl);
- bounding.br = this.getRelativeVector(bounding.br);
-
- return bounding;
- }
-
getRelativeVector(coord: Vector2) {
const sceneTrans = this.scene.transform.clone().invert();
const scroll = this.transformScroll();
@@ -627,29 +436,6 @@ export class Viewport {
return svCoord;
}
- private drawScrollbar(ctx: CanvasRenderingContext2D) {
- if (!this._scrollBar) {
- return;
- }
- const parent = this._scene.getParent();
- if (parent.classType === RENDER_CLASS_TYPE.SCENE_VIEWER) {
- this._scrollBar.render(ctx);
- } else if (parent.classType === RENDER_CLASS_TYPE.ENGINE) {
- this._scrollBar.render(ctx);
- }
- }
-
- private _applyCache(ctx?: CanvasRenderingContext2D) {
- if (!ctx) {
- return;
- }
- const pixelRatio = this._cacheCanvas.getPixelRatio();
- const width = this._cacheCanvas.getWidth() * pixelRatio;
- const height = this._cacheCanvas.getHeight() * pixelRatio;
- // console.log(this.viewPortKey, this._cacheCanvas, width, height, this.left, this.top, this.width, this.height, pixelRatio);
- ctx.drawImage(this._cacheCanvas.getCanvasEle(), 0, 0, width, height, this.left, this.top, this.width || 0, this.height || 0);
- }
-
onMouseWheel(evt: IWheelEvent, state: EventState) {
if (!this._scrollBar) {
return;
@@ -778,11 +564,225 @@ export class Viewport {
this._scrollBar?.dispose();
}
- onMouseWheelObserver = new Observable<IWheelEvent>();
+ private _resizeCacheCanvasAndScrollBar(forceCalculate = false) {
+ const { width, height } = this._getViewPortSize(forceCalculate);
- onScrollAfterObserver = new Observable<IScrollObserverParam>();
+ this.width = width;
+ this.height = height;
- onScrollBeforeObserver = new Observable<IScrollObserverParam>();
+ const contentWidth = this._scene.width * this._scene.scaleX;
+ const contentHeight = this._scene.height * this._scene.scaleY;
- onScrollStopObserver = new Observable<IScrollObserverParam>();
+ this._scrollBar?.resize(width, height, contentWidth, contentHeight);
+ this.makeDirty(true);
+ }
+
+ private _getViewPortSize(forceCalculate = false) {
+ const parent = this._scene?.getParent();
+ let width;
+ let height;
+
+ if (!forceCalculate && this._widthOrigin !== undefined) {
+ width = this._widthOrigin!;
+ } else {
+ const referenceWidth = parent.width;
+ let containerWidth = parent.classType === RENDER_CLASS_TYPE.SCENE_VIEWER ? referenceWidth * (parent as SceneViewer).scaleX : referenceWidth;
+ width = containerWidth - (this._left + this._right);
+ }
+
+ if (!forceCalculate && this._heightOrigin !== undefined) {
+ height = this._heightOrigin!;
+ } else {
+ const referenceHeight = parent.height;
+ let containerHeight = parent.classType === RENDER_CLASS_TYPE.SCENE_VIEWER ? referenceHeight * (parent as SceneViewer).scaleY : referenceHeight;
+ height = containerHeight - (this._top + this._bottom);
+ }
+
+ return {
+ width,
+ height,
+ };
+ }
+
+ private _getApplyCanvasState() {
+ return this._allowCache && this._renderClipState;
+ }
+
+ private _scrollRendered() {
+ this._preScrollX = this.scrollX;
+ this._preScrollY = this.scrollY;
+ }
+
+ private _limitedScroll() {
+ if (!this._scrollBar) {
+ return;
+ }
+
+ const limitX = this._scrollBar?.limitX || Infinity;
+ const limitY = this._scrollBar?.limitY || Infinity;
+
+ let isLimitedX = true;
+ let isLimitedY = true;
+
+ if (this.scrollX < 0) {
+ this.scrollX = 0;
+ } else if (this.scrollX > limitX) {
+ this.scrollX = limitX;
+ } else {
+ isLimitedX = false;
+ }
+
+ if (this.scrollY < 0) {
+ this.scrollY = 0;
+ } else if (this.scrollY > limitY) {
+ this.scrollY = limitY;
+ } else {
+ isLimitedY = false;
+ }
+
+ return {
+ isLimitedX,
+ isLimitedY,
+ };
+ }
+
+ private _triggerScrollStop(
+ scroll: {
+ x: number;
+ y: number;
+ },
+ x?: number,
+ y?: number
+ ) {
+ window.clearTimeout(this._scrollStopNum);
+ this._scrollStopNum = window.setTimeout(() => {
+ this.onScrollStopObserver.notifyObservers({
+ viewport: this,
+ scrollX: this.scrollX,
+ scrollY: this.scrollY,
+ x,
+ y,
+ actualScrollX: scroll.x,
+ actualScrollY: scroll.y,
+ limitX: this._scrollBar?.limitX,
+ limitY: this._scrollBar?.limitY,
+ });
+ }, 0);
+ }
+
+ private _scroll(scrollType: SCROLL_TYPE, pos: IScrollBarPosition) {
+ const { x, y } = pos;
+ if (x !== undefined) {
+ if (scrollType === SCROLL_TYPE.scrollBy) {
+ this.scrollX += x;
+ } else {
+ this.scrollX = x;
+ }
+ }
+
+ if (y !== undefined) {
+ if (scrollType === SCROLL_TYPE.scrollBy) {
+ this.scrollY += y;
+ } else {
+ this.scrollY = y;
+ }
+ }
+
+ const limited = this._limitedScroll(); // 限制滚动范围
+
+ this.onScrollBeforeObserver.notifyObservers({
+ viewport: this,
+ scrollX: this.scrollX,
+ scrollY: this.scrollY,
+ x,
+ y,
+ limitX: this._scrollBar?.limitX,
+ limitY: this._scrollBar?.limitY,
+ });
+
+ if (this._scrollBar) {
+ this._scrollBar.makeDirty(true);
+ } else {
+ this.makeDirty(true);
+ }
+
+ const scroll = this.transformScroll();
+ this.actualScrollX = scroll.x;
+ this.actualScrollY = scroll.y;
+
+ this.onScrollAfterObserver.notifyObservers({
+ viewport: this,
+ scrollX: this.scrollX,
+ scrollY: this.scrollY,
+ x,
+ y,
+ actualScrollX: scroll.x,
+ actualScrollY: scroll.y,
+ limitX: this._scrollBar?.limitX,
+ limitY: this._scrollBar?.limitY,
+ });
+
+ this._triggerScrollStop(scroll, x, y);
+
+ return limited;
+ }
+
+ private _calViewportRelativeBounding() {
+ let ratioScrollX = this._scrollBar?.ratioScrollX ?? 1;
+ let ratioScrollY = this._scrollBar?.ratioScrollY ?? 1;
+ let xFrom: number = this.left;
+ let xTo: number = (this.width || 0) + this.left;
+ let yFrom: number = this.top;
+ let yTo: number = (this.height || 0) + this.top;
+
+ let differenceX = 0;
+ let differenceY = 0;
+
+ if (this._preScrollX != null) {
+ differenceX = (this._preScrollX - this.scrollX) / ratioScrollX;
+ }
+
+ if (this._preScrollY != null) {
+ differenceY = (this._preScrollY - this.scrollY) / ratioScrollY;
+ }
+
+ const bounding: IBoundRect = {
+ tl: Vector2.FromArray([xFrom, yFrom]),
+ tr: Vector2.FromArray([xTo, yFrom]),
+ bl: Vector2.FromArray([xFrom, yTo]),
+ br: Vector2.FromArray([xTo, yTo]),
+ dx: differenceX,
+ dy: differenceY,
+ };
+
+ bounding.tl = this.getRelativeVector(bounding.tl);
+ bounding.tr = this.getRelativeVector(bounding.tr);
+ bounding.bl = this.getRelativeVector(bounding.bl);
+ bounding.br = this.getRelativeVector(bounding.br);
+
+ return bounding;
+ }
+
+ private drawScrollbar(ctx: CanvasRenderingContext2D) {
+ if (!this._scrollBar) {
+ return;
+ }
+ const parent = this._scene.getParent();
+ if (parent.classType === RENDER_CLASS_TYPE.SCENE_VIEWER) {
+ this._scrollBar.render(ctx);
+ } else if (parent.classType === RENDER_CLASS_TYPE.ENGINE) {
+ this._scrollBar.render(ctx);
+ }
+ }
+
+ private _applyCache(ctx?: CanvasRenderingContext2D) {
+ if (!ctx) {
+ return;
+ }
+ const pixelRatio = this._cacheCanvas.getPixelRatio();
+ const width = this._cacheCanvas.getWidth() * pixelRatio;
+ const height = this._cacheCanvas.getHeight() * pixelRatio;
+ // console.log(this.viewPortKey, this._cacheCanvas, width, height, this.left, this.top, this.width, this.height, pixelRatio);
+ ctx.drawImage(this._cacheCanvas.getCanvasEle(), 0, 0, width, height, this.left, this.top, this.width || 0, this.height || 0);
+ }
}