Skip to content

Commit

Permalink
chore(TS): extract config values in its own module (#8194)
Browse files Browse the repository at this point in the history
  • Loading branch information
ShaMan123 authored Aug 28, 2022
1 parent d5f2a00 commit cd69a80
Show file tree
Hide file tree
Showing 34 changed files with 459 additions and 298 deletions.
116 changes: 19 additions & 97 deletions HEADER.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,14 @@
/*! Fabric.js Copyright 2008-2015, Printio (Juriy Zaytsev, Maxim Chernyak) */

import { config } from './src/config';
import { iMatrix, VERSION } from './src/constants';

var fabric = fabric || { version: VERSION };
var fabric = fabric || {
version: VERSION,
config,
iMatrix
};

if (typeof exports !== 'undefined') {
exports.fabric = fabric;
}
Expand Down Expand Up @@ -71,95 +77,25 @@ fabric.SHARED_ATTRIBUTES = [
];
/* _FROM_SVG_END_ */

/**
* Pixel per Inch as a default value set to 96. Can be changed for more realistic conversion.
*/
fabric.DPI = 96;

fabric.reNonWord = /[ \n\.,;!\?\-]/;
fabric.fontPaths = { };
fabric.iMatrix = iMatrix;


/**
* Pixel limit for cache canvases. 1Mpx , 4Mpx should be fine.
* @since 1.7.14
* @type Number
* @default
*/
fabric.perfLimitSizeTotal = 2097152;

/**
* Pixel limit for cache canvases width or height. IE fixes the maximum at 5000
* @since 1.7.14
* @type Number
* @default
* @todo move to config when window is exported
*/
fabric.maxCacheSideLimit = 4096;

/**
* Lowest pixel limit for cache canvases, set at 256PX
* @since 1.7.14
* @type Number
* @default
*/
fabric.minCacheSideLimit = 256;
config.configure({
devicePixelRatio: fabric.window.devicePixelRatio ||
fabric.window.webkitDevicePixelRatio ||
fabric.window.mozDevicePixelRatio ||
1
});

/**
* Cache Object for widths of chars in text rendering.
*/
fabric.charWidthsCache = { };

/**
* if webgl is enabled and available, textureSize will determine the size
* of the canvas backend
* @since 2.0.0
* @type Number
* @default
*/
fabric.textureSize = 2048;

/**
* When 'true', style information is not retained when copy/pasting text, making
* pasted text use destination style.
* Defaults to 'false'.
* @type Boolean
* @default
*/
fabric.disableStyleCopyPaste = false;

/**
* Enable webgl for filtering picture is available
* A filtering backend will be initialized, this will both take memory and
* time since a default 2048x2048 canvas will be created for the gl context
* @since 2.0.0
* @type Boolean
* @default
*/
fabric.enableGLFiltering = true;

/**
* Device Pixel Ratio
* @see https://developer.apple.com/library/safari/documentation/AudioVideo/Conceptual/HTML-canvas-guide/SettingUptheCanvas/SettingUptheCanvas.html
*/
fabric.devicePixelRatio = fabric.window.devicePixelRatio ||
fabric.window.webkitDevicePixelRatio ||
fabric.window.mozDevicePixelRatio ||
1;
/**
* Browser-specific constant to adjust CanvasRenderingContext2D.shadowBlur value,
* which is unitless and not rendered equally across browsers.
*
* Values that work quite well (as of October 2017) are:
* - Chrome: 1.5
* - Edge: 1.75
* - Firefox: 0.9
* - Safari: 0.95
*
* @since 2.0.0
* @type Number
* @default 1
*/
fabric.browserShadowBlurConstant = 1;
fabric.charWidthsCache = {};

/**
* This object contains the result of arc to bezier conversion for faster retrieving if the same arc needs to be converted again.
Expand All @@ -177,25 +113,11 @@ fabric.arcToSegmentsCache = { };
*/
fabric.boundsOfCurveCache = { };

/**
* If disabled boundsOfCurveCache is not used. For apps that make heavy usage of pencil drawing probably disabling it is better
* @default true
*/
fabric.cachesBoundsOfCurve = true;

/**
* Skip performance testing of setupGLContext and force the use of putImageData that seems to be the one that works best on
* Chrome + old hardware. if your users are experiencing empty images after filtering you may try to force this to true
* this has to be set before instantiating the filtering backend ( before filtering the first image )
* @type Boolean
* @default false
*/
fabric.forceGLPutImageData = false;

fabric.initFilterBackend = function() {
if (fabric.enableGLFiltering && fabric.isWebglSupported && fabric.isWebglSupported(fabric.textureSize)) {
console.log('max texture size: ' + fabric.maxTextureSize);
return (new fabric.WebglFilterBackend({ tileSize: fabric.textureSize }));
if (config.enableGLFiltering && fabric.isWebglSupported && fabric.isWebglSupported(config.textureSize)) {
console.log(`fabric: max texture size: ${config.maxTextureSize}`);
return (new fabric.WebglFilterBackend({ tileSize: config.textureSize }));
}
else if (fabric.Canvas2dFilterBackend) {
return (new fabric.Canvas2dFilterBackend());
Expand Down
171 changes: 171 additions & 0 deletions src/config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,171 @@
import { TWebGLPrecision } from "./typedefs";

export type TConfiguration = Partial<BaseConfiguration>;

class BaseConfiguration {

/**
* Browser-specific constant to adjust CanvasRenderingContext2D.shadowBlur value,
* which is unitless and not rendered equally across browsers.
*
* Values that work quite well (as of October 2017) are:
* - Chrome: 1.5
* - Edge: 1.75
* - Firefox: 0.9
* - Safari: 0.95
*
* @since 2.0.0
* @type Number
* @default 1
*/
browserShadowBlurConstant = 1


/**
* Pixel per Inch as a default value set to 96. Can be changed for more realistic conversion.
*/
DPI = 96

/**
* Device Pixel Ratio
* @see https://developer.apple.com/library/safari/documentation/AudioVideo/Conceptual/HTML-canvas-guide/SettingUptheCanvas/SettingUptheCanvas.html
*/
devicePixelRatio = 1

/**
* Pixel limit for cache canvases. 1Mpx , 4Mpx should be fine.
* @since 1.7.14
* @type Number
* @default
*/
perfLimitSizeTotal = 2097152

/**
* Pixel limit for cache canvases width or height. IE fixes the maximum at 5000
* @since 1.7.14
* @type Number
* @default
*/
maxCacheSideLimit = 4096

/**
* Lowest pixel limit for cache canvases, set at 256PX
* @since 1.7.14
* @type Number
* @default
*/
minCacheSideLimit = 256

/**
* When 'true', style information is not retained when copy/pasting text, making
* pasted text use destination style.
* Defaults to 'false'.
* @type Boolean
* @default
* @deprecated
*/
disableStyleCopyPaste = false

/**
* Enable webgl for filtering picture is available
* A filtering backend will be initialized, this will both take memory and
* time since a default 2048x2048 canvas will be created for the gl context
* @since 2.0.0
* @type Boolean
* @default
*/
enableGLFiltering = true

/**
* if webgl is enabled and available, textureSize will determine the size
* of the canvas backend
*
* In order to support old hardware set to `2048` to avoid OOM
*
* @since 2.0.0
* @type Number
* @default
*/
textureSize = 4096

/**
* Skip performance testing of setupGLContext and force the use of putImageData that seems to be the one that works best on
* Chrome + old hardware. if your users are experiencing empty images after filtering you may try to force this to true
* this has to be set before instantiating the filtering backend ( before filtering the first image )
* @type Boolean
* @default false
*/
forceGLPutImageData = false

/**
* WebGL
*/
maxTextureSize?: number

/**
* WebGL
*/
webGLPrecision?: TWebGLPrecision

/**
* If disabled boundsOfCurveCache is not used. For apps that make heavy usage of pencil drawing probably disabling it is better
* @default true
*/
cachesBoundsOfCurve = true

/**
* Map of font files
* Map<fontFamily, pathToFile> of font files
*/
fontPaths: Record</** fontFamily */ string, /** pathToFile */ string> = {}

/**
* Defines the number of fraction digits to use when serializing object values.
* Used in exporting methods (`toObject`, `toJSON`, `toSVG`)
* You can use it to increase/decrease precision of such values like left, top, scaleX, scaleY, etc.
*/
NUM_FRACTION_DIGITS = 4
}

export class Configuration extends BaseConfiguration {

constructor(config?: TConfiguration) {
super();
this.configure(config);
}

configure(config: TConfiguration = {}) {
Object.assign(this, config);
}

/**
* Map<fontFamily, pathToFile> of font files
*/
addFonts(paths: Record</** fontFamily */ string, /** pathToFile */ string> = {}) {
this.fontPaths = {
...this.fontPaths,
...paths
};
}

removeFonts(fontFamilys: string[] = []) {
fontFamilys.forEach(fontFamily => {
delete this.fontPaths[fontFamily];
});
}

clearFonts() {
this.fontPaths = {};
}

restoreDefaults<T extends BaseConfiguration>(keys?: (keyof T)[]) {
const defaults = new BaseConfiguration() as T;
const config = keys?.reduce((acc, key) => {
acc[key] = defaults[key];
return acc;
}, {} as T) || defaults;
this.configure(config);
}
}

export const config = new Configuration();
11 changes: 8 additions & 3 deletions src/filters/base_filter.class.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,9 @@
//@ts-nocheck

import { config } from "../config";
import { TWebGLPrecision } from "../typedefs";


(function(global) {
var fabric = global.fabric;
/**
Expand Down Expand Up @@ -72,10 +77,10 @@
createProgram: function(gl, fragmentSource, vertexSource) {
fragmentSource = fragmentSource || this.fragmentSource;
vertexSource = vertexSource || this.vertexSource;
if (fabric.webGlPrecision !== 'highp'){
if (config.webGLPrecision !== TWebGLPrecision.high) {
fragmentSource = fragmentSource.replace(
/precision highp float/g,
'precision ' + fabric.webGlPrecision + ' float'
new RegExp(`precision ${TWebGLPrecision.high} float`,'g'),
`precision ${config.webGLPrecision} float`
);
}
var vertexShader = gl.createShader(gl.VERTEX_SHADER);
Expand Down
25 changes: 13 additions & 12 deletions src/filters/webgl_backend.class.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,15 @@
//@ts-nocheck

import { config } from "../config";
import { TWebGLPrecision, WebGLPrecision } from "../typedefs";


(function(global) {
var fabric = global.fabric;
/**
* Tests if webgl supports certain precision
* @param {WebGL} Canvas WebGL context to test on
* @param {String} Precision to test can be any of following: 'lowp', 'mediump', 'highp'
* @param {TWebGLPrecision} Precision to test can be any of following
* @returns {Boolean} Whether the user's browser WebGL supports given precision.
*/
function testPrecision(gl, precision){
Expand All @@ -31,17 +36,13 @@
var canvas = document.createElement('canvas');
var gl = canvas.getContext('webgl') || canvas.getContext('experimental-webgl');
var isSupported = false;
// eslint-disable-next-line
if (gl) {
fabric.maxTextureSize = gl.getParameter(gl.MAX_TEXTURE_SIZE);
isSupported = fabric.maxTextureSize >= tileSize;
var precisions = ['highp', 'mediump', 'lowp'];
for (var i = 0; i < 3; i++){
if (testPrecision(gl, precisions[i])){
fabric.webGlPrecision = precisions[i];
break;
};
}
config.configure({ maxTextureSize: gl.getParameter(gl.MAX_TEXTURE_SIZE) });
isSupported = config.maxTextureSize >= tileSize;
const percisionKey = WebGLPrecision.find(key => testPrecision(gl, key));
config.configure({
webGLPrecision: percisionKey
});
}
this.isSupported = isSupported;
return isSupported;
Expand Down Expand Up @@ -111,7 +112,7 @@
var targetCanvas = fabric.util.createCanvasElement();
// eslint-disable-next-line no-undef
var imageBuffer = new ArrayBuffer(width * height * 4);
if (fabric.forceGLPutImageData) {
if (config.forceGLPutImageData) {
this.imageBuffer = imageBuffer;
this.copyGLTo2D = copyGLTo2DPutImageData;
return;
Expand Down
Loading

0 comments on commit cd69a80

Please sign in to comment.