Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

zrender

Package Overview
Dependencies
Maintainers
11
Versions
76
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

zrender - npm Package Compare versions

Comparing version 5.0.4 to 5.1.0

6

index.js
export * from './lib/zrender';
export * from './lib/export';
import './lib/svg/svg';
import {registerPainter} from './lib/zrender';
import CanvasPainter from './lib/canvas/Painter';
import SVGPainter from './lib/svg/Painter';
registerPainter('canvas', CanvasPainter);
registerPainter('svg', SVGPainter);

2

lib/animation/Animator.js

@@ -238,3 +238,3 @@ import Clip from './Clip';

}
else if (typeof value !== 'number') {
else if (typeof value !== 'number' || isNaN(value)) {
this.interpolable = false;

@@ -241,0 +241,0 @@ return;

@@ -48,3 +48,4 @@ import { DEFAULT_COMMON_STYLE } from '../graphic/Displayable';

var canvasPattern = ctx.createPattern(image, pattern.repeat || 'repeat');
if (typeof DOMMatrix === 'function') {
if (typeof DOMMatrix === 'function'
&& canvasPattern.setTransform) {
var matrix = new DOMMatrix();

@@ -292,3 +293,4 @@ matrix.rotateSelf(0, 0, (pattern.rotation || 0) / Math.PI * 180);

}
ctx.globalAlpha = style.opacity == null ? DEFAULT_COMMON_STYLE.opacity : style.opacity;
var opacity = Math.max(Math.min(style.opacity, 1), 0);
ctx.globalAlpha = isNaN(opacity) ? DEFAULT_COMMON_STYLE.opacity : opacity;
}

@@ -295,0 +297,0 @@ if (forceSetAll || style.blend !== prevStyle.blend) {

@@ -19,4 +19,6 @@ declare class Browser {

domSupported: boolean;
transformSupported: boolean;
transform3dSupported: boolean;
}
declare const env: Env;
export default env;

@@ -22,2 +22,4 @@ var Browser = (function () {

this.domSupported = false;
this.transformSupported = false;
this.transform3dSupported = false;
}

@@ -73,3 +75,11 @@ return Env;

env.domSupported = typeof document !== 'undefined';
var style = document.documentElement.style;
env.transform3dSupported = ((browser.ie && 'transition' in style)
|| browser.edge
|| (('WebKitCSSMatrix' in window) && ('m11' in new WebKitCSSMatrix()))
|| 'MozPerspective' in style)
&& !('OTransition' in style);
env.transformSupported = env.transform3dSupported
|| (browser.ie && +browser.version >= 9);
}
export default env;

@@ -76,3 +76,5 @@ import { Dictionary, ArrayLike, KeyOfDistributive } from './types';

};
constructor(obj?: HashMap<T, KEY> | Dictionary<T> | any[]);
constructor(obj?: HashMap<T, KEY> | {
[key in KEY]?: T;
} | KEY[]);
get(key: KEY): T;

@@ -84,3 +86,5 @@ set(key: KEY, value: T): T;

}
export declare function createHashMap<T, KEY extends string | number = string | number>(obj?: HashMap<T, KEY> | Dictionary<T> | any[]): HashMap<T, KEY>;
export declare function createHashMap<T, KEY extends string | number = string | number>(obj?: HashMap<T, KEY> | {
[key in KEY]?: T;
} | KEY[]): HashMap<T, KEY>;
export declare function concatArray<T, R>(a: ArrayLike<T>, b: ArrayLike<R>): ArrayLike<T | R>;

@@ -87,0 +91,0 @@ export declare function createObject<T>(proto?: object, properties?: T): T;

@@ -156,5 +156,5 @@ import Transformable from './core/Transformable';

protected canBeInsideText(): boolean;
protected getInsideTextFill(): string;
protected getInsideTextStroke(textFill: string): string;
protected getOutsideFill(): "#333" | "#ccc";
protected getInsideTextFill(): string | undefined;
protected getInsideTextStroke(textFill: string): string | undefined;
protected getOutsideFill(): string | undefined;
protected getOutsideStroke(textFill: string): string;

@@ -190,2 +190,3 @@ traverse<Context>(cb: (this: Context, el: Element<Props>) => void, context?: Context): void;

setTextConfig(cfg: ElementTextConfig): void;
removeTextConfig(): void;
removeTextContent(): void;

@@ -192,0 +193,0 @@ getTextGuideLine(): Polyline;

@@ -588,2 +588,6 @@ import Transformable from './core/Transformable';

};
Element.prototype.removeTextConfig = function () {
this.textConfig = null;
this.markRedraw();
};
Element.prototype.removeTextContent = function () {

@@ -590,0 +594,0 @@ var textEl = this._textContent;

@@ -8,31 +8,31 @@ import * as zrUtil from './core/util';

import { morphPath } from './tool/morphPath';
export { default as Point } from './core/Point';
export { default as Element } from './Element';
export { default as Group } from './graphic/Group';
export { default as Path } from './graphic/Path';
export { default as Image } from './graphic/Image';
export { default as CompoundPath } from './graphic/CompoundPath';
export { default as TSpan } from './graphic/TSpan';
export { default as Point, PointLike } from './core/Point';
export { default as Element, ElementAnimateConfig, ElementTextConfig, ElementTextGuideLineConfig, ElementEvent, ElementEventCallback, ElementProps } from './Element';
export { default as Group, GroupProps } from './graphic/Group';
export { default as Path, PathStyleProps, PathProps, PathStatePropNames, PathState } from './graphic/Path';
export { default as Image, ImageStyleProps, ImageProps, ImageState } from './graphic/Image';
export { default as CompoundPath, CompoundPathShape } from './graphic/CompoundPath';
export { default as TSpan, TSpanStyleProps, TSpanProps, TSpanState } from './graphic/TSpan';
export { default as IncrementalDisplayable } from './graphic/IncrementalDisplayable';
export { default as Text } from './graphic/Text';
export { default as Arc } from './graphic/shape/Arc';
export { default as BezierCurve } from './graphic/shape/BezierCurve';
export { default as Circle } from './graphic/shape/Circle';
export { default as Droplet } from './graphic/shape/Droplet';
export { default as Ellipse } from './graphic/shape/Ellipse';
export { default as Heart } from './graphic/shape/Heart';
export { default as Isogon } from './graphic/shape/Isogon';
export { default as Line } from './graphic/shape/Line';
export { default as Polygon } from './graphic/shape/Polygon';
export { default as Polyline } from './graphic/shape/Polyline';
export { default as Rect } from './graphic/shape/Rect';
export { default as Ring } from './graphic/shape/Ring';
export { default as Rose } from './graphic/shape/Rose';
export { default as Sector } from './graphic/shape/Sector';
export { default as Star } from './graphic/shape/Star';
export { default as Trochoid } from './graphic/shape/Trochoid';
export { default as LinearGradient } from './graphic/LinearGradient';
export { default as RadialGradient } from './graphic/RadialGradient';
export { default as Pattern } from './graphic/Pattern';
export { default as BoundingRect } from './core/BoundingRect';
export { default as Text, TextStylePropsPart, TextStyleProps, TextProps, TextState } from './graphic/Text';
export { default as Arc, ArcProps, ArcShape } from './graphic/shape/Arc';
export { default as BezierCurve, BezierCurveProps, BezierCurveShape } from './graphic/shape/BezierCurve';
export { default as Circle, CircleProps, CircleShape } from './graphic/shape/Circle';
export { default as Droplet, DropletProps, DropletShape } from './graphic/shape/Droplet';
export { default as Ellipse, EllipseProps, EllipseShape } from './graphic/shape/Ellipse';
export { default as Heart, HeartProps, HeartShape } from './graphic/shape/Heart';
export { default as Isogon, IsogonProps, IsogonShape } from './graphic/shape/Isogon';
export { default as Line, LineProps, LineShape } from './graphic/shape/Line';
export { default as Polygon, PolygonProps, PolygonShape } from './graphic/shape/Polygon';
export { default as Polyline, PolylineProps, PolylineShape } from './graphic/shape/Polyline';
export { default as Rect, RectProps, RectShape } from './graphic/shape/Rect';
export { default as Ring, RingProps, RingShape } from './graphic/shape/Ring';
export { default as Rose, RoseProps, RoseShape } from './graphic/shape/Rose';
export { default as Sector, SectorProps, SectorShape } from './graphic/shape/Sector';
export { default as Star, StarProps, StarShape } from './graphic/shape/Star';
export { default as Trochoid, TrochoidProps, TrochoidShape } from './graphic/shape/Trochoid';
export { default as LinearGradient, LinearGradientObject } from './graphic/LinearGradient';
export { default as RadialGradient, RadialGradientObject } from './graphic/RadialGradient';
export { default as Pattern, PatternObject } from './graphic/Pattern';
export { default as BoundingRect, RectLike } from './core/BoundingRect';
export { default as OrientedBoundingRect } from './core/OrientedBoundingRect';

@@ -39,0 +39,0 @@ export { matrix };

@@ -17,18 +17,18 @@ import * as zrUtil from './core/util';

export { default as Text } from './graphic/Text';
export { default as Arc } from './graphic/shape/Arc';
export { default as BezierCurve } from './graphic/shape/BezierCurve';
export { default as Circle } from './graphic/shape/Circle';
export { default as Droplet } from './graphic/shape/Droplet';
export { default as Ellipse } from './graphic/shape/Ellipse';
export { default as Heart } from './graphic/shape/Heart';
export { default as Isogon } from './graphic/shape/Isogon';
export { default as Line } from './graphic/shape/Line';
export { default as Polygon } from './graphic/shape/Polygon';
export { default as Polyline } from './graphic/shape/Polyline';
export { default as Rect } from './graphic/shape/Rect';
export { default as Ring } from './graphic/shape/Ring';
export { default as Rose } from './graphic/shape/Rose';
export { default as Sector } from './graphic/shape/Sector';
export { default as Star } from './graphic/shape/Star';
export { default as Trochoid } from './graphic/shape/Trochoid';
export { default as Arc, ArcShape } from './graphic/shape/Arc';
export { default as BezierCurve, BezierCurveShape } from './graphic/shape/BezierCurve';
export { default as Circle, CircleShape } from './graphic/shape/Circle';
export { default as Droplet, DropletShape } from './graphic/shape/Droplet';
export { default as Ellipse, EllipseShape } from './graphic/shape/Ellipse';
export { default as Heart, HeartShape } from './graphic/shape/Heart';
export { default as Isogon, IsogonShape } from './graphic/shape/Isogon';
export { default as Line, LineShape } from './graphic/shape/Line';
export { default as Polygon, PolygonShape } from './graphic/shape/Polygon';
export { default as Polyline, PolylineShape } from './graphic/shape/Polyline';
export { default as Rect, RectShape } from './graphic/shape/Rect';
export { default as Ring, RingShape } from './graphic/shape/Ring';
export { default as Rose, RoseShape } from './graphic/shape/Rose';
export { default as Sector, SectorShape } from './graphic/shape/Sector';
export { default as Star, StarShape } from './graphic/shape/Star';
export { default as Trochoid, TrochoidShape } from './graphic/shape/Trochoid';
export { default as LinearGradient } from './graphic/LinearGradient';

@@ -35,0 +35,0 @@ export { default as RadialGradient } from './graphic/RadialGradient';

import Path from './Path';
import PathProxy from '../core/PathProxy';
interface CompoundPathShape {
export interface CompoundPathShape {
paths: Path[];

@@ -15,2 +15,1 @@ }

}
export {};

@@ -5,2 +5,5 @@ export interface GradientObject {

colorStops: GradientColorStop[];
global: boolean;
}
export interface InnerGradientObject extends GradientObject {
__canvasGradient: CanvasGradient;

@@ -16,5 +19,5 @@ }

colorStops: GradientColorStop[];
__canvasGradient: CanvasGradient;
global: boolean;
constructor(colorStops: GradientColorStop[]);
addColorStop(offset: number, color: string): void;
}
import * as imageHelper from '../helper/image';
import { extend, retrieve2, retrieve3, reduce } from '../../core/util';
import { getLineHeight, getWidth } from '../../contain/text';
import { getLineHeight, getWidth, parsePercent } from '../../contain/text';
var STYLE_REG = /\{([a-zA-Z0-9_]+)\|([^}]*)\}/g;

@@ -195,3 +195,2 @@ export function truncateText(text, containerWidth, font, ellipsis, options) {

var truncateLine = style.lineOverflow === 'truncate';
var prevToken;
function finishLine(line, lineWidth, lineHeight) {

@@ -269,3 +268,2 @@ line.width = lineWidth;

tokenStyle && (lineHeight = Math.max(lineHeight, token.lineHeight));
prevToken = token;
}

@@ -467,10 +465,1 @@ finishLine(line, lineWidth, lineHeight);

}
function parsePercent(value, maxValue) {
if (typeof value === 'string') {
if (value.lastIndexOf('%') >= 0) {
return parseFloat(value) / 100 * maxValue;
}
return parseFloat(value);
}
return value;
}

@@ -18,3 +18,3 @@ import Displayable, { DisplayableProps, CommonStyleProps, DisplayableStatePropNames } from './Displayable';

export declare const DEFAULT_IMAGE_ANIMATION_PROPS: MapToType<ImageProps, boolean>;
interface ImageProps extends DisplayableProps {
export interface ImageProps extends DisplayableProps {
style?: ImageStyleProps;

@@ -21,0 +21,0 @@ onload?: (image: ImageLike) => void;

@@ -8,3 +8,2 @@ import Gradient, { GradientObject, GradientColorStop } from './Gradient';

y2: number;
global: boolean;
}

@@ -17,4 +16,3 @@ export default class LinearGradient extends Gradient {

y2: number;
global: boolean;
constructor(x: number, y: number, x2: number, y2: number, colorStops?: GradientColorStop[], globalCoord?: boolean);
}

@@ -7,3 +7,2 @@ import Gradient, { GradientColorStop, GradientObject } from './Gradient';

r: number;
global: boolean;
}

@@ -15,5 +14,4 @@ declare class RadialGradient extends Gradient {

r: number;
global: boolean;
constructor(x: number, y: number, r: number, colorStops?: GradientColorStop[], globalCoord?: boolean);
}
export default RadialGradient;
import Path, { PathProps } from '../Path';
declare class ArcShape {
export declare class ArcShape {
cx: number;

@@ -10,3 +10,3 @@ cy: number;

}
interface ArcProps extends PathProps {
export interface ArcProps extends PathProps {
shape?: Partial<ArcShape>;

@@ -13,0 +13,0 @@ }

@@ -14,2 +14,3 @@ import { __extends } from "tslib";

}());
export { ArcShape };
var Arc = (function (_super) {

@@ -16,0 +17,0 @@ __extends(Arc, _super);

import Path, { PathProps } from '../Path';
declare class BezierCurveShape {
export declare class BezierCurveShape {
x1: number;

@@ -13,3 +13,3 @@ y1: number;

}
interface BezierCurveProps extends PathProps {
export interface BezierCurveProps extends PathProps {
shape?: Partial<BezierCurveShape>;

@@ -16,0 +16,0 @@ }

@@ -18,2 +18,3 @@ import { __extends } from "tslib";

}());
export { BezierCurveShape };
function someVectorAt(shape, t, isTangent) {

@@ -20,0 +21,0 @@ var cpx2 = shape.cpx2;

import Path, { PathProps } from '../Path';
declare class CircleShape {
export declare class CircleShape {
cx: number;

@@ -7,3 +7,3 @@ cy: number;

}
interface CircleProps extends PathProps {
export interface CircleProps extends PathProps {
shape?: Partial<CircleShape>;

@@ -10,0 +10,0 @@ }

@@ -11,2 +11,3 @@ import { __extends } from "tslib";

}());
export { CircleShape };
var Circle = (function (_super) {

@@ -13,0 +14,0 @@ __extends(Circle, _super);

import Path, { PathProps } from '../Path';
declare class DropletShape {
export declare class DropletShape {
cx: number;

@@ -8,3 +8,3 @@ cy: number;

}
interface DropletProps extends PathProps {
export interface DropletProps extends PathProps {
shape?: Partial<DropletShape>;

@@ -11,0 +11,0 @@ }

@@ -12,2 +12,3 @@ import { __extends } from "tslib";

}());
export { DropletShape };
var Droplet = (function (_super) {

@@ -14,0 +15,0 @@ __extends(Droplet, _super);

import Path, { PathProps } from '../Path';
declare class EllipseShape {
export declare class EllipseShape {
cx: number;

@@ -8,3 +8,3 @@ cy: number;

}
interface EllipseProps extends PathProps {
export interface EllipseProps extends PathProps {
shape?: Partial<EllipseShape>;

@@ -11,0 +11,0 @@ }

@@ -12,2 +12,3 @@ import { __extends } from "tslib";

}());
export { EllipseShape };
var Ellipse = (function (_super) {

@@ -14,0 +15,0 @@ __extends(Ellipse, _super);

import Path, { PathProps } from '../Path';
declare class HeartShape {
export declare class HeartShape {
cx: number;

@@ -8,3 +8,3 @@ cy: number;

}
interface HeartProps extends PathProps {
export interface HeartProps extends PathProps {
shape?: Partial<HeartShape>;

@@ -11,0 +11,0 @@ }

@@ -12,2 +12,3 @@ import { __extends } from "tslib";

}());
export { HeartShape };
var Heart = (function (_super) {

@@ -14,0 +15,0 @@ __extends(Heart, _super);

import Path, { PathProps } from '../Path';
declare class IsogonShape {
export declare class IsogonShape {
x: number;

@@ -8,3 +8,3 @@ y: number;

}
interface IsogonProps extends PathProps {
export interface IsogonProps extends PathProps {
shape?: Partial<IsogonShape>;

@@ -11,0 +11,0 @@ }

@@ -15,2 +15,3 @@ import { __extends } from "tslib";

}());
export { IsogonShape };
var Isogon = (function (_super) {

@@ -17,0 +18,0 @@ __extends(Isogon, _super);

import Path, { PathProps } from '../Path';
import { VectorArray } from '../../core/vector';
declare class LineShape {
export declare class LineShape {
x1: number;

@@ -10,3 +10,3 @@ y1: number;

}
interface LineProps extends PathProps {
export interface LineProps extends PathProps {
shape?: Partial<LineShape>;

@@ -13,0 +13,0 @@ }

@@ -15,2 +15,3 @@ import { __extends } from "tslib";

}());
export { LineShape };
var Line = (function (_super) {

@@ -17,0 +18,0 @@ __extends(Line, _super);

import Path, { PathProps } from '../Path';
import { VectorArray } from '../../core/vector';
declare class PolygonShape {
export declare class PolygonShape {
points: VectorArray[];

@@ -8,3 +8,3 @@ smooth?: number | 'spline';

}
interface PolygonProps extends PathProps {
export interface PolygonProps extends PathProps {
shape?: Partial<PolygonShape>;

@@ -11,0 +11,0 @@ }

@@ -12,2 +12,3 @@ import { __extends } from "tslib";

}());
export { PolygonShape };
var Polygon = (function (_super) {

@@ -14,0 +15,0 @@ __extends(Polygon, _super);

import Path, { PathProps } from '../Path';
import { VectorArray } from '../../core/vector';
declare class PolylineShape {
export declare class PolylineShape {
points: VectorArray[];

@@ -9,3 +9,3 @@ percent?: number;

}
interface PolylineProps extends PathProps {
export interface PolylineProps extends PathProps {
shape?: Partial<PolylineShape>;

@@ -12,0 +12,0 @@ }

@@ -13,2 +13,3 @@ import { __extends } from "tslib";

}());
export { PolylineShape };
var Polyline = (function (_super) {

@@ -15,0 +16,0 @@ __extends(Polyline, _super);

import Path, { PathProps } from '../Path';
declare class RectShape {
export declare class RectShape {
r?: number | number[];

@@ -9,3 +9,3 @@ x: number;

}
interface RectProps extends PathProps {
export interface RectProps extends PathProps {
shape?: Partial<RectShape>;

@@ -12,0 +12,0 @@ }

@@ -14,2 +14,3 @@ import { __extends } from "tslib";

}());
export { RectShape };
var subPixelOptimizeOutputShape = {};

@@ -16,0 +17,0 @@ var Rect = (function (_super) {

import Path, { PathProps } from '../Path';
declare class RingShape {
export declare class RingShape {
cx: number;

@@ -8,3 +8,3 @@ cy: number;

}
interface RingProps extends PathProps {
export interface RingProps extends PathProps {
shape?: Partial<RingShape>;

@@ -11,0 +11,0 @@ }

@@ -12,2 +12,3 @@ import { __extends } from "tslib";

}());
export { RingShape };
var Ring = (function (_super) {

@@ -14,0 +15,0 @@ __extends(Ring, _super);

import Path, { PathProps } from '../Path';
declare class RoseShape {
export declare class RoseShape {
cx: number;

@@ -9,3 +9,3 @@ cy: number;

}
interface RoseProps extends PathProps {
export interface RoseProps extends PathProps {
shape?: Partial<RoseShape>;

@@ -12,0 +12,0 @@ }

@@ -16,2 +16,3 @@ import { __extends } from "tslib";

}());
export { RoseShape };
var Rose = (function (_super) {

@@ -18,0 +19,0 @@ __extends(Rose, _super);

import Path, { PathProps } from '../Path';
declare class SectorShape {
export declare class SectorShape {
cx: number;

@@ -13,3 +13,3 @@ cy: number;

}
interface SectorProps extends PathProps {
export interface SectorProps extends PathProps {
shape?: Partial<SectorShape>;

@@ -16,0 +16,0 @@ }

@@ -18,2 +18,3 @@ import { __extends } from "tslib";

}());
export { SectorShape };
var Sector = (function (_super) {

@@ -20,0 +21,0 @@ __extends(Sector, _super);

import Path, { PathProps } from '../Path';
declare class StarShape {
export declare class StarShape {
cx: number;

@@ -9,3 +9,3 @@ cy: number;

}
interface StarProps extends PathProps {
export interface StarProps extends PathProps {
shape?: Partial<StarShape>;

@@ -12,0 +12,0 @@ }

@@ -15,2 +15,3 @@ import { __extends } from "tslib";

}());
export { StarShape };
var Star = (function (_super) {

@@ -17,0 +18,0 @@ __extends(Star, _super);

import Path, { PathProps } from '../Path';
declare class TrochoidShape {
export declare class TrochoidShape {
cx: number;

@@ -10,3 +10,3 @@ cy: number;

}
interface TrochoidProps extends PathProps {
export interface TrochoidProps extends PathProps {
shape?: Partial<TrochoidShape>;

@@ -13,0 +13,0 @@ }

@@ -16,2 +16,3 @@ import { __extends } from "tslib";

}());
export { TrochoidShape };
var Trochoid = (function (_super) {

@@ -18,0 +19,0 @@ __extends(Trochoid, _super);

@@ -59,3 +59,3 @@ import { TextAlign, TextVerticalAlign, ImageLike, Dictionary, MapToType } from '../core/types';

rich?: Dictionary<TextStylePropsPart>;
overflow?: 'break' | 'breakAll' | 'truncate';
overflow?: 'break' | 'breakAll' | 'truncate' | 'none';
lineOverflow?: 'truncate';

@@ -62,0 +62,0 @@ ellipsis?: string;

@@ -13,3 +13,3 @@ import Displayable, { DisplayableProps, DisplayableStatePropNames } from './Displayable';

export declare const DEFAULT_TSPAN_STYLE: TSpanStyleProps;
interface TSpanProps extends DisplayableProps {
export interface TSpanProps extends DisplayableProps {
style?: TSpanStyleProps;

@@ -16,0 +16,0 @@ }

@@ -41,3 +41,2 @@ import Path from '../graphic/Path';

_paintList(list: Displayable[]): void;
_getDefs(isForceCreating?: boolean): SVGElement;
resize(width: number | string, height: number | string): void;

@@ -44,0 +43,0 @@ getWidth(): number;

@@ -231,32 +231,2 @@ import { createElement } from './core';

};
SVGPainter.prototype._getDefs = function (isForceCreating) {
var svgRoot = this._svgDom;
var defs = svgRoot.getElementsByTagName('defs');
if (defs.length === 0) {
if (isForceCreating) {
var defs_1 = svgRoot.insertBefore(createElement('defs'), svgRoot.firstChild);
if (!defs_1.contains) {
defs_1.contains = function (el) {
var children = defs_1.children;
if (!children) {
return false;
}
for (var i = children.length - 1; i >= 0; --i) {
if (children[i] === el) {
return true;
}
}
return false;
};
}
return defs_1;
}
else {
return null;
}
}
else {
return defs[0];
}
};
SVGPainter.prototype.resize = function (width, height) {

@@ -263,0 +233,0 @@ var viewport = this._viewport;

import Group from '../graphic/Group';
import Element from '../Element';
import { RectLike } from '../core/BoundingRect';

@@ -10,3 +11,3 @@ import { parseXML } from './parseXML';

}
interface SVGParserResult {
export interface SVGParserResult {
root: Group;

@@ -21,4 +22,12 @@ width: number;

};
named: SVGParserResultNamedItem[];
}
export declare function makeViewBoxTransform(viewBoxRect: RectLike, width: number, height: number): {
export interface SVGParserResultNamedItem {
name: string;
namedFrom: SVGParserResultNamedItem;
svgNodeTagLower: SVGNodeTagLower;
el: Element;
}
export declare type SVGNodeTagLower = 'g' | 'rect' | 'circle' | 'line' | 'ellipse' | 'polygon' | 'polyline' | 'image' | 'text' | 'tspan' | 'path' | 'defs' | 'switch';
export declare function makeViewBoxTransform(viewBoxRect: RectLike, boundingRect: RectLike): {
scale: number;

@@ -25,0 +34,0 @@ x: number;

@@ -7,3 +7,2 @@ import Group from '../graphic/Group';

import Line from '../graphic/shape/Line';
import Path from '../graphic/Path';
import Polygon from '../graphic/shape/Polygon';

@@ -13,8 +12,35 @@ import Polyline from '../graphic/shape/Polyline';

import { createFromString } from './path';
import { extend, defaults, trim, each, map } from '../core/util';
import { defaults, trim, each, map, keys, hasOwn } from '../core/util';
import LinearGradient from '../graphic/LinearGradient';
import RadialGradient from '../graphic/RadialGradient';
import TSpan from '../graphic/TSpan';
import { parseXML } from './parseXML';
var DILIMITER_REG = /[\s,]+/;
;
var nodeParsers;
var INHERITABLE_STYLE_ATTRIBUTES_MAP = {
'fill': 'fill',
'stroke': 'stroke',
'stroke-width': 'lineWidth',
'opacity': 'opacity',
'fill-opacity': 'fillOpacity',
'stroke-opacity': 'strokeOpacity',
'stroke-dasharray': 'lineDash',
'stroke-dashoffset': 'lineDashOffset',
'stroke-linecap': 'lineCap',
'stroke-linejoin': 'lineJoin',
'stroke-miterlimit': 'miterLimit',
'font-family': 'fontFamily',
'font-size': 'fontSize',
'font-style': 'fontStyle',
'font-weight': 'fontWeight',
'text-anchor': 'textAlign',
'visibility': 'visibility',
'display': 'display'
};
var INHERITABLE_STYLE_ATTRIBUTES_MAP_KEYS = keys(INHERITABLE_STYLE_ATTRIBUTES_MAP);
var SELF_STYLE_ATTRIBUTES_MAP = {
'alignment-baseline': 'textBaseline',
'stop-color': 'stopColor'
};
var SELF_STYLE_ATTRIBUTES_MAP_KEYS = keys(SELF_STYLE_ATTRIBUTES_MAP);
var SVGParser = (function () {

@@ -24,4 +50,2 @@ function SVGParser() {

this._root = null;
this._isDefine = false;
this._isText = false;
}

@@ -34,4 +58,6 @@ SVGParser.prototype.parse = function (xml, opt) {

}
this._defsUsePending = [];
var root = new Group();
this._root = root;
var named = [];
var viewBox = svg.getAttribute('viewBox') || '';

@@ -42,12 +68,14 @@ var width = parseFloat((svg.getAttribute('width') || opt.width));

isNaN(height) && (height = null);
parseAttributes(svg, root, null, true);
parseAttributes(svg, root, null, true, false);
var child = svg.firstChild;
while (child) {
this._parseNode(child, root);
this._parseNode(child, root, named, null, false, false);
child = child.nextSibling;
}
applyDefs(this._defs, this._defsUsePending);
this._defsUsePending = [];
var viewBoxRect;
var viewBoxTransform;
if (viewBox) {
var viewBoxArr = trim(viewBox).split(DILIMITER_REG);
var viewBoxArr = splitNumberSequence(viewBox);
if (viewBoxArr.length >= 4) {

@@ -63,3 +91,3 @@ viewBoxRect = {

if (viewBoxRect && width != null && height != null) {
viewBoxTransform = makeViewBoxTransform(viewBoxRect, width, height);
viewBoxTransform = makeViewBoxTransform(viewBoxRect, { x: 0, y: 0, width: width, height: height });
if (!opt.ignoreViewBox) {

@@ -84,17 +112,50 @@ var elRoot = root;

viewBoxRect: viewBoxRect,
viewBoxTransform: viewBoxTransform
viewBoxTransform: viewBoxTransform,
named: named
};
};
SVGParser.prototype._parseNode = function (xmlNode, parentGroup) {
SVGParser.prototype._parseNode = function (xmlNode, parentGroup, named, namedFrom, isInDefs, isInText) {
var nodeName = xmlNode.nodeName.toLowerCase();
var el;
var namedFromForSub = namedFrom;
if (nodeName === 'defs') {
this._isDefine = true;
isInDefs = true;
}
else if (nodeName === 'text') {
this._isText = true;
if (nodeName === 'text') {
isInText = true;
}
var el;
if (this._isDefine) {
var parser = defineParsers[nodeName];
if (parser) {
if (nodeName === 'defs' || nodeName === 'switch') {
el = parentGroup;
}
else {
if (!isInDefs) {
var parser_1 = nodeParsers[nodeName];
if (parser_1 && hasOwn(nodeParsers, nodeName)) {
el = parser_1.call(this, xmlNode, parentGroup);
var nameAttr = xmlNode.getAttribute('name');
if (nameAttr) {
var newNamed = {
name: nameAttr,
namedFrom: null,
svgNodeTagLower: nodeName,
el: el
};
named.push(newNamed);
if (nodeName === 'g') {
namedFromForSub = newNamed;
}
}
else if (namedFrom) {
named.push({
name: namedFrom.name,
namedFrom: namedFrom,
svgNodeTagLower: nodeName,
el: el
});
}
parentGroup.add(el);
}
}
var parser = paintServerParsers[nodeName];
if (parser && hasOwn(paintServerParsers, nodeName)) {
var def = parser.call(this, xmlNode);

@@ -107,16 +168,9 @@ var id = xmlNode.getAttribute('id');

}
else {
var parser = nodeParsers[nodeName];
if (parser) {
el = parser.call(this, xmlNode, parentGroup);
parentGroup.add(el);
}
}
if (el) {
if (el && el.isGroup) {
var child = xmlNode.firstChild;
while (child) {
if (child.nodeType === 1) {
this._parseNode(child, el);
this._parseNode(child, el, named, namedFromForSub, isInDefs, isInText);
}
if (child.nodeType === 3 && this._isText) {
else if (child.nodeType === 3 && isInText) {
this._parseText(child, el);

@@ -127,16 +181,4 @@ }

}
if (nodeName === 'defs') {
this._isDefine = false;
}
else if (nodeName === 'text') {
this._isText = false;
}
};
SVGParser.prototype._parseText = function (xmlNode, parentGroup) {
if (xmlNode.nodeType === 1) {
var dx = xmlNode.getAttribute('dx') || 0;
var dy = xmlNode.getAttribute('dy') || 0;
this._textX += parseFloat(dx);
this._textY += parseFloat(dy);
}
var text = new TSpan({

@@ -146,2 +188,3 @@ style: {

},
silent: true,
x: this._textX || 0,

@@ -151,3 +194,4 @@ y: this._textY || 0

inheritStyle(parentGroup, text);
parseAttributes(xmlNode, text, this._defs);
parseAttributes(xmlNode, text, this._defsUsePending, false, false);
applyTextAlignment(text, parentGroup);
var textStyle = text.style;

@@ -177,3 +221,3 @@ var fontSize = textStyle.fontSize;

inheritStyle(parentGroup, g);
parseAttributes(xmlNode, g, this._defs);
parseAttributes(xmlNode, g, this._defsUsePending, false, false);
return g;

@@ -184,3 +228,3 @@ },

inheritStyle(parentGroup, rect);
parseAttributes(xmlNode, rect, this._defs);
parseAttributes(xmlNode, rect, this._defsUsePending, false, false);
rect.setShape({

@@ -192,2 +236,3 @@ x: parseFloat(xmlNode.getAttribute('x') || '0'),

});
rect.silent = true;
return rect;

@@ -198,3 +243,3 @@ },

inheritStyle(parentGroup, circle);
parseAttributes(xmlNode, circle, this._defs);
parseAttributes(xmlNode, circle, this._defsUsePending, false, false);
circle.setShape({

@@ -205,2 +250,3 @@ cx: parseFloat(xmlNode.getAttribute('cx') || '0'),

});
circle.silent = true;
return circle;

@@ -211,3 +257,3 @@ },

inheritStyle(parentGroup, line);
parseAttributes(xmlNode, line, this._defs);
parseAttributes(xmlNode, line, this._defsUsePending, false, false);
line.setShape({

@@ -219,2 +265,3 @@ x1: parseFloat(xmlNode.getAttribute('x1') || '0'),

});
line.silent = true;
return line;

@@ -225,3 +272,3 @@ },

inheritStyle(parentGroup, ellipse);
parseAttributes(xmlNode, ellipse, this._defs);
parseAttributes(xmlNode, ellipse, this._defsUsePending, false, false);
ellipse.setShape({

@@ -233,2 +280,3 @@ cx: parseFloat(xmlNode.getAttribute('cx') || '0'),

});
ellipse.silent = true;
return ellipse;

@@ -245,12 +293,10 @@ },

points: pointsArr || []
}
},
silent: true
});
inheritStyle(parentGroup, polygon);
parseAttributes(xmlNode, polygon, this._defs);
parseAttributes(xmlNode, polygon, this._defsUsePending, false, false);
return polygon;
},
'polyline': function (xmlNode, parentGroup) {
var path = new Path();
inheritStyle(parentGroup, path);
parseAttributes(xmlNode, path, this._defs);
var pointsStr = xmlNode.getAttribute('points');

@@ -264,4 +310,7 @@ var pointsArr;

points: pointsArr || []
}
},
silent: true
});
inheritStyle(parentGroup, polyline);
parseAttributes(xmlNode, polyline, this._defsUsePending, false, false);
return polyline;

@@ -272,3 +321,3 @@ },

inheritStyle(parentGroup, img);
parseAttributes(xmlNode, img, this._defs);
parseAttributes(xmlNode, img, this._defsUsePending, false, false);
img.setStyle({

@@ -281,2 +330,3 @@ image: xmlNode.getAttribute('xlink:href'),

});
img.silent = true;
return img;

@@ -293,3 +343,3 @@ },

inheritStyle(parentGroup, g);
parseAttributes(xmlNode, g, this._defs);
parseAttributes(xmlNode, g, this._defsUsePending, false, true);
return g;

@@ -306,9 +356,9 @@ },

}
var dx = xmlNode.getAttribute('dx') || 0;
var dy = xmlNode.getAttribute('dy') || 0;
var dx = xmlNode.getAttribute('dx') || '0';
var dy = xmlNode.getAttribute('dy') || '0';
var g = new Group();
inheritStyle(parentGroup, g);
parseAttributes(xmlNode, g, this._defs);
this._textX += dx;
this._textY += dy;
parseAttributes(xmlNode, g, this._defsUsePending, false, true);
this._textX += parseFloat(dx);
this._textY += parseFloat(dy);
return g;

@@ -320,3 +370,4 @@ },

inheritStyle(parentGroup, path);
parseAttributes(xmlNode, path, this._defs);
parseAttributes(xmlNode, path, this._defsUsePending, false, false);
path.silent = true;
return path;

@@ -328,3 +379,3 @@ }

}());
var defineParsers = {
var paintServerParsers = {
'lineargradient': function (xmlNode) {

@@ -336,13 +387,30 @@ var x1 = parseInt(xmlNode.getAttribute('x1') || '0', 10);

var gradient = new LinearGradient(x1, y1, x2, y2);
_parseGradientColorStops(xmlNode, gradient);
parsePaintServerUnit(xmlNode, gradient);
parseGradientColorStops(xmlNode, gradient);
return gradient;
},
'radialgradient': function (xmlNode) {
var cx = parseInt(xmlNode.getAttribute('cx') || '0', 10);
var cy = parseInt(xmlNode.getAttribute('cy') || '0', 10);
var r = parseInt(xmlNode.getAttribute('r') || '0', 10);
var gradient = new RadialGradient(cx, cy, r);
parsePaintServerUnit(xmlNode, gradient);
parseGradientColorStops(xmlNode, gradient);
return gradient;
}
};
function _parseGradientColorStops(xmlNode, gradient) {
function parsePaintServerUnit(xmlNode, gradient) {
var gradientUnits = xmlNode.getAttribute('gradientUnits');
if (gradientUnits === 'userSpaceOnUse') {
gradient.global = true;
}
}
function parseGradientColorStops(xmlNode, gradient) {
var stop = xmlNode.firstChild;
while (stop) {
if (stop.nodeType === 1) {
if (stop.nodeType === 1
&& stop.nodeName.toLocaleLowerCase() === 'stop') {
var offsetStr = stop.getAttribute('offset');
var offset = void 0;
if (offsetStr.indexOf('%') > 0) {
if (offsetStr && offsetStr.indexOf('%') > 0) {
offset = parseInt(offsetStr, 10) / 100;

@@ -356,3 +424,7 @@ }

}
var stopColor = stop.getAttribute('stop-color') || '#000000';
var styleVals = {};
parseInlineStyle(stop, styleVals, styleVals);
var stopColor = styleVals.stopColor
|| stop.getAttribute('stop-color')
|| '#000000';
gradient.colorStops.push({

@@ -375,3 +447,3 @@ offset: offset,

function parsePoints(pointsString) {
var list = trim(pointsString).split(DILIMITER_REG);
var list = splitNumberSequence(pointsString);
var points = [];

@@ -385,81 +457,109 @@ for (var i = 0; i < list.length; i += 2) {

}
var attributesMap = {
'fill': 'fill',
'stroke': 'stroke',
'stroke-width': 'lineWidth',
'opacity': 'opacity',
'fill-opacity': 'fillOpacity',
'stroke-opacity': 'strokeOpacity',
'stroke-dasharray': 'lineDash',
'stroke-dashoffset': 'lineDashOffset',
'stroke-linecap': 'lineCap',
'stroke-linejoin': 'lineJoin',
'stroke-miterlimit': 'miterLimit',
'font-family': 'fontFamily',
'font-size': 'fontSize',
'font-style': 'fontStyle',
'font-weight': 'fontWeight',
'text-align': 'textAlign',
'alignment-baseline': 'textBaseline'
};
function parseAttributes(xmlNode, el, defs, onlyInlineStyle) {
function parseAttributes(xmlNode, el, defsUsePending, onlyInlineStyle, isTextGroup) {
var disp = el;
var zrStyle = disp.__inheritedStyle || {};
var inheritedStyle = disp.__inheritedStyle = disp.__inheritedStyle || {};
var selfStyle = {};
if (xmlNode.nodeType === 1) {
parseTransformAttribute(xmlNode, el);
extend(zrStyle, parseStyleAttribute(xmlNode));
parseInlineStyle(xmlNode, inheritedStyle, selfStyle);
if (!onlyInlineStyle) {
for (var svgAttrName in attributesMap) {
if (attributesMap.hasOwnProperty(svgAttrName)) {
var attrValue = xmlNode.getAttribute(svgAttrName);
if (attrValue != null) {
zrStyle[attributesMap[svgAttrName]] = attrValue;
}
}
}
parseAttributeStyle(xmlNode, inheritedStyle, selfStyle);
}
}
disp.style = disp.style || {};
zrStyle.fill != null && (disp.style.fill = getPaint(zrStyle.fill, defs));
zrStyle.stroke != null && (disp.style.stroke = getPaint(zrStyle.stroke, defs));
if (inheritedStyle.fill != null) {
disp.style.fill = getFillStrokeStyle(disp, 'fill', inheritedStyle.fill, defsUsePending);
}
if (inheritedStyle.stroke != null) {
disp.style.stroke = getFillStrokeStyle(disp, 'stroke', inheritedStyle.stroke, defsUsePending);
}
each([
'lineWidth', 'opacity', 'fillOpacity', 'strokeOpacity', 'miterLimit', 'fontSize'
], function (propName) {
zrStyle[propName] != null && (disp.style[propName] = parseFloat(zrStyle[propName]));
if (inheritedStyle[propName] != null) {
disp.style[propName] = parseFloat(inheritedStyle[propName]);
}
});
if (!zrStyle.textBaseline || zrStyle.textBaseline === 'auto') {
zrStyle.textBaseline = 'alphabetic';
}
if (zrStyle.textBaseline === 'alphabetic') {
zrStyle.textBaseline = 'bottom';
}
if (zrStyle.textAlign === 'start') {
zrStyle.textAlign = 'left';
}
if (zrStyle.textAlign === 'end') {
zrStyle.textAlign = 'right';
}
each(['lineDashOffset', 'lineCap', 'lineJoin',
'fontWeight', 'fontFamily', 'fontStyle', 'textAlign', 'textBaseline'
each([
'lineDashOffset', 'lineCap', 'lineJoin', 'fontWeight', 'fontFamily', 'fontStyle', 'textAlign'
], function (propName) {
zrStyle[propName] != null && (disp.style[propName] = zrStyle[propName]);
if (inheritedStyle[propName] != null) {
disp.style[propName] = inheritedStyle[propName];
}
});
if (zrStyle.lineDash) {
disp.style.lineDash = map(trim(zrStyle.lineDash).split(DILIMITER_REG), function (str) {
if (isTextGroup) {
disp.__selfStyle = selfStyle;
}
if (inheritedStyle.lineDash) {
disp.style.lineDash = map(splitNumberSequence(inheritedStyle.lineDash), function (str) {
return parseFloat(str);
});
}
disp.__inheritedStyle = zrStyle;
if (inheritedStyle.visibility === 'hidden' || inheritedStyle.visibility === 'collapse') {
disp.invisible = true;
}
if (inheritedStyle.display === 'none') {
disp.ignore = true;
}
disp.z = -10000;
disp.z2 = -1000;
}
var urlRegex = /url\(\s*#(.*?)\)/;
function getPaint(str, defs) {
var urlMatch = defs && str && str.match(urlRegex);
function applyTextAlignment(text, parentGroup) {
var parentSelfStyle = parentGroup.__selfStyle;
if (parentSelfStyle) {
var textBaseline = parentSelfStyle.textBaseline;
var zrTextBaseline = textBaseline;
if (!textBaseline || textBaseline === 'auto') {
zrTextBaseline = 'alphabetic';
}
else if (textBaseline === 'baseline') {
zrTextBaseline = 'alphabetic';
}
else if (textBaseline === 'before-edge' || textBaseline === 'text-before-edge') {
zrTextBaseline = 'top';
}
else if (textBaseline === 'after-edge' || textBaseline === 'text-after-edge') {
zrTextBaseline = 'bottom';
}
else if (textBaseline === 'central' || textBaseline === 'mathematical') {
zrTextBaseline = 'middle';
}
text.style.textBaseline = zrTextBaseline;
}
var parentInheritedStyle = parentGroup.__inheritedStyle;
if (parentInheritedStyle) {
var textAlign = parentInheritedStyle.textAlign;
var zrTextAlign = textAlign;
if (textAlign) {
if (textAlign === 'middle') {
zrTextAlign = 'center';
}
text.style.textAlign = zrTextAlign;
}
}
}
var urlRegex = /^url\(\s*#(.*?)\)/;
function getFillStrokeStyle(el, method, str, defsUsePending) {
var urlMatch = str && str.match(urlRegex);
if (urlMatch) {
var url = trim(urlMatch[1]);
var def = defs[url];
return def;
defsUsePending.push([el, method, url]);
return;
}
if (str === 'none') {
str = null;
}
return str;
}
var transformRegex = /(translate|scale|rotate|skewX|skewY|matrix)\(([\-\s0-9\.e,]*)\)/g;
function applyDefs(defs, defsUsePending) {
for (var i = 0; i < defsUsePending.length; i++) {
var item = defsUsePending[i];
item[0].style[item[1]] = defs[item[2]];
}
}
var numberReg = /-?([0-9]*\.)?[0-9]+([eE]-?[0-9]+)?/g;
function splitNumberSequence(rawStr) {
return rawStr.match(numberReg) || [];
}
var transformRegex = /(translate|scale|rotate|skewX|skewY|matrix)\(([\-\s0-9\.eE,]*)\)/g;
function parseTransformAttribute(xmlNode, node) {

@@ -470,3 +570,3 @@ var transform = xmlNode.getAttribute('transform');

var transformOps_1 = [];
var m = null;
var mt = null;
transform.replace(transformRegex, function (str, type, value) {

@@ -480,62 +580,82 @@ transformOps_1.push(type, value);

var valueArr = void 0;
m = m || matrix.create();
mt = mt || matrix.create();
switch (type) {
case 'translate':
valueArr = trim(value).split(DILIMITER_REG);
matrix.translate(m, m, [parseFloat(valueArr[0]), parseFloat(valueArr[1] || '0')]);
valueArr = splitNumberSequence(value);
matrix.translate(mt, mt, [parseFloat(valueArr[0]), parseFloat(valueArr[1] || '0')]);
break;
case 'scale':
valueArr = trim(value).split(DILIMITER_REG);
matrix.scale(m, m, [parseFloat(valueArr[0]), parseFloat(valueArr[1] || valueArr[0])]);
valueArr = splitNumberSequence(value);
matrix.scale(mt, mt, [parseFloat(valueArr[0]), parseFloat(valueArr[1] || valueArr[0])]);
break;
case 'rotate':
valueArr = trim(value).split(DILIMITER_REG);
matrix.rotate(m, m, parseFloat(valueArr[0]));
valueArr = splitNumberSequence(value);
matrix.rotate(mt, mt, -parseFloat(valueArr[0]) / 180 * Math.PI);
break;
case 'skew':
valueArr = trim(value).split(DILIMITER_REG);
valueArr = splitNumberSequence(value);
console.warn('Skew transform is not supported yet');
break;
case 'matrix':
valueArr = trim(value).split(DILIMITER_REG);
m[0] = parseFloat(valueArr[0]);
m[1] = parseFloat(valueArr[1]);
m[2] = parseFloat(valueArr[2]);
m[3] = parseFloat(valueArr[3]);
m[4] = parseFloat(valueArr[4]);
m[5] = parseFloat(valueArr[5]);
valueArr = splitNumberSequence(value);
mt[0] = parseFloat(valueArr[0]);
mt[1] = parseFloat(valueArr[1]);
mt[2] = parseFloat(valueArr[2]);
mt[3] = parseFloat(valueArr[3]);
mt[4] = parseFloat(valueArr[4]);
mt[5] = parseFloat(valueArr[5]);
break;
}
}
node.setLocalTransform(m);
node.setLocalTransform(mt);
}
}
var styleRegex = /([^\s:;]+)\s*:\s*([^:;]+)/g;
function parseStyleAttribute(xmlNode) {
function parseInlineStyle(xmlNode, inheritableStyleResult, selfStyleResult) {
var style = xmlNode.getAttribute('style');
var result = {};
if (!style) {
return result;
return;
}
var styleList = {};
styleRegex.lastIndex = 0;
var styleRegResult;
while ((styleRegResult = styleRegex.exec(style)) != null) {
styleList[styleRegResult[1]] = styleRegResult[2];
var svgStlAttr = styleRegResult[1];
var zrInheritableStlAttr = hasOwn(INHERITABLE_STYLE_ATTRIBUTES_MAP, svgStlAttr)
? INHERITABLE_STYLE_ATTRIBUTES_MAP[svgStlAttr]
: null;
if (zrInheritableStlAttr) {
inheritableStyleResult[zrInheritableStlAttr] = styleRegResult[2];
}
var zrSelfStlAttr = hasOwn(SELF_STYLE_ATTRIBUTES_MAP, svgStlAttr)
? SELF_STYLE_ATTRIBUTES_MAP[svgStlAttr]
: null;
if (zrSelfStlAttr) {
selfStyleResult[zrSelfStlAttr] = styleRegResult[2];
}
}
for (var svgAttrName in attributesMap) {
if (attributesMap.hasOwnProperty(svgAttrName) && styleList[svgAttrName] != null) {
result[attributesMap[svgAttrName]] = styleList[svgAttrName];
}
function parseAttributeStyle(xmlNode, inheritableStyleResult, selfStyleResult) {
for (var i = 0; i < INHERITABLE_STYLE_ATTRIBUTES_MAP_KEYS.length; i++) {
var svgAttrName = INHERITABLE_STYLE_ATTRIBUTES_MAP_KEYS[i];
var attrValue = xmlNode.getAttribute(svgAttrName);
if (attrValue != null) {
inheritableStyleResult[INHERITABLE_STYLE_ATTRIBUTES_MAP[svgAttrName]] = attrValue;
}
}
return result;
for (var i = 0; i < SELF_STYLE_ATTRIBUTES_MAP_KEYS.length; i++) {
var svgAttrName = SELF_STYLE_ATTRIBUTES_MAP_KEYS[i];
var attrValue = xmlNode.getAttribute(svgAttrName);
if (attrValue != null) {
selfStyleResult[SELF_STYLE_ATTRIBUTES_MAP[svgAttrName]] = attrValue;
}
}
}
export function makeViewBoxTransform(viewBoxRect, width, height) {
var scaleX = width / viewBoxRect.width;
var scaleY = height / viewBoxRect.height;
export function makeViewBoxTransform(viewBoxRect, boundingRect) {
var scaleX = boundingRect.width / viewBoxRect.width;
var scaleY = boundingRect.height / viewBoxRect.height;
var scale = Math.min(scaleX, scaleY);
return {
scale: scale,
x: -(viewBoxRect.x + viewBoxRect.width / 2) * scale + width / 2,
y: -(viewBoxRect.y + viewBoxRect.height / 2) * scale + height / 2
x: -(viewBoxRect.x + viewBoxRect.width / 2) * scale + (boundingRect.x + boundingRect.width / 2),
y: -(viewBoxRect.y + viewBoxRect.height / 2) * scale + (boundingRect.y + boundingRect.height / 2)
};

@@ -542,0 +662,0 @@ }

@@ -91,5 +91,5 @@ /*!

export declare function registerPainter(name: string, Ctor: PainterBaseCtor): void;
export declare const version = "5.0.4";
export declare const version = "5.1.0";
export interface ZRenderType extends ZRender {
}
export {};

@@ -265,3 +265,3 @@ /*!

}
export var version = '5.0.4';
export var version = '5.1.0';
;
{
"name": "zrender",
"version": "5.0.4",
"version": "5.1.0",
"description": "A lightweight canvas library.",

@@ -5,0 +5,0 @@ "keywords": [

@@ -381,3 +381,3 @@ /**

}
else if (typeof value !== 'number') {
else if (typeof value !== 'number' || isNaN(value)) {
this.interpolable = false;

@@ -384,0 +384,0 @@ return;

@@ -67,3 +67,6 @@ import Displayable, { DEFAULT_COMMON_STYLE } from '../graphic/Displayable';

const canvasPattern = ctx.createPattern(image, pattern.repeat || 'repeat');
if (typeof DOMMatrix === 'function') {
if (
typeof DOMMatrix === 'function'
&& canvasPattern.setTransform // setTransform may not be supported in some old devices.
) {
const matrix = new DOMMatrix();

@@ -403,3 +406,5 @@ matrix.rotateSelf(0, 0, (pattern.rotation || 0) / Math.PI * 180);

}
ctx.globalAlpha = style.opacity == null ? DEFAULT_COMMON_STYLE.opacity : style.opacity;
// Ensure opacity is between 0 ~ 1. Invalid opacity will lead to a failure set and use the leaked opacity from the previous.
const opacity = Math.max(Math.min(style.opacity, 1), 0);
ctx.globalAlpha = isNaN(opacity) ? DEFAULT_COMMON_STYLE.opacity : opacity;
}

@@ -406,0 +411,0 @@

@@ -5,3 +5,3 @@ import * as util from '../core/util';

import CanvasPainter from './Painter';
import { GradientObject } from '../graphic/Gradient';
import { GradientObject, InnerGradientObject } from '../graphic/Gradient';
import { ZRCanvasRenderingContext } from '../core/types';

@@ -437,3 +437,3 @@ import Eventful from '../core/Eventful';

// Cache canvas gradient
clearColorGradientOrPattern = clearColor.__canvasGradient
clearColorGradientOrPattern = (clearColor as InnerGradientObject).__canvasGradient
|| getCanvasGradient(ctx, clearColor, {

@@ -446,3 +446,3 @@ x: 0,

clearColor.__canvasGradient = clearColorGradientOrPattern;
(clearColor as InnerGradientObject).__canvasGradient = clearColorGradientOrPattern;
}

@@ -449,0 +449,0 @@ // Pattern

@@ -25,2 +25,4 @@ declare const wx: {

domSupported = false
transformSupported = false
transform3dSupported = false
}

@@ -91,2 +93,25 @@

env.domSupported = typeof document !== 'undefined';
const style = document.documentElement.style;
env.transform3dSupported = (
// IE9 only supports transform 2D
// transform 3D supported since IE10
// we detect it by whether 'transition' is in style
(browser.ie && 'transition' in style)
// edge
|| browser.edge
// webkit
|| (('WebKitCSSMatrix' in window) && ('m11' in new WebKitCSSMatrix()))
// gecko-based browsers
|| 'MozPerspective' in style
) // Opera supports CSS transforms after version 12
&& !('OTransition' in style);
// except IE 6-8 and very old firefox 2-3 & opera 10.1
// other browsers all support `transform`
env.transformSupported = env.transform3dSupported
// transform 2D is supported in IE9
|| (browser.ie && +browser.version >= 9);
}

@@ -93,0 +118,0 @@

@@ -665,3 +665,3 @@ import { Dictionary, ArrayLike, KeyOfDistributive } from './types';

constructor(obj?: HashMap<T, KEY> | Dictionary<T> | any[]) {
constructor(obj?: HashMap<T, KEY> | { [key in KEY]?: T } | KEY[]) {
const isArr = isArray(obj);

@@ -688,3 +688,3 @@ // Key should not be set on this, otherwise

}
set(key: KEY, value: T) {
set(key: KEY, value: T): T {
// Comparing with invocation chaining, `return value` is more commonly

@@ -716,3 +716,3 @@ // used in this case: `const someVal = map.set('a', genVal());`

export function createHashMap<T, KEY extends string | number = string | number>(
obj?: HashMap<T, KEY> | Dictionary<T> | any[]
obj?: HashMap<T, KEY> | { [key in KEY]?: T } | KEY[]
) {

@@ -719,0 +719,0 @@ return new HashMap<T, KEY>(obj);

@@ -675,11 +675,11 @@ import Transformable from './core/Transformable';

protected getInsideTextFill(): string {
protected getInsideTextFill(): string | undefined {
return '#fff';
}
protected getInsideTextStroke(textFill: string): string {
protected getInsideTextStroke(textFill: string): string | undefined {
return '#000';
}
protected getOutsideFill() {
protected getOutsideFill(): string | undefined {
return this.__zr && this.__zr.isDarkMode() ? LIGHT_LABEL_COLOR : DARK_LABEL_COLOR;

@@ -1306,2 +1306,10 @@ }

/**
* Remove text config
*/
removeTextConfig() {
this.textConfig = null;
this.markRedraw();
}
/**
* Remove attached text element.

@@ -1960,2 +1968,2 @@ */

export default Element;
export default Element;

@@ -13,35 +13,43 @@ /**

export {default as Point} from './core/Point';
export {default as Point, PointLike} from './core/Point';
export {default as Element} from './Element';
export {
default as Element,
ElementAnimateConfig,
ElementTextConfig,
ElementTextGuideLineConfig,
ElementEvent,
ElementEventCallback,
ElementProps
} from './Element';
export {default as Group} from './graphic/Group';
export {default as Path} from './graphic/Path';
export {default as Image} from './graphic/Image';
export {default as CompoundPath} from './graphic/CompoundPath';
export {default as TSpan} from './graphic/TSpan';
export {default as Group, GroupProps} from './graphic/Group';
export {default as Path, PathStyleProps, PathProps, PathStatePropNames, PathState} from './graphic/Path';
export {default as Image, ImageStyleProps, ImageProps, ImageState} from './graphic/Image';
export {default as CompoundPath, CompoundPathShape} from './graphic/CompoundPath';
export {default as TSpan, TSpanStyleProps, TSpanProps, TSpanState} from './graphic/TSpan';
export {default as IncrementalDisplayable} from './graphic/IncrementalDisplayable';
export {default as Text} from './graphic/Text';
export {default as Text, TextStylePropsPart, TextStyleProps, TextProps, TextState} from './graphic/Text';
export {default as Arc} from './graphic/shape/Arc';
export {default as BezierCurve} from './graphic/shape/BezierCurve';
export {default as Circle} from './graphic/shape/Circle';
export {default as Droplet} from './graphic/shape/Droplet';
export {default as Ellipse} from './graphic/shape/Ellipse';
export {default as Heart} from './graphic/shape/Heart';
export {default as Isogon} from './graphic/shape/Isogon';
export {default as Line} from './graphic/shape/Line';
export {default as Polygon} from './graphic/shape/Polygon';
export {default as Polyline} from './graphic/shape/Polyline';
export {default as Rect} from './graphic/shape/Rect';
export {default as Ring} from './graphic/shape/Ring';
export {default as Rose} from './graphic/shape/Rose';
export {default as Sector} from './graphic/shape/Sector';
export {default as Star} from './graphic/shape/Star';
export {default as Trochoid} from './graphic/shape/Trochoid';
export {default as Arc, ArcProps, ArcShape} from './graphic/shape/Arc';
export {default as BezierCurve, BezierCurveProps, BezierCurveShape} from './graphic/shape/BezierCurve';
export {default as Circle, CircleProps, CircleShape} from './graphic/shape/Circle';
export {default as Droplet, DropletProps, DropletShape} from './graphic/shape/Droplet';
export {default as Ellipse, EllipseProps, EllipseShape} from './graphic/shape/Ellipse';
export {default as Heart, HeartProps, HeartShape} from './graphic/shape/Heart';
export {default as Isogon, IsogonProps, IsogonShape} from './graphic/shape/Isogon';
export {default as Line, LineProps, LineShape} from './graphic/shape/Line';
export {default as Polygon, PolygonProps, PolygonShape} from './graphic/shape/Polygon';
export {default as Polyline, PolylineProps, PolylineShape} from './graphic/shape/Polyline';
export {default as Rect, RectProps, RectShape} from './graphic/shape/Rect';
export {default as Ring, RingProps, RingShape} from './graphic/shape/Ring';
export {default as Rose, RoseProps, RoseShape} from './graphic/shape/Rose';
export {default as Sector, SectorProps, SectorShape} from './graphic/shape/Sector';
export {default as Star, StarProps, StarShape} from './graphic/shape/Star';
export {default as Trochoid, TrochoidProps, TrochoidShape} from './graphic/shape/Trochoid';
export {default as LinearGradient} from './graphic/LinearGradient';
export {default as RadialGradient} from './graphic/RadialGradient';
export {default as Pattern} from './graphic/Pattern';
export {default as BoundingRect} from './core/BoundingRect';
export {default as LinearGradient, LinearGradientObject} from './graphic/LinearGradient';
export {default as RadialGradient, RadialGradientObject} from './graphic/RadialGradient';
export {default as Pattern, PatternObject} from './graphic/Pattern';
export {default as BoundingRect, RectLike} from './core/BoundingRect';
export {default as OrientedBoundingRect} from './core/OrientedBoundingRect';

@@ -48,0 +56,0 @@

@@ -6,3 +6,3 @@ // CompoundPath to improve performance

interface CompoundPathShape {
export interface CompoundPathShape {
paths: Path[]

@@ -9,0 +9,0 @@ }

@@ -10,2 +10,6 @@ // TODO Should GradientObject been LinearGradientObject | RadialGradientObject

global: boolean
}
export interface InnerGradientObject extends GradientObject {
__canvasGradient: CanvasGradient

@@ -27,3 +31,3 @@ }

__canvasGradient: CanvasGradient
global: boolean

@@ -30,0 +34,0 @@ constructor(colorStops: GradientColorStop[]) {

@@ -10,3 +10,3 @@ import * as imageHelper from '../helper/image';

import { TextStyleProps } from '../Text';
import { getLineHeight, getWidth } from '../../contain/text';
import { getLineHeight, getWidth, parsePercent } from '../../contain/text';

@@ -356,3 +356,3 @@ const STYLE_REG = /\{([a-zA-Z0-9_]+)\|([^}]*)\}/g;

let prevToken: RichTextToken;
// let prevToken: RichTextToken;

@@ -468,3 +468,3 @@ function finishLine(line: RichTextLine, lineWidth: number, lineHeight: number) {

prevToken = token;
// prevToken = token;
}

@@ -745,12 +745,2 @@

};
}
function parsePercent(value: string | number, maxValue: number) {
if (typeof value === 'string') {
if (value.lastIndexOf('%') >= 0) {
return parseFloat(value) / 100 * maxValue;
}
return parseFloat(value);
}
return value;
}

@@ -42,3 +42,3 @@ import Displayable, { DisplayableProps,

interface ImageProps extends DisplayableProps {
export interface ImageProps extends DisplayableProps {
style?: ImageStyleProps

@@ -45,0 +45,0 @@

@@ -10,4 +10,2 @@ import Gradient, {GradientObject, GradientColorStop} from './Gradient';

y2: number
global: boolean
}

@@ -27,4 +25,2 @@ /**

global: boolean
constructor(

@@ -31,0 +27,0 @@ x: number, y: number, x2: number, y2: number,

@@ -9,3 +9,2 @@ import Gradient, {GradientColorStop, GradientObject} from './Gradient';

r: number
global: boolean
}

@@ -22,3 +21,2 @@ /**

r: number
global: boolean

@@ -25,0 +23,0 @@ constructor(

@@ -7,3 +7,3 @@ /**

class ArcShape {
export class ArcShape {
cx = 0;

@@ -17,3 +17,3 @@ cy = 0;

interface ArcProps extends PathProps {
export interface ArcProps extends PathProps {
shape?: Partial<ArcShape>

@@ -20,0 +20,0 @@ }

@@ -18,3 +18,3 @@ /**

class BezierCurveShape {
export class BezierCurveShape {
x1 = 0

@@ -49,3 +49,3 @@ y1 = 0

interface BezierCurveProps extends PathProps {
export interface BezierCurveProps extends PathProps {
shape?: Partial<BezierCurveShape>

@@ -52,0 +52,0 @@ }

@@ -7,3 +7,3 @@ /**

class CircleShape {
export class CircleShape {
cx = 0

@@ -14,3 +14,3 @@ cy = 0

interface CircleProps extends PathProps {
export interface CircleProps extends PathProps {
shape?: Partial<CircleShape>

@@ -17,0 +17,0 @@ }

@@ -7,3 +7,3 @@ /**

class DropletShape {
export class DropletShape {
cx = 0

@@ -15,3 +15,3 @@ cy = 0

interface DropletProps extends PathProps {
export interface DropletProps extends PathProps {
shape?: Partial<DropletShape>

@@ -18,0 +18,0 @@ }

@@ -7,3 +7,3 @@ /**

class EllipseShape {
export class EllipseShape {
cx = 0

@@ -15,3 +15,3 @@ cy = 0

interface EllipseProps extends PathProps {
export interface EllipseProps extends PathProps {
shape?: Partial<EllipseShape>

@@ -18,0 +18,0 @@ }

@@ -7,3 +7,3 @@ /**

class HeartShape {
export class HeartShape {
cx = 0

@@ -15,3 +15,3 @@ cy = 0

interface HeartProps extends PathProps {
export interface HeartProps extends PathProps {
shape?: Partial<HeartShape>

@@ -18,0 +18,0 @@ }

@@ -11,3 +11,3 @@ /**

class IsogonShape {
export class IsogonShape {
x = 0

@@ -19,3 +19,3 @@ y = 0

interface IsogonProps extends PathProps {
export interface IsogonProps extends PathProps {
shape?: Partial<IsogonShape>

@@ -22,0 +22,0 @@ }

@@ -8,3 +8,2 @@ /**

import {subPixelOptimizeLine} from '../helper/subPixelOptimize';
import PathProxy from '../../core/PathProxy';
import { VectorArray } from '../../core/vector';

@@ -15,3 +14,3 @@

class LineShape {
export class LineShape {
// Start point

@@ -27,3 +26,3 @@ x1 = 0

interface LineProps extends PathProps {
export interface LineProps extends PathProps {
shape?: Partial<LineShape>

@@ -30,0 +29,0 @@ }

@@ -10,3 +10,3 @@ /**

class PolygonShape {
export class PolygonShape {
points: VectorArray[] = null

@@ -17,3 +17,3 @@ smooth?: number | 'spline' = 0

interface PolygonProps extends PathProps {
export interface PolygonProps extends PathProps {
shape?: Partial<PolygonShape>

@@ -20,0 +20,0 @@ }

@@ -9,3 +9,3 @@ /**

class PolylineShape {
export class PolylineShape {
points: VectorArray[] = null

@@ -18,3 +18,3 @@ // Percent of displayed polyline. For animating purpose

interface PolylineProps extends PathProps {
export interface PolylineProps extends PathProps {
shape?: Partial<PolylineShape>

@@ -21,0 +21,0 @@ }

@@ -10,3 +10,3 @@ /**

class RectShape {
export class RectShape {
// 左上、右上、右下、左下角的半径依次为r1、r2、r3、r4

@@ -25,3 +25,3 @@ // r缩写为1 相当于 [1, 1, 1, 1]

interface RectProps extends PathProps {
export interface RectProps extends PathProps {
shape?: Partial<RectShape>

@@ -28,0 +28,0 @@ }

@@ -7,3 +7,3 @@ /**

class RingShape {
export class RingShape {
cx = 0

@@ -15,3 +15,3 @@ cy = 0

interface RingProps extends PathProps {
export interface RingProps extends PathProps {
shape?: Partial<RingShape>

@@ -18,0 +18,0 @@ }

@@ -12,3 +12,3 @@ /**

class RoseShape {
export class RoseShape {
cx = 0

@@ -21,3 +21,3 @@ cy = 0

interface RoseProps extends PathProps {
export interface RoseProps extends PathProps {
shape?: Partial<RoseShape>

@@ -24,0 +24,0 @@ }

import Path, { PathProps } from '../Path';
import * as roundSectorHelper from '../helper/roundSector';
class SectorShape {
export class SectorShape {
cx = 0

@@ -16,3 +16,3 @@ cy = 0

interface SectorProps extends PathProps {
export interface SectorProps extends PathProps {
shape?: Partial<SectorShape>

@@ -19,0 +19,0 @@ }

@@ -12,3 +12,3 @@ /**

class StarShape {
export class StarShape {
cx = 0

@@ -21,3 +21,3 @@ cy = 0

interface StarProps extends PathProps {
export interface StarProps extends PathProps {
shape?: Partial<StarShape>

@@ -24,0 +24,0 @@ }

@@ -11,3 +11,3 @@ /**

class TrochoidShape {
export class TrochoidShape {
cx = 0

@@ -21,3 +21,3 @@ cy = 0

interface TrochoidProps extends PathProps {
export interface TrochoidProps extends PathProps {
shape?: Partial<TrochoidShape>

@@ -24,0 +24,0 @@ }

@@ -164,3 +164,3 @@ /**

*/
overflow?: 'break' | 'breakAll' | 'truncate'
overflow?: 'break' | 'breakAll' | 'truncate' | 'none'

@@ -293,2 +293,3 @@ /**

for (let i = 0; i < this._children.length; i++) {

@@ -527,2 +528,11 @@ const child = this._children[i];

: (!bgColorDrawn
// If we use "auto lineWidth" widely, it probably bring about some bad case.
// So the current strategy is:
// If `style.fill` is specified (i.e., `useDefaultFill` is `false`)
// (A) And if `textConfig.insideStroke/outsideStroke` is not specified as a color
// (i.e., `defaultStyle.autoStroke` is `true`), we do not actually display
// the auto stroke because we can not make sure wether the stoke is approperiate to
// the given `fill`.
// (B) But if `textConfig.insideStroke/outsideStroke` is specified as a color,
// we give the auto lineWidth to display the given stoke color.
&& (!defaultStyle.autoStroke || useDefaultFill)

@@ -742,2 +752,3 @@ )

&& !parentBgColorDrawn
// See the strategy explained above.
&& (!defaultStyle.autoStroke || useDefaultFill)

@@ -744,0 +755,0 @@ ) ? (defaultLineWidth = DEFAULT_STROKE_LINE_WIDTH, defaultStyle.stroke)

@@ -34,3 +34,3 @@ import Displayable, { DisplayableProps, DisplayableStatePropNames } from './Displayable';

interface TSpanProps extends DisplayableProps {
export interface TSpanProps extends DisplayableProps {
style?: TSpanStyleProps

@@ -37,0 +37,0 @@ }

@@ -333,37 +333,38 @@ /**

_getDefs(isForceCreating?: boolean) {
let svgRoot = this._svgDom;
let defs = svgRoot.getElementsByTagName('defs');
if (defs.length === 0) {
// Not exist
if (isForceCreating) {
let defs = svgRoot.insertBefore(
createElement('defs'), // Create new tag
svgRoot.firstChild // Insert in the front of svg
);
if (!defs.contains) {
// IE doesn't support contains method
defs.contains = function (el) {
const children = defs.children;
if (!children) {
return false;
}
for (let i = children.length - 1; i >= 0; --i) {
if (children[i] === el) {
return true;
}
}
return false;
};
}
return defs;
}
else {
return null;
}
}
else {
return defs[0];
}
}
// Not used any more
// _getDefs(isForceCreating?: boolean) {
// let svgRoot = this._svgDom;
// let defs = svgRoot.getElementsByTagName('defs');
// if (defs.length === 0) {
// // Not exist
// if (isForceCreating) {
// let defs = svgRoot.insertBefore(
// createElement('defs'), // Create new tag
// svgRoot.firstChild // Insert in the front of svg
// );
// if (!defs.contains) {
// // IE doesn't support contains method
// defs.contains = function (el) {
// const children = defs.children;
// if (!children) {
// return false;
// }
// for (let i = children.length - 1; i >= 0; --i) {
// if (children[i] === el) {
// return true;
// }
// }
// return false;
// };
// }
// return defs;
// }
// else {
// return null;
// }
// }
// else {
// return defs[0];
// }
// }

@@ -370,0 +371,0 @@ resize(width: number | string, height: number | string) {

@@ -7,3 +7,2 @@ import Group from '../graphic/Group';

import Line from '../graphic/shape/Line';
import Path from '../graphic/Path';
import Polygon from '../graphic/shape/Polygon';

@@ -13,3 +12,3 @@ import Polyline from '../graphic/shape/Polyline';

import { createFromString } from './path';
import { extend, defaults, trim, each, map } from '../core/util';
import { defaults, trim, each, map, keys, hasOwn } from '../core/util';
import Displayable from '../graphic/Displayable';

@@ -21,63 +20,118 @@ import Element from '../Element';

import LinearGradient, { LinearGradientObject } from '../graphic/LinearGradient';
import { RadialGradientObject } from '../graphic/RadialGradient';
import { GradientObject } from '../graphic/Gradient';
import RadialGradient, { RadialGradientObject } from '../graphic/RadialGradient';
import Gradient, { GradientObject } from '../graphic/Gradient';
import TSpan, { TSpanStyleProps } from '../graphic/TSpan';
import { parseXML } from './parseXML';
// Most of the values can be separated by comma and/or white space.
const DILIMITER_REG = /[\s,]+/;
interface SVGParserOption {
// Default width if svg width not specified or is a percent value.
width?: number
width?: number;
// Default height if svg height not specified or is a percent value.
height?: number
ignoreViewBox?: boolean
ignoreRootClip?: boolean
height?: number;
ignoreViewBox?: boolean;
ignoreRootClip?: boolean;
}
interface SVGParserResult {
export interface SVGParserResult {
// Group, The root of the the result tree of zrender shapes
root: Group
root: Group;
// number, the viewport width of the SVG
width: number
width: number;
// number, the viewport height of the SVG
height: number
height: number;
// {x, y, width, height}, the declared viewBox rect of the SVG, if exists
viewBoxRect: RectLike
viewBoxRect: RectLike;
// the {scale, position} calculated by viewBox and viewport, is exists
viewBoxTransform: {
x: number
y: number
scale: number
}
x: number;
y: number;
scale: number;
};
named: SVGParserResultNamedItem[];
}
export interface SVGParserResultNamedItem {
name: string;
// If a tag has no name attribute but its ancester <g> is named,
// `namedFrom` is set to the named item of the ancester <g>.
// Otherwise null/undefined
namedFrom: SVGParserResultNamedItem;
svgNodeTagLower: SVGNodeTagLower;
el: Element;
};
type DefsMap = Dictionary<LinearGradientObject | RadialGradientObject | PatternObject>
export type SVGNodeTagLower =
'g' | 'rect' | 'circle' | 'line' | 'ellipse' | 'polygon'
| 'polyline' | 'image' | 'text' | 'tspan' | 'path' | 'defs' | 'switch';
type DefsId = string;
type DefsMap = { [id in DefsId]: LinearGradientObject | RadialGradientObject | PatternObject };
type DefsUsePending = [Displayable, 'fill' | 'stroke', DefsId][];
type ElementExtended = Element & {
__inheritedStyle: Dictionary<string>
__inheritedStyle?: InheritedStyleByZRKey;
__selfStyle?: SelfStyleByZRKey;
}
type DisplayableExtended = Displayable & {
__inheritedStyle: Dictionary<string>
__inheritedStyle?: InheritedStyleByZRKey;
__selfStyle?: SelfStyleByZRKey;
}
type TextStyleOptionExtended = TSpanStyleProps & {
fontSize: number
fontFamily: string
fontWeight: string
fontStyle: string
fontSize: number;
fontFamily: string;
fontWeight: string;
fontStyle: string;
}
let nodeParsers: Dictionary<(this: SVGParser, xmlNode: SVGElement, parentGroup: Group) => Element>;
let nodeParsers: {[name in SVGNodeTagLower]?: (
this: SVGParser, xmlNode: SVGElement, parentGroup: Group
) => Element};
type InheritedStyleByZRKey = {[name in InheritableStyleZRKey]?: string};
type InheritableStyleZRKey =
typeof INHERITABLE_STYLE_ATTRIBUTES_MAP[keyof typeof INHERITABLE_STYLE_ATTRIBUTES_MAP];
const INHERITABLE_STYLE_ATTRIBUTES_MAP = {
'fill': 'fill',
'stroke': 'stroke',
'stroke-width': 'lineWidth',
'opacity': 'opacity',
'fill-opacity': 'fillOpacity',
'stroke-opacity': 'strokeOpacity',
'stroke-dasharray': 'lineDash',
'stroke-dashoffset': 'lineDashOffset',
'stroke-linecap': 'lineCap',
'stroke-linejoin': 'lineJoin',
'stroke-miterlimit': 'miterLimit',
'font-family': 'fontFamily',
'font-size': 'fontSize',
'font-style': 'fontStyle',
'font-weight': 'fontWeight',
'text-anchor': 'textAlign',
'visibility': 'visibility',
'display': 'display'
} as const;
const INHERITABLE_STYLE_ATTRIBUTES_MAP_KEYS = keys(INHERITABLE_STYLE_ATTRIBUTES_MAP);
type SelfStyleByZRKey = {[name in SelfStyleZRKey]?: string};
type SelfStyleZRKey =
typeof SELF_STYLE_ATTRIBUTES_MAP[keyof typeof SELF_STYLE_ATTRIBUTES_MAP];
const SELF_STYLE_ATTRIBUTES_MAP = {
'alignment-baseline': 'textBaseline',
'stop-color': 'stopColor'
};
const SELF_STYLE_ATTRIBUTES_MAP_KEYS = keys(SELF_STYLE_ATTRIBUTES_MAP);
class SVGParser {
private _defs: DefsMap = {};
// The use of <defs> can be in front of <defs> declared.
// So save them temporarily in `_defsUsePending`.
private _defsUsePending: DefsUsePending;
private _root: Group = null;
private _isDefine = false;
private _isText = false;
private _textX: number;
private _textY: number;
private _textX: number
private _textY: number
parse(xml: string | Document | SVGElement, opt: SVGParserOption): SVGParserResult {

@@ -92,4 +146,6 @@ opt = opt || {};

this._defsUsePending = [];
let root = new Group();
this._root = root;
const named: SVGParserResult['named'] = [];
// parse view port

@@ -107,10 +163,13 @@ const viewBox = svg.getAttribute('viewBox') || '';

// Apply inline style on svg element.
parseAttributes(svg, root, null, true);
parseAttributes(svg, root, null, true, false);
let child = svg.firstChild as SVGElement;
while (child) {
this._parseNode(child, root);
this._parseNode(child, root, named, null, false, false);
child = child.nextSibling as SVGElement;
}
applyDefs(this._defs, this._defsUsePending);
this._defsUsePending = [];
let viewBoxRect;

@@ -120,3 +179,3 @@ let viewBoxTransform;

if (viewBox) {
const viewBoxArr = trim(viewBox).split(DILIMITER_REG);
const viewBoxArr = splitNumberSequence(viewBox);
// Some invalid case like viewBox: 'none'.

@@ -134,3 +193,3 @@ if (viewBoxArr.length >= 4) {

if (viewBoxRect && width != null && height != null) {
viewBoxTransform = makeViewBoxTransform(viewBoxRect, width, height);
viewBoxTransform = makeViewBoxTransform(viewBoxRect, { x: 0, y: 0, width: width, height: height });

@@ -167,26 +226,81 @@ if (!opt.ignoreViewBox) {

viewBoxRect: viewBoxRect,
viewBoxTransform: viewBoxTransform
viewBoxTransform: viewBoxTransform,
named: named
};
}
_parseNode(xmlNode: SVGElement, parentGroup: Group) {
private _parseNode(
xmlNode: SVGElement,
parentGroup: Group,
named: SVGParserResultNamedItem[],
namedFrom: SVGParserResultNamedItem['namedFrom'],
isInDefs: boolean,
isInText: boolean
): void {
const nodeName = xmlNode.nodeName.toLowerCase();
const nodeName = xmlNode.nodeName.toLowerCase() as SVGNodeTagLower;
// TODO
// TODO:
// support <style>...</style> in svg, where nodeName is 'style',
// CSS classes is defined globally wherever the style tags are declared.
let el;
let namedFromForSub = namedFrom;
if (nodeName === 'defs') {
// define flag
this._isDefine = true;
isInDefs = true;
}
else if (nodeName === 'text') {
this._isText = true;
if (nodeName === 'text') {
isInText = true;
}
let el;
if (this._isDefine) {
const parser = defineParsers[nodeName];
if (parser) {
if (nodeName === 'defs' || nodeName === 'switch') {
// Just make <switch> displayable. Do not support
// the full feature of it.
el = parentGroup;
}
else {
// In <defs>, elments will not be rendered.
// TODO:
// do not support elements in <defs> yet, until requirement come.
// other graphic elements can also be in <defs> and referenced by
// <use x="5" y="5" xlink:href="#myCircle" />
// multiple times
if (!isInDefs) {
const parser = nodeParsers[nodeName];
if (parser && hasOwn(nodeParsers, nodeName)) {
el = parser.call(this, xmlNode, parentGroup);
// Do not support empty string;
const nameAttr = xmlNode.getAttribute('name');
if (nameAttr) {
const newNamed: SVGParserResultNamedItem = {
name: nameAttr,
namedFrom: null,
svgNodeTagLower: nodeName,
el: el
};
named.push(newNamed);
if (nodeName === 'g') {
namedFromForSub = newNamed;
}
}
else if (namedFrom) {
named.push({
name: namedFrom.name,
namedFrom: namedFrom,
svgNodeTagLower: nodeName,
el: el
});
}
parentGroup.add(el);
}
}
// Whether gradients/patterns are declared in <defs> or not,
// they all work.
const parser = paintServerParsers[nodeName];
if (parser && hasOwn(paintServerParsers, nodeName)) {
const def = parser.call(this, xmlNode);

@@ -199,19 +313,13 @@ const id = xmlNode.getAttribute('id');

}
else {
const parser = nodeParsers[nodeName];
if (parser) {
el = parser.call(this, xmlNode, parentGroup);
parentGroup.add(el);
}
}
if (el) { // No parsers available
// If xmlNode is <g>, <text>, <tspan>, <defs>, <switch>,
// el will be a group, and traverse the children.
if (el && el.isGroup) {
let child = xmlNode.firstChild as SVGElement;
while (child) {
if (child.nodeType === 1) {
// el should be a group if it has child.
this._parseNode(child, el as Group);
this._parseNode(child, el as Group, named, namedFromForSub, isInDefs, isInText);
}
// Is text
if (child.nodeType === 3 && this._isText) {
// Is plain text rather than a tagged node.
else if (child.nodeType === 3 && isInText) {
this._parseText(child, el as Group);

@@ -222,19 +330,6 @@ }

}
// Quit define
if (nodeName === 'defs') {
this._isDefine = false;
}
else if (nodeName === 'text') {
this._isText = false;
}
}
_parseText(xmlNode: SVGElement, parentGroup: Group) {
if (xmlNode.nodeType === 1) {
const dx = xmlNode.getAttribute('dx') || 0;
const dy = xmlNode.getAttribute('dy') || 0;
this._textX += parseFloat(dx as string);
this._textY += parseFloat(dy as string);
}
private _parseText(xmlNode: SVGElement, parentGroup: Group): TSpan {
const text = new TSpan({

@@ -244,2 +339,3 @@ style: {

},
silent: true,
x: this._textX || 0,

@@ -250,4 +346,7 @@ y: this._textY || 0

inheritStyle(parentGroup, text);
parseAttributes(xmlNode, text, this._defs);
parseAttributes(xmlNode, text, this._defsUsePending, false, false);
applyTextAlignment(text, parentGroup);
const textStyle = text.style as TextStyleOptionExtended;

@@ -283,13 +382,13 @@ const fontSize = textStyle.fontSize;

nodeParsers = {
'g': function (xmlNode: SVGElement, parentGroup: Group) {
'g': function (xmlNode, parentGroup) {
const g = new Group();
inheritStyle(parentGroup, g);
parseAttributes(xmlNode, g, this._defs);
parseAttributes(xmlNode, g, this._defsUsePending, false, false);
return g;
},
'rect': function (xmlNode: SVGElement, parentGroup: Group) {
'rect': function (xmlNode, parentGroup) {
const rect = new Rect();
inheritStyle(parentGroup, rect);
parseAttributes(xmlNode, rect, this._defs);
parseAttributes(xmlNode, rect, this._defsUsePending, false, false);

@@ -303,8 +402,10 @@ rect.setShape({

rect.silent = true;
return rect;
},
'circle': function (xmlNode: SVGElement, parentGroup: Group) {
'circle': function (xmlNode, parentGroup) {
const circle = new Circle();
inheritStyle(parentGroup, circle);
parseAttributes(xmlNode, circle, this._defs);
parseAttributes(xmlNode, circle, this._defsUsePending, false, false);

@@ -317,8 +418,10 @@ circle.setShape({

circle.silent = true;
return circle;
},
'line': function (xmlNode: SVGElement, parentGroup: Group) {
'line': function (xmlNode, parentGroup) {
const line = new Line();
inheritStyle(parentGroup, line);
parseAttributes(xmlNode, line, this._defs);
parseAttributes(xmlNode, line, this._defsUsePending, false, false);

@@ -332,8 +435,10 @@ line.setShape({

line.silent = true;
return line;
},
'ellipse': function (xmlNode: SVGElement, parentGroup: Group) {
'ellipse': function (xmlNode, parentGroup) {
const ellipse = new Ellipse();
inheritStyle(parentGroup, ellipse);
parseAttributes(xmlNode, ellipse, this._defs);
parseAttributes(xmlNode, ellipse, this._defsUsePending, false, false);

@@ -346,5 +451,8 @@ ellipse.setShape({

});
ellipse.silent = true;
return ellipse;
},
'polygon': function (xmlNode: SVGElement, parentGroup: Group) {
'polygon': function (xmlNode, parentGroup) {
const pointsStr = xmlNode.getAttribute('points');

@@ -358,15 +466,12 @@ let pointsArr;

points: pointsArr || []
}
},
silent: true
});
inheritStyle(parentGroup, polygon);
parseAttributes(xmlNode, polygon, this._defs);
parseAttributes(xmlNode, polygon, this._defsUsePending, false, false);
return polygon;
},
'polyline': function (xmlNode: SVGElement, parentGroup: Group) {
const path = new Path();
inheritStyle(parentGroup, path);
parseAttributes(xmlNode, path, this._defs);
'polyline': function (xmlNode, parentGroup) {
const pointsStr = xmlNode.getAttribute('points');

@@ -380,11 +485,15 @@ let pointsArr;

points: pointsArr || []
}
},
silent: true
});
inheritStyle(parentGroup, polyline);
parseAttributes(xmlNode, polyline, this._defsUsePending, false, false);
return polyline;
},
'image': function (xmlNode: SVGElement, parentGroup: Group) {
'image': function (xmlNode, parentGroup) {
const img = new ZRImage();
inheritStyle(parentGroup, img);
parseAttributes(xmlNode, img, this._defs);
parseAttributes(xmlNode, img, this._defsUsePending, false, false);

@@ -398,6 +507,7 @@ img.setStyle({

});
img.silent = true;
return img;
},
'text': function (xmlNode: SVGElement, parentGroup: Group) {
'text': function (xmlNode, parentGroup) {
const x = xmlNode.getAttribute('x') || '0';

@@ -413,7 +523,7 @@ const y = xmlNode.getAttribute('y') || '0';

inheritStyle(parentGroup, g);
parseAttributes(xmlNode, g, this._defs);
parseAttributes(xmlNode, g, this._defsUsePending, false, true);
return g;
},
'tspan': function (xmlNode: SVGElement, parentGroup: Group) {
'tspan': function (xmlNode, parentGroup) {
const x = xmlNode.getAttribute('x');

@@ -429,4 +539,4 @@ const y = xmlNode.getAttribute('y');

}
const dx = xmlNode.getAttribute('dx') || 0;
const dy = xmlNode.getAttribute('dy') || 0;
const dx = xmlNode.getAttribute('dx') || '0';
const dy = xmlNode.getAttribute('dy') || '0';

@@ -436,10 +546,10 @@ const g = new Group();

inheritStyle(parentGroup, g);
parseAttributes(xmlNode, g, this._defs);
parseAttributes(xmlNode, g, this._defsUsePending, false, true);
this._textX += dx as number;
this._textY += dy as number;
this._textX += parseFloat(dx);
this._textY += parseFloat(dy);
return g;
},
'path': function (xmlNode: SVGElement, parentGroup: Group) {
'path': function (xmlNode, parentGroup) {
// TODO svg fill rule

@@ -455,4 +565,6 @@ // https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/fill-rule

inheritStyle(parentGroup, path);
parseAttributes(xmlNode, path, this._defs);
parseAttributes(xmlNode, path, this._defsUsePending, false, false);
path.silent = true;
return path;

@@ -466,5 +578,7 @@ }

const defineParsers: Dictionary<(xmlNode: SVGElement) => any> = {
const paintServerParsers: Dictionary<(xmlNode: SVGElement) => any> = {
'lineargradient': function (xmlNode: SVGElement) {
// TODO:
// Support that x1,y1,x2,y2 are not declared lineargradient but in node.
const x1 = parseInt(xmlNode.getAttribute('x1') || '0', 10);

@@ -477,24 +591,54 @@ const y1 = parseInt(xmlNode.getAttribute('y1') || '0', 10);

_parseGradientColorStops(xmlNode, gradient);
parsePaintServerUnit(xmlNode, gradient);
return gradient as LinearGradientObject;
parseGradientColorStops(xmlNode, gradient);
return gradient;
},
'radialgradient': function (xmlNode) {
// TODO:
// Support that x1,y1,x2,y2 are not declared radialgradient but in node.
// TODO:
// Support fx, fy, fr.
const cx = parseInt(xmlNode.getAttribute('cx') || '0', 10);
const cy = parseInt(xmlNode.getAttribute('cy') || '0', 10);
const r = parseInt(xmlNode.getAttribute('r') || '0', 10);
const gradient = new RadialGradient(cx, cy, r);
parsePaintServerUnit(xmlNode, gradient);
parseGradientColorStops(xmlNode, gradient);
return gradient;
}
// 'radialgradient': function (xmlNode) {
// TODO
// 'pattern': function (xmlNode: SVGElement) {
// }
};
function _parseGradientColorStops(xmlNode: SVGElement, gradient: GradientObject) {
function parsePaintServerUnit(xmlNode: SVGElement, gradient: Gradient) {
const gradientUnits = xmlNode.getAttribute('gradientUnits');
if (gradientUnits === 'userSpaceOnUse') {
gradient.global = true;
}
}
function parseGradientColorStops(xmlNode: SVGElement, gradient: GradientObject): void {
let stop = xmlNode.firstChild as SVGStopElement;
while (stop) {
if (stop.nodeType === 1) {
if (stop.nodeType === 1
// there might be some other irrelevant tags used by editor.
&& stop.nodeName.toLocaleLowerCase() === 'stop'
) {
const offsetStr = stop.getAttribute('offset');
let offset: number;
if (offsetStr.indexOf('%') > 0) { // percentage
if (offsetStr && offsetStr.indexOf('%') > 0) { // percentage
offset = parseInt(offsetStr, 10) / 100;
}
else if (offsetStr) { // number from 0 to 1
else if (offsetStr) { // number from 0 to 1
offset = parseFloat(offsetStr);

@@ -506,3 +650,9 @@ }

const stopColor = stop.getAttribute('stop-color') || '#000000';
// <stop style="stop-color:red"/> has higher priority than
// <stop stop-color="red"/>
const styleVals = {} as Dictionary<string>;
parseInlineStyle(stop, styleVals, styleVals);
const stopColor = styleVals.stopColor
|| stop.getAttribute('stop-color')
|| '#000000';

@@ -518,3 +668,3 @@ gradient.colorStops.push({

function inheritStyle(parent: Element, child: Element) {
function inheritStyle(parent: Element, child: Element): void {
if (parent && (parent as ElementExtended).__inheritedStyle) {

@@ -528,4 +678,4 @@ if (!(child as ElementExtended).__inheritedStyle) {

function parsePoints(pointsString: string) {
const list = trim(pointsString).split(DILIMITER_REG);
function parsePoints(pointsString: string): number[][] {
const list = splitNumberSequence(pointsString);
const points = [];

@@ -541,31 +691,12 @@

const attributesMap = {
'fill': 'fill',
'stroke': 'stroke',
'stroke-width': 'lineWidth',
'opacity': 'opacity',
'fill-opacity': 'fillOpacity',
'stroke-opacity': 'strokeOpacity',
'stroke-dasharray': 'lineDash',
'stroke-dashoffset': 'lineDashOffset',
'stroke-linecap': 'lineCap',
'stroke-linejoin': 'lineJoin',
'stroke-miterlimit': 'miterLimit',
'font-family': 'fontFamily',
'font-size': 'fontSize',
'font-style': 'fontStyle',
'font-weight': 'fontWeight',
'text-align': 'textAlign',
'alignment-baseline': 'textBaseline'
};
function parseAttributes(
xmlNode: SVGElement,
el: Element,
defs: DefsMap,
onlyInlineStyle?: boolean
) {
defsUsePending: DefsUsePending,
onlyInlineStyle: boolean,
isTextGroup: boolean
): void {
const disp = el as DisplayableExtended;
const zrStyle = disp.__inheritedStyle || {};
const inheritedStyle = disp.__inheritedStyle = disp.__inheritedStyle || {};
const selfStyle: SelfStyleByZRKey = {};

@@ -576,13 +707,6 @@ // TODO Shadow

extend(zrStyle, parseStyleAttribute(xmlNode));
parseInlineStyle(xmlNode, inheritedStyle, selfStyle);
if (!onlyInlineStyle) {
for (let svgAttrName in attributesMap) {
if (attributesMap.hasOwnProperty(svgAttrName)) {
const attrValue = xmlNode.getAttribute(svgAttrName);
if (attrValue != null) {
zrStyle[attributesMap[svgAttrName as keyof typeof attributesMap]] = attrValue;
}
}
}
parseAttributeStyle(xmlNode, inheritedStyle, selfStyle);
}

@@ -593,57 +717,140 @@ }

zrStyle.fill != null && (disp.style.fill = getPaint(zrStyle.fill, defs));
zrStyle.stroke != null && (disp.style.stroke = getPaint(zrStyle.stroke, defs));
if (inheritedStyle.fill != null) {
disp.style.fill = getFillStrokeStyle(disp, 'fill', inheritedStyle.fill, defsUsePending);
}
if (inheritedStyle.stroke != null) {
disp.style.stroke = getFillStrokeStyle(disp, 'stroke', inheritedStyle.stroke, defsUsePending);
}
each([
'lineWidth', 'opacity', 'fillOpacity', 'strokeOpacity', 'miterLimit', 'fontSize'
], function (propName) {
zrStyle[propName] != null && (disp.style[propName] = parseFloat(zrStyle[propName]));
] as const, function (propName) {
if (inheritedStyle[propName] != null) {
disp.style[propName] = parseFloat(inheritedStyle[propName]);
}
});
if (!zrStyle.textBaseline || zrStyle.textBaseline === 'auto') {
zrStyle.textBaseline = 'alphabetic';
each([
'lineDashOffset', 'lineCap', 'lineJoin', 'fontWeight', 'fontFamily', 'fontStyle', 'textAlign'
] as const, function (propName) {
if (inheritedStyle[propName] != null) {
disp.style[propName] = inheritedStyle[propName];
}
});
// Because selfStyle only support textBaseline, so only text group need it.
// in other cases selfStyle can be released.
if (isTextGroup) {
disp.__selfStyle = selfStyle;
}
if (zrStyle.textBaseline === 'alphabetic') {
zrStyle.textBaseline = 'bottom';
if (inheritedStyle.lineDash) {
disp.style.lineDash = map(splitNumberSequence(inheritedStyle.lineDash), function (str) {
return parseFloat(str);
});
}
if (zrStyle.textAlign === 'start') {
zrStyle.textAlign = 'left';
if (inheritedStyle.visibility === 'hidden' || inheritedStyle.visibility === 'collapse') {
disp.invisible = true;
}
if (zrStyle.textAlign === 'end') {
zrStyle.textAlign = 'right';
if (inheritedStyle.display === 'none') {
disp.ignore = true;
}
each(['lineDashOffset', 'lineCap', 'lineJoin',
'fontWeight', 'fontFamily', 'fontStyle', 'textAlign', 'textBaseline'
], function (propName) {
zrStyle[propName] != null && (disp.style[propName] = zrStyle[propName]);
});
disp.z = -10000;
disp.z2 = -1000;
}
if (zrStyle.lineDash) {
disp.style.lineDash = map(trim(zrStyle.lineDash).split(DILIMITER_REG), function (str) {
return parseFloat(str);
});
function applyTextAlignment(
text: TSpan,
parentGroup: Group
): void {
const parentSelfStyle = (parentGroup as ElementExtended).__selfStyle;
if (parentSelfStyle) {
const textBaseline = parentSelfStyle.textBaseline;
let zrTextBaseline = textBaseline as CanvasTextBaseline;
if (!textBaseline || textBaseline === 'auto') {
// FIXME: 'auto' means the value is the dominant-baseline of the script to
// which the character belongs - i.e., use the dominant-baseline of the parent.
zrTextBaseline = 'alphabetic';
}
else if (textBaseline === 'baseline') {
zrTextBaseline = 'alphabetic';
}
else if (textBaseline === 'before-edge' || textBaseline === 'text-before-edge') {
zrTextBaseline = 'top';
}
else if (textBaseline === 'after-edge' || textBaseline === 'text-after-edge') {
zrTextBaseline = 'bottom';
}
else if (textBaseline === 'central' || textBaseline === 'mathematical') {
zrTextBaseline = 'middle';
}
text.style.textBaseline = zrTextBaseline;
}
disp.__inheritedStyle = zrStyle;
const parentInheritedStyle = (parentGroup as ElementExtended).__inheritedStyle;
if (parentInheritedStyle) {
// PENDING:
// canvas `direction` is an experimental attribute.
// so we do not support SVG direction "rtl" for text-anchor yet.
const textAlign = parentInheritedStyle.textAlign;
let zrTextAlign = textAlign as CanvasTextAlign;
if (textAlign) {
if (textAlign === 'middle') {
zrTextAlign = 'center';
}
text.style.textAlign = zrTextAlign;
}
}
}
const urlRegex = /url\(\s*#(.*?)\)/;
function getPaint(str: string, defs: DefsMap) {
// if (str === 'none') {
// return;
// }
const urlMatch = defs && str && str.match(urlRegex);
// Support `fill:url(#someId)`.
const urlRegex = /^url\(\s*#(.*?)\)/;
function getFillStrokeStyle(
el: Displayable,
method: 'fill' | 'stroke',
str: string,
defsUsePending: DefsUsePending
): string {
const urlMatch = str && str.match(urlRegex);
if (urlMatch) {
const url = trim(urlMatch[1]);
const def = defs[url];
return def;
defsUsePending.push([el, method, url]);
return;
}
// SVG fill and stroke can be 'none'.
if (str === 'none') {
str = null;
}
return str;
}
const transformRegex = /(translate|scale|rotate|skewX|skewY|matrix)\(([\-\s0-9\.e,]*)\)/g;
function applyDefs(
defs: DefsMap,
defsUsePending: DefsUsePending
): void {
for (let i = 0; i < defsUsePending.length; i++) {
const item = defsUsePending[i];
item[0].style[item[1]] = defs[item[2]];
}
}
function parseTransformAttribute(xmlNode: SVGElement, node: Element) {
// value can be like:
// '2e-4', 'l.5.9' (ignore 0), 'M-10-10', 'l-2.43e-1,34.9983',
// 'l-.5E1,54', '121-23-44-11' (no delimiter)
// PENDING: here continuous commas are treat as one comma, but the
// browser SVG parser treats this by printing error.
const numberReg = /-?([0-9]*\.)?[0-9]+([eE]-?[0-9]+)?/g;
function splitNumberSequence(rawStr: string): string[] {
return rawStr.match(numberReg) || [];
}
// Most of the values can be separated by comma and/or white space.
// const DILIMITER_REG = /[\s,]+/;
const transformRegex = /(translate|scale|rotate|skewX|skewY|matrix)\(([\-\s0-9\.eE,]*)\)/g;
function parseTransformAttribute(xmlNode: SVGElement, node: Element): void {
let transform = xmlNode.getAttribute('transform');

@@ -653,3 +860,3 @@ if (transform) {

const transformOps: string[] = [];
let m = null;
let mt = null;
transform.replace(transformRegex, function (str: string, type: string, value: string) {

@@ -663,32 +870,32 @@ transformOps.push(type, value);

let valueArr: string[];
m = m || matrix.create();
mt = mt || matrix.create();
switch (type) {
case 'translate':
valueArr = trim(value).split(DILIMITER_REG);
matrix.translate(m, m, [parseFloat(valueArr[0]), parseFloat(valueArr[1] || '0')]);
valueArr = splitNumberSequence(value);
matrix.translate(mt, mt, [parseFloat(valueArr[0]), parseFloat(valueArr[1] || '0')]);
break;
case 'scale':
valueArr = trim(value).split(DILIMITER_REG);
matrix.scale(m, m, [parseFloat(valueArr[0]), parseFloat(valueArr[1] || valueArr[0])]);
valueArr = splitNumberSequence(value);
matrix.scale(mt, mt, [parseFloat(valueArr[0]), parseFloat(valueArr[1] || valueArr[0])]);
break;
case 'rotate':
valueArr = trim(value).split(DILIMITER_REG);
matrix.rotate(m, m, parseFloat(valueArr[0]));
valueArr = splitNumberSequence(value);
matrix.rotate(mt, mt, -parseFloat(valueArr[0]) / 180 * Math.PI);
break;
case 'skew':
valueArr = trim(value).split(DILIMITER_REG);
valueArr = splitNumberSequence(value);
console.warn('Skew transform is not supported yet');
break;
case 'matrix':
valueArr = trim(value).split(DILIMITER_REG);
m[0] = parseFloat(valueArr[0]);
m[1] = parseFloat(valueArr[1]);
m[2] = parseFloat(valueArr[2]);
m[3] = parseFloat(valueArr[3]);
m[4] = parseFloat(valueArr[4]);
m[5] = parseFloat(valueArr[5]);
valueArr = splitNumberSequence(value);
mt[0] = parseFloat(valueArr[0]);
mt[1] = parseFloat(valueArr[1]);
mt[2] = parseFloat(valueArr[2]);
mt[3] = parseFloat(valueArr[3]);
mt[4] = parseFloat(valueArr[4]);
mt[5] = parseFloat(valueArr[5]);
break;
}
}
node.setLocalTransform(m);
node.setLocalTransform(mt);
}

@@ -699,33 +906,62 @@ }

const styleRegex = /([^\s:;]+)\s*:\s*([^:;]+)/g;
function parseStyleAttribute(xmlNode: SVGElement) {
function parseInlineStyle(
xmlNode: SVGElement,
inheritableStyleResult: Dictionary<string>,
selfStyleResult: Dictionary<string>
): void {
const style = xmlNode.getAttribute('style');
const result: Dictionary<string> = {};
if (!style) {
return result;
return;
}
const styleList: Dictionary<string> = {};
styleRegex.lastIndex = 0;
let styleRegResult;
while ((styleRegResult = styleRegex.exec(style)) != null) {
styleList[styleRegResult[1]] = styleRegResult[2];
const svgStlAttr = styleRegResult[1];
const zrInheritableStlAttr = hasOwn(INHERITABLE_STYLE_ATTRIBUTES_MAP, svgStlAttr)
? INHERITABLE_STYLE_ATTRIBUTES_MAP[svgStlAttr as keyof typeof INHERITABLE_STYLE_ATTRIBUTES_MAP]
: null;
if (zrInheritableStlAttr) {
inheritableStyleResult[zrInheritableStlAttr] = styleRegResult[2];
}
const zrSelfStlAttr = hasOwn(SELF_STYLE_ATTRIBUTES_MAP, svgStlAttr)
? SELF_STYLE_ATTRIBUTES_MAP[svgStlAttr as keyof typeof SELF_STYLE_ATTRIBUTES_MAP]
: null;
if (zrSelfStlAttr) {
selfStyleResult[zrSelfStlAttr] = styleRegResult[2];
}
}
}
for (const svgAttrName in attributesMap) {
if (attributesMap.hasOwnProperty(svgAttrName) && styleList[svgAttrName] != null) {
result[attributesMap[svgAttrName as keyof typeof attributesMap]] = styleList[svgAttrName];
function parseAttributeStyle(
xmlNode: SVGElement,
inheritableStyleResult: Dictionary<string>,
selfStyleResult: Dictionary<string>
): void {
for (let i = 0; i < INHERITABLE_STYLE_ATTRIBUTES_MAP_KEYS.length; i++) {
const svgAttrName = INHERITABLE_STYLE_ATTRIBUTES_MAP_KEYS[i];
const attrValue = xmlNode.getAttribute(svgAttrName);
if (attrValue != null) {
inheritableStyleResult[INHERITABLE_STYLE_ATTRIBUTES_MAP[svgAttrName]] = attrValue;
}
}
return result;
for (let i = 0; i < SELF_STYLE_ATTRIBUTES_MAP_KEYS.length; i++) {
const svgAttrName = SELF_STYLE_ATTRIBUTES_MAP_KEYS[i];
const attrValue = xmlNode.getAttribute(svgAttrName);
if (attrValue != null) {
selfStyleResult[SELF_STYLE_ATTRIBUTES_MAP[svgAttrName]] = attrValue;
}
}
}
export function makeViewBoxTransform(viewBoxRect: RectLike, width: number, height: number): {
scale: number
x: number
y: number
export function makeViewBoxTransform(viewBoxRect: RectLike, boundingRect: RectLike): {
scale: number;
x: number;
y: number;
} {
const scaleX = width / viewBoxRect.width;
const scaleY = height / viewBoxRect.height;
const scaleX = boundingRect.width / viewBoxRect.width;
const scaleY = boundingRect.height / viewBoxRect.height;
const scale = Math.min(scaleX, scaleY);

@@ -736,4 +972,4 @@ // preserveAspectRatio 'xMidYMid'

scale,
x: -(viewBoxRect.x + viewBoxRect.width / 2) * scale + width / 2,
y: -(viewBoxRect.y + viewBoxRect.height / 2) * scale + height / 2
x: -(viewBoxRect.x + viewBoxRect.width / 2) * scale + (boundingRect.x + boundingRect.width / 2),
y: -(viewBoxRect.y + viewBoxRect.height / 2) * scale + (boundingRect.y + boundingRect.height / 2)
};

@@ -749,2 +985,2 @@ }

// Also export parseXML to avoid breaking change.
export {parseXML};
export {parseXML};

@@ -523,5 +523,5 @@ /*!

*/
export const version = '5.0.4';
export const version = '5.1.0';
export interface ZRenderType extends ZRender {};

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is too big to display

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc