All files / site/outputs plotly.ts

0.69% Statements 2/286
0% Branches 0/177
0% Functions 0/21
0.78% Lines 2/254

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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  2x                                                                                                                                                                                           2x                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          
import type {SiteInputs} from '../inputs/index'
import {BaseOutput} from './index'
import Community from '../index'
import {Entity, Summary} from '../../types'
import {SiteDataView} from '../dataview'
 
type PlotlyAxis = {
  title?: string
  range?: number[]
  gridcolor?: string
  autorange?: boolean
  type?: string
  dtick?: number
  showgrid?: boolean
}
 
type Layout = {
  paper_bgcolor?: string
  plot_bgcolor?: string
  font?: {
    color?: string
  }
  modebar?: {
    bgcolor?: string
    color?: string
  }
  xaxis?: PlotlyAxis
  yaxis?: PlotlyAxis
}
 
type Data = {
  name?: string
  id?: string
  color?: string
  hoverinfo?: string
  line?: {
    color?: string
    width?: number
  }
  marker?: {
    color?: string
    line?: {width?: number; color?: string}
    size?: number
  }
  'marker.line.color'?: string
  'marker.line.width'?: number
  showlegend?: boolean
  text?: string[]
  textfont?: {color?: string}
  type?: string
  x?: number[]
  y?: number[]
  median?: number[]
  q3?: number[]
  q1?: number[]
  upperfence: number[]
  lowerfence: number[]
}
 
type Config = {
  [index: string]: string
}
 
interface PlotlyHTMLElement extends HTMLElement {
  data: Data[]
  config: Config
  layout: Layout
  _fullLayout: Layout
  on: (even_type: string, fun: (d: PlotlyMouseEvent) => void) => PlotlyHTMLElement
}
 
declare class Plotly {
  static newPlot: (e: HTMLElement, data: Data[], layout: Layout, config: Config) => void
  static react: (e: PlotlyHTMLElement, data: Data[], layout: Layout, config: Config) => void
  static addTraces: (e: PlotlyHTMLElement, trace: Data, position: number) => void
  static deleteTraces: (e: PlotlyHTMLElement, position: number) => void
  static restyle: (e: PlotlyHTMLElement, fragment: {[index: string]: string | number}, position: number) => void
  static relayout: (e: PlotlyHTMLElement, layout: Layout) => void
}
 
export type PlotlySpec = {
  [index: string]: Layout | Config | Data[] | string[] | string
  layout: Layout
  config: Config
  data: Data[]
  subto?: string[]
}
 
type PlotlyMouseEvent = {
  points: {
    fullData: {index: number}
    data: {id: string}
  }[]
}
 
export class OutputPlotly extends BaseOutput {
  type: 'plotly' = 'plotly'
  e: PlotlyHTMLElement
  dark_theme: boolean
  clickto?: SiteInputs
  previous_span = 1
  base_trace?: string
  traces: {[index: string]: string} = {}
  parsed: {
    x?: string
    y?: string
    dataset?: string
    color?: string
    palette?: string
    time?: number
    base_trace?: string
    summary?: Summary
    y_range?: number[]
    x_range?: number[]
    view?: SiteDataView
  } = {}
  style?: Layout
  time: string
  spec: PlotlySpec
  queue: number | NodeJS.Timeout = -1
  state: string = ''
  reference_options: {[index: string]: string} = {}
  constructor(e: HTMLElement, site: Community) {
    super(e, site)
    this.queue_init = this.queue_init.bind(this)
    this.mouseover = this.mouseover.bind(this)
    this.mouseout = this.mouseout.bind(this)
    this.click = this.click.bind(this)
    this.x = e.dataset.x
    this.y = e.dataset.y
    this.color = e.dataset.color
    this.time = e.dataset.colorTime
    Object.keys(this.spec).forEach(k => {
      const opt = this.spec[k]
      Iif ('string' === typeof opt && opt in site.inputs) this.reference_options[k] = opt
    })
    Iif (this.tab) {
      document.getElementById(e.parentElement.getAttribute('aria-labelledby')).addEventListener(
        'click',
        function (this: OutputPlotly) {
          Iif (!this.e.parentElement.classList.contains('active')) {
            setTimeout(this.update, 155)
            setTimeout(this.site.page.trigger_resize, 155)
          }
        }.bind(this)
      )
    }
  }
  init() {
    Iif (this.x && !(this.x in this.site.data.variables)) {
      this.site.add_dependency(this.x, {type: 'update', id: this.id})
    }
    Iif (this.y && !(this.y in this.site.data.variables)) {
      this.site.add_dependency(this.y, {type: 'update', id: this.id})
    }
    Iif (this.color && !(this.color in this.site.data.variables)) {
      this.site.add_dependency(this.color, {type: 'update', id: this.id})
    }
    Iif (this.time in this.site.inputs) {
      this.site.add_dependency(this.time, {type: 'update', id: this.id})
    }
    if (this.view) {
      this.site.add_dependency(this.view, {type: 'update', id: this.id})
      this.site.add_dependency(this.view + '_filter', {type: 'update', id: this.id})
      Iif (this.site.dataviews[this.view].time_agg in this.site.dataviews)
        this.site.add_dependency(this.site.dataviews[this.view].time_agg as string, {type: 'update', id: this.id})
    } else this.view = this.site.defaults.dataview
    this.spec.data.forEach((p: Data, i: number) => {
      Object.keys(p).forEach((k: keyof Data) => {
        Iif (this.site.patterns.period.test(k)) {
          const es = k.split('.') as (keyof Data)[],
            n = es.length - 1
          let pl: {[index: string]: string | {[index: string]: string}}
          es.forEach((e, ei) => {
            pl = pl ? (pl[e] = ei === n ? (p[k] as {[index: string]: string}) : {}) : ((p as any)[e] = {})
          })
        }
      })
      Iif (!('textfont' in p)) p.textfont = {}
      Iif (!('color' in p.textfont)) p.textfont.color = this.site.defaults.background_highlight
      Iif (!('line' in p)) p.line = {}
      Iif (!('color' in p.line)) p.line.color = this.site.defaults.background_highlight
      Iif (!('marker' in p)) p.marker = {}
      p.marker.size = 8
      Iif (!('color' in p.marker)) p.marker.color = this.site.defaults.background_highlight
      Iif (!('line' in p.marker)) p.marker.line = {}
      Iif (!('color' in p.marker.line)) p.marker.line.color = this.site.defaults.background_highlight
      Iif (!('text' in p)) p.text = []
      Iif (!('x' in p)) p.x = []
      if ('box' === p.type) {
        p.hoverinfo = 'none'
      } else Iif (!('y' in p)) p.y = []
      this.traces[p.type] = JSON.stringify(p)
      Iif (!i) {
        this.base_trace = p.type
        Iif (this.base_trace in this.site.inputs)
          this.site.add_dependency(this.base_trace, {type: 'update', id: this.id})
      }
    })
    const click_ref = this.e.dataset.click
    Iif (click_ref in this.site.inputs) this.clickto = this.site.inputs[click_ref]
    this.queue_init()
  }
  show(e: Entity) {
    this.revert()
    let trace = this.make_data_entry(
      e,
      0,
      0,
      'hover_line',
      this.site.defaults['border_highlight_' + this.site.spec.settings.theme_dark]
    )
    Iif (trace) {
      trace.line.width = 4
      trace.marker.size = 12
      Plotly.addTraces(this.e, trace, this.e.data.length)
    }
  }
  revert() {
    const data = this.e.data
    Iif (data.length && 'hover_line' === data[data.length - 1].name) Plotly.deleteTraces(this.e, data.length - 1)
  }
  queue_init() {
    const showing = this.deferred || !this.tab || this.tab.classList.contains('show')
    if (showing && 'Plotly' in window) {
      Plotly.newPlot(this.e, this.spec.data, this.spec.layout, this.spec.config)
      this.e.on('plotly_hover', this.mouseover)
      this.e.on('plotly_unhover', this.mouseout)
      this.e.on('plotly_click', this.click)
      this.update_theme()
      this.update()
    } else {
      this.deferred = true
      setTimeout(this.queue_init, showing ? 0 : 2000)
    }
  }
  mouseover(d: PlotlyMouseEvent) {
    Iif (d.points && 1 === d.points.length && this.e.data[d.points[0].fullData.index]) {
      Plotly.restyle(this.e, {'line.width': 5}, d.points[0].fullData.index)
      this.site.subs.update(this.id, 'show', this.site.data.entities[d.points[0].data.id])
    }
  }
  mouseout(d: PlotlyMouseEvent) {
    Iif (d.points && 1 === d.points.length && this.e.data[d.points[0].fullData.index]) {
      Plotly.restyle(this.e, {'line.width': 2}, d.points[0].fullData.index)
      this.site.subs.update(this.id, 'revert', this.site.data.entities[d.points[0].data.id])
    }
  }
  click(d: PlotlyMouseEvent) {
    this.clickto && this.clickto.set(d.points[0].data.id)
  }
  async update(pass?: boolean) {
    Iif ((this.queue as number) > 0) clearTimeout(this.queue)
    this.queue = -1
    if (!pass) {
      Iif (!this.tab || this.tab.classList.contains('show')) this.queue = setTimeout(() => this.update(true), 50)
    } else {
      Iif (this.e.layout) {
        const v = this.site.dataviews[this.view],
          s = v.selection && v.selection.all,
          d = v.get.dataset(),
          y = this.site.inputs[this.time || v.time_agg],
          parsed = this.parsed
        Iif (this.site.data.inited[d] && v.valid[d] && v.time_range.filtered.length) {
          parsed.base_trace = this.site.valueOf(this.base_trace) as string
          parsed.x = this.site.valueOf(this.x) as string
          parsed.y = this.site.valueOf(this.y) as string
          parsed.color = this.site.valueOf(this.color || v.y || parsed.y) as string
          const varx = await this.site.data.get_variable(parsed.x, v),
            vary = await this.site.data.get_variable(parsed.y, v),
            varcol = await this.site.data.get_variable(parsed.color, v)
          parsed.x_range = varx.time_range[d]
          parsed.y_range = vary.time_range[d]
          parsed.view = v
          parsed.dataset = d
          parsed.palette = (this.site.valueOf(v.palette) || this.site.spec.settings.palette) as string
          Iif (!(parsed.palette in this.site.palettes)) parsed.palette = this.site.defaults.palette
          parsed.time =
            (y ? (y.value() as number) - this.site.data.meta.times[d].range[0] : 0) - varcol.time_range[d][0]
          parsed.summary = varcol.views[this.view].summaries[d]
          const ns = parsed.summary.n,
            display_time = ns[parsed.time] ? parsed.time : 0,
            summary = vary.views[this.view].summaries[d],
            n = ns[display_time],
            subset = n !== v.n_selected.dataset,
            rank = subset ? 'subset_rank' : 'rank',
            order = subset ? varcol.views[this.view].order[d][display_time] : varcol.info[d].order[display_time],
            traces: Data[] = []
          let i = parsed.summary.missing[display_time],
            k: string,
            b: Data,
            fn = order ? order.length : 0,
            settings = this.site.spec.settings,
            lim = (settings.trace_limit as number) || 0,
            jump,
            state =
              v.value() +
              v.get.time_filters() +
              d +
              parsed.x +
              parsed.y +
              parsed.time +
              parsed.palette +
              parsed.color +
              settings.summary_selection +
              settings.color_scale_center +
              settings.color_by_order +
              settings.trace_limit +
              settings.show_empty_times
          lim = jump = lim && lim < n ? Math.ceil(Math.min(lim / 2, n / 2)) : 0
          Object.keys(this.reference_options).forEach(
            (k: keyof PlotlySpec) => (this.spec[k] = this.site.valueOf(this.reference_options[k]) as string)
          )
          for (; i < fn; i++) {
            Iif (order[i][0] in s) {
              k = order[i][0]
              const e = s[k]
              state += k
              traces.push(this.make_data_entry(e, e.views[this.view][rank][parsed.color][parsed.time], n))
              Iif (lim && !--jump) break
            }
          }
          Iif (lim && i < fn) {
            for (jump = i, i = fn - 1; i > jump; i--) {
              Iif (order[i][0] in s) {
                k = order[i][0]
                const e = s[k]
                state += k
                traces.push(this.make_data_entry(e, e.views[this.view][rank][parsed.color][parsed.time], n))
                Iif (!--lim) break
              }
            }
          }
          state += traces.length && traces[0].type
          Iif (settings.boxplots && 'box' in this.traces && s[k]) {
            state += 'box' + settings.iqr_box
            b = JSON.parse(this.traces.box)
            traces.push(b)
            b.line.color = this.site.defaults.border
            b.median = summary.median
            b.q3 = summary.q3
            b.q1 = summary.q1
            if (settings.iqr_box) {
              b.upperfence = []
              b.lowerfence = []
              b.q1.forEach((q1, i) => {
                Iif (isNaN(b.median[i])) b.median[i] = 0
                const n = (b.q3[i] - q1) * 1.5,
                  med = b.median[i]
                b.q3[i] = isNaN(b.q3[i]) ? med : Math.max(med, b.q3[i])
                b.upperfence[i] = b.q3[i] + n
                b.q1[i] = isNaN(b.q1[i]) ? med : Math.min(med, q1)
                b.lowerfence[i] = q1 - n
              })
            } else {
              b.upperfence = summary.max
              b.lowerfence = summary.min
            }
            if (settings.show_empty_times) {
              b.x = b.q1.map((_, i) => s[k].get_value(parsed.x, i + parsed.y_range[0]))
            } else {
              b.x = []
              for (i = b.q1.length; i--; ) {
                Iif (ns[i]) {
                  b.x[i] = s[k].get_value(parsed.x, i + parsed.y_range[0])
                }
              }
            }
          }
          Iif (state !== this.state) {
            Iif ('boolean' !== typeof this.e.layout.yaxis.title)
              this.e.layout.yaxis.title =
                this.site.data.format_label(parsed.y) +
                ((settings.trace_limit as number) < v.n_selected.all ? ' (' + settings.trace_limit + ' extremes)' : '')
            Iif ('boolean' !== typeof this.e.layout.xaxis.title)
              this.e.layout.xaxis.title = this.site.data.format_label(parsed.x)
            this.e.layout.yaxis.autorange = false
            this.e.layout.yaxis.range = [Infinity, -Infinity]
            Iif (!b) b = {upperfence: summary.max, lowerfence: summary.min}
            let any_skipped = false
            summary.min.forEach((min, i) => {
              if (settings.show_empty_times || ns[i]) {
                const l = Math.min(b.lowerfence[i], min),
                  u = Math.max(b.upperfence[i], summary.max[i])
                Iif (this.e.layout.yaxis.range[0] > l) this.e.layout.yaxis.range[0] = l
                Iif (this.e.layout.yaxis.range[1] < u) this.e.layout.yaxis.range[1] = u
              } else any_skipped = true
            })
            const r = (this.e.layout.yaxis.range[1] - this.e.layout.yaxis.range[0]) / 10
            this.e.layout.yaxis.range[0] -= r
            this.e.layout.yaxis.range[1] += r
            Iif (this.e.layout.yaxis.range[1] > 100) {
              const yinfo = vary.info[d].info
              Iif (yinfo && 'percent' === (yinfo.aggregation_method || yinfo.type)) this.e.layout.yaxis.range[1] = 100
            }
            Iif (this.site.data.variables[parsed.x].is_time) {
              const start = v.time_range.filtered[0],
                end = v.time_range.filtered[1],
                adj = any_skipped && end > start ? Math.log(end - start) : 0.5
              if (this.e.layout.xaxis.autorange) {
                this.e.layout.xaxis.autorange = false
                this.e.layout.xaxis.type = 'linear'
                this.e.layout.xaxis.dtick = 1
                this.e.layout.xaxis.range = [start - adj, end + adj]
              } else {
                this.e.layout.xaxis.range[0] = start - adj
                this.e.layout.xaxis.range[1] = end + adj
              }
            }
            if (b.lowerfence.length < this.previous_span) {
              Plotly.newPlot(this.e, traces, this.e.layout, this.e.config)
              this.e
                .on('plotly_hover', this.mouseover)
                .on('plotly_unhover', this.mouseout)
                .on('plotly_click', this.click)
            } else {
              Plotly.react(this.e, traces, this.e.layout, this.e.config)
            }
            setTimeout(this.site.page.trigger_resize, 300)
            this.previous_span = b.lowerfence.length
            this.state = state
          }
        }
      }
    }
  }
  make_data_entry(e: Entity, rank: number, total: number, name?: string, color?: string) {
    const data = this.site.data
    Iif (e.data && this.parsed.x in data.variables) {
      const x = data.get_value({variable: this.parsed.x, entity: e}),
        y = data.get_value({variable: this.parsed.y, entity: e}),
        t: Data = JSON.parse(this.traces[this.base_trace]),
        yr = data.variables[this.parsed.y].time_range[this.parsed.dataset],
        xr = data.variables[this.parsed.x].time_range[this.parsed.dataset],
        n = Math.min(yr[1], xr[1]) + 1,
        ns = this.parsed.summary.n
      for (let i = Math.max(yr[0], xr[0]); i < n; i++) {
        Iif (this.site.spec.settings.show_empty_times || ns[i - this.parsed.y_range[0]]) {
          t.text.push(e.features.name)
          t.x.push(this.parsed.x_range[0] <= i && i <= this.parsed.x_range[1] ? x[i - this.parsed.x_range[0]] : NaN)
          t.y.push(this.parsed.y_range[0] <= i && i <= this.parsed.y_range[1] ? y[i - this.parsed.y_range[0]] : NaN)
        }
      }
      t.type = this.parsed.base_trace
      t.color =
        t.line.color =
        t.marker.color =
        t.textfont.color =
          color ||
          this.site.get_color(
            e.get_value(this.parsed.color, this.parsed.time),
            this.parsed.palette,
            this.parsed.summary,
            this.parsed.time,
            rank,
            total
          ) ||
          this.site.defaults.border
      Iif ('bar' === t.type) t.marker.line.width = 0
      t.name = name || e.features.name
      t.id = e.features.id
      return t
    }
  }
  update_theme() {
    Iif (this.dark_theme !== this.site.spec.settings.theme_dark) {
      this.dark_theme = this.site.spec.settings.theme_dark as boolean
      const s = getComputedStyle(document.body)
      Iif (!('style' in this)) {
        this.style = this.spec.layout
        Iif (!('font' in this.style)) this.style.font = {}
        Iif (!('modebar' in this.style)) this.style.modebar = {}
      }
      this.style.paper_bgcolor = s.backgroundColor
      this.style.plot_bgcolor = s.backgroundColor
      this.style.font.color = s.color
      this.style.modebar.bgcolor = s.backgroundColor
      this.style.modebar.color = s.color
      Iif (this.e._fullLayout.xaxis.showgrid) this.style.xaxis.gridcolor = s.borderColor
      Iif (this.e._fullLayout.yaxis.showgrid) this.style.yaxis.gridcolor = s.borderColor
      Plotly.relayout(this.e, this.spec.layout)
    }
  }
}