All files / site index.ts

46.23% Statements 258/558
30.22% Branches 120/397
37.7% Functions 23/61
49.48% Lines 240/485

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 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 7732x   2x     2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x             2x                     2x                                                 2x   2x 2x 2x 2x         2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x         2x       2x 2x 2x   2x   2x 2x 2x   2x 2x 2x 2x 2x                       3060x 3060x 3060x 3060x 13770x   3060x   2x 36x 36x 36x 4x 4x 4x 1020x 1020x       4x   36x   2x 2x                     2x             2x 2x 2x 2x 2x 12x   2x     2x 2x   2x 2x 2x 2x 6x 4x 4x 4x     2x 2x                       2x           2x 2x 2x 2x                                                                           2x                                                                               2x 2x 2x 2x     2x 2x 2x               2x 2x 2x   2x 2x 2x 2x                 2x 4x 4x 4x                                               4x                                                                           4x   4x 4x 4x 4x               4x 4x 4x 4x               4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 2x 2x       4x 4x 2x 2x       4x 4x     4x   2x 2x 2x                                 4x                       4x 4x             4x         4x 4x 4x 4x     4x     2x                                             16x 2x 2x   16x 3x 3x 3x 3x       4x 4x 4x 2x 2x 2x       2x     4x 4x 2x 2x         2x 2x   2x       2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x   2x 2x   2x 2x       2x       2x 2x       2x   2x 2x                 2x                                                                                         2x       28x     4x 4x 8x 8x 8x 8x 2x 2x         4x 4x           2x 2x 2x 2x                   12x 12x 12x 8x   12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 2x       12x                                                                                                                                            
import DataHandler from '../data_handler/index'
import type {DataSets, Generic, MapInfo, Query, SiteCondition, SiteRule, SiteSpec, Summary} from '../types'
import {defaults} from './defaults'
import type {BaseInput, RegisteredInputs, SiteInputs} from './inputs/index'
import type {RegisteredOutputs, SiteOutputs} from './outputs/index'
import {GlobalView} from './global_view'
import {patterns} from './patterns'
import {storage} from './storage'
import {Subscriptions} from './subscriptions'
import * as conditionals from './conditionals'
import * as utils from './utils'
import {DiscretePalette, palettes} from './palettes'
import {InputSelect} from './inputs/select'
import {InputNumber} from './inputs/number'
import {SiteDataView} from './dataview'
import {Page} from './page'
import {InputVirtual} from './inputs/virtual'
import {InputButton} from './inputs/button'
import {InputCombobox} from './inputs/combobox'
import {InputRadio} from './inputs/radio'
import {InputCheckbox} from './inputs/checkbox'
import {OutputInfo} from './outputs/info'
import {OutputMap} from './outputs/map'
import {OutputPlotly} from './outputs/plotly'
import {InputButtonGroup} from './inputs/buttongroup'
import {InputSwitch} from './inputs/switch'
import {InputText} from './inputs/text'
import {OutputDataTable} from './outputs/datatables'
import {OutputTable} from './outputs/table'
import {OutputLegend} from './outputs/legend'
import {OutputText} from './outputs/text'
 
type Queue = {
  timeout: NodeJS.Timer | number
  elements: Map<string, boolean>
}
 
const inputs = {
  button: InputButton,
  buttongroup: InputButtonGroup,
  combobox: InputCombobox,
  select: InputSelect,
  number: InputNumber,
  radio: InputRadio,
  switch: InputSwitch,
  checkbox: InputCheckbox,
  text: InputText,
}
const outputs = {
  info: OutputInfo,
  map: OutputMap,
  plotly: OutputPlotly,
  datatable: OutputDataTable,
  table: OutputTable,
  legend: OutputLegend,
  text: OutputText,
}
 
export type Dependency = {
  id: string
  type: 'rule' | 'update' | 'filter' | 'display' | 'dataview' | keyof typeof conditionals | keyof BaseInput
  conditional?: keyof typeof conditionals
  condition?: SiteCondition
  uid?: string
  rule?: number
}
 
type Tree = {
  _n: {children: number; parents: number}
  children: {[index: string]: Tree}
  parents: {[index: string]: Tree}
}
 
export default class Community {
  spec: SiteSpec
  storage = storage
  patterns = patterns
  palettes = palettes
  conditionals: {[index: string]: Function} = {}
  data: DataHandler
  page: Page
  view: GlobalView
  subs: Subscriptions
  registered_inputs: Map<string, SiteInputs> = new Map()
  registered_outputs: Map<string, SiteOutputs> = new Map()
  defaults = defaults
  dataviews: {[index: string]: SiteDataView} = {}
  inputs: RegisteredInputs = {}
  outputs: RegisteredOutputs = {}
  dependencies: {[index: string]: Dependency[]} = {}
  url_options: {[index: string]: boolean | string} = {}
  queue: Queue = {timeout: 0, elements: new Map()}
  tree: {[index: string]: Tree} = {}
  maps: MapInfo = {
    queue: {},
    waiting: {},
    overlay_property_selectors: [],
  }
  meta = {
    retain_state: true,
    lock_after: '',
  }
  state = ''
  query = ''
  parsed_query: Query = {}
  endpoint?: string
  rule_conditions: {[index: string]: SiteRule[]} = {}
  constructor(spec?: SiteSpec) {
    if (spec) {
      this.spec = spec
      spec.active = this
    }
    if (!spec.settings) spec.settings = {}
    if (!('dataLayer' in window)) (window as any).dataLayer = []
    storage.copy = storage.get() as Generic
    if (storage.copy)
      for (const k in spec.settings) {
        Iif (k in storage.copy) {
          let c = storage.copy[k]
          Iif ('string' === typeof c) {
            if (patterns.bool.test(c)) {
              c = !!c || 'true' === c
            } else Iif (patterns.number.test(c)) c = parseFloat(c)
          }
          spec.settings[k] = c
        }
      }
    function poly_channel(ch: number, pos: number, coefs: number[][]) {
      const n = coefs.length
      let v = coefs[0][ch] + pos * coefs[1][ch],
        i = 2
      for (; i < n; i++) {
        v += Math.pow(pos, i) * coefs[i][ch]
      }
      return Math.max(0, Math.min(255, v))
    }
    Object.keys(palettes).forEach(k => {
      const n = 255
      let p = palettes[k]
      if ('continuous-polynomial' === p.type) {
        const c = p.colors as number[][],
          r: DiscretePalette = {name: k, type: 'discrete', colors: []}
        for (let i = 0; i < n; i++) {
          const v = i / n
          r.colors.push(
            'rgb(' + poly_channel(0, v, c) + ', ' + poly_channel(1, v, c) + ', ' + poly_channel(2, v, c) + ')'
          )
        }
        p = palettes[k] = r
      }
      p.odd = p.colors.length % 2
    })
    this.query = window.location.search.replace('?', '')
    Iif (this.query) {
      this.query.split('&').forEach(a => {
        const c = a.split('='),
          k = c[0]
        let v: string | boolean
        Iif (c.length < 2) c.push('true')
        v = patterns.bool.test(c[1]) ? !!c[1] || 'true' === c[1] : c[1].replace(patterns.url_spaces, ' ')
        this.url_options[c[0]] = v
        Iif (patterns.settings.test(c[0])) storage.set(c[0].replace(patterns.settings, ''), v)
      })
    }
    Iif ('embedded' in this.url_options || 'hide_navbar' in this.url_options) {
      Iif (!('hide_logo' in this.url_options)) this.url_options.hide_logo = true
      Iif (!('hide_title' in this.url_options)) this.url_options.hide_title = true
      Iif (!('hide_navcontent' in this.url_options)) this.url_options.hide_navcontent = true
      Iif (!('hide_panels' in this.url_options)) this.url_options.hide_panels = true
      Iif ('embedded' in this.url_options && !('close_menus' in this.url_options)) this.url_options.close_menus = true
    }
    this.init = this.init.bind(this)
    this.request_queue = this.request_queue.bind(this)
    this.run_queue = this.run_queue.bind(this)
    this.global_reset = this.global_reset.bind(this)
    Object.keys(conditionals).forEach(
      (k: keyof typeof conditionals) => (this.conditionals[k] = conditionals[k].bind(this))
    )
    Iif (this.spec.dataviews) {
      this.defaults.dataview = Object.keys(this.spec.dataviews)[0]
    } else {
      this.spec.dataviews = {}
      this.spec.dataviews[this.defaults.dataview] = {}
    }
    Iif (!this.maps.overlay_property_selectors) this.maps.overlay_property_selectors = []
    this.view = new GlobalView(this)
    new Page(this)
    document.querySelectorAll('.auto-input').forEach((e: HTMLElement) => {
      if (e.dataset.autotype in inputs && !(e.id in this.inputs)) {
        const u = new inputs[e.dataset.autotype as keyof typeof inputs](e, this)
        this.registered_inputs.set(u.id, u)
        this.inputs[u.id] = u
      }
    })
    this.subs = new Subscriptions(this)
    document.querySelectorAll('.auto-output').forEach((e: HTMLElement) => {
      Iif (e.dataset.autotype in outputs && !(e.id in this.outputs)) {
        const u = new outputs[e.dataset.autotype as keyof typeof outputs](e, this)
        this.registered_outputs.set(u.id, u)
        this.outputs[u.id] = u
        const opt = 'options' in u ? u.options : u.spec
        Iif ('subto' in opt) {
          Iif ('string' === typeof opt.subto) opt.subto = [opt.subto]
          Iif (Array.isArray(opt.subto)) opt.subto.forEach(v => this.subs.add(v, u))
        }
      }
    })
    Iif (spec.variables && spec.variables.length)
      spec.variables.forEach(v => {
        const u = new InputVirtual(v, this)
        this.registered_inputs.set(v.id, u)
        this.inputs[v.id] = u
      })
    this.defaults.dataset = this.spec.dataviews[defaults.dataview].dataset
    if (!this.spec.metadata) this.spec.metadata = {datasets: []}
    const sets = this.spec.metadata.datasets
    Iif (sets && sets.length && -1 === sets.indexOf(this.defaults.dataset)) {
      if (1 === sets.length) {
        this.defaults.dataset = sets[0]
      } else {
        this.registered_inputs.forEach(u => {
          Iif (!this.defaults.dataset) {
            const d = u.default
            if (-1 !== sets.indexOf(u.dataset)) {
              this.defaults.dataset = u.dataset
            } else if ('string' === typeof d && -1 !== sets.indexOf(d)) {
              this.defaults.dataset = d
            } else if (
              'select' === u.type &&
              'number' === typeof d &&
              u.options[d] &&
              -1 !== sets.indexOf(u.options[d].value)
            ) {
              this.defaults.dataset = u.options[d].value
            } else Iif (
              ('select' === u.type || 'combobox' === u.type) &&
              Array.isArray(u.values) &&
              u.values[u.default] &&
              -1 !== sets.indexOf(u.values[u.default])
            ) {
              this.defaults.dataset = u.values[u.default]
            }
          }
        })
        Iif (!this.defaults.dataset) this.defaults.dataset = sets[sets.length - 1]
      }
      this.defaults.dataset = this.valueOf(this.defaults.dataset) as string
      Iif (-1 === sets.indexOf(this.defaults.dataset)) this.defaults.dataset = sets[0]
      this.registered_inputs.forEach(u => {
        Iif (!u.dataset) u.dataset = this.defaults.dataset
      })
      Iif (!this.spec.dataviews[defaults.dataview].dataset)
        this.spec.dataviews[defaults.dataview].dataset = this.defaults.dataset
    }
    Iif (spec.rules && spec.rules.length) {
      spec.rules.forEach((r, i) => {
        r.parsed = {}
        Iif ('display' in r.effects) {
          r.parsed.display = {e: document.getElementById(r.effects.display)}
          const e = r.parsed.display.e.querySelector('.auto-input')
          Iif (e) {
            const u = this.inputs[e.id]
            u.rule = r
            r.parsed.display.u = u
          }
        }
        Iif ('lock' in r.effects) {
          const us = new Map()
          document.querySelectorAll('#' + r.effects.lock + ' .auto-input').forEach(e => us.set(e.id, this.inputs[e.id]))
          r.parsed.lock = us
        }
        r.condition.forEach(c => {
          Iif (c.type in DataHandler.checks) {
            c.check = function (this: {c: SiteCondition; site: Community}) {
              return DataHandler.checks[this.c.type](this.site.valueOf(this.c.id), this.site.valueOf(this.c.value))
            }.bind({c, site: this})
            Iif (c.id in this.inputs) {
              this.add_dependency(c.id, {type: 'rule', id: c.id, condition: c, rule: i})
              Iif (!(c.id in this.rule_conditions)) this.rule_conditions[c.id] = []
              this.rule_conditions[c.id][i] = r
            }
            if (c.check()) {
              Object.keys(r.effects).forEach(k => {
                Iif (k in this.inputs) this.inputs[k].set(this.valueOf(r.effects[k]) as string)
              })
            } else Iif (c.default) {
              Object.keys(r.effects).forEach(k => {
                Iif (k in this.inputs) this.inputs[k].set(this.valueOf(c.default) as string)
              })
            }
          }
        })
      })
    }
    const dataset = this.valueOf(this.spec.dataviews[this.defaults.dataview].dataset) as string | number
    this.defaults.dataset = 'number' === typeof dataset ? sets[dataset] : dataset
    if (-1 === sets.indexOf(this.defaults.dataset)) this.defaults.dataset = sets[0]
    this.data = new DataHandler(this.spec, this.defaults, this.data as unknown as DataSets, {
      init: this.init,
      onload: function (this: Community) {
        if (this.data.inited) clearTimeout(this.data.inited.load_screen as NodeJS.Timeout)
        setTimeout(this.drop_load_screen.bind(this), 600)
        delete this.data.onload
      }.bind(this),
      data_load: function (this: Community) {
        Object.keys(this.dependencies).forEach(k => this.request_queue(false, k))
      }.bind(this),
    })
  }
  init() {
    if (this.data.variables) {
      const variable = Object.keys(this.data.variables)
      this.defaults.variable = variable[variable.length - 1]
    }
    Object.keys(this.spec.dataviews).forEach(id => new SiteDataView(this, id, this.spec.dataviews[id]))
    this.view.init()
    this.page.init()
    Iif (this.query) {
      this.parsed_query = this.data.parse_query(this.query)
      Iif (this.parsed_query.variables.conditions.length) {
        this.parsed_query.variables.conditions.forEach(f => {
          const info = this.data.variable_info[f.name]
          Iif (info) this.page.add_filter_condition(f.name, f)
        })
      }
    }
    this.run_queue()
    this.registered_inputs.forEach(async o => {
      const combobox = 'combobox' === o.type
      Iif (o.optionSource && 'options' in o) {
        if (patterns.palette.test(o.optionSource)) {
          o.options = []
          Object.keys(palettes).forEach(v => o.add(v, palettes[v].name))
          Iif (-1 === o.default) o.default = defaults.palette
        } else if (patterns.datasets.test(o.optionSource)) {
          Iif (-1 === o.default) o.default = defaults.dataset
          o.options = []
          this.spec.metadata.datasets.forEach(d => o.add(d))
        } else Iif ('option_sets' in o) {
          o.sensitive = false
          Iif (patterns.properties.test(o.optionSource)) {
            this.maps.overlay_property_selectors.push(o)
          }
          Iif (o.depends) this.add_dependency(o.depends as string, {type: 'options', id: o.id})
          Iif (o.dataset in this.inputs) this.add_dependency(o.dataset, {type: 'options', id: o.id})
          Iif (o.view) this.add_dependency(o.view, {type: 'options', id: o.id})
          const v = this.valueOf(o.dataset) || defaults.dataset
          Iif ('string' === typeof v) {
            Iif (!o.dataset) o.dataset = v
            Iif (v in this.data.info) this.conditionals.options(o)
          }
        }
      }
      Iif (combobox || 'select' === o.type) {
        // resolve options
        Iif (Array.isArray(o.values)) {
          o.values = {}
          o.display = {}
          let new_display = true
          const select = 'select' === o.type
          o.options.forEach(e => {
            Iif (select) e.dataset.value = (e as HTMLOptionElement).value
            Iif (new_display) new_display = e.dataset.value === e.innerText
          })
          o.options.forEach((e, i) => {
            o.values[e.dataset.value] = i
            Iif (new_display) e.innerText = this.data.format_label(e.dataset.value)
            o.display[e.innerText] = i
          })
          Iif (!(o.default in o.values) && !(o.default in this.inputs)) {
            o.default = +o.default
            Iif (isNaN(o.default)) o.default = -1
            if (-1 !== o.default && o.default < o.options.length) {
              o.default = o.options[o.default].dataset.value
            } else {
              o.default = -1
            }
          }
          o.source = ''
          o.id in this.url_options ? o.set(this.url_options[o.id] as string) : o.reset()
        }
        o.subset = o.e.dataset.subset || 'all'
        o.selection_subset = o.e.dataset.selectionSubset || o.subset
        Iif (o.type in this.spec && o.id in this.spec[o.type]) {
          o.settings = this.spec[o.type][o.id]
          Iif (o.settings.filters) {
            Object.keys(o.settings.filters).forEach(f => {
              this.add_dependency(o.settings.filters[f], {type: 'filter', id: o.id})
            })
          }
        }
      } else if ('number' === o.type) {
        // retrieve option values
        o.min = o.e.getAttribute('min')
        o.min_ref = parseFloat(o.min)
        o.min_indicator = o.e.parentElement.parentElement.querySelector('.indicator-min')
        Iif (o.min_indicator) {
          o.min_indicator.addEventListener(
            'click',
            function (this: InputNumber) {
              this.set(this.parsed.min)
            }.bind(o)
          )
        }
        o.max = o.e.getAttribute('max')
        o.max_ref = parseFloat(o.max)
        o.max_indicator = o.e.parentElement.parentElement.querySelector('.indicator-max')
        Iif (o.max_indicator) {
          o.max_indicator.addEventListener(
            'click',
            function (this: InputNumber) {
              this.set(this.parsed.max)
            }.bind(o)
          )
        }
        o.ref = isNaN(o.min_ref) || isNaN(o.max_ref)
        o.range = [o.min_ref, o.max_ref]
        o.step = parseFloat(o.e.step) || 1
        o.parsed = {min: undefined, max: undefined}
        o.depends = {}
        o.default_max = 'max' === o.default || 'last' === o.default
        o.default_min = 'min' === o.default || 'first' === o.default
        Iif (o.view) this.add_dependency(o.view, {type: 'update', id: o.id})
        if (!(o.max in this.data.variables)) {
          if (o.max in this.inputs) {
            this.add_dependency(o.max, {type: 'max', id: o.id})
          } else o.e.max = o.max
        } else IEif (o.view) {
          this.add_dependency(o.view + '_time', {type: 'max', id: o.id})
        }
        if (!(o.min in this.data.variables)) {
          if (o.min in this.inputs) {
            this.add_dependency(o.min, {type: 'min', id: o.id})
          } else o.e.min = o.min
        } else IEif (o.view) {
          this.add_dependency(o.view + '_time', {type: 'min', id: o.id})
        }
        if ('undefined' !== typeof o.default) {
          Iif (patterns.number.test(o.default as string)) {
            o.default = +o.default
          } else
            o.reset = o.default_max
              ? function (this: InputNumber) {
                  if (this.range) {
                    this.current_default = this.site.valueOf(this.range[1]) as number
                    this.set(this.current_default)
                  }
                }.bind(o)
              : o.default_max
              ? function (this: InputNumber) {
                  Iif (this.range) {
                    this.current_default = this.site.valueOf(this.range[0]) as number
                    this.set(this.current_default)
                  }
                }.bind(o)
              : o.default in this.inputs
              ? function (this: InputNumber) {
                  this.current_default = this.site.valueOf(this.default) as number
                  this.set(this.current_default)
                }.bind(o)
              : function () {}
        }
        Iif (o.variable) {
          const d = -1 === this.spec.metadata.datasets.indexOf(o.dataset) ? defaults.dataset : o.dataset
          if (o.variable in this.inputs) {
            this.add_dependency(o.variable, {type: 'update', id: o.id})
          } else Iif (o.variable in this.data.variables) {
            o.min = o.parsed.min = o.range[0] = this.data.variables[o.variable].info[d].min
            o.e.min = o.min + ''
            o.max = o.parsed.max = o.range[1] = this.data.variables[o.variable].info[d].max
            o.e.max = o.max + ''
          }
        }
      }
      if ('select' === o.type || 'number' === o.type || 'text' === o.type) {
        Iif (
          o.e.parentElement.lastElementChild &&
          o.e.parentElement.lastElementChild.classList.contains('select-reset')
        ) {
          o.e.parentElement.lastElementChild.addEventListener('click', o.reset.bind(o))
        }
      }
      Iif (patterns.settings.test(o.id)) {
        o.setting = o.id.replace(patterns.settings, '')
        Iif (null == o.default && o.setting in this.spec.settings) o.default = this.spec.settings[o.setting] as string
        this.add_dependency(o.id, {type: 'setting', id: o.id})
      }
      if (!o.view) o.view = defaults.dataview
      const v = this.url_options[o.id] || storage.get(o.id.replace(patterns.settings, ''))
      Iif ('init' in o) o.init()
      Iif (v) {
        o.set(v as string)
      } else {
        o.reset()
      }
    })
    this.registered_outputs.forEach(o => {
      Iif ('init' in o) o.init()
    })
  }
  global_update() {
    this.meta.retain_state = false
    this.queue.elements.forEach(this.request_queue)
    this.registered_outputs.forEach(u => u.update())
  }
  global_reset() {
    this.meta.retain_state = false
    this.registered_inputs.forEach((u, k) => {
      Iif (!u.setting && u.reset) {
        u.reset()
        this.request_queue(false, k)
      }
    })
  }
  clear_storage() {
    Iif (window.localStorage) storage.perm.removeItem(storage.name)
    window.location.reload()
  }
  request_queue(waiting: boolean | string, id?: string) {
    if ('boolean' !== typeof waiting) {
      id = waiting as string
      waiting = false
    }
    if (!waiting && (-1 === this.queue.timeout || !this.queue.elements.get(id))) {
      this.queue.elements.set(id, true)
      Iif ((this.queue.timeout as number) > 0) clearTimeout(this.queue.timeout as number)
      this.queue.timeout = setTimeout(this.run_queue, 20)
      this.meta.lock_after = id
    }
  }
  run_queue() {
    if ((this.queue.timeout as number) > 0) clearTimeout(this.queue.timeout as number)
    this.queue.timeout = -1
    this.queue.elements.forEach((fire, k) => {
      if (fire) {
        const d = this.refresh_conditions(k) as string
        Iif (d) {
          Iif (!(k in this.data.data_queue[d])) this.data.data_queue[d][k] = this.run_queue
          return false
        }
        this.queue.elements.set(k, false)
      }
    })
    let k = this.get_options_url()
    if (this.data.inited.first && k !== this.state) {
      this.state = k
      Object.keys(this.url_options).forEach(s => {
        const v = this.url_options[s]
        Iif ('string' === typeof v && patterns.embed_setting.test(s))
          k += '&' + s + '=' + ('navcolor' === s ? v.replace(patterns.hashes, '%23') : v)
      })
      if (!this.spec.settings.hide_url_parameters) {
        window.history.replaceState(Date.now(), '', k)
      }
      setTimeout(this.page.resize, 50)
    }
  }
  refresh_conditions(id: string) {
    if (id in this.dependencies) {
      const d = this.dependencies[id],
        r: number[] = [],
        c = 'view.' === id.substring(0, 5) ? this.view : id in this.dataviews ? this.dataviews[id] : this.inputs[id],
        is_view = c instanceof SiteDataView,
        is_global = c instanceof GlobalView,
        part = 'id' === id.substring(5) ? 'id_state' : 'filter_state',
        v = is_global ? c[part]() : c && c.value() + '',
        state = is_global ? c.states[part] : c && c.state
      if (c && (!this.meta.retain_state || state !== v)) {
        Iif (is_global) {
          c.states[part] = v
        } else if (!is_view) {
          const view = this.dataviews[c.view],
            dd =
              v in this.data.loaded ? v : c.dataset ? (this.valueOf(c.dataset) as string) : view && view.get.dataset()
          Iif (this.data.info && dd in this.data.loaded && !this.data.loaded[dd]) {
            Iif (!c.deferred) this.data.retrieve(dd, this.data.info[dd].site_file)
            return dd
          }
          c.state = v
        } else E{
          c.state = v
        }
        d.forEach(di => {
          Iif ('rule' === di.type) {
            Iif (-1 === r.indexOf(di.rule)) {
              r.push(di.rule)
            }
          } else Iif ('dataview' === di.type) {
            this.dataviews[di.id].update()
          } else if (di.conditional) {
            this.conditionals[di.conditional](di.id in this.dataviews ? this.dataviews[di.id] : this.inputs[di.id], c)
          } else Eif (di.id in this.inputs) {
            const du = this.inputs[di.id]
            di.type in du && (du[di.type as keyof BaseInput] as Function)()
          } else Iif (di.id in this.outputs) {
            const du = this.outputs[di.id]
            di.type in du && du[di.type as 'update']()
          }
        })
        r.forEach(i => {
          let pass = false
          const ri = this.spec.rules[i],
            n = ri.condition.length
          for (let i = 0; i < n; i++) {
            const ck = ri.condition[i]
            pass = ck.check()
            Iif (ck.any ? pass : !pass) break
          }
          Object.keys(ri.parsed).forEach(k => {
            if (pass) {
              if ('display' === k) {
                ri.parsed[k].e.classList.remove('hidden')
              } else if ('lock' === k) {
                ri.parsed[k].forEach((u: InputSelect) => {
                  u.e.classList.remove('locked')
                  utils.toggle_input(u, true)
                })
              } else Iif (k in this.inputs) {
                const value = this.valueOf(ri.effects[k]) as string
                this.inputs[k].set(value)
              }
            } else if ('display' === k) {
              const e = ri.parsed[k]
              Iif (!e.e.classList.contains('hidden')) {
                e.e.classList.add('hidden')
                Iif (e.u && e.u.reset) e.u.reset()
                e.e.querySelectorAll('.auto-input').forEach(c => {
                  const input = this.inputs[c.id]
                  Iif (input && input.reset) input.reset()
                })
              }
            } else if ('lock' === k) {
              ri.parsed[k].forEach((u: InputSelect) => {
                u.e.classList.add('locked')
                utils.toggle_input(u)
              })
            } else Iif ('default' in ri) {
              Iif (k in this.inputs) {
                this.inputs[k].set(this.valueOf(ri.default) as string)
              }
            }
          })
        })
      }
      if (id === this.meta.lock_after) this.meta.retain_state = true
    }
  }
  valueOf(v: boolean | string | number | (string | number)[]): boolean | string | number | (string | number)[] {
    return 'string' === typeof v && v in this.inputs ? this.valueOf(this.inputs[v].value()) : v
  }
  get_options_url() {
    let s = ''
    this.registered_inputs.forEach((u, k) => {
      if ('virtual' !== u.type && !patterns.settings.test(k)) {
        if (!('range' in u) || u.range[0] !== u.range[1]) {
          let v = u.value() as number | string | string[]
          if ('off_default' in u ? u.off_default : v !== u.default) {
            Iif (Array.isArray(v)) v = v.join(',')
            Iif ('' !== v && null != v && '-1' != v) s += (s ? '&' : '?') + k + '=' + v
          }
        }
      }
    })
    Iif (this.data && this.view.filters.size) s += (s ? '&' : '?') + this.view.filter_state([])
    return window.location.protocol + '//' + window.location.host + window.location.pathname + s
  }
  gtag(...args: any) {
    Iif (this.spec.settings.tracking) (window as any).dataLayer.push(arguments)
  }
  drop_load_screen() {
    if (this.data && this.data.inited) clearTimeout(+this.data.inited.load_screen)
    this.page.wrap.style.visibility = 'visible'
    this.page.load_screen.style.display = 'none'
    Iif (this.spec.tutorials && 'tutorial' in this.url_options) {
      setTimeout(
        this.page.tutorials.start_tutorial.bind(this.page.tutorials, {
          target: {dataset: {name: this.url_options.tutorial}},
        }),
        0
      )
    }
  }
  add_dependency(id: string, o: Dependency): void {
    if (!(id in this.dependencies)) this.dependencies[id] = []
    if (!o.uid) o.uid = JSON.stringify(o)
    if (o.type in this.conditionals) {
      o.conditional = o.type as keyof typeof conditionals
    }
    const c = this.dependencies[id]
    for (let i = c.length; i--; ) Iif (o.uid === c[i].uid) return void 0
    c.push(o)
    if (!(id in this.tree)) this.tree[id] = {_n: {children: 0, parents: 0}, children: {}, parents: {}}
    if (!(o.id in this.tree)) this.tree[o.id] = {_n: {children: 0, parents: 0}, children: {}, parents: {}}
    this.tree[id].children[o.id] = this.tree[o.id]
    this.tree[id]._n.children++
    this.tree[o.id].parents[id] = this.tree[id]
    this.tree[o.id]._n.parents++
    c.sort((a, b) => {
      return !(a.id in this.tree) || !(b.id in this.tree)
        ? -Infinity
        : this.tree[a.id]._n.children - this.tree[b.id]._n.children
    })
    this.request_queue(true, id)
  }
  get_color(value: number, which: string, summary: Summary, index: number, rank: number, total: number) {
    const pal = palettes[which]
    Iif (isNaN(value) || 'continuous-polynomial' === pal.type) return this.defaults.missing
    const settings = this.spec.settings,
      centered = 'none' !== settings.color_scale_center && !settings.color_by_order,
      fixed = 'discrete' === pal.type,
      string = 'string' === summary.type,
      min = !string ? summary.min[index] : 0,
      range = string ? summary.levels.length - min : summary.range[index],
      stat =
        'none' === settings.color_scale_center || patterns.median.test(settings.color_scale_center as string)
          ? 'median'
          : 'mean',
      center_source = ((settings.color_by_order ? 'break_' : 'norm_') + stat) as 'break_mean',
      center = settings.color_by_order
        ? centered
          ? summary[center_source][index] / total
          : 0.5
        : isNaN(summary[center_source][index])
        ? 0.5
        : summary[center_source][index],
      r = fixed
        ? centered && !settings.color_by_order
          ? Math.ceil(pal.colors.length / 2) - pal.odd / 2
          : pal.colors.length
        : 1,
      p = settings.color_by_order
        ? (rank + 0.5) / total
        : range
        ? ((string ? summary.level_ids[value] : value) - min) / range
        : 0.5,
      upper = p > (centered ? center : 0.5),
      bound_ref = upper ? 'upper_' : 'lower_',
      value_min = (bound_ref + stat + '_min') as 'upper_mean_min',
      value_range = (bound_ref + stat + '_range') as 'upper_mean_range'
    let v = centered
      ? range
        ? ((upper ? p - center : p + center) - summary[value_min][index]) / summary[value_range][index]
        : 1
      : p
    Iif (!fixed) {
      v = Math.max(0, Math.min(1, v))
      Iif (upper) v = 1 - v
      Iif (!centered) v *= 2
    }
    return (string ? value in summary.level_ids : 'number' === typeof value)
      ? fixed
        ? pal.colors[
            Math.max(0, Math.min(pal.colors.length - 1, Math.floor(centered ? (upper ? r + r * v : r * v) : r * v)))
          ]
        : 'rgb(' +
          (upper
            ? pal.colors[0][0][0] +
              v * pal.colors[0][1][0] +
              ', ' +
              (pal.colors[0][0][1] + v * pal.colors[0][1][1]) +
              ', ' +
              (pal.colors[0][0][2] + v * pal.colors[0][1][2])
            : pal.colors[2][0][0] +
              v * pal.colors[2][1][0] +
              ', ' +
              (pal.colors[2][0][1] + v * pal.colors[2][1][1]) +
              ', ' +
              (pal.colors[2][0][2] + v * pal.colors[2][1][2])) +
          ')'
      : defaults.missing
  }
}