1
1
import { line as d3Line } from 'd3-shape'
2
2
import type { Selection } from 'd3-selection'
3
3
4
- import type { FunctionPlotOptions } from '../types.js'
5
- import { Mark } from '../graph-types/mark.js'
4
+ import type { FunctionPlotAnnotation } from '../types.js'
6
5
7
- const line = d3Line ( )
8
- . x ( ( d ) => d [ 0 ] )
9
- . y ( ( d ) => d [ 1 ] )
6
+ import { Mark } from '../graph-types/mark.js'
10
7
11
8
export class Annotation extends Mark {
9
+ x ?: number
10
+ y ?: number
11
+ label ?: string
12
+
12
13
constructor ( options : any ) {
13
14
super ( options )
15
+ this . x = options . x
16
+ this . y = options . y
17
+ this . label = options . label
14
18
}
15
19
16
- render ( parentSelection : Selection < any , FunctionPlotOptions , any , any > ) {
20
+ render ( parentSelection : Selection < any , FunctionPlotAnnotation , any , any > ) {
21
+ const self = this
22
+
17
23
// join
18
- const selection = parentSelection . selectAll ( 'g.annotations ' ) . data ( function ( d : FunctionPlotOptions ) {
19
- return d . annotations || [ ]
24
+ const selection = parentSelection . selectAll ( 'g.annotation ' ) . data ( function ( ) {
25
+ return [ self ]
20
26
} )
21
27
22
28
// enter
23
- const enter = selection . enter ( ) . append ( 'g' ) . attr ( 'class' , 'annotations ' )
29
+ const enter = selection . enter ( ) . append ( 'g' ) . attr ( 'class' , 'annotation ' )
24
30
25
31
const xScale = this . chart . meta . xScale
26
32
const yScale = this . chart . meta . yScale
@@ -33,14 +39,21 @@ export class Annotation extends Mark {
33
39
// prettier-ignore
34
40
const path = selection . merge ( enter ) . selectAll ( 'path' )
35
41
. data ( function ( d ) {
36
- if ( 'x' in d ) {
42
+ if ( typeof d . x !== "undefined" ) {
37
43
return [ [ [ 0 , yRange [ 0 ] ] , [ 0 , yRange [ 1 ] ] ] ]
38
- } else {
44
+ } else if ( typeof d . y !== "undefined" ) {
39
45
return [ [ [ xRange [ 0 ] , 0 ] , [ xRange [ 1 ] , 0 ] ] ]
46
+ } else {
47
+ throw new Error ( `Property x or y wasn't set in the annotation` )
40
48
}
41
49
} )
42
50
// enter
43
51
const pathEnter = path . enter ( ) . append ( 'path' )
52
+
53
+ const line = d3Line ( )
54
+ . x ( ( d ) => d [ 0 ] )
55
+ . y ( ( d ) => d [ 1 ] )
56
+
44
57
// enter + update
45
58
path
46
59
. merge ( pathEnter )
@@ -56,7 +69,7 @@ export class Annotation extends Mark {
56
69
{
57
70
label : d . label || '' ,
58
71
// used to determine if x or y is set.
59
- xIsSet : 'x' in d
72
+ xIsSet : typeof d . x !== 'undefined'
60
73
}
61
74
] )
62
75
// enter
@@ -85,7 +98,7 @@ export class Annotation extends Mark {
85
98
// enter + update
86
99
// move group
87
100
selection . merge ( enter ) . attr ( 'transform' , function ( d ) {
88
- if ( 'x' in d ) {
101
+ if ( typeof d . x !== 'undefined' ) {
89
102
return 'translate(' + xScale ( d . x ) + ', 0)'
90
103
} else {
91
104
return 'translate(0, ' + yScale ( d . y ) + ')'
0 commit comments