This repository has been archived by the owner on Aug 30, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 6
/
dygraph.go
63 lines (56 loc) · 1.69 KB
/
dygraph.go
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
package main
import (
"bytes"
"fmt"
"html/template"
)
// Based on script from: https://github.com/tsenart/vegeta/blob/master/lib/plot/assets/plot.html.tpl#L24
const chartHTML = `<script>
document.addEventListener("DOMContentLoaded", () => {
const c = document.getElementById("{{ .ID }}");
const d = {{ .Data }};
const o = {{ .Opts }};
new Dygraph(c, d, o);
});
</script>
<div id="{{ .ID }}" class="dygraphChart"></div>`
// GenerateChart creates a JS snippet that creates a Dygraph chart
// based on given data and options. Dygraph charts require a container
// to attach to, which can be identified by dom element id.
//
// TODO(abhi): Figure out reasonable defaults for dygraph options
func GenerateChart(id string, data []byte, opts DygraphsOpts) (template.HTML, error) {
t, err := template.New(fmt.Sprintf("%s dygraph chart", id)).Parse(chartHTML)
if err != nil {
return "", err
}
var b bytes.Buffer
err = t.Execute(&b, ChartData{
ID: id,
Data: template.JS(data),
Opts: opts,
})
if err != nil {
return "", err
}
return template.HTML(b.String()), nil
}
// DygraphsOpts configures options for a Dygraph Chart
// See: https://dygraphs.com/options.html
type DygraphsOpts struct {
Title string `json:"title"`
Labels []string `json:"labels,omitempty"`
YLabel string `json:"ylabel"`
XLabel string `json:"xlabel"`
Colors []string `json:"colors,omitempty"`
Legend string `json:"legend"`
ShowRoller bool `json:"showRoller"`
StrokeWidth float64 `json:"strokeWidth"`
Width int `json:"width,omitempty"`
RollPeriod int `json:"rollPeriod,omitempty"`
}
type ChartData struct {
ID string
Data template.JS
Opts DygraphsOpts
}