WriteTo writes the HTML plot to the give io.Writer.
(w io.Writer)
| 165 | |
| 166 | // WriteTo writes the HTML plot to the give io.Writer. |
| 167 | func (p *Plot) WriteTo(w io.Writer) (n int64, err error) { |
| 168 | type uiOpts struct { |
| 169 | Title string `json:"title"` |
| 170 | Labels []string `json:"labels,omitempty"` |
| 171 | Colors []string `json:"colors,omitempty"` |
| 172 | } |
| 173 | |
| 174 | type plotData struct { |
| 175 | Title string |
| 176 | UPlotCSS template.CSS |
| 177 | UPlotJS template.JS |
| 178 | PluginsJS template.JS |
| 179 | Data template.JS |
| 180 | Opts template.JS |
| 181 | } |
| 182 | |
| 183 | dp, labels, err := p.data() |
| 184 | if err != nil { |
| 185 | return 0, err |
| 186 | } |
| 187 | |
| 188 | var sz int |
| 189 | if len(dp) > 0 { |
| 190 | sz = len(dp) * len(dp[0]) * 12 // heuristic |
| 191 | } |
| 192 | |
| 193 | data := dp.Append(make([]byte, 0, sz)) |
| 194 | |
| 195 | opts := uiOpts{ |
| 196 | Title: p.title, |
| 197 | Labels: labels, |
| 198 | Colors: labelColors(labels[1:]), |
| 199 | } |
| 200 | |
| 201 | optsJSON, err := json.MarshalIndent(&opts, " ", " ") |
| 202 | if err != nil { |
| 203 | return 0, err |
| 204 | } |
| 205 | |
| 206 | assets := map[string][]byte{} |
| 207 | for _, path := range []string{"uPlot.min.js", "uPlot.min.css", "uplot-plugins.js"} { |
| 208 | bs, err := asset(path) |
| 209 | if err != nil { |
| 210 | return 0, err |
| 211 | } |
| 212 | assets[path] = bs |
| 213 | } |
| 214 | |
| 215 | cw := countingWriter{w: w} |
| 216 | err = plotTemplate.Execute(&cw, &plotData{ |
| 217 | Title: p.title, |
| 218 | UPlotCSS: template.CSS(assets["uPlot.min.css"]), |
| 219 | UPlotJS: template.JS(assets["uPlot.min.js"]), |
| 220 | PluginsJS: template.JS(assets["uplot-plugins.js"]), |
| 221 | Data: template.JS(data), |
| 222 | Opts: template.JS(optsJSON), |
| 223 | }) |
| 224 |