Copybara | 854996b | 2021-09-07 19:36:02 +0000 | [diff] [blame] | 1 | // Copyright 2019 The Chromium Authors. All rights reserved. |
| 2 | // Use of this source code is governed by a BSD-style license that can be |
| 3 | // found in the LICENSE file. |
| 4 | |
| 5 | import {LitElement, html, css} from 'lit-element'; |
| 6 | |
| 7 | /** |
| 8 | * `<chops-chart>` |
| 9 | * |
| 10 | * Web components wrapper around Chart.js. |
| 11 | * |
| 12 | */ |
| 13 | export class ChopsChart extends LitElement { |
| 14 | /** @override */ |
| 15 | static get styles() { |
| 16 | return css` |
| 17 | :host { |
| 18 | display: block; |
| 19 | } |
| 20 | `; |
| 21 | } |
| 22 | |
| 23 | /** @override */ |
| 24 | render() { |
| 25 | return html` |
| 26 | <canvas></canvas> |
| 27 | `; |
| 28 | } |
| 29 | |
| 30 | /** @override */ |
| 31 | static get properties() { |
| 32 | return { |
| 33 | type: {type: String}, |
| 34 | data: {type: Object}, |
| 35 | options: {type: Object}, |
| 36 | _chart: {type: Object}, |
| 37 | _chartConstructor: {type: Object}, |
| 38 | }; |
| 39 | } |
| 40 | |
| 41 | /** @override */ |
| 42 | constructor() { |
| 43 | super(); |
| 44 | this.type = 'line'; |
| 45 | this.data = {}; |
| 46 | this.options = {}; |
| 47 | } |
| 48 | |
| 49 | /** |
| 50 | * Dynamically chartJs to reduce single EZT bundle size |
| 51 | * Move to static import once EZT is deprecated |
| 52 | */ |
| 53 | async connectedCallback() { |
| 54 | super.connectedCallback(); |
| 55 | /* eslint-disable max-len */ |
| 56 | const {default: Chart} = await import( |
| 57 | /* webpackChunkName: "chartjs" */ 'chart.js/dist/Chart.bundle.min.js'); |
| 58 | this._chartConstructor = Chart; |
| 59 | } |
| 60 | |
| 61 | /** |
| 62 | * Refetch and rerender chart after property changes |
| 63 | * @override |
| 64 | * @param {Map} changedProperties |
| 65 | */ |
| 66 | updated(changedProperties) { |
| 67 | // Make sure chartJS has loaded before attempting to create a chart |
| 68 | if (this._chartConstructor) { |
| 69 | if (!this._chart) { |
| 70 | const {type, data, options} = this; |
| 71 | const ctx = this.shadowRoot.querySelector('canvas').getContext('2d'); |
| 72 | this._chart = new this._chartConstructor(ctx, {type, data, options}); |
| 73 | } else if ( |
| 74 | changedProperties.has('type') || |
| 75 | changedProperties.has('data') || |
| 76 | changedProperties.has('options')) { |
| 77 | this._updateChart(); |
| 78 | } |
| 79 | } |
| 80 | } |
| 81 | |
| 82 | /** |
| 83 | * Sets chartJs options and calls update |
| 84 | */ |
| 85 | _updateChart() { |
| 86 | this._chart.type = this.type; |
| 87 | this._chart.data = this.data; |
| 88 | this._chart.options = this.options; |
| 89 | |
| 90 | this._chart.update(); |
| 91 | } |
| 92 | } |
| 93 | |
| 94 | customElements.define('chops-chart', ChopsChart); |