Skip to content

Commit

Permalink
chore(TS): finish converting utils (fabricjs#8230)
Browse files Browse the repository at this point in the history
  • Loading branch information
asturur authored and frankrousseau committed Jan 6, 2023
1 parent 9558697 commit a377f54
Show file tree
Hide file tree
Showing 29 changed files with 1,202 additions and 1,450 deletions.
5 changes: 0 additions & 5 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,6 @@ import './src/mixins/collection.mixin';
import './src/mixins/shared_methods.mixin';
import './src/util/misc/misc';
// import './src/util/named_accessors.mixin'; i would imagine dead forever or proper setters/getters
import './src/util/lang_class';
import './src/util/dom_misc';
import './src/util/animate'; // optional animation
import './src/util/animate_color'; // optional animation
import './src/util/anim_ease'; // optional easing
import './src/parser'; // optional parser
import './src/point.class';
import './src/intersection.class';
Expand Down
16 changes: 16 additions & 0 deletions src/cache.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { config } from './config';

export class Cache {
/**
Expand Down Expand Up @@ -44,6 +45,21 @@ export class Cache {
}
}

/**
* Given current aspect ratio, determines the max width and height that can
* respect the total allowed area for the cache.
* @memberOf fabric.util
* @param {number} ar aspect ratio
* @return {number[]} Limited dimensions X and Y
*/
limitDimsByArea(ar: number) {
const { perfLimitSizeTotal } = config;
const roughWidth = Math.sqrt(perfLimitSizeTotal * ar);
// we are not returning a point on purpose, to avoid circular dependencies
// this is an internal utility
return [Math.floor(roughWidth), Math.floor(perfLimitSizeTotal / roughWidth)];
}

/**
* This object contains the result of arc to bezier conversion for faster retrieving if the same arc needs to be converted again.
* It was an internal variable, is accessible since version 2.3.4
Expand Down
25 changes: 13 additions & 12 deletions src/canvas.class.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1044,19 +1044,20 @@ import { Point } from './point.class';
* @throws {CANVAS_INIT_ERROR} If canvas can not be initialized
*/
_createUpperCanvas: function () {
var lowerCanvasClass = this.lowerCanvasEl.className.replace(/\s*lower-canvas\s*/, ''),
lowerCanvasEl = this.lowerCanvasEl, upperCanvasEl = this.upperCanvasEl;
var lowerCanvasEl = this.lowerCanvasEl, upperCanvasEl = this.upperCanvasEl;

// there is no need to create a new upperCanvas element if we have already one.
if (upperCanvasEl) {
upperCanvasEl.className = '';
}
else {
// if there is no upperCanvas (most common case) we create one.
if (!upperCanvasEl) {
upperCanvasEl = this._createCanvasElement();
this.upperCanvasEl = upperCanvasEl;
}
fabric.util.addClass(upperCanvasEl, 'upper-canvas ' + lowerCanvasClass);
this.upperCanvasEl.setAttribute('data-fabric', 'top');
// we assign the same classname of the lowerCanvas
upperCanvasEl.className = lowerCanvasEl.className;
// but then we remove the lower-canvas specific className
upperCanvasEl.classList.remove('lower-canvas');
// we add the specific upper-canvas class
upperCanvasEl.classList.add('upper-canvas');
upperCanvasEl.setAttribute('data-fabric', 'top');
this.wrapperEl.appendChild(upperCanvasEl);

this._copyCanvasStyle(lowerCanvasEl, upperCanvasEl);
Expand All @@ -1082,9 +1083,9 @@ import { Point } from './point.class';
if (this.wrapperEl) {
return;
}
this.wrapperEl = fabric.util.wrapElement(this.lowerCanvasEl, 'div', {
'class': this.containerClass
});
const container = fabric.document.createElement('div');
container.classList.add(this.containerClass);
this.wrapperEl = fabric.util.wrapElement(this.lowerCanvasEl, container);
this.wrapperEl.setAttribute('data-fabric', 'wrapper');
fabric.util.setStyle(this.wrapperEl, {
width: this.width + 'px',
Expand Down
3 changes: 2 additions & 1 deletion src/constants.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import { TMat2D } from "./typedefs";

export { version as VERSION } from '../package.json';
export const noop = () => {};
export function noop() {};
export const halfPI = Math.PI / 2;
export const twoMathPi = Math.PI * 2;
export const PiBy180 = Math.PI / 180;
export const iMatrix = Object.freeze([1, 0, 0, 1, 0, 0]) as TMat2D;
export const DEFAULT_SVG_FONT_SIZE = 16;
Expand Down
4 changes: 2 additions & 2 deletions src/parser/parseSVGDocument.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ export function parseSVGDocument(doc, callback, reviver, parsingOptions) {
}
parseUseDirectives(doc);

let svgUid = fabric.Object.__uid++, i, len, options = applyViewboxTransform(doc), descendants = fabric.util.toArray(doc.getElementsByTagName('*'));
let svgUid = fabric.Object.__uid++, i, len, options = applyViewboxTransform(doc), descendants = Array.from(doc.getElementsByTagName('*'));
options.crossOrigin = parsingOptions && parsingOptions.crossOrigin;
options.svgUid = svgUid;
options.signal = parsingOptions && parsingOptions.signal;
Expand Down Expand Up @@ -61,7 +61,7 @@ export function parseSVGDocument(doc, callback, reviver, parsingOptions) {
return el.nodeName.replace('svg:', '') === 'clipPath';
}).forEach(function (el) {
const id = el.getAttribute('id');
localClipPaths[id] = fabric.util.toArray(el.getElementsByTagName('*')).filter(function (el) {
localClipPaths[id] = Array.from(el.getElementsByTagName('*')).filter(function (el) {
return svgValidTagNamesRegEx.test(el.nodeName.replace('svg:', ''));
});
});
Expand Down
18 changes: 14 additions & 4 deletions src/point.class.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import { fabric } from '../HEADER';
import { TMat2D, TRadian } from './typedefs';
import { sin } from './util/misc/sin';
import { cos } from './util/misc/cos';

export interface IPoint {
x: number
Expand Down Expand Up @@ -350,16 +352,22 @@ export class Point {

/**
* Rotates `point` around `origin` with `radians`
* WARNING: this is probably a source of circular dependency.
* evaluate what to do when importing rotateVector directly from the file
* @static
* @memberOf fabric.util
* @param {Point} origin The origin of the rotation
* @param {TRadian} radians The radians of the angle for the rotation
* @return {Point} The new rotated point
*/
rotate(origin: Point, radians: TRadian): Point {
return fabric.util.rotateVector(this.subtract(origin), radians).add(origin);
rotate(radians: TRadian, origin: Point = originZero): Point {
// TODO benchmark and verify the add and subtract how much cost
// and then in case early return if no origin is passed
const sinus = sin(radians), cosinus = cos(radians);
const p = this.subtract(origin);
const rotated = new Point(
p.x * cosinus - p.y * sinus,
p.x * sinus + p.y * cosinus,
);
return rotated.add(origin);
}

/**
Expand All @@ -378,4 +386,6 @@ export class Point {
}
}

const originZero = new Point(0, 0);

fabric.Point = Point;
3 changes: 2 additions & 1 deletion src/shadow.class.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import { Color } from "./color";
import { config } from "./config";
import { Point } from "./point.class";

(function(global) {
var fabric = global.fabric || (global.fabric = { }),
Expand Down Expand Up @@ -119,7 +120,7 @@ import { config } from "./config";
toSVG: function(object) {
var fBoxX = 40, fBoxY = 40, NUM_FRACTION_DIGITS = config.NUM_FRACTION_DIGITS,
offset = fabric.util.rotateVector(
{ x: this.offsetX, y: this.offsetY },
new Point(this.offsetX, this.offsetY),
fabric.util.degreesToRadians(-object.angle)),
BLUR_BOX = 20, color = new Color(this.color);

Expand Down
8 changes: 4 additions & 4 deletions src/shapes/image.class.ts
Original file line number Diff line number Diff line change
Expand Up @@ -163,6 +163,7 @@
this._element = element;
this._originalElement = element;
this._initConfig(options);
element.classList.add(fabric.Image.CSS_CANVAS);
if (this.filters.length !== 0) {
this.applyFilters();
}
Expand Down Expand Up @@ -477,7 +478,7 @@
* @param {CanvasRenderingContext2D} ctx Context to render on
*/
_render: function(ctx) {
fabric.util.setImageSmoothing(ctx, this.imageSmoothing);
ctx.imageSmoothingEnabled = this.imageSmoothing;
if (this.isMoving !== true && this.resizeFilter && this._needsResize()) {
this.applyResizeFilters();
}
Expand All @@ -491,7 +492,7 @@
* @param {CanvasRenderingContext2D} ctx Context to render on
*/
drawCacheOnCanvas: function(ctx) {
fabric.util.setImageSmoothing(ctx, this.imageSmoothing);
ctx.imageSmoothingEnabled = this.imageSmoothing;
fabric.Object.prototype.drawCacheOnCanvas.call(this, ctx);
},

Expand Down Expand Up @@ -557,8 +558,7 @@
* @param {Object} [options] Options object
*/
_initElement: function(element, options) {
this.setElement(fabric.util.getById(element), options);
fabric.util.addClass(this.getElement(), fabric.Image.CSS_CANVAS);
this.setElement(fabric.document.getElementById(element) || element, options);
},

/**
Expand Down
20 changes: 11 additions & 9 deletions src/shapes/object.class.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
//@ts-nocheck

import { cache } from '../cache';
import { config } from '../config';
import { VERSION } from '../constants';
import { Point } from '../point.class';
import { capValue } from '../util/misc/capValue';
import { pick } from '../util/misc/pick';
import { runningAnimations } from '../util/animation_registry';

(function(global) {
var fabric = global.fabric || (global.fabric = { }),
Expand Down Expand Up @@ -684,10 +685,9 @@ import { pick } from '../util/misc/pick';
* @return {Object}.zoomY zoomY zoom value to unscale the canvas before drawing cache
*/
_limitCacheSize: function(dims) {
var perfLimitSizeTotal = config.perfLimitSizeTotal,
width = dims.width, height = dims.height,
var width = dims.width, height = dims.height,
max = config.maxCacheSideLimit, min = config.minCacheSideLimit;
if (width <= max && height <= max && width * height <= perfLimitSizeTotal) {
if (width <= max && height <= max && width * height <= config.perfLimitSizeTotal) {
if (width < min) {
dims.width = min;
}
Expand All @@ -696,9 +696,9 @@ import { pick } from '../util/misc/pick';
}
return dims;
}
var ar = width / height, limitedDims = fabric.util.limitDimsByArea(ar, perfLimitSizeTotal),
x = capValue(min, limitedDims.x, max),
y = capValue(min, limitedDims.y, max);
var ar = width / height, [limX, limY] = cache.limitDimsByArea(ar),
x = capValue(min, limX, max),
y = capValue(min, limY, max);
if (width > x) {
dims.zoomX /= width / x;
dims.width = x;
Expand Down Expand Up @@ -1904,8 +1904,10 @@ import { pick } from '../util/misc/pick';
* override if necessary to dispose artifacts such as `clipPath`
*/
dispose: function () {
if (fabric.runningAnimations) {
fabric.runningAnimations.cancelByTarget(this);
// todo verify this.
// runningAnimations is always truthy
if (runningAnimations) {
runningAnimations.cancelByTarget(this);
}
}
});
Expand Down
6 changes: 3 additions & 3 deletions src/static_canvas.class.ts
Original file line number Diff line number Diff line change
Expand Up @@ -310,14 +310,14 @@ import { pick } from './util/misc/pick';
this.lowerCanvasEl = canvasEl;
}
else {
this.lowerCanvasEl = fabric.util.getById(canvasEl) || this._createCanvasElement();
this.lowerCanvasEl = fabric.document.getElementById(canvasEl) || canvasEl || this._createCanvasElement();
}
if (this.lowerCanvasEl.hasAttribute('data-fabric')) {
/* _DEV_MODE_START_ */
throw new Error('fabric.js: trying to initialize a canvas that has already been initialized');
/* _DEV_MODE_END_ */
}
fabric.util.addClass(this.lowerCanvasEl, 'lower-canvas');
this.lowerCanvasEl.classList.add('lower-canvas');
this.lowerCanvasEl.setAttribute('data-fabric', 'main');
if (this.interactive) {
this._originalCanvasStyle = this.lowerCanvasEl.style.cssText;
Expand Down Expand Up @@ -752,7 +752,7 @@ import { pick } from './util/misc/pick';
this.cancelRequestedRender();
this.calcViewportBoundaries();
this.clearContext(ctx);
fabric.util.setImageSmoothing(ctx, this.imageSmoothingEnabled);
ctx.imageSmoothingEnabled = this.imageSmoothingEnabled;
ctx.patternQuality = 'best';
this.fire('before:render', { ctx: ctx, });
this._renderBackground(ctx);
Expand Down
Loading

0 comments on commit a377f54

Please sign in to comment.