-
Notifications
You must be signed in to change notification settings - Fork 3.5k
/
SVGElement.ts
2707 lines (2441 loc) · 82.9 KB
/
SVGElement.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* *
*
* (c) 2010-2024 Torstein Honsi
*
* License: www.highcharts.com/license
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*
* */
'use strict';
/* *
*
* Imports
*
* */
import type AlignObject from '../AlignObject';
import type AnimationOptions from '../../Animation/AnimationOptions';
import type BBoxObject from '../BBoxObject';
import type ColorString from '../../Color/ColorString';
import type ColorType from '../../Color/ColorType';
import type CSSObject from '../CSSObject';
import type {
DOMElementType,
HTMLDOMElement,
SVGDOMElement
} from '../DOMElementType';
import type FontMetricsObject from '../FontMetricsObject';
import type GradientColor from '../../Color/GradientColor';
import type RectangleObject from '../RectangleObject';
import type ShadowOptionsObject from '../ShadowOptionsObject';
import type SVGAttributes from './SVGAttributes';
import type SVGElementLike from './SVGElementLike';
import type SVGPath from './SVGPath';
import type SVGRenderer from './SVGRenderer';
import A from '../../Animation/AnimationUtilities.js';
const {
animate,
animObject,
stop
} = A;
import Color from '../../Color/Color.js';
import H from '../../Globals.js';
const {
deg2rad,
doc,
svg,
SVG_NS,
win
} = H;
import U from '../../Utilities.js';
const {
addEvent,
attr,
createElement,
css,
defined,
erase,
extend,
fireEvent,
isArray,
isFunction,
isObject,
isString,
merge,
objectEach,
pick,
pInt,
replaceNested,
syncTimeout,
uniqueKey
} = U;
/* *
*
* Declarations
*
* */
/**
* @private
*/
declare module '../CSSObject' {
interface CSSObject {
strokeWidth?: (number|string);
}
}
interface TextPathObject {
path: SVGElement;
undo: Function;
}
/* *
*
* Class
*
* */
/* eslint-disable no-invalid-this, valid-jsdoc */
/**
* The SVGElement prototype is a JavaScript wrapper for SVG elements used in the
* rendering layer of Highcharts. Combined with the
* {@link Highcharts.SVGRenderer}
* object, these prototypes allow freeform annotation in the charts or even in
* HTML pages without instanciating a chart. The SVGElement can also wrap HTML
* labels, when `text` or `label` elements are created with the `useHTML`
* parameter.
*
* The SVGElement instances are created through factory functions on the
* {@link Highcharts.SVGRenderer}
* object, like
* {@link Highcharts.SVGRenderer#rect|rect},
* {@link Highcharts.SVGRenderer#path|path},
* {@link Highcharts.SVGRenderer#text|text},
* {@link Highcharts.SVGRenderer#label|label},
* {@link Highcharts.SVGRenderer#g|g}
* and more.
*
* See [How to use the SVG Renderer](
* https://www.highcharts.com/docs/advanced-chart-features/renderer) for a
* comprehensive tutorial on how to draw SVG elements on a chart.
*
* @class
* @name Highcharts.SVGElement
*/
class SVGElement implements SVGElementLike {
/* *
*
* Properties
*
* */
// Custom attributes used for symbols, these should be filtered out when
// setting SVGElement attributes (#9375).
public static symbolCustomAttribs: Array<string> = [
'anchorX',
'anchorY',
'clockwise',
'end',
'height',
'innerR',
'r',
'start',
'width',
'x',
'y'
];
public added?: boolean;
// @todo public alignAttr?: SVGAttributes;
public alignByTranslate?: boolean;
// @todo public alignOptions?: AlignObject;
public alignTo?: string;
public alignValue?: ('left'|'center'|'right');
public clipPath?: SVGElement;
// @todo public d?: number;
public div?: HTMLDOMElement;
public doTransform?: boolean;
public element: DOMElementType;
public fakeTS?: boolean;
public firstLineMetrics?: FontMetricsObject;
public handleZ?: boolean;
public hasBoxWidthChanged?: boolean;
public height?: number;
public imgwidth?: number;
public imgheight?: number;
public inverted: undefined;
public matrix?: Array<number>;
public onEvents: Record<string, Function> = {};
public opacity = 1; // Default base for animation
// @todo public options?: AnyRecord;
public parentGroup?: SVGElement;
public pathArray?: SVGPath;
public placed?: boolean;
public r?: number;
public radAttr?: SVGAttributes;
public renderer: SVGRenderer;
public rotation?: number;
public rotationOriginX?: number;
public rotationOriginY?: number;
public scaleX?: number;
public scaleY?: number;
public stops?: Array<SVGElement>;
public stroke?: ColorType;
// @todo public 'stroke-width'?: number;
public styledMode?: boolean;
public styles: CSSObject;
public SVG_NS = SVG_NS;
public symbolName?: string;
public text?: SVGElement;
public textStr?: string;
public textWidth?: number;
public textPath?: TextPathObject;
// @todo public textPxLength?: number;
public translateX?: number;
public translateY?: number;
public visibility?: 'hidden'|'inherit'|'visible';
public width?: number;
public x?: number;
public y?: number;
// @todo public zIndex?: number;
/* *
*
* Functions
*
* */
/**
* Get the current value of an attribute or pseudo attribute,
* used mainly for animation. Called internally from
* the {@link Highcharts.SVGRenderer#attr} function.
*
* @private
* @function Highcharts.SVGElement#_defaultGetter
*
* @param {string} key
* Property key.
*
* @return {number|string}
* Property value.
*/
private _defaultGetter(key: string): (number|string) {
let ret = pick(
(this as AnyRecord)[key + 'Value'], // align getter
(this as AnyRecord)[key],
this.element ? this.element.getAttribute(key) : null,
0
);
if (/^[\-0-9\.]+$/.test(ret)) { // is numerical
ret = parseFloat(ret);
}
return ret;
}
/**
* @private
* @function Highcharts.SVGElement#_defaultSetter
*
* @param {string} value
*
* @param {string} key
*
* @param {Highcharts.SVGDOMElement} element
*
*/
public _defaultSetter(
value: string,
key: string,
element: SVGDOMElement
): void {
element.setAttribute(key, value);
}
/**
* Add the element to the DOM. All elements must be added this way.
*
* @sample highcharts/members/renderer-g
* Elements added to a group
*
* @function Highcharts.SVGElement#add
*
* @param {Highcharts.SVGElement} [parent]
* The parent item to add it to. If undefined, the element is added
* to the {@link Highcharts.SVGRenderer.box}.
*
* @return {Highcharts.SVGElement}
* Returns the SVGElement for chaining.
*/
public add(parent?: SVGElement): this {
const renderer = this.renderer,
element = this.element;
let inserted;
if (parent) {
this.parentGroup = parent;
}
// Build formatted text
if (
typeof this.textStr !== 'undefined' &&
this.element.nodeName === 'text' // Not for SVGLabel instances
) {
renderer.buildText(this);
}
// Mark as added
this.added = true;
// If we're adding to renderer root, or other elements in the group
// have a z index, we need to handle it
if (!parent || parent.handleZ || this.zIndex) {
inserted = this.zIndexSetter();
}
// If zIndex is not handled, append at the end
if (!inserted) {
(parent ?
parent.element :
renderer.box
).appendChild(element);
}
// fire an event for internal hooks
if (this.onAdd) {
this.onAdd();
}
return this;
}
/**
* Add a class name to an element.
*
* @function Highcharts.SVGElement#addClass
*
* @param {string} className
* The new class name to add.
*
* @param {boolean} [replace=false]
* When true, the existing class name(s) will be overwritten with the new
* one. When false, the new one is added.
*
* @return {Highcharts.SVGElement}
* Return the SVG element for chainability.
*/
public addClass(
className: string,
replace?: boolean
): this {
const currentClassName = replace ? '' : (this.attr('class') || '');
// Trim the string and remove duplicates
className = (className || '')
.split(/ /g)
.reduce(function (
newClassName: Array<string>,
name: string
): Array<string> {
if ((currentClassName as any).indexOf(name) === -1) {
newClassName.push(name);
}
return newClassName;
}, (currentClassName ?
[currentClassName] :
[]
) as Array<string>)
.join(' ');
if (className !== currentClassName) {
this.attr('class', className);
}
return this;
}
/**
* This method is executed in the end of `attr()`, after setting all
* attributes in the hash. In can be used to efficiently consolidate
* multiple attributes in one SVG property -- e.g., translate, rotate and
* scale are merged in one "transform" attribute in the SVG node.
*
* @private
* @function Highcharts.SVGElement#afterSetters
*/
public afterSetters(): void {
// Update transform. Do this outside the loop to prevent redundant
// updating for batch setting of attributes.
if (this.doTransform) {
this.updateTransform();
this.doTransform = false;
}
}
/**
* Align the element relative to the chart or another box.
*
* @function Highcharts.SVGElement#align
*
* @param {Highcharts.AlignObject} [alignOptions]
* The alignment options. The function can be called without this
* parameter in order to re-align an element after the box has been
* updated.
*
* @param {boolean} [alignByTranslate]
* Align element by translation.
*
* @param {string|Highcharts.BBoxObject} [box]
* The box to align to, needs a width and height. When the box is a
* string, it refers to an object in the Renderer. For example, when
* box is `spacingBox`, it refers to `Renderer.spacingBox` which
* holds `width`, `height`, `x` and `y` properties.
*
* @param {boolean} [redraw]
* Decide if SVGElement should be redrawn with new alignment or
* just change its attributes.
*
* @return {Highcharts.SVGElement} Returns the SVGElement for chaining.
*/
public align(
alignOptions?: AlignObject,
alignByTranslate?: boolean,
box?: (string|BBoxObject),
redraw: boolean = true
): this {
const attribs = {} as SVGAttributes,
renderer = this.renderer,
alignedObjects: Array<SVGElement> = renderer.alignedObjects as any;
let x,
y,
alignTo: (string|undefined),
alignFactor,
vAlignFactor;
// First call on instanciate
if (alignOptions) {
this.alignOptions = alignOptions;
this.alignByTranslate = alignByTranslate;
if (!box || isString(box)) {
this.alignTo = alignTo = box || 'renderer';
// prevent duplicates, like legendGroup after resize
erase(alignedObjects, this);
alignedObjects.push(this);
box = void 0; // reassign it below
}
// When called on resize, no arguments are supplied
} else {
alignOptions = this.alignOptions;
alignByTranslate = this.alignByTranslate;
alignTo = this.alignTo;
}
box = pick(
box,
(renderer as any)[alignTo as any],
renderer as any
);
// Assign variables
const align = (alignOptions as any).align,
vAlign = (alignOptions as any).verticalAlign;
// default: left align
x = ((box as any).x || 0) + ((alignOptions as any).x || 0);
// default: top align
y = ((box as any).y || 0) + ((alignOptions as any).y || 0);
// Align
if (align === 'right') {
alignFactor = 1;
} else if (align === 'center') {
alignFactor = 2;
}
if (alignFactor) {
x += ((box as any).width - ((alignOptions as any).width || 0)) /
alignFactor;
}
attribs[alignByTranslate ? 'translateX' : 'x'] = Math.round(x);
// Vertical align
if (vAlign === 'bottom') {
vAlignFactor = 1;
} else if (vAlign === 'middle') {
vAlignFactor = 2;
}
if (vAlignFactor) {
y += ((box as any).height - ((alignOptions as any).height || 0)) /
vAlignFactor;
}
attribs[alignByTranslate ? 'translateY' : 'y'] = Math.round(y);
// Animate only if already placed
if (redraw) {
this[this.placed ? 'animate' : 'attr'](attribs);
this.placed = true;
}
this.alignAttr = attribs;
return this;
}
/**
* @private
* @function Highcharts.SVGElement#alignSetter
* @param {"left"|"center"|"right"} value
*/
public alignSetter(value: ('left'|'center'|'right')): void {
const convert: Record<string, string> = {
left: 'start',
center: 'middle',
right: 'end'
};
if (convert[value]) {
this.alignValue = value;
this.element.setAttribute('text-anchor', convert[value]);
}
}
/**
* Animate to given attributes or CSS properties.
*
* @sample highcharts/members/element-on/
* Setting some attributes by animation
*
* @function Highcharts.SVGElement#animate
*
* @param {Highcharts.SVGAttributes} params
* SVG attributes or CSS to animate.
*
* @param {boolean|Partial<Highcharts.AnimationOptionsObject>} [options]
* Animation options.
*
* @param {Function} [complete]
* Function to perform at the end of animation.
*
* @return {Highcharts.SVGElement}
* Returns the SVGElement for chaining.
*/
public animate(
params: SVGAttributes,
options?: (boolean|DeepPartial<AnimationOptions>),
complete?: Function
): this {
const animOptions = animObject(
pick(options, this.renderer.globalAnimation, true)
),
deferTime = animOptions.defer;
// When the page is hidden save resources in the background by not
// running animation at all (#9749).
if (doc.hidden) {
animOptions.duration = 0;
}
if (animOptions.duration !== 0) {
// allows using a callback with the global animation without
// overwriting it
if (complete) {
animOptions.complete = complete;
}
// If defer option is defined delay the animation #12901
syncTimeout((): void => {
if (this.element) {
animate(this, params, animOptions);
}
}, deferTime);
} else {
this.attr(params, void 0, complete || animOptions.complete);
// Call the end step synchronously
objectEach(params, function (val: any, prop: string): void {
if (animOptions.step) {
animOptions.step.call(
this,
val,
{ prop: prop, pos: 1, elem: this }
);
}
}, this);
}
return this;
}
/**
* Apply a text outline through a custom CSS property, by copying the text
* element and apply stroke to the copy. Used internally. Contrast checks at
* [example](https://jsfiddle.net/highcharts/43soe9m1/2/).
*
* @example
* // Specific color
* text.css({
* textOutline: '1px black'
* });
* // Automatic contrast
* text.css({
* color: '#000000', // black text
* textOutline: '1px contrast' // => white outline
* });
*
* @private
* @function Highcharts.SVGElement#applyTextOutline
*
* @param {string} textOutline
* A custom CSS `text-outline` setting, defined by `width color`.
*/
public applyTextOutline(textOutline: string): void {
const elem = this.element,
hasContrast = textOutline.indexOf('contrast') !== -1,
styles: CSSObject = {};
// When the text shadow is set to contrast, use dark stroke for light
// text and vice versa.
if (hasContrast) {
styles.textOutline = textOutline = textOutline.replace(
/contrast/g,
this.renderer.getContrast(elem.style.fill)
);
}
// Extract the stroke width and color
const parts = textOutline.split(' ');
const color: ColorString = parts[parts.length - 1];
let strokeWidth = parts[0];
if (strokeWidth && strokeWidth !== 'none' && H.svg) {
this.fakeTS = true; // Fake text shadow
// Since the stroke is applied on center of the actual outline, we
// need to double it to get the correct stroke-width outside the
// glyphs.
strokeWidth = strokeWidth.replace(
/(^[\d\.]+)(.*?)$/g,
function (match: string, digit: string, unit: string): string {
return (2 * Number(digit)) + unit;
}
);
// Remove shadows from previous runs.
this.removeTextOutline();
const outline = doc.createElementNS(
SVG_NS,
'tspan'
) as DOMElementType;
attr(outline, {
'class': 'highcharts-text-outline',
fill: color,
stroke: color,
'stroke-width': strokeWidth as any,
'stroke-linejoin': 'round'
});
// For each of the tspans and text nodes, create a copy in the
// outline.
const parentElem = elem.querySelector('textPath') || elem;
[].forEach.call(
parentElem.childNodes,
(childNode: ChildNode): void => {
const clone = childNode.cloneNode(true);
if ((clone as DOMElementType).removeAttribute) {
['fill', 'stroke', 'stroke-width', 'stroke'].forEach(
(prop): void => (clone as DOMElementType)
.removeAttribute(prop)
);
}
outline.appendChild(clone);
}
);
// Collect the sum of dy from all children, included nested ones
let totalHeight = 0;
[].forEach.call(
parentElem.querySelectorAll('text tspan'),
(element): void => {
totalHeight += Number(
(element as DOMElementType).getAttribute('dy')
);
}
);
// Insert an absolutely positioned break before the original text
// to keep it in place
const br = doc.createElementNS(SVG_NS, 'tspan') as DOMElementType;
br.textContent = '\u200B';
// Reset the position for the following text
attr(br, {
x: Number(elem.getAttribute('x')),
dy: -totalHeight
});
// Insert the outline
outline.appendChild(br);
parentElem.insertBefore(outline, parentElem.firstChild);
}
}
public attr(key: string): (number|string);
public attr(
key: string,
val: (number|string|ColorType|SVGPath),
complete?: Function,
continueAnimation?: boolean
): this;
public attr(
hash?: SVGAttributes,
val?: undefined,
complete?: Function,
continueAnimation?: boolean
): this;
/**
* @function Highcharts.SVGElement#attr
* @param {string} key
* @return {number|string}
*//**
* Apply native and custom attributes to the SVG elements.
*
* In order to set the rotation center for rotation, set x and y to 0 and
* use `translateX` and `translateY` attributes to position the element
* instead.
*
* Attributes frequently used in Highcharts are `fill`, `stroke`,
* `stroke-width`.
*
* @sample highcharts/members/renderer-rect/
* Setting some attributes
*
* @example
* // Set multiple attributes
* element.attr({
* stroke: 'red',
* fill: 'blue',
* x: 10,
* y: 10
* });
*
* // Set a single attribute
* element.attr('stroke', 'red');
*
* // Get an attribute
* element.attr('stroke'); // => 'red'
*
* @function Highcharts.SVGElement#attr
*
* @param {string|Highcharts.SVGAttributes} [hash]
* The native and custom SVG attributes.
*
* @param {number|string|Highcharts.SVGPathArray} [val]
* If the type of the first argument is `string`, the second can be a
* value, which will serve as a single attribute setter. If the first
* argument is a string and the second is undefined, the function
* serves as a getter and the current value of the property is
* returned.
*
* @param {Function} [complete]
* A callback function to execute after setting the attributes. This
* makes the function compliant and interchangeable with the
* {@link SVGElement#animate} function.
*
* @param {boolean} [continueAnimation=true]
* Used internally when `.attr` is called as part of an animation
* step. Otherwise, calling `.attr` for an attribute will stop
* animation for that attribute.
*
* @return {Highcharts.SVGElement}
* If used as a setter, it returns the current
* {@link Highcharts.SVGElement} so the calls can be chained. If
* used as a getter, the current value of the attribute is returned.
*/
public attr(
hash?: (string|SVGAttributes),
val?: (number|string|ColorType|SVGPath),
complete?: Function,
continueAnimation?: boolean
): (number|string|this) {
const element = this.element,
symbolCustomAttribs = SVGElement.symbolCustomAttribs;
let key,
hasSetSymbolSize: boolean,
ret = this,
skipAttr,
setter;
// single key-value pair
if (typeof hash === 'string' && typeof val !== 'undefined') {
key = hash;
hash = {};
(hash as any)[key] = val;
}
// used as a getter: first argument is a string, second is undefined
if (typeof hash === 'string') {
ret = (
(this as AnyRecord)[hash + 'Getter'] ||
(this as AnyRecord)._defaultGetter
).call(
this,
hash,
element
);
// setter
} else {
objectEach(hash, function eachAttribute(
val: any,
key: string
): void {
skipAttr = false;
// Unless .attr is from the animator update, stop current
// running animation of this property
if (!continueAnimation) {
stop(this as any, key);
}
// Special handling of symbol attributes
if (
this.symbolName &&
symbolCustomAttribs.indexOf(key) !== -1
) {
if (!hasSetSymbolSize) {
this.symbolAttr(hash as any);
hasSetSymbolSize = true;
}
skipAttr = true;
}
if (this.rotation && (key === 'x' || key === 'y')) {
this.doTransform = true;
}
if (!skipAttr) {
setter = (
(this as AnyRecord)[key + 'Setter'] ||
(this as AnyRecord)._defaultSetter
);
setter.call(this, val, key, element);
}
}, this);
this.afterSetters();
}
// In accordance with animate, run a complete callback
if (complete) {
complete.call(this);
}
return ret;
}
/**
* Apply a clipping shape to this element.
*
* @function Highcharts.SVGElement#clip
*
* @param {SVGElement} [clipElem]
* The clipping shape. If skipped, the current clip is removed.
*
* @return {Highcharts.SVGElement}
* Returns the SVG element to allow chaining.
*/
public clip(clipElem?: SVGElement): this {
if (clipElem && !clipElem.clipPath) {
// Add a hyphen at the end to avoid confusion in testing indexes
// -1 and -10, -11 etc (#6550)
const id = uniqueKey() + '-',
clipPath = this.renderer.createElement('clipPath')
.attr({ id })
.add(this.renderer.defs);
extend(clipElem, { clipPath, id, count: 0 });
clipElem.add(clipPath);
}
return this.attr(
'clip-path',
clipElem ?
`url(${this.renderer.url}#${clipElem.id})` :
'none'
);
}
/**
* Calculate the coordinates needed for drawing a rectangle crisply and
* return the calculated attributes.
*
* @function Highcharts.SVGElement#crisp
*
* @param {Highcharts.RectangleObject} rect
* Rectangle to crisp.
*
* @param {number} [strokeWidth]
* The stroke width to consider when computing crisp positioning. It can
* also be set directly on the rect parameter.
*
* @return {Highcharts.RectangleObject}
* The modified rectangle arguments.
*/
public crisp(
rect: RectangleObject,
strokeWidth?: number
): RectangleObject {
const wrapper = this;
strokeWidth = strokeWidth || rect.strokeWidth || 0;
// Math.round because strokeWidth can sometimes have roundoff errors
const normalizer = Math.round(strokeWidth) % 2 / 2;
// normalize for crisp edges
rect.x = Math.floor(rect.x || wrapper.x || 0) + normalizer;
rect.y = Math.floor(rect.y || wrapper.y || 0) + normalizer;
rect.width = Math.floor(
(rect.width || wrapper.width || 0) - 2 * normalizer
);
rect.height = Math.floor(
(rect.height || wrapper.height || 0) - 2 * normalizer
);
if (defined(rect.strokeWidth)) {
rect.strokeWidth = strokeWidth;
}
return rect;
}
/**
* Build and apply an SVG gradient out of a common JavaScript configuration
* object. This function is called from the attribute setters. An event
* hook is added for supporting other complex color types.
*
* @private
* @function Highcharts.SVGElement#complexColor
*
* @param {Highcharts.GradientColorObject|Highcharts.PatternObject} colorOptions
* The gradient or pattern options structure.
*
* @param {string} prop
* The property to apply, can either be `fill` or `stroke`.
*
* @param {Highcharts.SVGDOMElement} elem
* SVG element to apply the gradient on.
*/
public complexColor(
colorOptions: Exclude<ColorType, ColorString>,
prop: string,
elem: SVGDOMElement
): void {
const renderer = this.renderer;
let colorObject,
gradName: keyof GradientColor,
gradAttr: SVGAttributes,
radAttr: SVGAttributes,
gradients: Record<string, SVGElement>,
stops: (GradientColor['stops']|undefined),
stopColor: ColorString,
stopOpacity,
radialReference: Array<number>,
id,
key: (string|Array<string>) = [],
value: string;
fireEvent(this.renderer, 'complexColor', {
args: arguments
}, function (): void {
// Apply linear or radial gradients
if ((colorOptions as GradientColor).radialGradient) {
gradName = 'radialGradient';
} else if ((colorOptions as GradientColor).linearGradient) {
gradName = 'linearGradient';
}
if (gradName) {
gradAttr = (colorOptions as GradientColor)[gradName] as any;
gradients = renderer.gradients as any;
stops = (colorOptions as GradientColor).stops;
radialReference = (elem as any).radialReference;
// Keep < 2.2 compatibility
if (isArray(gradAttr)) {
(colorOptions as any)[gradName] = gradAttr = {
x1: gradAttr[0] as number,
y1: gradAttr[1] as number,
x2: gradAttr[2] as number,
y2: gradAttr[3] as number,
gradientUnits: 'userSpaceOnUse'
};
}
// Correct the radial gradient for the radial reference system
if (
gradName === 'radialGradient' &&
radialReference &&
!defined(gradAttr.gradientUnits)
) {
// Save the radial attributes for updating
radAttr = gradAttr;
gradAttr = merge(
gradAttr,
renderer.getRadialAttr(radialReference, radAttr),
{ gradientUnits: 'userSpaceOnUse' }
);
}
// Build the unique key to detect whether we need to create a
// new element (#1282)
objectEach(gradAttr, function (value, n): void {
if (n !== 'id') {