Typescript conversion (#1828)

* initial typescript conversion

* test: update overflow+transform ref test

* fix: correctly render pseudo element content

* fix: testrunner build

* fix: karma test urls

* test: update underline tests with <u> elements

* test: update to es6-promise polyfill

* test: remove watch from server

* test: remove flow

* format: update prettier for typescript

* test: update eslint to use typescript parser

* test: update linear gradient reftest

* test: update test runner

* test: update testrunner promise polyfill

* fix: handle display: -webkit-flex correctly (fix #1817)

* fix: correctly render gradients with clip & repeat (fix #1773)

* fix: webkit-gradient function support

* fix: implement radial gradients

* fix: text-decoration rendering

* fix: missing scroll positions for elements

* ci: fix ios 11 tests

* fix: ie logging

* ci: improve device availability logging

* fix: lint errors

* ci: update to ios 12

* fix: check for console availability

* ci: fix build dependency

* test: update text reftests

* fix: window reference for unit tests

* feat: add hsl/hsla color support

* fix: render options

* fix: CSSKeyframesRule cssText Permission Denied on Internet Explorer 11 (#1830)

* fix: option lint

* fix: list type rendering

* test: fix platform import

* fix: ie css parsing for numbers

* ci: add minified build

* fix: form element rendering

* fix: iframe rendering

* fix: re-introduce experimental foreignobject renderer

* fix: text-shadow rendering

* feat: improve logging

* fix: unit test logging

* fix: cleanup resources

* test: update overflow scrolling to work with ie

* build: update build to include typings

* fix: do not parse select element children

* test: fix onclone test to work with older IEs

* test: reduce reftest canvas sizes

* test: remove dynamic setUp from list tests

* test: update linear-gradient tests

* build: remove old source files

* build: update docs dependencies

* build: fix typescript definition path

* ci: include test.js on docs website
This commit is contained in:
Niklas von Hertzen
2019-05-25 15:54:41 -07:00
committed by GitHub
parent 20a797cbeb
commit 522a443055
221 changed files with 13668 additions and 23699 deletions

291
src/render/background.ts Normal file
View File

@@ -0,0 +1,291 @@
import {Bounds} from '../css/layout/bounds';
import {BACKGROUND_ORIGIN} from '../css/property-descriptors/background-origin';
import {ElementContainer} from '../dom/element-container';
import {BACKGROUND_SIZE, BackgroundSizeInfo} from '../css/property-descriptors/background-size';
import {Vector} from './vector';
import {BACKGROUND_REPEAT} from '../css/property-descriptors/background-repeat';
import {getAbsoluteValue, getAbsoluteValueForTuple, isLengthPercentage} from '../css/types/length-percentage';
import {CSSValue, isIdentToken} from '../css/syntax/parser';
import {contentBox, paddingBox} from './box-sizing';
import {Path} from './path';
import {BACKGROUND_CLIP} from '../css/property-descriptors/background-clip';
export const calculateBackgroundPositioningArea = (
backgroundOrigin: BACKGROUND_ORIGIN,
element: ElementContainer
): Bounds => {
if (backgroundOrigin === BACKGROUND_ORIGIN.BORDER_BOX) {
return element.bounds;
}
if (backgroundOrigin === BACKGROUND_ORIGIN.CONTENT_BOX) {
return contentBox(element);
}
return paddingBox(element);
};
export const calculateBackgroundPaintingArea = (backgroundClip: BACKGROUND_CLIP, element: ElementContainer): Bounds => {
if (backgroundClip === BACKGROUND_CLIP.BORDER_BOX) {
return element.bounds;
}
if (backgroundClip === BACKGROUND_CLIP.CONTENT_BOX) {
return contentBox(element);
}
return paddingBox(element);
};
export const calculateBackgroundRendering = (
container: ElementContainer,
index: number,
intrinsicSize: [number | null, number | null, number | null]
): [Path[], number, number, number, number] => {
const backgroundPositioningArea = calculateBackgroundPositioningArea(
getBackgroundValueForIndex(container.styles.backgroundOrigin, index),
container
);
const backgroundPaintingArea = calculateBackgroundPaintingArea(
getBackgroundValueForIndex(container.styles.backgroundClip, index),
container
);
const backgroundImageSize = calculateBackgroundSize(
getBackgroundValueForIndex(container.styles.backgroundSize, index),
intrinsicSize,
backgroundPositioningArea
);
const [sizeWidth, sizeHeight] = backgroundImageSize;
const position = getAbsoluteValueForTuple(
getBackgroundValueForIndex(container.styles.backgroundPosition, index),
backgroundPositioningArea.width - sizeWidth,
backgroundPositioningArea.height - sizeHeight
);
const path = calculateBackgroundRepeatPath(
getBackgroundValueForIndex(container.styles.backgroundRepeat, index),
position,
backgroundImageSize,
backgroundPositioningArea,
backgroundPaintingArea
);
const offsetX = Math.round(backgroundPositioningArea.left + position[0]);
const offsetY = Math.round(backgroundPositioningArea.top + position[1]);
return [path, offsetX, offsetY, sizeWidth, sizeHeight];
};
export const isAuto = (token: CSSValue): boolean => isIdentToken(token) && token.value === BACKGROUND_SIZE.AUTO;
const hasIntrinsicValue = (value: number | null): value is number => typeof value === 'number';
export const calculateBackgroundSize = (
size: BackgroundSizeInfo[],
[intrinsicWidth, intrinsicHeight, intrinsicProportion]: [number | null, number | null, number | null],
bounds: Bounds
): [number, number] => {
const [first, second] = size;
if (isLengthPercentage(first) && second && isLengthPercentage(second)) {
return [getAbsoluteValue(first, bounds.width), getAbsoluteValue(second, bounds.height)];
}
const hasIntrinsicProportion = hasIntrinsicValue(intrinsicProportion);
if (isIdentToken(first) && (first.value === BACKGROUND_SIZE.CONTAIN || first.value === BACKGROUND_SIZE.COVER)) {
if (hasIntrinsicValue(intrinsicProportion)) {
const targetRatio = bounds.width / bounds.height;
return targetRatio < intrinsicProportion !== (first.value === BACKGROUND_SIZE.COVER)
? [bounds.width, bounds.width / intrinsicProportion]
: [bounds.height * intrinsicProportion, bounds.height];
}
return [bounds.width, bounds.height];
}
const hasIntrinsicWidth = hasIntrinsicValue(intrinsicWidth);
const hasIntrinsicHeight = hasIntrinsicValue(intrinsicHeight);
const hasIntrinsicDimensions = hasIntrinsicWidth || hasIntrinsicHeight;
// If the background-size is auto or auto auto:
if (isAuto(first) && (!second || isAuto(second))) {
// If the image has both horizontal and vertical intrinsic dimensions, it's rendered at that size.
if (hasIntrinsicWidth && hasIntrinsicHeight) {
return [intrinsicWidth as number, intrinsicHeight as number];
}
// If the image has no intrinsic dimensions and has no intrinsic proportions,
// it's rendered at the size of the background positioning area.
if (!hasIntrinsicProportion && !hasIntrinsicDimensions) {
return [bounds.width, bounds.height];
}
// TODO If the image has no intrinsic dimensions but has intrinsic proportions, it's rendered as if contain had been specified instead.
// If the image has only one intrinsic dimension and has intrinsic proportions, it's rendered at the size corresponding to that one dimension.
// The other dimension is computed using the specified dimension and the intrinsic proportions.
if (hasIntrinsicDimensions && hasIntrinsicProportion) {
const width = hasIntrinsicWidth
? (intrinsicWidth as number)
: (intrinsicHeight as number) * (intrinsicProportion as number);
const height = hasIntrinsicHeight
? (intrinsicHeight as number)
: (intrinsicWidth as number) / (intrinsicProportion as number);
return [width, height];
}
// If the image has only one intrinsic dimension but has no intrinsic proportions,
// it's rendered using the specified dimension and the other dimension of the background positioning area.
const width = hasIntrinsicWidth ? (intrinsicWidth as number) : bounds.width;
const height = hasIntrinsicHeight ? (intrinsicHeight as number) : bounds.height;
return [width, height];
}
// If the image has intrinsic proportions, it's stretched to the specified dimension.
// The unspecified dimension is computed using the specified dimension and the intrinsic proportions.
if (hasIntrinsicProportion) {
let width = 0;
let height = 0;
if (isLengthPercentage(first)) {
width = getAbsoluteValue(first, bounds.width);
} else if (isLengthPercentage(second)) {
height = getAbsoluteValue(second, bounds.height);
}
if (isAuto(first)) {
width = height * (intrinsicProportion as number);
} else if (!second || isAuto(second)) {
height = width / (intrinsicProportion as number);
}
return [width, height];
}
// If the image has no intrinsic proportions, it's stretched to the specified dimension.
// The unspecified dimension is computed using the image's corresponding intrinsic dimension,
// if there is one. If there is no such intrinsic dimension,
// it becomes the corresponding dimension of the background positioning area.
let width = null;
let height = null;
if (isLengthPercentage(first)) {
width = getAbsoluteValue(first, bounds.width);
} else if (second && isLengthPercentage(second)) {
height = getAbsoluteValue(second, bounds.height);
}
if (width !== null && (!second || isAuto(second))) {
height =
hasIntrinsicWidth && hasIntrinsicHeight
? (width / (intrinsicWidth as number)) * (intrinsicHeight as number)
: bounds.height;
}
if (height !== null && isAuto(first)) {
width =
hasIntrinsicWidth && hasIntrinsicHeight
? (height / (intrinsicHeight as number)) * (intrinsicWidth as number)
: bounds.width;
}
if (width !== null && height !== null) {
return [width, height];
}
throw new Error(`Unable to calculate background-size for element`);
};
export const getBackgroundValueForIndex = <T>(values: T[], index: number): T => {
const value = values[index];
if (typeof value === 'undefined') {
return values[0];
}
return value;
};
export const calculateBackgroundRepeatPath = (
repeat: BACKGROUND_REPEAT,
[x, y]: [number, number],
[width, height]: [number, number],
backgroundPositioningArea: Bounds,
backgroundPaintingArea: Bounds
) => {
switch (repeat) {
case BACKGROUND_REPEAT.REPEAT_X:
return [
new Vector(Math.round(backgroundPositioningArea.left), Math.round(backgroundPositioningArea.top + y)),
new Vector(
Math.round(backgroundPositioningArea.left + backgroundPositioningArea.width),
Math.round(backgroundPositioningArea.top + y)
),
new Vector(
Math.round(backgroundPositioningArea.left + backgroundPositioningArea.width),
Math.round(height + backgroundPositioningArea.top + y)
),
new Vector(
Math.round(backgroundPositioningArea.left),
Math.round(height + backgroundPositioningArea.top + y)
)
];
case BACKGROUND_REPEAT.REPEAT_Y:
return [
new Vector(Math.round(backgroundPositioningArea.left + x), Math.round(backgroundPositioningArea.top)),
new Vector(
Math.round(backgroundPositioningArea.left + x + width),
Math.round(backgroundPositioningArea.top)
),
new Vector(
Math.round(backgroundPositioningArea.left + x + width),
Math.round(backgroundPositioningArea.height + backgroundPositioningArea.top)
),
new Vector(
Math.round(backgroundPositioningArea.left + x),
Math.round(backgroundPositioningArea.height + backgroundPositioningArea.top)
)
];
case BACKGROUND_REPEAT.NO_REPEAT:
return [
new Vector(
Math.round(backgroundPositioningArea.left + x),
Math.round(backgroundPositioningArea.top + y)
),
new Vector(
Math.round(backgroundPositioningArea.left + x + width),
Math.round(backgroundPositioningArea.top + y)
),
new Vector(
Math.round(backgroundPositioningArea.left + x + width),
Math.round(backgroundPositioningArea.top + y + height)
),
new Vector(
Math.round(backgroundPositioningArea.left + x),
Math.round(backgroundPositioningArea.top + y + height)
)
];
default:
return [
new Vector(Math.round(backgroundPaintingArea.left), Math.round(backgroundPaintingArea.top)),
new Vector(
Math.round(backgroundPaintingArea.left + backgroundPaintingArea.width),
Math.round(backgroundPaintingArea.top)
),
new Vector(
Math.round(backgroundPaintingArea.left + backgroundPaintingArea.width),
Math.round(backgroundPaintingArea.height + backgroundPaintingArea.top)
),
new Vector(
Math.round(backgroundPaintingArea.left),
Math.round(backgroundPaintingArea.height + backgroundPaintingArea.top)
)
];
}
};

View File

@@ -0,0 +1,38 @@
import {Vector} from './vector';
import {IPath, PathType, Path} from './path';
const lerp = (a: Vector, b: Vector, t: number): Vector => {
return new Vector(a.x + (b.x - a.x) * t, a.y + (b.y - a.y) * t);
};
export class BezierCurve implements IPath {
type: PathType;
start: Vector;
startControl: Vector;
endControl: Vector;
end: Vector;
constructor(start: Vector, startControl: Vector, endControl: Vector, end: Vector) {
this.type = PathType.BEZIER_CURVE;
this.start = start;
this.startControl = startControl;
this.endControl = endControl;
this.end = end;
}
subdivide(t: number, firstHalf: boolean): BezierCurve {
const ab = lerp(this.start, this.startControl, t);
const bc = lerp(this.startControl, this.endControl, t);
const cd = lerp(this.endControl, this.end, t);
const abbc = lerp(ab, bc, t);
const bccd = lerp(bc, cd, t);
const dest = lerp(abbc, bccd, t);
return firstHalf ? new BezierCurve(this.start, ab, abbc, dest) : new BezierCurve(dest, bccd, cd, this.end);
}
reverse(): BezierCurve {
return new BezierCurve(this.end, this.endControl, this.startControl, this.start);
}
}
export const isBezierCurve = (path: Path): path is BezierCurve => path.type === PathType.BEZIER_CURVE;

66
src/render/border.ts Normal file
View File

@@ -0,0 +1,66 @@
import {Path} from './path';
import {BoundCurves} from './bound-curves';
import {isBezierCurve} from './bezier-curve';
export const parsePathForBorder = (curves: BoundCurves, borderSide: number): Path[] => {
switch (borderSide) {
case 0:
return createPathFromCurves(
curves.topLeftBorderBox,
curves.topLeftPaddingBox,
curves.topRightBorderBox,
curves.topRightPaddingBox
);
case 1:
return createPathFromCurves(
curves.topRightBorderBox,
curves.topRightPaddingBox,
curves.bottomRightBorderBox,
curves.bottomRightPaddingBox
);
case 2:
return createPathFromCurves(
curves.bottomRightBorderBox,
curves.bottomRightPaddingBox,
curves.bottomLeftBorderBox,
curves.bottomLeftPaddingBox
);
case 3:
default:
return createPathFromCurves(
curves.bottomLeftBorderBox,
curves.bottomLeftPaddingBox,
curves.topLeftBorderBox,
curves.topLeftPaddingBox
);
}
};
const createPathFromCurves = (outer1: Path, inner1: Path, outer2: Path, inner2: Path): Path[] => {
const path = [];
if (isBezierCurve(outer1)) {
path.push(outer1.subdivide(0.5, false));
} else {
path.push(outer1);
}
if (isBezierCurve(outer2)) {
path.push(outer2.subdivide(0.5, true));
} else {
path.push(outer2);
}
if (isBezierCurve(inner2)) {
path.push(inner2.subdivide(0.5, true).reverse());
} else {
path.push(inner2);
}
if (isBezierCurve(inner1)) {
path.push(inner1.subdivide(0.5, false).reverse());
} else {
path.push(inner1);
}
return path;
};

241
src/render/bound-curves.ts Normal file
View File

@@ -0,0 +1,241 @@
import {ElementContainer} from '../dom/element-container';
import {getAbsoluteValue, getAbsoluteValueForTuple} from '../css/types/length-percentage';
import {Vector} from './vector';
import {BezierCurve} from './bezier-curve';
import {Path} from './path';
export class BoundCurves {
readonly topLeftBorderBox: Path;
readonly topRightBorderBox: Path;
readonly bottomRightBorderBox: Path;
readonly bottomLeftBorderBox: Path;
readonly topLeftPaddingBox: Path;
readonly topRightPaddingBox: Path;
readonly bottomRightPaddingBox: Path;
readonly bottomLeftPaddingBox: Path;
readonly topLeftContentBox: Path;
readonly topRightContentBox: Path;
readonly bottomRightContentBox: Path;
readonly bottomLeftContentBox: Path;
constructor(element: ElementContainer) {
const styles = element.styles;
const bounds = element.bounds;
let [tlh, tlv] = getAbsoluteValueForTuple(styles.borderTopLeftRadius, bounds.width, bounds.height);
let [trh, trv] = getAbsoluteValueForTuple(styles.borderTopRightRadius, bounds.width, bounds.height);
let [brh, brv] = getAbsoluteValueForTuple(styles.borderBottomRightRadius, bounds.width, bounds.height);
let [blh, blv] = getAbsoluteValueForTuple(styles.borderBottomLeftRadius, bounds.width, bounds.height);
const factors = [];
factors.push((tlh + trh) / bounds.width);
factors.push((blh + brh) / bounds.width);
factors.push((tlv + blv) / bounds.height);
factors.push((trv + brv) / bounds.height);
const maxFactor = Math.max(...factors);
if (maxFactor > 1) {
tlh /= maxFactor;
tlv /= maxFactor;
trh /= maxFactor;
trv /= maxFactor;
brh /= maxFactor;
brv /= maxFactor;
blh /= maxFactor;
blv /= maxFactor;
}
const topWidth = bounds.width - trh;
const rightHeight = bounds.height - brv;
const bottomWidth = bounds.width - brh;
const leftHeight = bounds.height - blv;
const borderTopWidth = styles.borderTopWidth;
const borderRightWidth = styles.borderRightWidth;
const borderBottomWidth = styles.borderBottomWidth;
const borderLeftWidth = styles.borderLeftWidth;
const paddingTop = getAbsoluteValue(styles.paddingTop, element.bounds.width);
const paddingRight = getAbsoluteValue(styles.paddingRight, element.bounds.width);
const paddingBottom = getAbsoluteValue(styles.paddingBottom, element.bounds.width);
const paddingLeft = getAbsoluteValue(styles.paddingLeft, element.bounds.width);
this.topLeftBorderBox =
tlh > 0 || tlv > 0
? getCurvePoints(bounds.left, bounds.top, tlh, tlv, CORNER.TOP_LEFT)
: new Vector(bounds.left, bounds.top);
this.topRightBorderBox =
trh > 0 || trv > 0
? getCurvePoints(bounds.left + topWidth, bounds.top, trh, trv, CORNER.TOP_RIGHT)
: new Vector(bounds.left + bounds.width, bounds.top);
this.bottomRightBorderBox =
brh > 0 || brv > 0
? getCurvePoints(bounds.left + bottomWidth, bounds.top + rightHeight, brh, brv, CORNER.BOTTOM_RIGHT)
: new Vector(bounds.left + bounds.width, bounds.top + bounds.height);
this.bottomLeftBorderBox =
blh > 0 || blv > 0
? getCurvePoints(bounds.left, bounds.top + leftHeight, blh, blv, CORNER.BOTTOM_LEFT)
: new Vector(bounds.left, bounds.top + bounds.height);
this.topLeftPaddingBox =
tlh > 0 || tlv > 0
? getCurvePoints(
bounds.left + borderLeftWidth,
bounds.top + borderTopWidth,
Math.max(0, tlh - borderLeftWidth),
Math.max(0, tlv - borderTopWidth),
CORNER.TOP_LEFT
)
: new Vector(bounds.left + borderLeftWidth, bounds.top + borderTopWidth);
this.topRightPaddingBox =
trh > 0 || trv > 0
? getCurvePoints(
bounds.left + Math.min(topWidth, bounds.width + borderLeftWidth),
bounds.top + borderTopWidth,
topWidth > bounds.width + borderLeftWidth ? 0 : trh - borderLeftWidth,
trv - borderTopWidth,
CORNER.TOP_RIGHT
)
: new Vector(bounds.left + bounds.width - borderRightWidth, bounds.top + borderTopWidth);
this.bottomRightPaddingBox =
brh > 0 || brv > 0
? getCurvePoints(
bounds.left + Math.min(bottomWidth, bounds.width - borderLeftWidth),
bounds.top + Math.min(rightHeight, bounds.height + borderTopWidth),
Math.max(0, brh - borderRightWidth),
brv - borderBottomWidth,
CORNER.BOTTOM_RIGHT
)
: new Vector(
bounds.left + bounds.width - borderRightWidth,
bounds.top + bounds.height - borderBottomWidth
);
this.bottomLeftPaddingBox =
blh > 0 || blv > 0
? getCurvePoints(
bounds.left + borderLeftWidth,
bounds.top + leftHeight,
Math.max(0, blh - borderLeftWidth),
blv - borderBottomWidth,
CORNER.BOTTOM_LEFT
)
: new Vector(bounds.left + borderLeftWidth, bounds.top + bounds.height - borderBottomWidth);
this.topLeftContentBox =
tlh > 0 || tlv > 0
? getCurvePoints(
bounds.left + borderLeftWidth + paddingLeft,
bounds.top + borderTopWidth + paddingTop,
Math.max(0, tlh - (borderLeftWidth + paddingLeft)),
Math.max(0, tlv - (borderTopWidth + paddingTop)),
CORNER.TOP_LEFT
)
: new Vector(bounds.left + borderLeftWidth + paddingLeft, bounds.top + borderTopWidth + paddingTop);
this.topRightContentBox =
trh > 0 || trv > 0
? getCurvePoints(
bounds.left + Math.min(topWidth, bounds.width + borderLeftWidth + paddingLeft),
bounds.top + borderTopWidth + paddingTop,
topWidth > bounds.width + borderLeftWidth + paddingLeft ? 0 : trh - borderLeftWidth + paddingLeft,
trv - (borderTopWidth + paddingTop),
CORNER.TOP_RIGHT
)
: new Vector(
bounds.left + bounds.width - (borderRightWidth + paddingRight),
bounds.top + borderTopWidth + paddingTop
);
this.bottomRightContentBox =
brh > 0 || brv > 0
? getCurvePoints(
bounds.left + Math.min(bottomWidth, bounds.width - (borderLeftWidth + paddingLeft)),
bounds.top + Math.min(rightHeight, bounds.height + borderTopWidth + paddingTop),
Math.max(0, brh - (borderRightWidth + paddingRight)),
brv - (borderBottomWidth + paddingBottom),
CORNER.BOTTOM_RIGHT
)
: new Vector(
bounds.left + bounds.width - (borderRightWidth + paddingRight),
bounds.top + bounds.height - (borderBottomWidth + paddingBottom)
);
this.bottomLeftContentBox =
blh > 0 || blv > 0
? getCurvePoints(
bounds.left + borderLeftWidth + paddingLeft,
bounds.top + leftHeight,
Math.max(0, blh - (borderLeftWidth + paddingLeft)),
blv - (borderBottomWidth + paddingBottom),
CORNER.BOTTOM_LEFT
)
: new Vector(
bounds.left + borderLeftWidth + paddingLeft,
bounds.top + bounds.height - (borderBottomWidth + paddingBottom)
);
}
}
enum CORNER {
TOP_LEFT = 0,
TOP_RIGHT = 1,
BOTTOM_RIGHT = 2,
BOTTOM_LEFT = 3
}
const getCurvePoints = (x: number, y: number, r1: number, r2: number, position: CORNER): BezierCurve => {
const kappa = 4 * ((Math.sqrt(2) - 1) / 3);
const ox = r1 * kappa; // control point offset horizontal
const oy = r2 * kappa; // control point offset vertical
const xm = x + r1; // x-middle
const ym = y + r2; // y-middle
switch (position) {
case CORNER.TOP_LEFT:
return new BezierCurve(
new Vector(x, ym),
new Vector(x, ym - oy),
new Vector(xm - ox, y),
new Vector(xm, y)
);
case CORNER.TOP_RIGHT:
return new BezierCurve(
new Vector(x, y),
new Vector(x + ox, y),
new Vector(xm, ym - oy),
new Vector(xm, ym)
);
case CORNER.BOTTOM_RIGHT:
return new BezierCurve(
new Vector(xm, y),
new Vector(xm, y + oy),
new Vector(x + ox, ym),
new Vector(x, ym)
);
case CORNER.BOTTOM_LEFT:
default:
return new BezierCurve(
new Vector(xm, ym),
new Vector(xm - ox, ym),
new Vector(x, y + oy),
new Vector(x, y)
);
}
};
export const calculateBorderBoxPath = (curves: BoundCurves): Path[] => {
return [curves.topLeftBorderBox, curves.topRightBorderBox, curves.bottomRightBorderBox, curves.bottomLeftBorderBox];
};
export const calculateContentBoxPath = (curves: BoundCurves): Path[] => {
return [
curves.topLeftContentBox,
curves.topRightContentBox,
curves.bottomRightContentBox,
curves.bottomLeftContentBox
];
};
export const calculatePaddingBoxPath = (curves: BoundCurves): Path[] => {
return [
curves.topLeftPaddingBox,
curves.topRightPaddingBox,
curves.bottomRightPaddingBox,
curves.bottomLeftPaddingBox
];
};

31
src/render/box-sizing.ts Normal file
View File

@@ -0,0 +1,31 @@
import {getAbsoluteValue} from '../css/types/length-percentage';
import {Bounds} from '../css/layout/bounds';
import {ElementContainer} from '../dom/element-container';
export const paddingBox = (element: ElementContainer): Bounds => {
const bounds = element.bounds;
const styles = element.styles;
return bounds.add(
styles.borderLeftWidth,
styles.borderTopWidth,
-(styles.borderRightWidth + styles.borderLeftWidth),
-(styles.borderTopWidth + styles.borderBottomWidth)
);
};
export const contentBox = (element: ElementContainer): Bounds => {
const styles = element.styles;
const bounds = element.bounds;
const paddingLeft = getAbsoluteValue(styles.paddingLeft, bounds.width);
const paddingRight = getAbsoluteValue(styles.paddingRight, bounds.width);
const paddingTop = getAbsoluteValue(styles.paddingTop, bounds.width);
const paddingBottom = getAbsoluteValue(styles.paddingBottom, bounds.width);
return bounds.add(
paddingLeft + styles.borderLeftWidth,
paddingTop + styles.borderTopWidth,
-(styles.borderRightWidth + styles.borderLeftWidth + paddingLeft + paddingRight),
-(styles.borderTopWidth + styles.borderBottomWidth + paddingTop + paddingBottom)
);
};

View File

@@ -0,0 +1,706 @@
import {ElementPaint, parseStackingContexts, StackingContext} from '../stacking-context';
import {asString, Color, isTransparent} from '../../css/types/color';
import {Logger} from '../../core/logger';
import {ElementContainer} from '../../dom/element-container';
import {BORDER_STYLE} from '../../css/property-descriptors/border-style';
import {CSSParsedDeclaration} from '../../css/index';
import {TextContainer} from '../../dom/text-container';
import {Path} from '../path';
import {BACKGROUND_CLIP} from '../../css/property-descriptors/background-clip';
import {BoundCurves, calculateBorderBoxPath, calculateContentBoxPath, calculatePaddingBoxPath} from '../bound-curves';
import {isBezierCurve} from '../bezier-curve';
import {Vector} from '../vector';
import {CSSImageType, CSSURLImage, isLinearGradient, isRadialGradient} from '../../css/types/image';
import {parsePathForBorder} from '../border';
import {Cache} from '../../core/cache-storage';
import {calculateBackgroundRendering, getBackgroundValueForIndex} from '../background';
import {isDimensionToken} from '../../css/syntax/parser';
import {TextBounds} from '../../css/layout/text';
import {fromCodePoint, toCodePoints} from 'css-line-break';
import {ImageElementContainer} from '../../dom/replaced-elements/image-element-container';
import {contentBox} from '../box-sizing';
import {CanvasElementContainer} from '../../dom/replaced-elements/canvas-element-container';
import {SVGElementContainer} from '../../dom/replaced-elements/svg-element-container';
import {ReplacedElementContainer} from '../../dom/replaced-elements/index';
import {EffectTarget, IElementEffect, isClipEffect, isTransformEffect} from '../effects';
import {contains} from '../../core/bitwise';
import {calculateGradientDirection, calculateRadius, processColorStops} from '../../css/types/functions/gradient';
import {FIFTY_PERCENT, getAbsoluteValue} from '../../css/types/length-percentage';
import {TEXT_DECORATION_LINE} from '../../css/property-descriptors/text-decoration-line';
import {FontMetrics} from '../font-metrics';
import {DISPLAY} from '../../css/property-descriptors/display';
import {Bounds} from '../../css/layout/bounds';
import {LIST_STYLE_TYPE} from '../../css/property-descriptors/list-style-type';
import {computeLineHeight} from '../../css/property-descriptors/line-height';
import {CHECKBOX, INPUT_COLOR, InputElementContainer, RADIO} from '../../dom/replaced-elements/input-element-container';
import {TEXT_ALIGN} from '../../css/property-descriptors/text-align';
import {TextareaElementContainer} from '../../dom/elements/textarea-element-container';
import {SelectElementContainer} from '../../dom/elements/select-element-container';
import {IFrameElementContainer} from '../../dom/replaced-elements/iframe-element-container';
import {TextShadow} from '../../css/property-descriptors/text-shadow';
export interface RenderOptions {
id: string;
scale: number;
canvas?: HTMLCanvasElement;
backgroundColor: Color | null;
x: number;
y: number;
scrollX: number;
scrollY: number;
width: number;
height: number;
windowWidth: number;
windowHeight: number;
cache: Cache;
}
export class CanvasRenderer {
canvas: HTMLCanvasElement;
ctx: CanvasRenderingContext2D;
options: RenderOptions;
private readonly _activeEffects: IElementEffect[] = [];
private readonly fontMetrics: FontMetrics;
constructor(options: RenderOptions) {
this.canvas = options.canvas ? options.canvas : document.createElement('canvas');
this.ctx = this.canvas.getContext('2d') as CanvasRenderingContext2D;
this.options = options;
this.canvas.width = Math.floor(options.width * options.scale);
this.canvas.height = Math.floor(options.height * options.scale);
this.canvas.style.width = `${options.width}px`;
this.canvas.style.height = `${options.height}px`;
this.fontMetrics = new FontMetrics(document);
this.ctx.scale(this.options.scale, this.options.scale);
this.ctx.translate(-options.x + options.scrollX, -options.y + options.scrollY);
this.ctx.textBaseline = 'bottom';
this._activeEffects = [];
Logger.getInstance(options.id).debug(
`Canvas renderer initialized (${options.width}x${options.height} at ${options.x},${options.y}) with scale ${
options.scale
}`
);
}
applyEffects(effects: IElementEffect[], target: EffectTarget) {
while (this._activeEffects.length) {
this.popEffect();
}
effects.filter(effect => contains(effect.target, target)).forEach(effect => this.applyEffect(effect));
}
applyEffect(effect: IElementEffect) {
this.ctx.save();
if (isTransformEffect(effect)) {
this.ctx.translate(effect.offsetX, effect.offsetY);
this.ctx.transform(
effect.matrix[0],
effect.matrix[1],
effect.matrix[2],
effect.matrix[3],
effect.matrix[4],
effect.matrix[5]
);
this.ctx.translate(-effect.offsetX, -effect.offsetY);
}
if (isClipEffect(effect)) {
this.path(effect.path);
this.ctx.clip();
}
this._activeEffects.push(effect);
}
popEffect() {
this._activeEffects.pop();
this.ctx.restore();
}
async renderStack(stack: StackingContext) {
const styles = stack.element.container.styles;
if (styles.isVisible()) {
this.ctx.globalAlpha = styles.opacity;
await this.renderStackContent(stack);
}
}
async renderNode(paint: ElementPaint) {
if (paint.container.styles.isVisible()) {
await this.renderNodeBackgroundAndBorders(paint);
await this.renderNodeContent(paint);
}
}
renderTextWithLetterSpacing(text: TextBounds, letterSpacing: number) {
if (letterSpacing === 0) {
this.ctx.fillText(text.text, text.bounds.left, text.bounds.top + text.bounds.height);
} else {
const letters = toCodePoints(text.text).map(i => fromCodePoint(i));
letters.reduce((left, letter) => {
this.ctx.fillText(letter, left, text.bounds.top + text.bounds.height);
return left + this.ctx.measureText(letter).width;
}, text.bounds.left);
}
}
private createFontStyle(styles: CSSParsedDeclaration): string[] {
const fontVariant = styles.fontVariant
.filter(variant => variant === 'normal' || variant === 'small-caps')
.join('');
const fontFamily = styles.fontFamily.join(', ');
const fontSize = isDimensionToken(styles.fontSize)
? `${styles.fontSize.number}${styles.fontSize.unit}`
: `${styles.fontSize.number}px`;
return [
[styles.fontStyle, fontVariant, styles.fontWeight, fontSize, fontFamily].join(' '),
fontFamily,
fontSize
];
}
async renderTextNode(text: TextContainer, styles: CSSParsedDeclaration) {
const [font, fontFamily, fontSize] = this.createFontStyle(styles);
this.ctx.font = font;
text.textBounds.forEach(text => {
this.ctx.fillStyle = asString(styles.color);
this.renderTextWithLetterSpacing(text, styles.letterSpacing);
const textShadows: TextShadow = styles.textShadow;
if (textShadows.length && text.text.trim().length) {
textShadows
.slice(0)
.reverse()
.forEach(textShadow => {
this.ctx.shadowColor = asString(textShadow.color);
this.ctx.shadowOffsetX = textShadow.offsetX.number * this.options.scale;
this.ctx.shadowOffsetY = textShadow.offsetY.number * this.options.scale;
this.ctx.shadowBlur = textShadow.blur.number;
this.ctx.fillText(text.text, text.bounds.left, text.bounds.top + text.bounds.height);
});
this.ctx.shadowColor = '';
this.ctx.shadowOffsetX = 0;
this.ctx.shadowOffsetY = 0;
this.ctx.shadowBlur = 0;
}
if (styles.textDecorationLine.length) {
this.ctx.fillStyle = asString(styles.textDecorationColor || styles.color);
styles.textDecorationLine.forEach(textDecorationLine => {
switch (textDecorationLine) {
case TEXT_DECORATION_LINE.UNDERLINE:
// Draws a line at the baseline of the font
// TODO As some browsers display the line as more than 1px if the font-size is big,
// need to take that into account both in position and size
const {baseline} = this.fontMetrics.getMetrics(fontFamily, fontSize);
this.ctx.fillRect(
text.bounds.left,
Math.round(text.bounds.top + baseline),
text.bounds.width,
1
);
break;
case TEXT_DECORATION_LINE.OVERLINE:
this.ctx.fillRect(text.bounds.left, Math.round(text.bounds.top), text.bounds.width, 1);
break;
case TEXT_DECORATION_LINE.LINE_THROUGH:
// TODO try and find exact position for line-through
const {middle} = this.fontMetrics.getMetrics(fontFamily, fontSize);
this.ctx.fillRect(
text.bounds.left,
Math.ceil(text.bounds.top + middle),
text.bounds.width,
1
);
break;
}
});
}
});
}
renderReplacedElement(
container: ReplacedElementContainer,
curves: BoundCurves,
image: HTMLImageElement | HTMLCanvasElement
) {
if (image && container.intrinsicWidth > 0 && container.intrinsicHeight > 0) {
const box = contentBox(container);
const path = calculatePaddingBoxPath(curves);
this.path(path);
this.ctx.save();
this.ctx.clip();
this.ctx.drawImage(
image,
0,
0,
container.intrinsicWidth,
container.intrinsicHeight,
box.left,
box.top,
box.width,
box.height
);
this.ctx.restore();
}
}
async renderNodeContent(paint: ElementPaint) {
this.applyEffects(paint.effects, EffectTarget.CONTENT);
const container = paint.container;
const curves = paint.curves;
const styles = container.styles;
for (const child of container.textNodes) {
await this.renderTextNode(child, styles);
}
if (container instanceof ImageElementContainer) {
try {
const image = await this.options.cache.match(container.src);
this.renderReplacedElement(container, curves, image);
} catch (e) {
Logger.getInstance(this.options.id).error(`Error loading image ${container.src}`);
}
}
if (container instanceof CanvasElementContainer) {
this.renderReplacedElement(container, curves, container.canvas);
}
if (container instanceof SVGElementContainer) {
try {
const image = await this.options.cache.match(container.svg);
this.renderReplacedElement(container, curves, image);
} catch (e) {
Logger.getInstance(this.options.id).error(`Error loading svg ${container.svg.substring(0, 255)}`);
}
}
if (container instanceof IFrameElementContainer && container.tree) {
const iframeRenderer = new CanvasRenderer({
id: this.options.id,
scale: this.options.scale,
backgroundColor: container.backgroundColor,
x: 0,
y: 0,
scrollX: 0,
scrollY: 0,
width: container.width,
height: container.height,
cache: this.options.cache,
windowWidth: container.width,
windowHeight: container.height
});
const canvas = await iframeRenderer.render(container.tree);
this.ctx.drawImage(
canvas,
0,
0,
container.width,
container.width,
container.bounds.left,
container.bounds.top,
container.bounds.width,
container.bounds.height
);
}
if (container instanceof InputElementContainer) {
const size = Math.min(container.bounds.width, container.bounds.height);
if (container.type === CHECKBOX) {
if (container.checked) {
this.ctx.save();
this.path([
new Vector(container.bounds.left + size * 0.39363, container.bounds.top + size * 0.79),
new Vector(container.bounds.left + size * 0.16, container.bounds.top + size * 0.5549),
new Vector(container.bounds.left + size * 0.27347, container.bounds.top + size * 0.44071),
new Vector(container.bounds.left + size * 0.39694, container.bounds.top + size * 0.5649),
new Vector(container.bounds.left + size * 0.72983, container.bounds.top + size * 0.23),
new Vector(container.bounds.left + size * 0.84, container.bounds.top + size * 0.34085),
new Vector(container.bounds.left + size * 0.39363, container.bounds.top + size * 0.79)
]);
this.ctx.fillStyle = asString(INPUT_COLOR);
this.ctx.fill();
this.ctx.restore();
}
} else if (container.type === RADIO) {
if (container.checked) {
this.ctx.save();
this.ctx.beginPath();
this.ctx.arc(
container.bounds.left + size / 2,
container.bounds.top + size / 2,
size / 4,
0,
Math.PI * 2,
true
);
this.ctx.fillStyle = asString(INPUT_COLOR);
this.ctx.fill();
this.ctx.restore();
}
}
}
if (isTextInputElement(container) && container.value.length) {
[this.ctx.font] = this.createFontStyle(styles);
this.ctx.fillStyle = asString(styles.color);
this.ctx.textBaseline = 'middle';
this.ctx.textAlign = canvasTextAlign(container.styles.textAlign);
const bounds = contentBox(container);
let x = 0;
switch (container.styles.textAlign) {
case TEXT_ALIGN.CENTER:
x += bounds.width / 2;
break;
case TEXT_ALIGN.RIGHT:
x += bounds.width;
break;
}
const textBounds = bounds.add(x, 0, 0, -bounds.height / 2 + 1);
this.ctx.save();
this.path([
new Vector(bounds.left, bounds.top),
new Vector(bounds.left + bounds.width, bounds.top),
new Vector(bounds.left + bounds.width, bounds.top + bounds.height),
new Vector(bounds.left, bounds.top + bounds.height)
]);
this.ctx.clip();
this.renderTextWithLetterSpacing(new TextBounds(container.value, textBounds), styles.letterSpacing);
this.ctx.restore();
this.ctx.textBaseline = 'bottom';
this.ctx.textAlign = 'left';
}
if (contains(container.styles.display, DISPLAY.LIST_ITEM)) {
if (container.styles.listStyleImage !== null) {
const img = container.styles.listStyleImage;
if (img.type === CSSImageType.URL) {
let image;
const url = (img as CSSURLImage).url;
try {
image = await this.options.cache.match(url);
this.ctx.drawImage(image, container.bounds.left - (image.width + 10), container.bounds.top);
} catch (e) {
Logger.getInstance(this.options.id).error(`Error loading list-style-image ${url}`);
}
}
} else if (paint.listValue && container.styles.listStyleType !== LIST_STYLE_TYPE.NONE) {
[this.ctx.font] = this.createFontStyle(styles);
this.ctx.fillStyle = asString(styles.color);
this.ctx.textBaseline = 'middle';
this.ctx.textAlign = 'right';
const bounds = new Bounds(
container.bounds.left,
container.bounds.top + getAbsoluteValue(container.styles.paddingTop, container.bounds.width),
container.bounds.width,
computeLineHeight(styles.lineHeight, styles.fontSize.number) / 2 + 1
);
this.renderTextWithLetterSpacing(new TextBounds(paint.listValue, bounds), styles.letterSpacing);
this.ctx.textBaseline = 'bottom';
this.ctx.textAlign = 'left';
}
}
}
async renderStackContent(stack: StackingContext) {
// https://www.w3.org/TR/css-position-3/#painting-order
// 1. the background and borders of the element forming the stacking context.
await this.renderNodeBackgroundAndBorders(stack.element);
// 2. the child stacking contexts with negative stack levels (most negative first).
for (const child of stack.negativeZIndex) {
await this.renderStack(child);
}
// 3. For all its in-flow, non-positioned, block-level descendants in tree order:
await this.renderNodeContent(stack.element);
for (const child of stack.nonInlineLevel) {
await this.renderNode(child);
}
// 4. All non-positioned floating descendants, in tree order. For each one of these,
// treat the element as if it created a new stacking context, but any positioned descendants and descendants
// which actually create a new stacking context should be considered part of the parent stacking context,
// not this new one.
for (const child of stack.nonPositionedFloats) {
await this.renderStack(child);
}
// 5. the in-flow, inline-level, non-positioned descendants, including inline tables and inline blocks.
for (const child of stack.nonPositionedInlineLevel) {
await this.renderStack(child);
}
for (const child of stack.inlineLevel) {
await this.renderNode(child);
}
// 6. All positioned, opacity or transform descendants, in tree order that fall into the following categories:
// All positioned descendants with 'z-index: auto' or 'z-index: 0', in tree order.
// For those with 'z-index: auto', treat the element as if it created a new stacking context,
// but any positioned descendants and descendants which actually create a new stacking context should be
// considered part of the parent stacking context, not this new one. For those with 'z-index: 0',
// treat the stacking context generated atomically.
//
// All opacity descendants with opacity less than 1
//
// All transform descendants with transform other than none
for (const child of stack.zeroOrAutoZIndexOrTransformedOrOpacity) {
await this.renderStack(child);
}
// 7. Stacking contexts formed by positioned descendants with z-indices greater than or equal to 1 in z-index
// order (smallest first) then tree order.
for (const child of stack.positiveZIndex) {
await this.renderStack(child);
}
}
path(paths: Path[]) {
this.ctx.beginPath();
paths.forEach((point, index) => {
const start: Vector = isBezierCurve(point) ? point.start : point;
if (index === 0) {
this.ctx.moveTo(start.x, start.y);
} else {
this.ctx.lineTo(start.x, start.y);
}
if (isBezierCurve(point)) {
this.ctx.bezierCurveTo(
point.startControl.x,
point.startControl.y,
point.endControl.x,
point.endControl.y,
point.end.x,
point.end.y
);
}
});
this.ctx.closePath();
}
renderRepeat(path: Path[], pattern: CanvasPattern | CanvasGradient, offsetX: number, offsetY: number) {
this.path(path);
this.ctx.fillStyle = pattern;
this.ctx.translate(offsetX, offsetY);
this.ctx.fill();
this.ctx.translate(-offsetX, -offsetY);
}
resizeImage(image: HTMLImageElement, width: number, height: number): HTMLCanvasElement | HTMLImageElement {
if (image.width === width && image.height === height) {
return image;
}
const canvas = (this.canvas.ownerDocument as Document).createElement('canvas');
canvas.width = width;
canvas.height = height;
const ctx = canvas.getContext('2d') as CanvasRenderingContext2D;
ctx.drawImage(image, 0, 0, image.width, image.height, 0, 0, width, height);
return canvas;
}
async renderBackgroundImage(container: ElementContainer) {
let index = container.styles.backgroundImage.length - 1;
for (const backgroundImage of container.styles.backgroundImage.slice(0).reverse()) {
if (backgroundImage.type === CSSImageType.URL) {
let image;
const url = (backgroundImage as CSSURLImage).url;
try {
image = await this.options.cache.match(url);
} catch (e) {
Logger.getInstance(this.options.id).error(`Error loading background-image ${url}`);
}
if (image) {
const [path, x, y, width, height] = calculateBackgroundRendering(container, index, [
image.width,
image.height,
image.width / image.height
]);
const pattern = this.ctx.createPattern(
this.resizeImage(image, width, height),
'repeat'
) as CanvasPattern;
this.renderRepeat(path, pattern, x, y);
}
} else if (isLinearGradient(backgroundImage)) {
const [path, x, y, width, height] = calculateBackgroundRendering(container, index, [null, null, null]);
const [lineLength, x0, x1, y0, y1] = calculateGradientDirection(backgroundImage.angle, width, height);
const canvas = document.createElement('canvas');
canvas.width = width;
canvas.height = height;
const ctx = canvas.getContext('2d') as CanvasRenderingContext2D;
const gradient = ctx.createLinearGradient(x0, y0, x1, y1);
processColorStops(backgroundImage.stops, lineLength).forEach(colorStop =>
gradient.addColorStop(colorStop.stop, asString(colorStop.color))
);
ctx.fillStyle = gradient;
ctx.fillRect(0, 0, width, height);
const pattern = this.ctx.createPattern(canvas, 'repeat') as CanvasPattern;
this.renderRepeat(path, pattern, x, y);
} else if (isRadialGradient(backgroundImage)) {
const [path, left, top, width, height] = calculateBackgroundRendering(container, index, [
null,
null,
null
]);
const position = backgroundImage.position.length === 0 ? [FIFTY_PERCENT] : backgroundImage.position;
const x = getAbsoluteValue(position[0], width);
const y = getAbsoluteValue(position[position.length - 1], height);
const [rx, ry] = calculateRadius(backgroundImage, x, y, width, height);
if (rx > 0 && rx > 0) {
const radialGradient = this.ctx.createRadialGradient(left + x, top + y, 0, left + x, top + y, rx);
processColorStops(backgroundImage.stops, rx * 2).forEach(colorStop =>
radialGradient.addColorStop(colorStop.stop, asString(colorStop.color))
);
this.path(path);
this.ctx.fillStyle = radialGradient;
if (rx !== ry) {
// transforms for elliptical radial gradient
const midX = container.bounds.left + 0.5 * container.bounds.width;
const midY = container.bounds.top + 0.5 * container.bounds.height;
const f = ry / rx;
const invF = 1 / f;
this.ctx.save();
this.ctx.translate(midX, midY);
this.ctx.transform(1, 0, 0, f, 0, 0);
this.ctx.translate(-midX, -midY);
this.ctx.fillRect(left, invF * (top - midY) + midY, width, height * invF);
this.ctx.restore();
} else {
this.ctx.fill();
}
}
}
index--;
}
}
async renderBorder(color: Color, side: number, curvePoints: BoundCurves) {
this.path(parsePathForBorder(curvePoints, side));
this.ctx.fillStyle = asString(color);
this.ctx.fill();
}
async renderNodeBackgroundAndBorders(paint: ElementPaint) {
this.applyEffects(paint.effects, EffectTarget.BACKGROUND_BORDERS);
const styles = paint.container.styles;
const hasBackground = !isTransparent(styles.backgroundColor) || styles.backgroundImage.length;
const borders = [
{style: styles.borderTopStyle, color: styles.borderTopColor},
{style: styles.borderRightStyle, color: styles.borderRightColor},
{style: styles.borderBottomStyle, color: styles.borderBottomColor},
{style: styles.borderLeftStyle, color: styles.borderLeftColor}
];
const backgroundPaintingArea = calculateBackgroundCurvedPaintingArea(
getBackgroundValueForIndex(styles.backgroundClip, 0),
paint.curves
);
if (hasBackground) {
this.ctx.save();
this.path(backgroundPaintingArea);
this.ctx.clip();
if (!isTransparent(styles.backgroundColor)) {
this.ctx.fillStyle = asString(styles.backgroundColor);
this.ctx.fill();
}
await this.renderBackgroundImage(paint.container);
this.ctx.restore();
}
let side = 0;
for (const border of borders) {
if (border.style !== BORDER_STYLE.NONE && !isTransparent(border.color)) {
await this.renderBorder(border.color, side++, paint.curves);
}
}
}
async render(element: ElementContainer): Promise<HTMLCanvasElement> {
if (this.options.backgroundColor) {
this.ctx.fillStyle = asString(this.options.backgroundColor);
this.ctx.fillRect(
this.options.x - this.options.scrollX,
this.options.y - this.options.scrollY,
this.options.width,
this.options.height
);
}
const stack = parseStackingContexts(element);
await this.renderStack(stack);
this.applyEffects([], EffectTarget.BACKGROUND_BORDERS);
return this.canvas;
}
}
const isTextInputElement = (
container: ElementContainer
): container is InputElementContainer | TextareaElementContainer | SelectElementContainer => {
if (container instanceof TextareaElementContainer) {
return true;
} else if (container instanceof SelectElementContainer) {
return true;
} else if (container instanceof InputElementContainer && container.type !== RADIO && container.type !== CHECKBOX) {
return true;
}
return false;
};
const calculateBackgroundCurvedPaintingArea = (clip: BACKGROUND_CLIP, curves: BoundCurves): Path[] => {
switch (clip) {
case BACKGROUND_CLIP.BORDER_BOX:
return calculateBorderBoxPath(curves);
case BACKGROUND_CLIP.CONTENT_BOX:
return calculateContentBoxPath(curves);
case BACKGROUND_CLIP.PADDING_BOX:
default:
return calculatePaddingBoxPath(curves);
}
};
const canvasTextAlign = (textAlign: TEXT_ALIGN): CanvasTextAlign => {
switch (textAlign) {
case TEXT_ALIGN.CENTER:
return 'center';
case TEXT_ALIGN.RIGHT:
return 'right';
case TEXT_ALIGN.LEFT:
default:
return 'left';
}
};

View File

@@ -0,0 +1,60 @@
import {RenderOptions} from './canvas-renderer';
import {Logger} from '../../core/logger';
import {createForeignObjectSVG} from '../../core/features';
import {asString} from '../../css/types/color';
export class ForeignObjectRenderer {
canvas: HTMLCanvasElement;
ctx: CanvasRenderingContext2D;
options: RenderOptions;
constructor(options: RenderOptions) {
this.canvas = options.canvas ? options.canvas : document.createElement('canvas');
this.ctx = this.canvas.getContext('2d') as CanvasRenderingContext2D;
this.options = options;
this.canvas.width = Math.floor(options.width * options.scale);
this.canvas.height = Math.floor(options.height * options.scale);
this.canvas.style.width = `${options.width}px`;
this.canvas.style.height = `${options.height}px`;
this.ctx.scale(this.options.scale, this.options.scale);
this.ctx.translate(-options.x + options.scrollX, -options.y + options.scrollY);
Logger.getInstance(options.id).debug(
`EXPERIMENTAL ForeignObject renderer initialized (${options.width}x${options.height} at ${options.x},${
options.y
}) with scale ${options.scale}`
);
}
async render(element: HTMLElement) {
const svg = createForeignObjectSVG(
Math.max(this.options.windowWidth, this.options.width) * this.options.scale,
Math.max(this.options.windowHeight, this.options.height) * this.options.scale,
this.options.scrollX * this.options.scale,
this.options.scrollY * this.options.scale,
element
);
const img = await loadSerializedSVG(svg);
if (this.options.backgroundColor) {
this.ctx.fillStyle = asString(this.options.backgroundColor);
this.ctx.fillRect(0, 0, this.options.width * this.options.scale, this.options.height * this.options.scale);
}
this.ctx.drawImage(img, -this.options.x * this.options.scale, -this.options.y * this.options.scale);
return this.canvas;
}
}
export const loadSerializedSVG = (svg: Node): Promise<HTMLImageElement> =>
new Promise((resolve, reject) => {
const img = new Image();
img.onload = () => {
resolve(img);
};
img.onerror = reject;
img.src = `data:image/svg+xml;charset=utf-8,${encodeURIComponent(new XMLSerializer().serializeToString(svg))}`;
});

49
src/render/effects.ts Normal file
View File

@@ -0,0 +1,49 @@
import {Matrix} from '../css/property-descriptors/transform';
import {Path} from './path';
export const enum EffectType {
TRANSFORM = 0,
CLIP = 1
}
export const enum EffectTarget {
BACKGROUND_BORDERS = 1 << 1,
CONTENT = 1 << 2
}
export interface IElementEffect {
readonly type: EffectType;
readonly target: number;
}
export class TransformEffect implements IElementEffect {
readonly type: EffectType;
readonly target: number;
readonly offsetX: number;
readonly offsetY: number;
readonly matrix: Matrix;
constructor(offsetX: number, offsetY: number, matrix: Matrix) {
this.type = EffectType.TRANSFORM;
this.offsetX = offsetX;
this.offsetY = offsetY;
this.matrix = matrix;
this.target = EffectTarget.BACKGROUND_BORDERS | EffectTarget.CONTENT;
}
}
export class ClipEffect implements IElementEffect {
readonly type: EffectType;
readonly target: number;
readonly path: Path[];
constructor(path: Path[], target: EffectTarget) {
this.type = EffectType.CLIP;
this.target = target;
this.path = path;
}
}
export const isTransformEffect = (effect: IElementEffect): effect is TransformEffect =>
effect.type === EffectType.TRANSFORM;
export const isClipEffect = (effect: IElementEffect): effect is ClipEffect => effect.type === EffectType.CLIP;

View File

@@ -0,0 +1,71 @@
import {SMALL_IMAGE} from '../core/util';
export interface FontMetric {
baseline: number;
middle: number;
}
const SAMPLE_TEXT = 'Hidden Text';
export class FontMetrics {
private readonly _data: {[key: string]: FontMetric};
private readonly _document: Document;
constructor(document: Document) {
this._data = {};
this._document = document;
}
private parseMetrics(fontFamily: string, fontSize: string): FontMetric {
const container = this._document.createElement('div');
const img = this._document.createElement('img');
const span = this._document.createElement('span');
const body = this._document.body as HTMLBodyElement;
container.style.visibility = 'hidden';
container.style.fontFamily = fontFamily;
container.style.fontSize = fontSize;
container.style.margin = '0';
container.style.padding = '0';
body.appendChild(container);
img.src = SMALL_IMAGE;
img.width = 1;
img.height = 1;
img.style.margin = '0';
img.style.padding = '0';
img.style.verticalAlign = 'baseline';
span.style.fontFamily = fontFamily;
span.style.fontSize = fontSize;
span.style.margin = '0';
span.style.padding = '0';
span.appendChild(this._document.createTextNode(SAMPLE_TEXT));
container.appendChild(span);
container.appendChild(img);
const baseline = img.offsetTop - span.offsetTop + 2;
container.removeChild(span);
container.appendChild(this._document.createTextNode(SAMPLE_TEXT));
container.style.lineHeight = 'normal';
img.style.verticalAlign = 'super';
const middle = img.offsetTop - container.offsetTop + 2;
body.removeChild(container);
return {baseline, middle};
}
getMetrics(fontFamily: string, fontSize: string): FontMetric {
const key = `${fontFamily} ${fontSize}`;
if (typeof this._data[key] === 'undefined') {
this._data[key] = this.parseMetrics(fontFamily, fontSize);
}
return this._data[key];
}
}

20
src/render/path.ts Normal file
View File

@@ -0,0 +1,20 @@
import {BezierCurve} from './bezier-curve';
import {Vector} from './vector';
export enum PathType {
VECTOR = 0,
BEZIER_CURVE = 1
}
export interface IPath {
type: PathType;
}
export const equalPath = (a: Path[], b: Path[]): boolean => {
if (a.length === b.length) {
return a.some((v, i) => v === b[i]);
}
return false;
};
export type Path = Vector | BezierCurve;

View File

@@ -0,0 +1,182 @@
import {ElementContainer, FLAGS} from '../dom/element-container';
import {contains} from '../core/bitwise';
import {BoundCurves, calculateBorderBoxPath, calculatePaddingBoxPath} from './bound-curves';
import {ClipEffect, EffectTarget, IElementEffect, TransformEffect} from './effects';
import {OVERFLOW} from '../css/property-descriptors/overflow';
import {equalPath} from './path';
import {DISPLAY} from '../css/property-descriptors/display';
import {OLElementContainer} from '../dom/elements/ol-element-container';
import {LIElementContainer} from '../dom/elements/li-element-container';
import {createCounterText} from '../css/types/functions/counter';
export class StackingContext {
element: ElementPaint;
negativeZIndex: StackingContext[];
zeroOrAutoZIndexOrTransformedOrOpacity: StackingContext[];
positiveZIndex: StackingContext[];
nonPositionedFloats: StackingContext[];
nonPositionedInlineLevel: StackingContext[];
inlineLevel: ElementPaint[];
nonInlineLevel: ElementPaint[];
constructor(container: ElementPaint) {
this.element = container;
this.inlineLevel = [];
this.nonInlineLevel = [];
this.negativeZIndex = [];
this.zeroOrAutoZIndexOrTransformedOrOpacity = [];
this.positiveZIndex = [];
this.nonPositionedFloats = [];
this.nonPositionedInlineLevel = [];
}
}
export class ElementPaint {
container: ElementContainer;
effects: IElementEffect[];
curves: BoundCurves;
listValue?: string;
constructor(element: ElementContainer, parentStack: IElementEffect[]) {
this.container = element;
this.effects = parentStack.slice(0);
this.curves = new BoundCurves(element);
if (element.styles.transform !== null) {
const offsetX = element.bounds.left + element.styles.transformOrigin[0].number;
const offsetY = element.bounds.top + element.styles.transformOrigin[1].number;
const matrix = element.styles.transform;
this.effects.push(new TransformEffect(offsetX, offsetY, matrix));
}
if (element.styles.overflow !== OVERFLOW.VISIBLE) {
const borderBox = calculateBorderBoxPath(this.curves);
const paddingBox = calculatePaddingBoxPath(this.curves);
if (equalPath(borderBox, paddingBox)) {
this.effects.push(new ClipEffect(borderBox, EffectTarget.BACKGROUND_BORDERS | EffectTarget.CONTENT));
} else {
this.effects.push(new ClipEffect(borderBox, EffectTarget.BACKGROUND_BORDERS));
this.effects.push(new ClipEffect(paddingBox, EffectTarget.CONTENT));
}
}
}
getParentEffects(): IElementEffect[] {
const effects = this.effects.slice(0);
if (this.container.styles.overflow !== OVERFLOW.VISIBLE) {
const borderBox = calculateBorderBoxPath(this.curves);
const paddingBox = calculatePaddingBoxPath(this.curves);
if (!equalPath(borderBox, paddingBox)) {
effects.push(new ClipEffect(paddingBox, EffectTarget.BACKGROUND_BORDERS | EffectTarget.CONTENT));
}
}
return effects;
}
}
const parseStackTree = (
parent: ElementPaint,
stackingContext: StackingContext,
realStackingContext: StackingContext,
listItems: ElementPaint[]
) => {
parent.container.elements.forEach(child => {
const treatAsRealStackingContext = contains(child.flags, FLAGS.CREATES_REAL_STACKING_CONTEXT);
const createsStackingContext = contains(child.flags, FLAGS.CREATES_STACKING_CONTEXT);
const paintContainer = new ElementPaint(child, parent.getParentEffects());
if (contains(child.styles.display, DISPLAY.LIST_ITEM)) {
listItems.push(paintContainer);
}
const listOwnerItems = contains(child.flags, FLAGS.IS_LIST_OWNER) ? [] : listItems;
if (treatAsRealStackingContext || createsStackingContext) {
const parentStack =
treatAsRealStackingContext || child.styles.isPositioned() ? realStackingContext : stackingContext;
const stack = new StackingContext(paintContainer);
if (child.styles.isPositioned() || child.styles.opacity < 1 || child.styles.isTransformed()) {
const order = child.styles.zIndex.order;
if (order < 0) {
let index = 0;
parentStack.negativeZIndex.some((current, i) => {
if (order > current.element.container.styles.zIndex.order) {
index = i;
return true;
}
return false;
});
parentStack.negativeZIndex.splice(index, 0, stack);
} else if (order > 0) {
let index = 0;
parentStack.positiveZIndex.some((current, i) => {
if (order > current.element.container.styles.zIndex.order) {
index = i + 1;
return true;
}
return false;
});
parentStack.positiveZIndex.splice(index, 0, stack);
} else {
parentStack.zeroOrAutoZIndexOrTransformedOrOpacity.push(stack);
}
} else {
if (child.styles.isFloating()) {
parentStack.nonPositionedFloats.push(stack);
} else {
parentStack.nonPositionedInlineLevel.push(stack);
}
}
parseStackTree(
paintContainer,
stack,
treatAsRealStackingContext ? stack : realStackingContext,
listOwnerItems
);
} else {
if (child.styles.isInlineLevel()) {
stackingContext.inlineLevel.push(paintContainer);
} else {
stackingContext.nonInlineLevel.push(paintContainer);
}
parseStackTree(paintContainer, stackingContext, realStackingContext, listOwnerItems);
}
if (contains(child.flags, FLAGS.IS_LIST_OWNER)) {
processListItems(child, listOwnerItems);
}
});
};
const processListItems = (owner: ElementContainer, elements: ElementPaint[]) => {
let numbering = owner instanceof OLElementContainer ? owner.start : 1;
const reversed = owner instanceof OLElementContainer ? owner.reversed : false;
for (let i = 0; i < elements.length; i++) {
const item = elements[i];
if (
item.container instanceof LIElementContainer &&
typeof item.container.value === 'number' &&
item.container.value !== 0
) {
numbering = item.container.value;
}
item.listValue = createCounterText(numbering, item.container.styles.listStyleType, true);
numbering += reversed ? -1 : 1;
}
};
export const parseStackingContexts = (container: ElementContainer): StackingContext => {
const paintContainer = new ElementPaint(container, []);
const root = new StackingContext(paintContainer);
const listItems: ElementPaint[] = [];
parseStackTree(paintContainer, root, root, listItems);
processListItems(paintContainer.container, listItems);
return root;
};

15
src/render/vector.ts Normal file
View File

@@ -0,0 +1,15 @@
import {IPath, Path, PathType} from './path';
export class Vector implements IPath {
type: PathType;
x: number;
y: number;
constructor(x: number, y: number) {
this.type = PathType.VECTOR;
this.x = x;
this.y = y;
}
}
export const isVector = (path: Path): path is Vector => path.type === PathType.VECTOR;