@oicl/openbridge-webcomponents-full-bundle 2.1.0-next.6 → 2.1.0-next.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.storybook/vitest.hidden-mount.setup.ts +96 -0
- package/bundle/openbridge-webcomponents.bundle.js +47 -8
- package/bundle/openbridge-webcomponents.bundle.js.map +1 -1
- package/custom-elements.json +65 -3
- package/dist/ar/chart-object-vessel-button/chart-object-vessel-button.d.ts.map +1 -1
- package/dist/ar/chart-object-vessel-button/chart-object-vessel-button.js +1 -1
- package/dist/ar/chart-object-vessel-button/chart-object-vessel-button.js.map +1 -1
- package/dist/building-blocks/chart-line/chart-line-base.css.js +8 -0
- package/dist/building-blocks/chart-line/chart-line-base.css.js.map +1 -1
- package/dist/building-blocks/chart-line/chart-line-base.d.ts +3 -1
- package/dist/building-blocks/chart-line/chart-line-base.d.ts.map +1 -1
- package/dist/building-blocks/chart-line/chart-line-base.js +9 -4
- package/dist/building-blocks/chart-line/chart-line-base.js.map +1 -1
- package/dist/charthelpers/label-threshold.d.ts +7 -2
- package/dist/charthelpers/label-threshold.d.ts.map +1 -1
- package/dist/charthelpers/label-threshold.js +14 -2
- package/dist/charthelpers/label-threshold.js.map +1 -1
- package/dist/navigation-instruments/watch-flat/watch-flat.d.ts +8 -0
- package/dist/navigation-instruments/watch-flat/watch-flat.d.ts.map +1 -1
- package/dist/navigation-instruments/watch-flat/watch-flat.js +17 -1
- package/dist/navigation-instruments/watch-flat/watch-flat.js.map +1 -1
- package/package.json +2 -1
- package/src/ar/chart-object-vessel-button/chart-object-vessel-button.ts +3 -1
- package/src/building-blocks/chart-line/chart-line-base.css +8 -0
- package/src/building-blocks/chart-line/chart-line-base.ts +16 -5
- package/src/charthelpers/label-threshold.spec.ts +28 -0
- package/src/charthelpers/label-threshold.ts +16 -3
- package/src/navigation-instruments/rot-linear/rot-linear.spec.ts +36 -0
- package/src/navigation-instruments/watch-flat/watch-flat.spec.ts +76 -0
- package/src/navigation-instruments/watch-flat/watch-flat.ts +22 -1
package/custom-elements.json
CHANGED
|
@@ -303,7 +303,7 @@
|
|
|
303
303
|
{
|
|
304
304
|
"kind": "variable",
|
|
305
305
|
"name": "ObcChartObjectVesselButton",
|
|
306
|
-
"default": "class ObcChartObjectVesselButton extends LitElement { constructor(..._args) { super(..._args); this.heading = 0; this.course = 0; this.speedIndicator = \"two\"; this.turnRate = 0; this.number = void 0; this.name = void 0; this.state = \"enabled\"; this.type = \"flat\"; this.selected = false; this.courseArrowPx = void 0; this.ownShipIndicator = false; this.vesselImage = null; this.vesselImageSize = 80; } render() { const tag = [ \"button\", \"large\", \"button-speed-rot\" ].includes(this.type) ? literal`button` : literal`div`; const hasAlert = [ \"alarm\", \"warning\", \"caution\" ].includes(this.state); return html$1` <${tag} class=${classMap({ wrapper: true, [`state-${this.state}`]: true, [`type-${this.type}`]: true, \"has-alert\": hasAlert, selected: this.selected })} style=\"--heading: ${this.heading}deg;\" > ${this.getVesselImageIcon()} ${this.getCourseArrowIcon()} ${this.getOwnShipIndicatorIcon()} <div class=\"visible-wrapper\" style=\"transform: rotate(${this.heading}deg);\"> ${this.getTurnRateIcon()} <div class=\"icon-wrapper\" > <span class=\"icon-silhouette\" part=\"icon-silhouette\"> <slot name=\"silhouette\"></slot> </span> <span class=\"icon-primary\" part=\"icon\"> <slot></slot> </span> </div> ${this.getSpeedIndicatorIcon()} ${hasAlert ? html$1`<div class=\"alert-ring\"></div>` : nothing} </div> ${this.selected ? html$1`<div class=\"selection-frame\"></div>` : nothing} ${this.number ? html$1`<div class=\"number-wrapper\"> <slot name=\"number\">${this.number}</slot> </div>` : nothing} ${this.name ? html$1`<div class=\"name-wrapper\"> <slot name=\"name\">${this.name}</slot> </div>` : nothing} </${tag}> `; } getSpeedIndicatorIcon() { if (![\"button-speed-rot\", \"flat-speed-rot\"].includes(this.type)) return nothing; let x = []; switch (this.speedIndicator) { case \"one\": x = [0]; break; case \"two\": x = [-2, 2]; break; case \"three\": x = [ -4, 0, 4 ]; } let extra = void 0; if (this.speedIndicator === \"stopped\") extra = svg$1` <circle cx=\"0\" cy=\"0\" r=\"4\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"1.5\" /> `; else if (this.speedIndicator === \"anchored\") return svg$1` <svg width=\"16\" height=\"12\" viewBox=\"0 0 16 12\" fill=\"none\" xmlns=\"http://www.w3.org/2000/svg\"> <path d=\"M8.75 3.25H10.75V4.75H8.75V8.38379C8.81975 8.36184 8.88925 8.33765 8.95703 8.30957C9.26022 8.18394 9.53551 7.99964 9.76758 7.76758C9.99964 7.53551 10.1839 7.26022 10.3096 6.95703C10.4352 6.65372 10.5 6.3283 10.5 6H12C12 6.52517 11.8962 7.04506 11.6953 7.53027C11.4943 8.01558 11.1996 8.45669 10.8281 8.82812C10.4567 9.19956 10.0156 9.49429 9.53027 9.69531C9.04506 9.89624 8.52517 10 8 10C7.47483 10 6.95494 9.89624 6.46973 9.69531C5.98442 9.49429 5.54331 9.19956 5.17188 8.82812C4.80044 8.45669 4.50571 8.01558 4.30469 7.53027C4.10376 7.04506 4 6.52517 4 6H5.5C5.5 6.3283 5.56479 6.65372 5.69043 6.95703C5.81606 7.26022 6.00036 7.53551 6.23242 7.76758C6.46449 7.99964 6.73978 8.18394 7.04297 8.30957C7.11075 8.33765 7.18025 8.36184 7.25 8.38379V4.75H5.25V3.25H7.25V1.25H8.75V3.25Z\" fill=\"currentColor\" /> </svg> `; return html$1` <svg width=\"16\" height=\"12\" viewBox=\"-8 -6 16 12\" fill=\"none\" xmlns=\"http://www.w3.org/2000/svg\" > ${x.map((x) => svg$1` <line x1=\"${x}\" y1=\"-3\" x2=\"${x}\" y2=\"3\" stroke-linecap=\"round\" stroke-width=\"1.5\" stroke=\"currentColor\" /> `)} ${extra} </svg> `; } getTurnRateIcon() { if (![\"button-speed-rot\", \"flat-speed-rot\"].includes(this.type)) return nothing; const deg = this.turnRate / 100 * 12; const R = 24; const x = -24 * Math.cos(degToRad(deg)) + R + 3; const y = R * Math.sin(degToRad(deg)) + 8; return html$1` <svg width=\"16\" height=\"12\" viewBox=\"0 0 16 12\" fill=\"none\" xmlns=\"http://www.w3.org/2000/svg\" > <path d=\"M8 9 V 3 A ${R} ${R} 0 0 1 ${y} ${x}\" stroke=\"currentColor\" stroke-width=\"1.5\" stroke-linecap=\"round\" stroke-linejoin=\"round\" /> </svg> `; } getCourseArrowIcon() { if (this.courseArrowPx === void 0) return nothing; const height = this.courseArrowPx; let color = \"var(--element-active-color)\"; if (this.state === \"alarm\") color = \"var(--alert-alarm-color)\"; return html$1` <svg width=\"256\" height=${height} viewBox=\"-128 0 256 ${height}\" fill=\"none\" xmlns=\"http://www.w3.org/2000/svg\" class=\"course-arrow\" style=\"--course: ${this.course}deg; --color: ${color}\" > <line x1=\"0\" y1=\"24\" x2=\"0\" y2=${height} stroke-width=\"4\" stroke=\"var(--border-silhouette-color)\" stroke-linecap=\"round\" /> <line x1=\"0\" y1=\"24\" x2=\"0\" y2=${height} stroke-width=\"2\" stroke=\"var(--color)\" stroke-linecap=\"square\" stroke-dasharray=\"4 4\" stroke-linejoin=\"square\" /> <g transform=\"translate(-12 0)\"> <path d=\"M11.5457 11.2919L13.3638 12.1253L13.3638 12.1252L11.5457 11.2919ZM12.4548 11.2919L10.6367 12.1252L10.6367 12.1253L12.4548 11.2919ZM16.7136 20.5829L18.5317 19.7496L18.5317 19.7495L16.7136 20.5829ZM15.8044 21.9999L15.8044 23.9999L15.805 23.9999L15.8044 21.9999ZM14.8953 21.4169L13.0772 22.2503L13.0774 22.2507L14.8953 21.4169ZM11.9998 15.1005L13.8178 14.2671L11.9994 10.3004L10.1816 14.2673L11.9998 15.1005ZM9.10522 21.4169L10.9233 22.2504L10.9234 22.2501L9.10522 21.4169ZM8.19604 21.9999L8.19604 23.9999L8.1964 23.9999L8.19604 21.9999ZM7.28687 20.5829L5.46877 19.7495L5.46874 19.7496L7.28687 20.5829ZM11.5457 2.2919L13.3638 3.12527L13.3638 3.12521L11.5457 2.2919ZM12.4548 2.2919L10.6367 3.12521L10.6367 3.12527L12.4548 2.2919ZM16.7136 11.5829L18.5317 10.7496L18.5317 10.7495L16.7136 11.5829ZM15.8044 12.9999L15.8044 14.9999L15.805 14.9999L15.8044 12.9999ZM14.8953 12.4169L13.0772 13.2503L13.0774 13.2507L14.8953 12.4169ZM11.9998 6.10049L13.8178 5.26706L11.9994 1.30035L10.1816 5.2673L11.9998 6.10049ZM9.10522 12.4169L10.9233 13.2504L10.9234 13.2501L9.10522 12.4169ZM8.19604 12.9999L8.19604 14.9999L8.19643 14.9999L8.19604 12.9999ZM7.28687 11.5829L5.46877 10.7495L5.46874 10.7496L7.28687 11.5829ZM11.5457 11.2919L13.3638 12.1252C12.829 13.2919 11.1714 13.2919 10.6367 12.1252L12.4548 11.2919L14.273 10.4586C13.3817 8.5141 10.6187 8.5141 9.72752 10.4586L11.5457 11.2919ZM12.4548 11.2919L10.6367 12.1253L14.8955 21.4163L16.7136 20.5829L18.5317 19.7495L14.2729 10.4585L12.4548 11.2919ZM16.7136 20.5829L14.8955 21.4162C14.5917 20.7534 15.076 20.0001 15.8039 19.9999L15.8044 21.9999L15.805 23.9999C17.9899 23.9993 19.4426 21.737 18.5317 19.7496L16.7136 20.5829ZM15.8044 21.9999V19.9999C16.1945 19.9999 16.5498 20.227 16.7132 20.5831L14.8953 21.4169L13.0774 22.2507C13.5666 23.3174 14.6325 23.9999 15.8044 23.9999V21.9999ZM14.8953 21.4169L16.7133 20.5835L13.8178 14.2671L11.9998 15.1005L10.1817 15.9339L13.0772 22.2503L14.8953 21.4169ZM11.9998 15.1005L10.1816 14.2673L7.28704 20.5837L9.10522 21.4169L10.9234 22.2501L13.8179 15.9337L11.9998 15.1005ZM9.10522 21.4169L7.28718 20.5834C7.45077 20.2266 7.80642 20 8.19569 19.9999L8.19604 21.9999L8.1964 23.9999C9.36748 23.9997 10.4339 23.3179 10.9233 22.2504L9.10522 21.4169ZM8.19604 21.9999L8.19604 19.9999C8.92502 19.9999 9.40845 20.7541 9.10499 21.4162L7.28687 20.5829L5.46874 19.7496C4.55809 21.7365 6.00978 23.9999 8.19604 23.9999V21.9999ZM7.28687 20.5829L9.10496 21.4163L13.3638 12.1253L11.5457 11.2919L9.72755 10.4585L5.46877 19.7495L7.28687 20.5829ZM11.5457 2.2919L13.3638 3.12521C12.829 4.2919 11.1714 4.2919 10.6367 3.12521L12.4548 2.2919L14.273 1.45859C13.3817 -0.485895 10.6187 -0.485895 9.72752 1.45859L11.5457 2.2919ZM12.4548 2.2919L10.6367 3.12527L14.8955 12.4163L16.7136 11.5829L18.5317 10.7495L14.2729 1.45852L12.4548 2.2919ZM16.7136 11.5829L14.8955 12.4162C14.5917 11.7534 15.076 11.0001 15.8039 10.9999L15.8044 12.9999L15.805 14.9999C17.9899 14.9993 19.4427 12.7371 18.5317 10.7496L16.7136 11.5829ZM15.8044 12.9999V10.9999C16.1946 10.9999 16.5498 11.227 16.7131 11.5831L14.8953 12.4169L13.0774 13.2507C13.5666 14.3174 14.6325 14.9999 15.8044 14.9999V12.9999ZM14.8953 12.4169L16.7133 11.5835L13.8178 5.26706L11.9998 6.10049L10.1817 6.93392L13.0772 13.2503L14.8953 12.4169ZM11.9998 6.10049L10.1816 5.2673L7.28704 11.5837L9.10522 12.4169L10.9234 13.2501L13.8179 6.93368L11.9998 6.10049ZM9.10522 12.4169L7.28717 11.5834C7.45078 11.2265 7.80645 11 8.19566 10.9999L8.19604 12.9999L8.19643 14.9999C9.36745 14.9997 10.4339 14.3179 10.9233 13.2504L9.10522 12.4169ZM8.19604 12.9999V10.9999C8.92502 10.9999 9.40845 11.7541 9.10499 12.4162L7.28687 11.5829L5.46874 10.7496C4.55809 12.7365 6.00978 14.9999 8.19604 14.9999V12.9999ZM7.28687 11.5829L9.10496 12.4163L13.3638 3.12527L11.5457 2.2919L9.72755 1.45852L5.46877 10.7495L7.28687 11.5829Z\" fill=\"var(--border-silhouette-color)\" /> <path d=\"M11.5457 11.2919C11.7239 10.903 12.2766 10.903 12.4548 11.2919L16.7136 20.5829C17.0172 21.2452 16.5329 21.9997 15.8044 21.9999C15.4135 21.9999 15.0582 21.7722 14.8953 21.4169L11.9998 15.1005L9.10522 21.4169C8.94231 21.7722 8.58695 21.9998 8.19604 21.9999C7.4674 21.9999 6.98327 21.2453 7.28687 20.5829L11.5457 11.2919ZM11.5457 2.2919C11.7239 1.903 12.2766 1.903 12.4548 2.2919L16.7136 11.5829C17.0172 12.2452 16.5329 12.9997 15.8044 12.9999C15.4135 12.9999 15.0582 12.7722 14.8953 12.4169L11.9998 6.10049L9.10522 12.4169C8.94232 12.7722 8.58695 12.9998 8.19604 12.9999C7.4674 12.9999 6.98327 12.2453 7.28687 11.5829L11.5457 2.2919Z\" fill=\"var(--color)\" /> </g> </svg> `; } getOwnShipIndicatorIcon() { if (!this.ownShipIndicator) return nothing; return html$1` <svg width=\"64\" height=\"256\" viewBox=\"-32 -128 64 256\" fill=\"none\" xmlns=\"http://www.w3.org/2000/svg\" class=\"cross-line\" > <circle cx=\"0\" cy=\"0\" r=\"2\" fill=\"var(--element-active-color)\" /> <line x1=\"-32\" x2=\"-4\" y1=\"0\" y2=\"0\" stroke=\"var(--element-active-color)\" stroke-width=\"1\" stroke-linecap=\"round\" stroke-linejoin=\"round\" /> <line x1=\"32\" x2=\"4\" y1=\"0\" y2=\"0\" stroke=\"var(--element-active-color)\" stroke-width=\"1\" stroke-linecap=\"round\" stroke-linejoin=\"round\" /> <line x1=\"0\" x2=\"0\" y1=\"-4\" y2=\"-128\" stroke=\"var(--element-active-color)\" stroke-width=\"1\" stroke-linecap=\"round\" stroke-linejoin=\"round\" /> <line x1=\"0\" x2=\"0\" y1=\"4\" y2=\"128\" stroke=\"var(--element-active-color)\" stroke-width=\"1\" stroke-dasharray=\"1 2\" /> </svg> `; } getVesselImageIcon() { if (!this.vesselImage) return html$1`<div class=\"vessel-image-wrapper\" style=\"--image-size: ${this.vesselImageSize}px;\" part=\"vessel-image-wrapper\" > <slot name=\"vessel-image\"></slot> </div>`; return html$1`<div class=\"vessel-image-wrapper\" style=\"--image-size: ${this.vesselImageSize}px;\" part=\"vessel-image-wrapper\" > ${vesselImages[this.vesselImage]} </div>`; } static { this.styles = unsafeCSS(chart_object_vessel_button_default); } }"
|
|
306
|
+
"default": "class ObcChartObjectVesselButton extends LitElement { constructor(..._args) { super(..._args); this.heading = 0; this.course = 0; this.speedIndicator = \"two\"; this.turnRate = 0; this.number = void 0; this.name = void 0; this.state = \"enabled\"; this.type = \"flat\"; this.selected = false; this.courseArrowPx = void 0; this.ownShipIndicator = false; this.vesselImage = null; this.vesselImageSize = 80; } render() { const tag = [ \"button\", \"large\", \"button-speed-rot\" ].includes(this.type) ? literal`button` : literal`div`; const hasAlert = [ \"alarm\", \"warning\", \"caution\" ].includes(this.state); return html$1` <${tag} class=${classMap({ wrapper: true, [`state-${this.state}`]: true, [`type-${this.type}`]: true, \"has-alert\": hasAlert, selected: this.selected })} style=\"--heading: ${this.heading}deg;\" > ${this.getVesselImageIcon()} ${this.getCourseArrowIcon()} ${this.getOwnShipIndicatorIcon()} <div class=\"visible-wrapper\" style=\"transform: rotate(${this.heading}deg);\"> ${this.getTurnRateIcon()} <div class=\"icon-wrapper\" > <span class=\"icon-silhouette\" part=\"icon-silhouette\"> <slot name=\"silhouette\"></slot> </span> <span class=\"icon-primary\" part=\"icon\"> <slot></slot> </span> </div> ${this.getSpeedIndicatorIcon()} ${hasAlert ? html$1`<div class=\"alert-ring\"></div>` : nothing} </div> ${this.selected ? html$1`<div class=\"selection-frame\"></div>` : nothing} ${this.number ? html$1`<div class=\"number-wrapper\"> <slot name=\"number\">${this.number}</slot> </div>` : nothing} ${this.name ? html$1`<div class=\"name-wrapper\"> <slot name=\"name\">${this.name}</slot> </div>` : nothing} </${tag}> `; } getSpeedIndicatorIcon() { if (![\"button-speed-rot\", \"flat-speed-rot\"].includes(this.type)) return nothing; let x = []; switch (this.speedIndicator) { case \"one\": x = [0]; break; case \"two\": x = [-2, 2]; break; case \"three\": x = [ -4, 0, 4 ]; } let extra = void 0; if (this.speedIndicator === \"stopped\") extra = svg$1` <circle cx=\"0\" cy=\"0\" r=\"4\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"1.5\" /> `; else if (this.speedIndicator === \"anchored\") return svg$1` <svg width=\"16\" height=\"12\" viewBox=\"0 0 16 12\" fill=\"none\" xmlns=\"http://www.w3.org/2000/svg\"> <path d=\"M8.75 3.25H10.75V4.75H8.75V8.38379C8.81975 8.36184 8.88925 8.33765 8.95703 8.30957C9.26022 8.18394 9.53551 7.99964 9.76758 7.76758C9.99964 7.53551 10.1839 7.26022 10.3096 6.95703C10.4352 6.65372 10.5 6.3283 10.5 6H12C12 6.52517 11.8962 7.04506 11.6953 7.53027C11.4943 8.01558 11.1996 8.45669 10.8281 8.82812C10.4567 9.19956 10.0156 9.49429 9.53027 9.69531C9.04506 9.89624 8.52517 10 8 10C7.47483 10 6.95494 9.89624 6.46973 9.69531C5.98442 9.49429 5.54331 9.19956 5.17188 8.82812C4.80044 8.45669 4.50571 8.01558 4.30469 7.53027C4.10376 7.04506 4 6.52517 4 6H5.5C5.5 6.3283 5.56479 6.65372 5.69043 6.95703C5.81606 7.26022 6.00036 7.53551 6.23242 7.76758C6.46449 7.99964 6.73978 8.18394 7.04297 8.30957C7.11075 8.33765 7.18025 8.36184 7.25 8.38379V4.75H5.25V3.25H7.25V1.25H8.75V3.25Z\" fill=\"currentColor\" /> </svg> `; return html$1` <svg width=\"16\" height=\"12\" viewBox=\"-8 -6 16 12\" fill=\"none\" xmlns=\"http://www.w3.org/2000/svg\" > ${x.map((x) => svg$1` <line x1=\"${x}\" y1=\"-3\" x2=\"${x}\" y2=\"3\" stroke-linecap=\"round\" stroke-width=\"1.5\" stroke=\"currentColor\" /> `)} ${extra} </svg> `; } getTurnRateIcon() { if (![\"button-speed-rot\", \"flat-speed-rot\"].includes(this.type)) return nothing; const deg = (Number.isFinite(this.turnRate) ? this.turnRate : 0) / 100 * 12; const R = 24; const x = -24 * Math.cos(degToRad(deg)) + R + 3; const y = R * Math.sin(degToRad(deg)) + 8; return html$1` <svg width=\"16\" height=\"12\" viewBox=\"0 0 16 12\" fill=\"none\" xmlns=\"http://www.w3.org/2000/svg\" > <path d=\"M8 9 V 3 A ${R} ${R} 0 0 1 ${y} ${x}\" stroke=\"currentColor\" stroke-width=\"1.5\" stroke-linecap=\"round\" stroke-linejoin=\"round\" /> </svg> `; } getCourseArrowIcon() { if (this.courseArrowPx === void 0) return nothing; const height = this.courseArrowPx; let color = \"var(--element-active-color)\"; if (this.state === \"alarm\") color = \"var(--alert-alarm-color)\"; return html$1` <svg width=\"256\" height=${height} viewBox=\"-128 0 256 ${height}\" fill=\"none\" xmlns=\"http://www.w3.org/2000/svg\" class=\"course-arrow\" style=\"--course: ${this.course}deg; --color: ${color}\" > <line x1=\"0\" y1=\"24\" x2=\"0\" y2=${height} stroke-width=\"4\" stroke=\"var(--border-silhouette-color)\" stroke-linecap=\"round\" /> <line x1=\"0\" y1=\"24\" x2=\"0\" y2=${height} stroke-width=\"2\" stroke=\"var(--color)\" stroke-linecap=\"square\" stroke-dasharray=\"4 4\" stroke-linejoin=\"square\" /> <g transform=\"translate(-12 0)\"> <path d=\"M11.5457 11.2919L13.3638 12.1253L13.3638 12.1252L11.5457 11.2919ZM12.4548 11.2919L10.6367 12.1252L10.6367 12.1253L12.4548 11.2919ZM16.7136 20.5829L18.5317 19.7496L18.5317 19.7495L16.7136 20.5829ZM15.8044 21.9999L15.8044 23.9999L15.805 23.9999L15.8044 21.9999ZM14.8953 21.4169L13.0772 22.2503L13.0774 22.2507L14.8953 21.4169ZM11.9998 15.1005L13.8178 14.2671L11.9994 10.3004L10.1816 14.2673L11.9998 15.1005ZM9.10522 21.4169L10.9233 22.2504L10.9234 22.2501L9.10522 21.4169ZM8.19604 21.9999L8.19604 23.9999L8.1964 23.9999L8.19604 21.9999ZM7.28687 20.5829L5.46877 19.7495L5.46874 19.7496L7.28687 20.5829ZM11.5457 2.2919L13.3638 3.12527L13.3638 3.12521L11.5457 2.2919ZM12.4548 2.2919L10.6367 3.12521L10.6367 3.12527L12.4548 2.2919ZM16.7136 11.5829L18.5317 10.7496L18.5317 10.7495L16.7136 11.5829ZM15.8044 12.9999L15.8044 14.9999L15.805 14.9999L15.8044 12.9999ZM14.8953 12.4169L13.0772 13.2503L13.0774 13.2507L14.8953 12.4169ZM11.9998 6.10049L13.8178 5.26706L11.9994 1.30035L10.1816 5.2673L11.9998 6.10049ZM9.10522 12.4169L10.9233 13.2504L10.9234 13.2501L9.10522 12.4169ZM8.19604 12.9999L8.19604 14.9999L8.19643 14.9999L8.19604 12.9999ZM7.28687 11.5829L5.46877 10.7495L5.46874 10.7496L7.28687 11.5829ZM11.5457 11.2919L13.3638 12.1252C12.829 13.2919 11.1714 13.2919 10.6367 12.1252L12.4548 11.2919L14.273 10.4586C13.3817 8.5141 10.6187 8.5141 9.72752 10.4586L11.5457 11.2919ZM12.4548 11.2919L10.6367 12.1253L14.8955 21.4163L16.7136 20.5829L18.5317 19.7495L14.2729 10.4585L12.4548 11.2919ZM16.7136 20.5829L14.8955 21.4162C14.5917 20.7534 15.076 20.0001 15.8039 19.9999L15.8044 21.9999L15.805 23.9999C17.9899 23.9993 19.4426 21.737 18.5317 19.7496L16.7136 20.5829ZM15.8044 21.9999V19.9999C16.1945 19.9999 16.5498 20.227 16.7132 20.5831L14.8953 21.4169L13.0774 22.2507C13.5666 23.3174 14.6325 23.9999 15.8044 23.9999V21.9999ZM14.8953 21.4169L16.7133 20.5835L13.8178 14.2671L11.9998 15.1005L10.1817 15.9339L13.0772 22.2503L14.8953 21.4169ZM11.9998 15.1005L10.1816 14.2673L7.28704 20.5837L9.10522 21.4169L10.9234 22.2501L13.8179 15.9337L11.9998 15.1005ZM9.10522 21.4169L7.28718 20.5834C7.45077 20.2266 7.80642 20 8.19569 19.9999L8.19604 21.9999L8.1964 23.9999C9.36748 23.9997 10.4339 23.3179 10.9233 22.2504L9.10522 21.4169ZM8.19604 21.9999L8.19604 19.9999C8.92502 19.9999 9.40845 20.7541 9.10499 21.4162L7.28687 20.5829L5.46874 19.7496C4.55809 21.7365 6.00978 23.9999 8.19604 23.9999V21.9999ZM7.28687 20.5829L9.10496 21.4163L13.3638 12.1253L11.5457 11.2919L9.72755 10.4585L5.46877 19.7495L7.28687 20.5829ZM11.5457 2.2919L13.3638 3.12521C12.829 4.2919 11.1714 4.2919 10.6367 3.12521L12.4548 2.2919L14.273 1.45859C13.3817 -0.485895 10.6187 -0.485895 9.72752 1.45859L11.5457 2.2919ZM12.4548 2.2919L10.6367 3.12527L14.8955 12.4163L16.7136 11.5829L18.5317 10.7495L14.2729 1.45852L12.4548 2.2919ZM16.7136 11.5829L14.8955 12.4162C14.5917 11.7534 15.076 11.0001 15.8039 10.9999L15.8044 12.9999L15.805 14.9999C17.9899 14.9993 19.4427 12.7371 18.5317 10.7496L16.7136 11.5829ZM15.8044 12.9999V10.9999C16.1946 10.9999 16.5498 11.227 16.7131 11.5831L14.8953 12.4169L13.0774 13.2507C13.5666 14.3174 14.6325 14.9999 15.8044 14.9999V12.9999ZM14.8953 12.4169L16.7133 11.5835L13.8178 5.26706L11.9998 6.10049L10.1817 6.93392L13.0772 13.2503L14.8953 12.4169ZM11.9998 6.10049L10.1816 5.2673L7.28704 11.5837L9.10522 12.4169L10.9234 13.2501L13.8179 6.93368L11.9998 6.10049ZM9.10522 12.4169L7.28717 11.5834C7.45078 11.2265 7.80645 11 8.19566 10.9999L8.19604 12.9999L8.19643 14.9999C9.36745 14.9997 10.4339 14.3179 10.9233 13.2504L9.10522 12.4169ZM8.19604 12.9999V10.9999C8.92502 10.9999 9.40845 11.7541 9.10499 12.4162L7.28687 11.5829L5.46874 10.7496C4.55809 12.7365 6.00978 14.9999 8.19604 14.9999V12.9999ZM7.28687 11.5829L9.10496 12.4163L13.3638 3.12527L11.5457 2.2919L9.72755 1.45852L5.46877 10.7495L7.28687 11.5829Z\" fill=\"var(--border-silhouette-color)\" /> <path d=\"M11.5457 11.2919C11.7239 10.903 12.2766 10.903 12.4548 11.2919L16.7136 20.5829C17.0172 21.2452 16.5329 21.9997 15.8044 21.9999C15.4135 21.9999 15.0582 21.7722 14.8953 21.4169L11.9998 15.1005L9.10522 21.4169C8.94231 21.7722 8.58695 21.9998 8.19604 21.9999C7.4674 21.9999 6.98327 21.2453 7.28687 20.5829L11.5457 11.2919ZM11.5457 2.2919C11.7239 1.903 12.2766 1.903 12.4548 2.2919L16.7136 11.5829C17.0172 12.2452 16.5329 12.9997 15.8044 12.9999C15.4135 12.9999 15.0582 12.7722 14.8953 12.4169L11.9998 6.10049L9.10522 12.4169C8.94232 12.7722 8.58695 12.9998 8.19604 12.9999C7.4674 12.9999 6.98327 12.2453 7.28687 11.5829L11.5457 2.2919Z\" fill=\"var(--color)\" /> </g> </svg> `; } getOwnShipIndicatorIcon() { if (!this.ownShipIndicator) return nothing; return html$1` <svg width=\"64\" height=\"256\" viewBox=\"-32 -128 64 256\" fill=\"none\" xmlns=\"http://www.w3.org/2000/svg\" class=\"cross-line\" > <circle cx=\"0\" cy=\"0\" r=\"2\" fill=\"var(--element-active-color)\" /> <line x1=\"-32\" x2=\"-4\" y1=\"0\" y2=\"0\" stroke=\"var(--element-active-color)\" stroke-width=\"1\" stroke-linecap=\"round\" stroke-linejoin=\"round\" /> <line x1=\"32\" x2=\"4\" y1=\"0\" y2=\"0\" stroke=\"var(--element-active-color)\" stroke-width=\"1\" stroke-linecap=\"round\" stroke-linejoin=\"round\" /> <line x1=\"0\" x2=\"0\" y1=\"-4\" y2=\"-128\" stroke=\"var(--element-active-color)\" stroke-width=\"1\" stroke-linecap=\"round\" stroke-linejoin=\"round\" /> <line x1=\"0\" x2=\"0\" y1=\"4\" y2=\"128\" stroke=\"var(--element-active-color)\" stroke-width=\"1\" stroke-dasharray=\"1 2\" /> </svg> `; } getVesselImageIcon() { if (!this.vesselImage) return html$1`<div class=\"vessel-image-wrapper\" style=\"--image-size: ${this.vesselImageSize}px;\" part=\"vessel-image-wrapper\" > <slot name=\"vessel-image\"></slot> </div>`; return html$1`<div class=\"vessel-image-wrapper\" style=\"--image-size: ${this.vesselImageSize}px;\" part=\"vessel-image-wrapper\" > ${vesselImages[this.vesselImage]} </div>`; } static { this.styles = unsafeCSS(chart_object_vessel_button_default); } }"
|
|
307
307
|
}
|
|
308
308
|
],
|
|
309
309
|
"exports": [
|
|
@@ -3349,7 +3349,7 @@
|
|
|
3349
3349
|
{
|
|
3350
3350
|
"kind": "variable",
|
|
3351
3351
|
"name": "ObcChartLineBase",
|
|
3352
|
-
"default": "class extends LitElement { constructor(..._args) { super(..._args); this.data = []; this.datasets = void 0; this.labels = void 0; this.colors = []; this.legend = false; this.showDebugOverlay = false; this.width = 480; this.height = 320; this.fixedAspectRatioScaling = false; this.scaleReferenceSize = 384; this.xAxisType = \"category\"; this.yAxisPosition = \"left\"; this.yAxes = void 0; this.xAxis = void 0; this.xMarker = void 0; this.yMarker = void 0; this.showGrid = false; this.showGridX = false; this.showGridY = false; this.showTickMarks = false; this.hasLabelPadding = true; this.rangeLabels = \"none\"; this.warnedDateDisplayScale = false; this.DEFAULT_TENSION = .4; this.POINT_RADIUS = 3; this.showPoints = false; this.lineMode = \"smooth\"; this.unit = \"\"; this.timeDisplay = \"date\"; this.xTicksLimit = void 0; this.xStepSize = void 0; this.yTicksLimit = void 0; this.yStepSize = void 0; this.state = InstrumentState.active; this.priority = Priority.regular; this.frameStyle = FrameStyle.regular; this.borderRadiusPosition = void 0; this.borderRadiusPositionExternalScales = void 0; this.instrumentMode = false; this.borderRadius = void 0; this.externalScaleDimensions = /* @__PURE__ */ new Map(); this.isUpdatingScales = false; this.currentBorderRadiusPx = 8; this.computedWidth = 480; this.computedHeight = 320; this.savedLabelThickness = /* @__PURE__ */ new WeakMap(); this.savedMainTickmarkLabels = /* @__PURE__ */ new WeakMap(); this.lastRangeLabels = []; this.lastMarkers = {}; this.rangeLabelCache = { y: [], x: [] }; this.updateBorderRadius = () => { if (!this.canvasEl) return; let next; if (this.instrumentMode) next = this.borderRadius ?? 8; else next = readExternalScaleBorderRadiusPx(this.canvasEl, ScaleType.regular, EXTERNAL_SCALE_BORDER_RADIUS_CSS_VAR); if (this.currentBorderRadiusPx !== next) { this.currentBorderRadiusPx = next; if (this.chart) { this.chart.destroy(); this.createChart(); } } }; this.handleSlotChange = () => { this.externalScaleDimensions.clear(); this.waitForScaleDimensions(); }; this.handleScaleDimensionsChanged = (e) => { if (this.isUpdatingScales) return; const { side, thickness } = e.detail; if (this.externalScaleDimensions.get(side) === thickness) return; this.externalScaleDimensions.set(side, thickness); if (this.dimensionUpdateTimer) clearTimeout(this.dimensionUpdateTimer); this.dimensionUpdateTimer = setTimeout(() => { this.syncScalesAndChart(); }, 16); }; } /** @internal - The y side wants range labels; an edge-to-edge chart never does. */ get rangeLabelsY() { return this.hasLabelPadding && (this.rangeLabels === \"y\" || this.rangeLabels === \"xy\"); } /** @internal - The x side wants range labels; an edge-to-edge chart never does. */ get rangeLabelsX() { return this.hasLabelPadding && (this.rangeLabels === \"x\" || this.rangeLabels === \"xy\"); } /** @internal - True when the x-axis positions points by numeric value. */ get isNumericXAxis() { return this.xAxisType === \"time\" || this.xAxisType === \"number\"; } /** * Id of the y scale a dataset lands on when it names none. Chart.js would * otherwise add a default `y` scale next to the configured ones and draw it. */ get primaryYAxisId() { return this.yAxes?.length ? this.yAxes[0].id ?? \"y0\" : \"y\"; } /** @internal - Normalization mode for the current x-axis type. */ get xValueMode() { return this.xAxisType === \"number\" ? XValueMode.number : XValueMode.time; } /** * `reverse` of the axis a side follows: the first axis positioned on that * side, else the first entry — the selection `resolveAxisRange()` makes. */ isYAxisReversed(side = \"left\") { if (!this.yAxes?.length) return false; return (this.yAxes.find((a) => (a.position ?? \"left\") === side) ?? this.yAxes[0]).reverse ?? false; } /** @internal - Warn once per data assignment about unparseable x-values. */ warnOnInvalidX(xValues, sourceRef) { const invalid = xValues.filter((x) => !Number.isFinite(x)).length; if (invalid === 0 || this.lastWarnedXSource === sourceRef) return; this.lastWarnedXSource = sourceRef; console.warn(`[obc-chart] ${invalid} x value(s) could not be parsed for xAxisType='${this.xAxisType}'; the points render as gaps.`); } /** * Should fill be applied to this chart? * Line graph returns false, area graph returns true. * Must be implemented in subclass. */ shouldApplyFill() { throw new Error(\"shouldApplyFill() must be implemented in subclass\"); } /** * Get fill mode for area rendering. * Line graph returns undefined, area graph returns 'semitransparent' | 'solid' | 'threshold'. * Must be implemented in subclass. */ getFillMode() { throw new Error(\"getFillMode() must be implemented in subclass\"); } /** * Should multi-series datasets be stacked? * Line graph returns false, area graph returns stacked property value. * Must be implemented in subclass. */ shouldStack() { throw new Error(\"shouldStack() must be implemented in subclass\"); } /** * Label band a slotted scale needs for its compact labels, in the scale's * own viewBox units. The scale prints the raw values, so those are what is * measured; the x band is one text line. */ compactLabelThickness(axis) { const context = this.canvasEl?.getContext(\"2d\"); if (!context) return void 0; const font = this.rangeLabelFont(); let visual; if (axis === \"y\") { const bounds = this.rangeLabelCache.bounds; if (!bounds) return void 0; const texts = yRangeLabelValues(bounds.min, bounds.max).map(String); visual = measureRangeLabelGutters(context, font, texts, []).side + 4; } else visual = measureRangeLabelGutters(context, font, [], [\"x\"]).bottom + 8; if (!this.fixedAspectRatioScaling) return Math.ceil(visual); const effectiveLength = axis === \"y\" ? this.getEffectiveHeight() : this.getEffectiveWidth(); return Math.ceil(visual * this.scaleReferenceSize / effectiveLength); } /** @internal - Ellipse clips applied last, in pixels by dataset index, for tests. */ get lastClips() { return (this.chart && datasetClipRecords.get(this.chart)) ?? {}; } slotFor(side) { return { left: this.leftScaleSlot, right: this.rightScaleSlot, top: this.topScaleSlot, bottom: this.bottomScaleSlot }[side]; } hasSlottedScale(side) { return (this.slotFor(side)?.assignedElements().length ?? 0) > 0; } /** @internal - Below the label threshold on either dimension. */ isBelowThreshold() { return this.getEffectiveWidth() < RECTANGULAR_CHART_DIMENSIONS.MIN_HEIGHT_WITH_LABELS || this.getEffectiveHeight() < RECTANGULAR_CHART_DIMENSIONS.MIN_HEIGHT_WITH_LABELS; } get ySide() { return (this.yAxes?.[0]?.position ?? this.yAxisPosition) === \"right\" ? \"right\" : \"left\"; } rangeLabelFont() { const sizePx = Number.parseFloat(getCssVariableValue(this, LINE_GRAPH_LABEL_CONFIG.fontSizeVar)); return { family: getCssVariableValue(this, LINE_GRAPH_LABEL_CONFIG.fontFamily), sizePx: Number.isFinite(sizePx) ? sizePx : 12, weight: getCssVariableValue(this, LINE_GRAPH_LABEL_CONFIG.fontWeightVar) }; } /** * Extent of the prepared data: one for x, one per y scale id. Each y axis * ranges from its own datasets, so a merged extent would label one axis * with another's values. */ dataExtents(prepared) { const x = { min: Infinity, max: -Infinity }; const y = /* @__PURE__ */ new Map(); const take = (extent, v) => { if (!Number.isFinite(v)) return; extent.min = Math.min(extent.min, v); extent.max = Math.max(extent.max, v); }; prepared.datasets.forEach((dataset) => { const id = dataset.yAxisID ?? this.primaryYAxisId; const extent = y.get(id) ?? { min: Infinity, max: -Infinity }; y.set(id, extent); dataset.data.forEach((point) => { if (typeof point === \"number\") take(extent, point); else if (point) { take(x, point.x); take(extent, point.y); } }); }); y.forEach((extent, id) => { if (!(extent.min <= extent.max)) y.delete(id); }); return { x: x.min <= x.max ? x : void 0, y }; } /** * Range the y labels describe. Below the threshold the axis runs on data * bounds, so its datasets' extent is exact and needs no chart to read from. */ yRangeBounds(extents) { let axis; let id = \"y\"; if (this.yAxes?.length) { const match = this.yAxes.findIndex((a) => (a.position ?? \"left\") === this.ySide); const index = match === -1 ? 0 : match; axis = this.yAxes[index]; id = axis.id ?? `y${index}`; } const extent = extents.get(id); const stackedScale = this.shouldStack() ? this.chart?.scales[id] : void 0; const min = axis?.min ?? stackedScale?.min ?? extent?.min; const max = axis?.max ?? stackedScale?.max ?? extent?.max; return min !== void 0 && max !== void 0 ? { min, max } : void 0; } /** First and last x label, or nothing when there is no span to label. */ xEdgeLabelTexts(prepared, extent) { if (!this.isNumericXAxis) { const labels = prepared.labels.map(String); const first = labels[0]; const last = labels[labels.length - 1]; return labels.length > 1 && first !== last ? [first, last] : []; } const min = this.xAxis?.min ?? extent?.min; const max = this.xAxis?.max ?? extent?.max; if (min === void 0 || max === void 0 || min === max) return []; const reference = this.timeDisplay === \"minutes\" ? this.computeTimeReference() : void 0; return [formatXValue(min, this.xValueMode, reference), formatXValue(max, this.xValueMode, reference)]; } /** * Recompute the range labels. A side with a slotted scale is labelled by * the scale, so it gets no text here; the y bounds are kept regardless, * since the scale's compact band is measured from them. */ refreshRangeLabels() { const cache = { y: [], x: [] }; if (this.isBelowThreshold() && (this.rangeLabelsY || this.rangeLabelsX)) { const prepared = this.prepareChartDataAndLabels(); const extents = this.dataExtents(prepared); if (this.rangeLabelsY) { cache.bounds = this.yRangeBounds(extents.y); if (cache.bounds && !this.hasSlottedScale(\"left\") && !this.hasSlottedScale(\"right\")) { const { min, max } = cache.bounds; cache.y = yRangeLabelValues(min, max).map((v) => formatRangeValue(v, min, max)); } } if (this.rangeLabelsX && !this.hasSlottedScale(\"top\") && !this.hasSlottedScale(\"bottom\")) cache.x = this.xEdgeLabelTexts(prepared, extents.x); } this.rangeLabelCache = cache; return cache; } /** * Value cursors drawn after the datasets, in the dataset's own colour, so no * annotation dependency is needed. A no-op while both markers are unset. */ createMarkersPlugin() { return { id: \"markers\", afterDatasetsDraw: (chart) => { this.lastMarkers = {}; if (!this.xMarker && !this.yMarker) return; const area = chart.chartArea; const ctx = chart.ctx; const datasetOf = (index = 0) => chart.data.datasets[index]; const yScaleOf = (ds) => chart.scales[ds?.yAxisID ?? this.primaryYAxisId]; const colorOf = (ds) => typeof ds?.borderColor === \"string\" ? ds.borderColor : getCssVariableValue(this, LINE_GRAPH_LABEL_CONFIG.fontColorVar); ctx.save(); ctx.beginPath(); ctx.rect(area.left, area.top, area.right - area.left, area.bottom - area.top); ctx.clip(); let dot; const xScale = chart.scales[\"x\"]; if (this.xMarker && xScale) { const ds = datasetOf(this.xMarker.datasetIndex); const xValue = this.isNumericXAxis ? normalizeXValue(this.xMarker.x, this.xValueMode) : typeof this.xMarker.x === \"number\" ? this.xMarker.x : (chart.data.labels ?? []).indexOf(this.xMarker.x); if (Number.isFinite(xValue) && (this.isNumericXAxis || xValue >= 0)) { const xPixel = xScale.getPixelForValue(xValue); const x = Math.round(xPixel) + .5; const hit = chart.getDatasetMeta(this.xMarker.datasetIndex ?? 0).dataset?.interpolate({ x: xPixel, y: 0 }, \"x\"); const hitY = (Array.isArray(hit) ? hit[0] : hit)?.y; const y = typeof hitY === \"number\" ? hitY : void 0; const color = colorOf(ds); ctx.strokeStyle = color; ctx.lineWidth = MARKER.lineWidth; ctx.setLineDash([]); ctx.beginPath(); ctx.moveTo(x, area.top); ctx.lineTo(x, y ?? area.top); ctx.stroke(); ctx.setLineDash([...MARKER.dash]); ctx.beginPath(); ctx.moveTo(x, y ?? area.top); ctx.lineTo(x, area.bottom); ctx.stroke(); ctx.setLineDash([]); if (y !== void 0 && xPixel >= area.left && xPixel <= area.right && y >= area.top && y <= area.bottom && (this.xMarker.showDot ?? true)) dot = { x, y, color }; this.lastMarkers.x = { x, y, dot: dot !== void 0 }; } } if (this.yMarker) { const ds = datasetOf(this.yMarker.datasetIndex); const yScale = yScaleOf(ds); if (yScale) { const y = yScale.getPixelForValue(this.yMarker.y); ctx.lineWidth = MARKER.lineWidth; ctx.strokeStyle = getCssVariableValue(this, MARKER.ringColorVar); ctx.beginPath(); ctx.moveTo(area.left, y + MARKER.valueLineWidth / 2 + .5); ctx.lineTo(area.right, y + MARKER.valueLineWidth / 2 + .5); ctx.stroke(); ctx.lineWidth = MARKER.valueLineWidth; ctx.strokeStyle = colorOf(ds); ctx.beginPath(); ctx.moveTo(area.left, y); ctx.lineTo(area.right, y); ctx.stroke(); this.lastMarkers.y = { y }; } } ctx.restore(); if (dot) { ctx.save(); ctx.beginPath(); ctx.arc(dot.x, dot.y, MARKER.dotRadius, 0, Math.PI * 2); ctx.fillStyle = dot.color; ctx.fill(); ctx.lineWidth = MARKER.dotRingWidth; ctx.strokeStyle = getCssVariableValue(this, MARKER.ringColorVar); ctx.stroke(); ctx.restore(); } } }; } /** * Paints min / 0 / max and first / last once Chart.js has drawn, inside the * gutters `getChartOptions()` reserved. The end labels sit flush with the * plot edges so no vertical padding is needed for them. */ createRangeLabelsPlugin() { return { id: \"rangeLabels\", afterDraw: (chart) => { this.lastRangeLabels = []; const { y: yTexts, x: xTexts, bounds } = this.rangeLabelCache; if (!yTexts.length && !xTexts.length) return; const area = chart.chartArea; const ctx = chart.ctx; const font = this.rangeLabelFont(); const lineHeight = rangeLabelLineHeight(font); ctx.save(); ctx.font = rangeLabelFontString(font); ctx.fillStyle = getCssVariableValue(this, LINE_GRAPH_LABEL_CONFIG.fontColorVar); const scale = chart.scales[this.primaryYAxisId]; if (yTexts.length && bounds && scale) { const onRight = this.ySide === \"right\"; const x = onRight ? area.right + 8 : area.left - 8; ctx.textAlign = onRight ? \"left\" : \"right\"; const values = yRangeLabelValues(bounds.min, bounds.max); const reversed = this.isYAxisReversed(this.ySide); for (let i = values.length - 1; i >= 0; i--) { const isMax = i === values.length - 1; const isMin = i === 0; const isEnd = isMax || isMin; const atTop = isMax !== reversed; const y = isEnd ? atTop ? area.top : area.bottom : scale.getPixelForValue(values[i]); if (!isMax && !isMin && (y - area.top < lineHeight || area.bottom - y < lineHeight)) continue; ctx.textBaseline = isEnd ? atTop ? \"top\" : \"bottom\" : \"middle\"; ctx.fillText(yTexts[i], x, y); this.lastRangeLabels.push({ axis: \"y\", text: yTexts[i], x, y }); } } if (xTexts.length === 2) { const y = area.bottom + 4; ctx.textBaseline = \"top\"; ctx.textAlign = \"left\"; ctx.fillText(xTexts[0], area.left, y); this.lastRangeLabels.push({ axis: \"x\", text: xTexts[0], x: area.left, y }); ctx.textAlign = \"right\"; ctx.fillText(xTexts[1], area.right, y); this.lastRangeLabels.push({ axis: \"x\", text: xTexts[1], x: area.right, y }); } ctx.restore(); } }; } /** * Check if a slotted scale element is actually visible (renders content). * For bar-vertical/bar-horizontal elements, checks hasBar and hasScale properties. */ hasVisibleScale(side) { return (this.slotFor(side)?.assignedElements() ?? []).some((el) => { const barEl = el; if (\"hasBar\" in barEl && \"hasScale\" in barEl) return barEl.hasBar === true || barEl.hasScale === true; return true; }); } computeRoundedCorners() { if (!this.borderRadiusPosition) return { topLeft: false, topRight: false, bottomLeft: false, bottomRight: false }; if (this.borderRadiusPosition === BorderRadiusPosition.middleChild) return { topLeft: false, topRight: false, bottomLeft: false, bottomRight: false }; if (this.borderRadiusPosition === BorderRadiusPosition.middleRoundedChild) return { topLeft: true, topRight: true, bottomLeft: true, bottomRight: true }; const hasLeft = this.hasVisibleScale(\"left\"); const hasRight = this.hasVisibleScale(\"right\"); const hasTop = this.hasVisibleScale(\"top\"); const hasBottom = this.hasVisibleScale(\"bottom\"); if (hasLeft && hasRight || hasTop && hasBottom) return { topLeft: false, topRight: false, bottomLeft: false, bottomRight: false }; const result = { topLeft: false, topRight: false, bottomLeft: false, bottomRight: false }; const isInner = this.borderRadiusPosition === BorderRadiusPosition.innerFirstChild; const isOuter = this.borderRadiusPosition === BorderRadiusPosition.outerLastChild; if (hasRight && hasBottom) { if (isInner) result.bottomRight = true; else if (isOuter) result.topLeft = true; } else if (hasRight && hasTop) { if (isInner) result.topRight = true; else if (isOuter) result.bottomLeft = true; } else if (hasLeft && hasBottom) { if (isInner) result.bottomLeft = true; else if (isOuter) result.topRight = true; } else if (hasLeft && hasTop) { if (isInner) result.topLeft = true; else if (isOuter) result.bottomRight = true; } else if (hasRight && !hasLeft) { if (isInner) { result.topLeft = true; result.bottomLeft = true; } else if (isOuter) { result.topRight = true; result.bottomRight = true; } } else if (hasLeft && !hasRight) { if (isInner) { result.topRight = true; result.bottomRight = true; } else if (isOuter) { result.topLeft = true; result.bottomLeft = true; } } else if (hasBottom && !hasTop) { if (isInner) { result.topLeft = true; result.topRight = true; } else if (isOuter) { result.bottomLeft = true; result.bottomRight = true; } } else if (hasTop && !hasBottom) { if (isInner) { result.bottomLeft = true; result.bottomRight = true; } else if (isOuter) { result.topLeft = true; result.topRight = true; } } return result; } /** * Create a Chart.js plugin that draws a border around the chart area with selective corner rounding * and clips content to that border. */ createBorderPlugin() { const corners = this.computeRoundedCorners(); const radius = this.currentBorderRadiusPx; let didApplyClip = false; const buildRoundedRectPath = (ctx, rect, cornerRadius) => { const { x, y, width, height } = rect; if (width <= 0 || height <= 0) return; const r = clamp(cornerRadius, 0, Math.max(0, Math.min(width, height) / 2)); ctx.moveTo(x + (corners.topLeft ? r : 0), y); ctx.lineTo(x + width - (corners.topRight ? r : 0), y); if (corners.topRight) ctx.arcTo(x + width, y, x + width, y + r, r); ctx.lineTo(x + width, y + height - (corners.bottomRight ? r : 0)); if (corners.bottomRight) ctx.arcTo(x + width, y + height, x + width - r, y + height, r); ctx.lineTo(x + (corners.bottomLeft ? r : 0), y + height); if (corners.bottomLeft) ctx.arcTo(x, y + height, x, y + height - r, r); ctx.lineTo(x, y + (corners.topLeft ? r : 0)); if (corners.topLeft) ctx.arcTo(x, y, x + r, y, r); }; return { id: \"chartAreaBorder\", beforeDatasetsDraw: (chart) => { const ctx = chart.ctx; const chartArea = chart.chartArea; if (!chartArea) return; const clipInset = 1; const { top, right, bottom, left } = chartArea; const rect = { x: left + clipInset, y: top + clipInset, width: right - left - 2, height: bottom - top - 2 }; const clipRadius = Math.max(0, radius - clipInset); ctx.save(); didApplyClip = true; ctx.beginPath(); buildRoundedRectPath(ctx, rect, clipRadius); ctx.closePath(); if (this.instrumentMode) { ctx.fillStyle = getCssVariableValue(this, CHART_AREA_BACKGROUND_COLOR_VAR); ctx.fill(); } ctx.clip(); }, afterDraw: (chart) => { const ctx = chart.ctx; const chartArea = chart.chartArea; if (!chartArea) return; const borderWidthPx = 1; const strokeInset = borderWidthPx / 2; const { top, right, bottom, left } = chartArea; const rect = { x: left + strokeInset, y: top + strokeInset, width: right - left - strokeInset * 2, height: bottom - top - strokeInset * 2 }; const strokeRadius = Math.max(0, radius - strokeInset); const skipTop = this.hasVisibleScale(\"top\"); const skipRight = this.hasVisibleScale(\"right\"); const skipBottom = this.hasVisibleScale(\"bottom\"); const skipLeft = this.hasVisibleScale(\"left\"); const borderColor = getCssVariableValue(this, \"--instrument-frame-tertiary-color\"); ctx.save(); ctx.strokeStyle = borderColor; ctx.lineWidth = borderWidthPx; const { x, y, width, height } = rect; const r = clamp(strokeRadius, 0, Math.max(0, Math.min(width, height) / 2)); if (!skipTop && !skipRight && !skipBottom && !skipLeft) { ctx.beginPath(); buildRoundedRectPath(ctx, rect, strokeRadius); ctx.closePath(); ctx.stroke(); } else { if (!skipTop) { ctx.beginPath(); if (!skipLeft && corners.topLeft) ctx.moveTo(x + r, y); else ctx.moveTo(x, y); if (!skipRight && corners.topRight) ctx.lineTo(x + width - r, y); else ctx.lineTo(x + width, y); ctx.stroke(); } if (!skipRight) { ctx.beginPath(); if (!skipTop && corners.topRight) ctx.moveTo(x + width, y + r); else ctx.moveTo(x + width, y); if (!skipBottom && corners.bottomRight) ctx.lineTo(x + width, y + height - r); else ctx.lineTo(x + width, y + height); ctx.stroke(); } if (!skipBottom) { ctx.beginPath(); if (!skipRight && corners.bottomRight) ctx.moveTo(x + width - r, y + height); else ctx.moveTo(x + width, y + height); if (!skipLeft && corners.bottomLeft) ctx.lineTo(x + r, y + height); else ctx.lineTo(x, y + height); ctx.stroke(); } if (!skipLeft) { ctx.beginPath(); if (!skipBottom && corners.bottomLeft) ctx.moveTo(x, y + height - r); else ctx.moveTo(x, y + height); if (!skipTop && corners.topLeft) ctx.lineTo(x, y + r); else ctx.lineTo(x, y); ctx.stroke(); } if (!skipTop && !skipLeft && corners.topLeft) { ctx.beginPath(); ctx.arc(x + r, y + r, r, Math.PI, Math.PI * 1.5); ctx.stroke(); } if (!skipTop && !skipRight && corners.topRight) { ctx.beginPath(); ctx.arc(x + width - r, y + r, r, Math.PI * 1.5, Math.PI * 2); ctx.stroke(); } if (!skipRight && !skipBottom && corners.bottomRight) { ctx.beginPath(); ctx.arc(x + width - r, y + height - r, r, 0, Math.PI * .5); ctx.stroke(); } if (!skipBottom && !skipLeft && corners.bottomLeft) { ctx.beginPath(); ctx.arc(x + r, y + height - r, r, Math.PI * .5, Math.PI); ctx.stroke(); } } ctx.restore(); if (this.showPoints) { ctx.save(); chart.data.datasets.forEach((_ds, datasetIndex) => { const meta = chart.getDatasetMeta(datasetIndex); if (!meta || meta.hidden) return; (meta.data ?? []).forEach((el) => { const point = el; if (point.skip) return; const r = point.options?.radius; if (typeof r === \"number\" && r <= 0) return; point.draw(ctx); }); }); ctx.restore(); } }, afterDatasetsDraw: (chart) => { if (didApplyClip) { chart.ctx.restore(); didApplyClip = false; } } }; } /** * Check if any external scales are slotted */ hasExternalScales() { const top = this.topScaleSlot?.assignedElements() ?? []; const bottom = this.bottomScaleSlot?.assignedElements() ?? []; const left = this.leftScaleSlot?.assignedElements() ?? []; const right = this.rightScaleSlot?.assignedElements() ?? []; return top.length > 0 || bottom.length > 0 || left.length > 0 || right.length > 0; } /** * Wait for all slotted scales to report their dimensions */ async waitForScaleDimensions() { if (!this.hasExternalScales()) { this.requestUpdate(); return; } const scaleElements = []; [ this.topScaleSlot, this.bottomScaleSlot, this.leftScaleSlot, this.rightScaleSlot ].forEach((slot) => { if (slot) { const assigned = slot.assignedElements(); scaleElements.push(...assigned); } }); const setScaleProps = (slot) => { if (!slot) return; slot.assignedElements().forEach((scale) => { scale.fixedAspectRatio = this.fixedAspectRatioScaling; scale.scaleReferenceSize = this.scaleReferenceSize; }); }; setScaleProps(this.leftScaleSlot); setScaleProps(this.rightScaleSlot); setScaleProps(this.topScaleSlot); setScaleProps(this.bottomScaleSlot); await Promise.all(scaleElements.map((el) => \"updateComplete\" in el && typeof el.updateComplete === \"object\" ? el.updateComplete : Promise.resolve())); if (this.externalScaleDimensions.size === 0 && scaleElements.length > 0) await new Promise((resolve) => setTimeout(resolve, 50)); this.syncScalesAndChart(); } /** * Synchronize scale and chart dimensions/data * This is the main coordination function */ syncScalesAndChart() { if (this.isUpdatingScales) return false; this.isUpdatingScales = true; try { const padding = this.computeChartPadding(); const effectiveWidth = this.getEffectiveWidth() - padding.left - padding.right; const effectiveHeight = this.getEffectiveHeight() - padding.top - padding.bottom; if (effectiveWidth <= 0 || effectiveHeight <= 0) { console.warn(\"[chart-line-base] Invalid effective dimensions\", { width: this.getEffectiveWidth(), height: this.getEffectiveHeight(), padding, effectiveWidth, effectiveHeight }); return false; } this.updateScaleProperties(padding); if (this.chart) this.chart.destroy(); this.createChart(); return true; } finally { this.isUpdatingScales = false; } } /** * Calculate chart padding from external scale dimensions. * * For sides without an external scale, falls back to `CHART_DIMENSIONS.CANVAS_PADDING` * (the chart's own padding to reserve room for axis tick labels). When * `hasLabelPadding=false` that fallback is 0 so the chart renders edge-to-edge, * and this same value is cascaded to slotted scales via `updateScaleProperties()` * — so the bar's main-axis padding (`paddingTop`/`paddingBottom` for vertical bars) * collapses with the chart's perpendicular padding and they stay visually aligned. */ calculatePaddingFromScales() { const defaultPadding = this.hasLabelPadding ? CHART_DIMENSIONS.CANVAS_PADDING : 0; return { top: this.externalScaleDimensions.get(\"top\") ?? defaultPadding, right: this.externalScaleDimensions.get(\"right\") ?? defaultPadding, bottom: this.externalScaleDimensions.get(\"bottom\") ?? defaultPadding, left: this.externalScaleDimensions.get(\"left\") ?? defaultPadding }; } /** * Range a slotted scale on the given side has to cover. * * A range pinned in the axis configuration is used as is: it is the source * of truth, and on the first sync there is no chart to read yet. Otherwise * the live Chart.js scale is read under the id `buildScalesConfig()` gives * it. A side with no axis of its own follows the first configured one. */ resolveAxisRange(side) { let id = side === \"x\" ? \"x\" : \"y\"; let configured; if (side === \"x\") configured = this.isNumericXAxis ? this.xAxis : void 0; else if (this.yAxes?.length) { const match = this.yAxes.findIndex((axis) => (axis.position ?? \"left\") === side); const index = match === -1 ? 0 : match; const axis = this.yAxes[index]; id = axis.id ?? `y${index}`; configured = axis; } if (configured?.min !== void 0 && configured.max !== void 0) return { min: configured.min, max: configured.max }; const scale = this.chart?.scales[id]; return { min: scale?.min ?? configured?.min ?? 0, max: scale?.max ?? configured?.max ?? 100 }; } /** * Range pushed to the top and bottom scales, or `undefined` to leave them * alone. A scale prints its values verbatim, and on a `time` axis the raw * range is epoch milliseconds. In `minutes` display the range is converted * to the minutes the chart's own labels show; `date` display has no numeric * equivalent, so the scale keeps its own range. */ resolveSlottedXRange() { const range = this.resolveAxisRange(\"x\"); if (this.xAxisType !== \"time\") return range; if (this.timeDisplay !== \"minutes\") { if (!this.warnedDateDisplayScale) { this.warnedDateDisplayScale = true; console.warn(\"[obc-chart] a slotted horizontal scale cannot label a time axis in 'date' display and keeps its own range; use timeDisplay='minutes' or a number axis.\"); } return; } const pinned = this.xAxis?.min !== void 0 && this.xAxis?.max !== void 0; const reference = this.computeTimeReference(); if (reference === void 0 || !this.chart && !pinned) return void 0; const minute = 6e4; return { min: (range.min - reference) / minute, max: (range.max - reference) / minute }; } /** * Update properties on slotted scale elements */ updateScaleProperties(padding) { const leftRange = this.resolveAxisRange(\"left\"); const rightRange = this.resolveAxisRange(\"right\"); const xRange = this.resolveSlottedXRange(); const effectiveWidth = this.getEffectiveWidth(); const effectiveHeight = this.getEffectiveHeight(); const aboveThreshold = effectiveWidth >= RECTANGULAR_CHART_DIMENSIONS.MIN_HEIGHT_WITH_LABELS && effectiveHeight >= RECTANGULAR_CHART_DIMENSIONS.MIN_HEIGHT_WITH_LABELS; const showLabels = this.hasLabelPadding && aboveThreshold; const compactY = !aboveThreshold && this.rangeLabelsY; const compactX = !aboveThreshold && this.rangeLabelsX; const compactYThickness = compactY ? this.compactLabelThickness(\"y\") : void 0; const compactXThickness = compactX ? this.compactLabelThickness(\"x\") : void 0; const mainLabelsFor = (scale, compact) => { if (compact) { if (!this.savedMainTickmarkLabels.has(scale)) this.savedMainTickmarkLabels.set(scale, scale.showMainTickmarkLabels ?? false); return true; } if (!this.savedMainTickmarkLabels.has(scale)) return void 0; const saved = this.savedMainTickmarkLabels.get(scale); this.savedMainTickmarkLabels.delete(scale); return saved; }; const bandFor = (scale, compact, thickness) => { if (compact) { if (thickness === void 0 || typeof scale.labelThickness !== \"number\") return; if (!this.savedLabelThickness.has(scale)) this.savedLabelThickness.set(scale, scale.labelThickness); return thickness; } const saved = this.savedLabelThickness.get(scale); this.savedLabelThickness.delete(scale); return saved; }; const verticalViewBoxPadding = this.fixedAspectRatioScaling ? { top: Math.round(padding.top * this.scaleReferenceSize / effectiveHeight), bottom: Math.round(padding.bottom * this.scaleReferenceSize / effectiveHeight) } : { top: padding.top, bottom: padding.bottom }; const horizontalViewBoxPadding = this.fixedAspectRatioScaling ? { left: Math.round(padding.left * this.scaleReferenceSize / effectiveWidth), right: Math.round(padding.right * this.scaleReferenceSize / effectiveWidth) } : { left: padding.left, right: padding.right }; const updates = []; /** Empty on a side whose slotted scale carries a range of its own. */ const rangeProps = (side, range) => this.ownsSlottedScaleRange(side) ? { minValue: range.min, maxValue: range.max, ...side === \"left\" || side === \"right\" ? { reverse: this.isYAxisReversed(side) } : {} } : {}; if (this.leftScaleSlot) this.leftScaleSlot.assignedElements().forEach((scale) => { const props = { ...rangeProps(\"left\", leftRange), height: effectiveHeight, paddingTop: verticalViewBoxPadding.top, paddingBottom: verticalViewBoxPadding.bottom, paddingStart: verticalViewBoxPadding.top, paddingEnd: verticalViewBoxPadding.bottom, showLabels: showLabels || compactY, fixedAspectRatio: this.fixedAspectRatioScaling, scaleReferenceSize: this.scaleReferenceSize, state: this.state, priority: this.priority, frameStyle: this.frameStyle, borderRadiusPosition: this.borderRadiusPositionExternalScales }; if (this.yStepSize !== void 0) props.primaryTickmarkInterval = this.yStepSize; const band = bandFor(scale, compactY, compactYThickness); const mainLabels = mainLabelsFor(scale, compactY); if (mainLabels !== void 0) props.showMainTickmarkLabels = mainLabels; if (band !== void 0) props.labelThickness = band; updates.push([ this.leftScaleSlot, scale, props ]); }); if (this.rightScaleSlot) this.rightScaleSlot.assignedElements().forEach((scale) => { const props = { ...rangeProps(\"right\", rightRange), height: effectiveHeight, paddingTop: verticalViewBoxPadding.top, paddingBottom: verticalViewBoxPadding.bottom, paddingStart: verticalViewBoxPadding.top, paddingEnd: verticalViewBoxPadding.bottom, showLabels: showLabels || compactY, fixedAspectRatio: this.fixedAspectRatioScaling, scaleReferenceSize: this.scaleReferenceSize, state: this.state, priority: this.priority, frameStyle: this.frameStyle, borderRadiusPosition: this.borderRadiusPositionExternalScales }; if (this.yStepSize !== void 0) props.primaryTickmarkInterval = this.yStepSize; const band = bandFor(scale, compactY, compactYThickness); const mainLabels = mainLabelsFor(scale, compactY); if (mainLabels !== void 0) props.showMainTickmarkLabels = mainLabels; if (band !== void 0) props.labelThickness = band; updates.push([ this.rightScaleSlot, scale, props ]); }); if (this.topScaleSlot) this.topScaleSlot.assignedElements().forEach((scale) => { const props = { ...xRange, width: effectiveWidth, paddingLeft: horizontalViewBoxPadding.left, paddingRight: horizontalViewBoxPadding.right, paddingStart: horizontalViewBoxPadding.left, paddingEnd: horizontalViewBoxPadding.right, showLabels: showLabels || compactX, fixedAspectRatio: this.fixedAspectRatioScaling, scaleReferenceSize: this.scaleReferenceSize, state: this.state, priority: this.priority, frameStyle: this.frameStyle, borderRadiusPosition: this.borderRadiusPositionExternalScales }; if (this.xStepSize !== void 0) props.primaryTickmarkInterval = this.xStepSize; const band = bandFor(scale, compactX, compactXThickness); const mainLabels = mainLabelsFor(scale, compactX); if (mainLabels !== void 0) props.showMainTickmarkLabels = mainLabels; if (band !== void 0) props.labelThickness = band; updates.push([ this.topScaleSlot, scale, props ]); }); if (this.bottomScaleSlot) this.bottomScaleSlot.assignedElements().forEach((scale) => { const props = { ...xRange, width: effectiveWidth, paddingLeft: horizontalViewBoxPadding.left, paddingRight: horizontalViewBoxPadding.right, paddingStart: horizontalViewBoxPadding.left, paddingEnd: horizontalViewBoxPadding.right, showLabels: showLabels || compactX, fixedAspectRatio: this.fixedAspectRatioScaling, scaleReferenceSize: this.scaleReferenceSize, state: this.state, priority: this.priority, frameStyle: this.frameStyle, borderRadiusPosition: this.borderRadiusPositionExternalScales }; if (this.xStepSize !== void 0) props.primaryTickmarkInterval = this.xStepSize; const band = bandFor(scale, compactX, compactXThickness); const mainLabels = mainLabelsFor(scale, compactX); if (mainLabels !== void 0) props.showMainTickmarkLabels = mainLabels; if (band !== void 0) props.labelThickness = band; updates.push([ this.bottomScaleSlot, scale, props ]); }); updates.forEach(([_slot, scale, props]) => { Object.assign(scale, props); }); } /** * Whether the chart's axis range is what a slotted scale on this side should * describe. A subclass that slots a scale of its own and gives it a separate * range returns false for that side, otherwise the sync below overwrites it. */ ownsSlottedScaleRange(_side) { return true; } /** * Push the current axis ranges to the slotted scales. The full * `updateScaleProperties()` cascade runs before the chart is (re)built and * so reads the previous chart's ranges; this closes that gap once the new * chart exists, and keeps auto-ranged scales in step with the data. */ syncSlottedScaleRanges() { const apply = (side, slot, range) => { if (!slot || !range || !this.ownsSlottedScaleRange(side)) return; slot.assignedElements().forEach((scale) => { scale.minValue = range.min; scale.maxValue = range.max; if (side === \"left\" || side === \"right\") scale.reverse = this.isYAxisReversed(side); }); }; apply(\"left\", this.leftScaleSlot, this.resolveAxisRange(\"left\")); apply(\"right\", this.rightScaleSlot, this.resolveAxisRange(\"right\")); const xRange = this.resolveSlottedXRange(); apply(\"top\", this.topScaleSlot, xRange); apply(\"bottom\", this.bottomScaleSlot, xRange); } hasAnyChanged(changed, props) { return props.some((prop) => changed.has(prop)); } /** * Apply fillMode rules to datasets. Must be called after the chart is created * so scales and pixel coordinates are available for gradient construction. * * NOTE: For non-threshold modes (solid, semitransparent), backgroundColor is already * set correctly in buildDataset(). This method now only handles threshold gradients * which require Chart.js scales to be available. */ applyFillModes() { if (!this.chart || !this.canvasEl || !this.canvasEl.isConnected) return; const chart = this.chart; const ctx = chart.ctx; if (!ctx) return; const fill = this.shouldApplyFill(); if (this.getFillMode() !== \"threshold\" || !fill) return; chart.data.datasets.forEach((ds, _idx) => { const dataset = ds; if (dataset.fill === false || !fill) return; const yScaleId = dataset.yAxisID ?? \"y\"; const yScale = chart.scales[yScaleId]; if (!yScale) return; const dataValues = dataset.data.map((d) => typeof d === \"number\" ? d : d.y).filter((v) => Number.isFinite(v)); if (dataValues.length === 0) return; const thresholdVal = (Math.min(...dataValues) + Math.max(...dataValues)) / 2; const thresholdPixel = yScale.getPixelForValue(thresholdVal); const range = yScale.bottom - yScale.top; let stop = (thresholdPixel - yScale.top) / range; if (!Number.isFinite(stop) || range === 0) stop = .5; else stop = clamp(stop, 0, 1); const lowRaw = LINE_GRAPH_GRID_CONFIG.thresholdLowColorVar; const highRaw = LINE_GRAPH_GRID_CONFIG.thresholdHighColorVar; const createGradient = (lowAlpha, highAlpha) => { const low = applyAlphaToColor(this, lowRaw, lowAlpha); const high = applyAlphaToColor(this, highRaw, highAlpha); const grad = ctx.createLinearGradient(0, yScale.top, 0, yScale.bottom); grad.addColorStop(0, high); grad.addColorStop(stop, high); grad.addColorStop(stop, low); grad.addColorStop(1, low); return grad; }; const fillGradient = createGradient(.35, .35); const borderGradient = createGradient(.8, .8); dataset.backgroundColor = fillGradient; dataset.borderColor = borderGradient; }); } updated(changed) { super.updated(changed); if (!this.hasAnyChanged(changed, LINE_GRAPH_WATCHED_PROP_NAMES)) return; if (this.hasAnyChanged(changed, LINE_GRAPH_DIMENSION_PROP_NAMES)) { if (this.updateComputedDimensions()) return; } const belowThreshold = this.isBelowThreshold(); const crossedThreshold = this.wasBelowThreshold !== void 0 && this.wasBelowThreshold !== belowThreshold; this.wasBelowThreshold = belowThreshold; if ((changed.has(\"hasLabelPadding\") || changed.has(\"rangeLabels\") || crossedThreshold) && this.hasExternalScales()) { this.syncScalesAndChart(); return; } if (this.hasAnyChanged(changed, LINE_GRAPH_RECREATE_PROP_NAMES)) { this.chart?.destroy(); this.createChart(); } else this.updateChart(); } async firstUpdated() { await this.waitForScaleDimensions(); if (!this.hasExternalScales()) this.createChart(); this.themeObserver = observeThemeChanges(() => { this.updateChartColors(); this.updateBorderRadius(); }); this.setupResizeObserver(); this.setupAspectRatioResizeObserver(); if (this.canvasEl) { if (!this.instrumentMode) this.borderRadiusObserver = startExternalScaleBorderRadiusObserver(this.canvasEl, this.updateBorderRadius); this.updateBorderRadius(); } } disconnectedCallback() { super.disconnectedCallback(); this.chart?.destroy(); this.themeObserver?.disconnect(); this.resizeObserver?.disconnect(); this.aspectRatioResizeObserver?.disconnect(); this.borderRadiusObserver?.disconnect(); if (this.dimensionUpdateTimer) clearTimeout(this.dimensionUpdateTimer); } /** * Crossing MIN_HEIGHT_WITH_LABELS changes the plugin set, so the chart is * rebuilt rather than updated. */ setupResizeObserver() { if (!this.canvasEl) return; this.resizeObserver = observeLabelThreshold(this.canvasEl, () => (this.canvasEl?.clientHeight ?? 0) >= RECTANGULAR_CHART_DIMENSIONS.MIN_HEIGHT_WITH_LABELS && (this.canvasEl?.clientWidth ?? 0) >= RECTANGULAR_CHART_DIMENSIONS.MIN_HEIGHT_WITH_LABELS, { rebuild: () => { this.chart?.destroy(); this.createChart(); }, update: () => this.updateChart() }); } /** * Setup resize observer for fixed aspect ratio scaling. * Observes the wrapper element and recalculates dimensions when parent size changes. */ setupAspectRatioResizeObserver() { const wrapper = this.renderRoot.querySelector(\".wrapper\"); if (!wrapper) return; this.updateComputedDimensions(); this.aspectRatioResizeObserver = new ResizeObserver(() => { if (!this.fixedAspectRatioScaling) return; this.updateComputedDimensions(); }); this.aspectRatioResizeObserver.observe(wrapper); } /** * Refresh `computedWidth` / `computedHeight`, the derived pixel size the * chart and its slotted scales are laid out from. * * In pixel mode they mirror `width` / `height`. Only in * `fixedAspectRatioScaling` mode are they derived — from the wrapper's * measured width and the aspect ratio the `width` / `height` pair defines — * and only then can this rebuild the chart. * * @returns `true` when the change was significant enough that the chart was * rebuilt here, so the caller must not rebuild it a second time. */ updateComputedDimensions() { if (!this.fixedAspectRatioScaling) { this.computedWidth = this.width; this.computedHeight = this.height; return false; } const wrapper = this.renderRoot.querySelector(\".wrapper\"); if (!wrapper) return false; const parentWidth = wrapper.clientWidth; if (parentWidth <= 0) return false; const aspectRatio = this.width / this.height; const newWidth = parentWidth; const newHeight = Math.round(parentWidth / aspectRatio); if (this.computedWidth !== newWidth || this.computedHeight !== newHeight) { this.computedWidth = newWidth; this.computedHeight = newHeight; if (this.hasExternalScales()) return this.syncScalesAndChart(); else if (this.chart) { this.chart.destroy(); this.createChart(); return true; } } return false; } /** * Get the effective width for chart rendering. * Returns computed width when fixedAspectRatioScaling is true, otherwise the width property. */ getEffectiveWidth() { return this.fixedAspectRatioScaling ? this.computedWidth : this.width; } /** * Get the effective height for chart rendering. * Returns computed height when fixedAspectRatioScaling is true, otherwise the height property. */ getEffectiveHeight() { return this.fixedAspectRatioScaling ? this.computedHeight : this.height; } /** * Get the scale factor for proportional scaling when fixedAspectRatioScaling is true. * Returns 1.0 when not in fixed aspect ratio mode. * The scale factor is based on computed width vs reference width (the width property). */ getScaleFactor() { if (!this.fixedAspectRatioScaling) return 1; return this.computedWidth / this.width; } /** * Build a complete dataset configuration with all styling properties. * Handles both new datasets (from values array) and existing datasets (normalization). * * @param data - Either numeric values array or existing dataset to normalize * @param index - Dataset index for color cycling * @param chartColors - Color palette array * @param totalCount - Total number of datasets (used for stacked divider logic) * @returns Fully configured Chart.js dataset */ buildDataset(data, index, chartColors, totalCount = 1) { const currentColor = chartColors[index % chartColors.length]; const existingDataset = Array.isArray(data) ? null : data; const values = Array.isArray(data) ? data : null; const borderColor = existingDataset?.borderColor ?? currentColor; const explicitFill = existingDataset?.fill; const fillFlag = explicitFill !== void 0 ? explicitFill !== false : this.shouldApplyFill(); const tension = this.lineMode === \"smooth\" ? this.DEFAULT_TENSION : 0; const needsDivider = this.shouldStack() && this.getFillMode() !== \"threshold\" && index < totalCount - 1; let backgroundColor = \"transparent\"; const fillMode = this.getFillMode(); if (fillFlag && fillMode) { const nextColor = chartColors[(index + 1) % chartColors.length]; if (fillMode === \"solid\") backgroundColor = String(borderColor); else if (fillMode === \"semitransparent\") backgroundColor = applyAlphaToColor(this, nextColor, .5); else if (fillMode === \"threshold\") backgroundColor = applyAlphaToColor(this, nextColor, .5); } return { ...existingDataset || {}, data: existingDataset?.data ?? values, yAxisID: existingDataset?.yAxisID ?? this.primaryYAxisId, borderColor, backgroundColor: existingDataset?.backgroundColor ?? backgroundColor, borderWidth: existingDataset?.borderWidth ?? 2, showLine: existingDataset?.showLine ?? true, tension: existingDataset?.tension ?? tension, pointRadius: existingDataset?.pointRadius ?? (this.showPoints ? this.POINT_RADIUS : 0), pointBackgroundColor: existingDataset?.pointBackgroundColor ?? \"#fff\", pointBorderColor: existingDataset?.pointBorderColor ?? borderColor, pointBorderWidth: existingDataset?.pointBorderWidth ?? 2, stepped: existingDataset?.stepped ?? this.lineMode === \"stepped\", fill: explicitFill === void 0 || explicitFill === true ? fillFlag ? \"start\" : false : explicitFill, spanGaps: existingDataset?.spanGaps ?? true, ...needsDivider && { segment: { borderColor: getCssVariableValue(this, LINE_GRAPH_GRID_CONFIG.stackedDividerColorVar), borderWidth: 1 } } }; } /** * Create threshold mode datasets: invisible baseline + main dataset with * above/below fills. Accepts plain values (category mode) or {x, y} points * (time/number mode); the baseline mirrors the input x-positions. */ createThresholdDatasets(values, chartColors) { const yValues = values.map((v) => typeof v === \"number\" ? v : v.y).filter((n) => Number.isFinite(n)); const threshold = ((yValues.length ? Math.min(...yValues) : 0) + (yValues.length ? Math.max(...yValues) : 100)) / 2; const baselineData = values.map((v) => typeof v === \"number\" ? threshold : { x: v.x, y: threshold }); const lowRaw = LINE_GRAPH_GRID_CONFIG.thresholdLowColorVar; const highRaw = LINE_GRAPH_GRID_CONFIG.thresholdHighColorVar; const highFill = applyAlphaToColor(this, highRaw, .35); const lowFill = applyAlphaToColor(this, lowRaw, .35); const baselineDataset = { label: \"threshold-baseline\", data: baselineData, yAxisID: this.primaryYAxisId, borderColor: \"transparent\", backgroundColor: \"transparent\", borderWidth: 0, pointRadius: 0, showLine: false, fill: false, spanGaps: true }; const main = this.buildDataset(values, 0, chartColors); main.fill = { target: 0, above: highFill, below: lowFill }; main.borderWidth = 2; return [baselineDataset, main]; } /** * Prepare normalized datasets for multi-series charts. * In time/number mode every point's x is normalized (epoch ms / number) * so strings, Dates and Temporal objects position correctly. */ prepareMultiSeriesDatasets() { const defaultPalette = this.priority === Priority.enhanced ? CHART_SECTOR_ENHANCED_COLORS : CHART_SECTOR_DEFAULT_COLORS; const chartColors = getChartColorsOrDefault(this, this.colors, defaultPalette); const normalized = this.datasets.map((ds) => this.normalizeDatasetX(ds)); if (this.isNumericXAxis) this.warnOnInvalidX(normalized.flatMap((ds) => (ds.data ?? []).map((pt) => pt && typeof pt === \"object\" ? pt.x : 0)), this.datasets); const totalCount = this.datasets.length; return normalized.map((ds, i) => this.buildDataset(ds, i, chartColors, totalCount)); } /** @internal - Return a copy of the dataset with normalized point x-values. */ normalizeDatasetX(ds) { if (!this.isNumericXAxis || !ds.data) return ds; const data = ds.data.map((pt) => pt && typeof pt === \"object\" && \"x\" in pt ? { ...pt, x: normalizeXValue(pt.x, this.xValueMode) } : pt); return { ...ds, data }; } /** * Prepare datasets for single-series charts. * Category mode: labels + numeric values (unchanged legacy path). * Time/number mode: normalized {x, y} points on a linear scale. * Handles both regular and threshold fill modes. */ prepareSingleSeriesDatasets() { const defaultPalette = this.priority === Priority.enhanced ? CHART_SECTOR_ENHANCED_COLORS : CHART_SECTOR_DEFAULT_COLORS; const chartColors = getChartColorsOrDefault(this, this.colors, defaultPalette); const fill = this.shouldApplyFill(); const fillMode = this.getFillMode(); if (this.isNumericXAxis) { const points = this.data.map((d) => ({ x: normalizeXValue(d.x ?? d.label ?? NaN, this.xValueMode), y: d.value })); this.warnOnInvalidX(points.map((p) => p.x), this.data); return { datasets: fill && fillMode === \"threshold\" ? this.createThresholdDatasets(points, chartColors) : [this.buildDataset(points, 0, chartColors)], labels: [] }; } const values = this.data.map((d) => d.value); const labels = this.data.map((d) => d.label ?? String(d.x ?? \"\")); return { datasets: fill && fillMode === \"threshold\" ? this.createThresholdDatasets(values, chartColors) : [this.buildDataset(values, 0, chartColors)], labels }; } /** * One padding source for the Chart.js layout and the slotted scales: two * sources painted the canvas over a scale and inset a scale inside a chart. */ computeChartPadding() { const isTooSmall = this.isBelowThreshold(); const scaleFactor = this.getScaleFactor(); const defaultPaddingScaled = !this.hasLabelPadding ? 0 : this.fixedAspectRatioScaling ? Math.round(CHART_DIMENSIONS.CANVAS_PADDING * scaleFactor) : CHART_DIMENSIONS.CANVAS_PADDING; const { y: yTexts, x: xTexts } = this.refreshRangeLabels(); const context = this.canvasEl?.getContext(\"2d\"); const gutters = (yTexts.length || xTexts.length) && context ? measureRangeLabelGutters(context, this.rangeLabelFont(), yTexts, xTexts) : { side: 0, bottom: 0 }; const scalePadding = this.calculatePaddingFromScales(); const freeSide = (side) => { if (!isTooSmall) return defaultPaddingScaled; if (side === \"bottom\") return gutters.bottom; return side === this.ySide ? gutters.side : 0; }; return { top: this.externalScaleDimensions.has(\"top\") ? scalePadding.top : freeSide(\"top\"), right: this.externalScaleDimensions.has(\"right\") ? scalePadding.right : freeSide(\"right\"), bottom: this.externalScaleDimensions.has(\"bottom\") ? scalePadding.bottom : freeSide(\"bottom\"), left: this.externalScaleDimensions.has(\"left\") ? scalePadding.left : freeSide(\"left\") }; } /** * Get Chart.js options with dynamic sizing and padding */ getChartOptions() { const effectiveWidth = this.getEffectiveWidth(); const effectiveHeight = this.getEffectiveHeight(); const isTooSmall = effectiveWidth < RECTANGULAR_CHART_DIMENSIONS.MIN_HEIGHT_WITH_LABELS || effectiveHeight < RECTANGULAR_CHART_DIMENSIONS.MIN_HEIGHT_WITH_LABELS; const padding = this.computeChartPadding(); if (this.fixedAspectRatioScaling) { this.style.setProperty(\"--chart-width\", \"100%\"); this.style.setProperty(\"--chart-height\", `${effectiveHeight}px`); } else { this.style.setProperty(\"--chart-width\", `${this.width}px`); this.style.setProperty(\"--chart-height\", `${this.height}px`); } const refTs = this.computeTimeReference(); const effectiveShowTickMarks = this.hasExternalScales() ? false : this.showTickMarks; return { responsive: true, maintainAspectRatio: false, layout: { padding }, plugins: { legend: { display: false, labels: { generateLabels: () => [] }, onClick: () => {} }, tooltip: { ...getChartTooltipOptions(this), enabled: !isTooSmall, callbacks: { title: () => \"\", label: (context) => { const value = typeof context.parsed === \"object\" && context.parsed !== null ? context.parsed.y : context.parsed; const numericValue = formatChartNumber(value, 1, false, 0); const unit = this.unit ? `${this.unit}` : \"\"; let label = context.label ?? \"\"; if (this.isNumericXAxis) { const x = typeof context.parsed === \"object\" && context.parsed !== null ? context.parsed.x : NaN; const relativeTo = this.timeDisplay === \"minutes\" ? refTs : void 0; label = formatXValue(x, this.xValueMode, relativeTo); } return `${label} ${numericValue}${unit}`; } } } }, animation: false, scales: this.buildScalesConfig(refTs, isTooSmall, effectiveShowTickMarks) }; } /** * Compute reference timestamp for time axis formatting. * Returns earliest timestamp for 'date' mode, latest for 'minutes' mode. * A pinned x range supplies the reference instead, so the axis edge stays * the reference while the data has not reached it yet. */ computeTimeReference() { if (this.xAxisType !== \"time\") return void 0; const pinned = this.timeDisplay === \"minutes\" ? this.xAxis?.max : this.xAxis?.min; if (pinned !== void 0 && Number.isFinite(pinned)) return pinned; const timestamps = []; if (this.datasets?.length) this.datasets.forEach((ds) => { if (!ds.data) return; ds.data.forEach((pt) => { if (pt && typeof pt === \"object\" && \"x\" in pt) { const ts = normalizeXValue(pt.x, XValueMode.time); if (Number.isFinite(ts)) timestamps.push(ts); } }); }); else if (this.data?.length) this.data.forEach((d) => { const ts = normalizeXValue(d.x ?? d.label ?? NaN, XValueMode.time); if (Number.isFinite(ts)) timestamps.push(ts); }); if (!timestamps.length && this.labels?.length) this.labels.forEach((l) => { if (typeof l === \"string\") { const ts = new Date(l).getTime(); if (Number.isFinite(ts)) timestamps.push(ts); } }); return timestamps.length ? this.timeDisplay === \"minutes\" ? Math.max(...timestamps) : Math.min(...timestamps) : void 0; } /** * Build Chart.js scale configuration with theme-aware styling. * Applies CSS variables for grid colors, tick colors, and label typography. * * @param minX - Reference timestamp for time-based x-axis (used for 'minutes' display) * @param isTooSmall - Whether chart is below 192px threshold (hides ticks when true) * @param showTickMarks - Whether to show tick marks (overridden to false when external scales present) * @returns Configured scales object for Chart.js options */ buildScalesConfig(minX, isTooSmall = false, showTickMarks = true) { const gridColor = getCssVariableValue(this, LINE_GRAPH_GRID_CONFIG.gridColorVar); const tickColor = getCssVariableValue(this, LINE_GRAPH_GRID_CONFIG.tickColorVar); const fontFamily = getCssVariableValue(this, LINE_GRAPH_LABEL_CONFIG.fontFamily); const fontSize = getCssVariableValue(this, LINE_GRAPH_LABEL_CONFIG.fontSizeVar); const fontWeight = getCssVariableValue(this, LINE_GRAPH_LABEL_CONFIG.fontWeightVar); const fontColor = getCssVariableValue(this, LINE_GRAPH_LABEL_CONFIG.fontColorVar); const showLabels = showTickMarks && !isTooSmall && this.hasLabelPadding; const showTicks = showTickMarks && !isTooSmall && this.hasLabelPadding; const fontConfig = { family: fontFamily, size: fontSize, weight: fontWeight }; const x = { type: this.xAxisType === \"category\" ? \"category\" : \"linear\", offset: false, grace: 0, bounds: \"data\", min: this.isNumericXAxis ? this.xAxis?.min : void 0, max: this.isNumericXAxis ? this.xAxis?.max : void 0, grid: { display: this.showGrid && this.showGridX, color: gridColor, offset: false, drawTicks: showTicks }, ticks: { display: showLabels, color: fontColor, font: fontConfig, maxRotation: 0, minRotation: 0, maxTicksLimit: this.xTicksLimit, stepSize: this.xStepSize, callback: (value) => { if (!this.isNumericXAxis) return String(value); const n = Number(value); if (!Number.isFinite(n)) return String(value); const relativeTo = this.timeDisplay === \"minutes\" ? minX : void 0; return formatXValue(n, this.xValueMode, relativeTo); } }, border: { display: showLabels, color: tickColor } }; const yAxesConfig = this.yAxes?.length ? this.yAxes.map((axis, i) => ({ id: axis.id ?? `y${i}`, position: axis.position ?? \"left\", min: axis.min, max: axis.max, reverse: axis.reverse ?? false, gridDisplay: axis.grid ?? (this.showGrid && this.showGridY) })) : [{ id: \"y\", position: this.yAxisPosition, min: void 0, max: void 0, reverse: false, gridDisplay: this.showGrid && this.showGridY }]; const scalesRecord = { x }; yAxesConfig.forEach(({ id, position, min, max, reverse, gridDisplay }) => { scalesRecord[id] = { type: \"linear\", display: true, position, reverse, stacked: this.shouldStack() && this.getFillMode() !== \"threshold\", grace: isTooSmall ? 0 : void 0, bounds: isTooSmall ? \"data\" : \"ticks\", grid: { display: gridDisplay, color: gridColor, drawTicks: showTicks }, ticks: { display: showLabels, color: fontColor, font: fontConfig, maxTicksLimit: this.yTicksLimit, stepSize: this.yStepSize }, border: { display: showLabels, color: tickColor }, min, max }; }); return scalesRecord; } /** * Prepare chart data and labels for both single and multi-series modes */ prepareChartDataAndLabels() { if (this.datasets?.length) return { datasets: this.prepareMultiSeriesDatasets(), labels: this.labels ?? [] }; return this.prepareSingleSeriesDatasets(); } createChart() { if (!this.canvasEl || !this.canvasEl.isConnected) return; const ctx = this.canvasEl.getContext(\"2d\"); if (!ctx) return; if (this.chart) { this.chart.destroy(); this.chart = void 0; } const { datasets, labels } = this.prepareChartDataAndLabels(); this.chart = new Chart(ctx, { type: \"line\", data: { labels, datasets }, options: this.getChartOptions(), plugins: [ ...this.borderRadiusPosition ? [this.createBorderPlugin()] : [], ...this.rangeLabels !== \"none\" ? [this.createRangeLabelsPlugin()] : [], this.createMarkersPlugin() ] }); requestAnimationFrame(() => this.updateLegend()); this.applyFillModes(); this.syncSlottedScaleRanges(); } updateChart() { if (!this.chart || !this.canvasEl || !this.canvasEl.isConnected) return; const { datasets, labels } = this.prepareChartDataAndLabels(); this.chart.data.labels = labels; this.chart.data.datasets = datasets; Object.assign(this.chart.options, this.getChartOptions()); this.applyFillModes(); this.chart.update(); this.syncSlottedScaleRanges(); requestAnimationFrame(() => this.updateLegend()); } /** * Update only chart colors without recalculating layout * Used by theme observer for efficient theme changes */ updateChartColors() { if (!this.chart || !this.canvasEl || !this.canvasEl.isConnected) return; this.applyFillModes(); this.chart.update(\"none\"); requestAnimationFrame(() => this.updateLegend()); } /** * Update the legend HTML content */ updateLegend() { if (!this.legend || !this.legendDiv || !this.chart) return; if (!this.chart.data.datasets || this.chart.data.datasets.length === 0) { this.legendDiv.innerHTML = \"\"; return; } try { const legendItems = this.chart.data.datasets.map((ds, i) => { const meta = this.chart.getDatasetMeta(i); if (!meta || !meta.controller) return null; const style = meta.controller.getStyle(0, false); const dataset = ds; return { fillStyle: dataset.borderColor ?? style.borderColor ?? \"\", label: dataset.label || `Series ${i + 1}`, value: \"\", unit: \"\" }; }).filter((item) => item !== null); if (legendItems.length > 0) { const legendHTML = generateLegendHTML(legendItems); this.legendDiv.innerHTML = legendHTML; } } catch (error) { console.debug(\"[chart-line-base] updateLegend: error generating legend HTML\", error); } } render() { return html` <div class=\"wrapper\"> <div class=\"canvas-and-slots-container\"> <slot name=\"top-scale\" @slotchange=${this.handleSlotChange} @scale-dimensions-changed=${this.handleScaleDimensionsChanged} ></slot> <slot name=\"bottom-scale\" @slotchange=${this.handleSlotChange} @scale-dimensions-changed=${this.handleScaleDimensionsChanged} ></slot> <slot name=\"left-scale\" @slotchange=${this.handleSlotChange} @scale-dimensions-changed=${this.handleScaleDimensionsChanged} ></slot> <slot name=\"right-scale\" @slotchange=${this.handleSlotChange} @scale-dimensions-changed=${this.handleScaleDimensionsChanged} ></slot> <canvas></canvas> </div> ${this.legend ? html`<div class=\"legend\"></div>` : \"\"} </div> `; } static { this.styles = [ unsafeCSS(chart_line_base_default), unsafeCSS(chart_common_default), unsafeCSS(chart_legend_default), unsafeCSS(chart_debug_default) ]; } }",
|
|
3352
|
+
"default": "class extends LitElement { constructor(..._args) { super(..._args); this.data = []; this.datasets = void 0; this.labels = void 0; this.colors = []; this.legend = false; this.showDebugOverlay = false; this.width = 480; this.height = 320; this.fixedAspectRatioScaling = false; this.scaleReferenceSize = 384; this.xAxisType = \"category\"; this.yAxisPosition = \"left\"; this.yAxes = void 0; this.xAxis = void 0; this.xMarker = void 0; this.yMarker = void 0; this.showGrid = false; this.showGridX = false; this.showGridY = false; this.showTickMarks = false; this.hasLabelPadding = true; this.rangeLabels = \"none\"; this.warnedDateDisplayScale = false; this.DEFAULT_TENSION = .4; this.POINT_RADIUS = 3; this.showPoints = false; this.lineMode = \"smooth\"; this.unit = \"\"; this.timeDisplay = \"date\"; this.xTicksLimit = void 0; this.xStepSize = void 0; this.yTicksLimit = void 0; this.yStepSize = void 0; this.state = InstrumentState.active; this.priority = Priority.regular; this.frameStyle = FrameStyle.regular; this.borderRadiusPosition = void 0; this.borderRadiusPositionExternalScales = void 0; this.instrumentMode = false; this.borderRadius = void 0; this.externalScaleDimensions = /* @__PURE__ */ new Map(); this.isUpdatingScales = false; this.currentBorderRadiusPx = 8; this.computedWidth = 480; this.computedHeight = 320; this.savedLabelThickness = /* @__PURE__ */ new WeakMap(); this.savedMainTickmarkLabels = /* @__PURE__ */ new WeakMap(); this.lastRangeLabels = []; this.lastMarkers = {}; this.rangeLabelCache = { y: [], x: [] }; this.updateBorderRadius = () => { if (!this.canvasEl) return; let next; if (this.instrumentMode) next = this.borderRadius ?? 8; else next = readExternalScaleBorderRadiusPx(this.canvasEl, ScaleType.regular, EXTERNAL_SCALE_BORDER_RADIUS_CSS_VAR); if (this.currentBorderRadiusPx !== next) { this.currentBorderRadiusPx = next; if (this.chart) { this.chart.destroy(); this.createChart(); } } }; this.handleSlotChange = () => { this.externalScaleDimensions.clear(); this.waitForScaleDimensions(); }; this.handleScaleDimensionsChanged = (e) => { if (this.isUpdatingScales) return; const { side, thickness } = e.detail; if (this.externalScaleDimensions.get(side) === thickness) return; this.externalScaleDimensions.set(side, thickness); if (this.dimensionUpdateTimer) clearTimeout(this.dimensionUpdateTimer); this.dimensionUpdateTimer = setTimeout(() => { this.syncScalesAndChart(); }, 16); }; } /** @internal - The y side wants range labels; an edge-to-edge chart never does. */ get rangeLabelsY() { return this.hasLabelPadding && (this.rangeLabels === \"y\" || this.rangeLabels === \"xy\"); } /** @internal - The x side wants range labels; an edge-to-edge chart never does. */ get rangeLabelsX() { return this.hasLabelPadding && (this.rangeLabels === \"x\" || this.rangeLabels === \"xy\"); } /** @internal - True when the x-axis positions points by numeric value. */ get isNumericXAxis() { return this.xAxisType === \"time\" || this.xAxisType === \"number\"; } /** * Id of the y scale a dataset lands on when it names none. Chart.js would * otherwise add a default `y` scale next to the configured ones and draw it. */ get primaryYAxisId() { return this.yAxes?.length ? this.yAxes[0].id ?? \"y0\" : \"y\"; } /** @internal - Normalization mode for the current x-axis type. */ get xValueMode() { return this.xAxisType === \"number\" ? XValueMode.number : XValueMode.time; } /** * `reverse` of the axis a side follows: the first axis positioned on that * side, else the first entry — the selection `resolveAxisRange()` makes. */ isYAxisReversed(side = \"left\") { if (!this.yAxes?.length) return false; return (this.yAxes.find((a) => (a.position ?? \"left\") === side) ?? this.yAxes[0]).reverse ?? false; } /** @internal - Warn once per data assignment about unparseable x-values. */ warnOnInvalidX(xValues, sourceRef) { const invalid = xValues.filter((x) => !Number.isFinite(x)).length; if (invalid === 0 || this.lastWarnedXSource === sourceRef) return; this.lastWarnedXSource = sourceRef; console.warn(`[obc-chart] ${invalid} x value(s) could not be parsed for xAxisType='${this.xAxisType}'; the points render as gaps.`); } /** * Should fill be applied to this chart? * Line graph returns false, area graph returns true. * Must be implemented in subclass. */ shouldApplyFill() { throw new Error(\"shouldApplyFill() must be implemented in subclass\"); } /** * Get fill mode for area rendering. * Line graph returns undefined, area graph returns 'semitransparent' | 'solid' | 'threshold'. * Must be implemented in subclass. */ getFillMode() { throw new Error(\"getFillMode() must be implemented in subclass\"); } /** * Should multi-series datasets be stacked? * Line graph returns false, area graph returns stacked property value. * Must be implemented in subclass. */ shouldStack() { throw new Error(\"shouldStack() must be implemented in subclass\"); } /** * Label band a slotted scale needs for its compact labels, in the scale's * own viewBox units. The scale prints the raw values, so those are what is * measured; the x band is one text line. */ compactLabelThickness(axis) { const context = this.canvasEl?.getContext(\"2d\"); if (!context) return void 0; const font = this.rangeLabelFont(); let visual; if (axis === \"y\") { const bounds = this.rangeLabelCache.bounds; if (!bounds) return void 0; const texts = yRangeLabelValues(bounds.min, bounds.max).map(String); visual = measureRangeLabelGutters(context, font, texts, []).side + 4; } else visual = measureRangeLabelGutters(context, font, [], [\"x\"]).bottom + 8; if (!this.fixedAspectRatioScaling) return Math.ceil(visual); const effectiveLength = axis === \"y\" ? this.getEffectiveHeight() : this.getEffectiveWidth(); return Math.ceil(visual * this.scaleReferenceSize / effectiveLength); } /** @internal - Ellipse clips applied last, in pixels by dataset index, for tests. */ get lastClips() { return (this.chart && datasetClipRecords.get(this.chart)) ?? {}; } slotFor(side) { return { left: this.leftScaleSlot, right: this.rightScaleSlot, top: this.topScaleSlot, bottom: this.bottomScaleSlot }[side]; } hasSlottedScale(side) { return (this.slotFor(side)?.assignedElements().length ?? 0) > 0; } /** @internal - Below the label threshold on either dimension. */ isBelowThreshold() { return this.getEffectiveWidth() < RECTANGULAR_CHART_DIMENSIONS.MIN_HEIGHT_WITH_LABELS || this.getEffectiveHeight() < RECTANGULAR_CHART_DIMENSIONS.MIN_HEIGHT_WITH_LABELS; } get ySide() { return (this.yAxes?.[0]?.position ?? this.yAxisPosition) === \"right\" ? \"right\" : \"left\"; } rangeLabelFont() { const sizePx = Number.parseFloat(getCssVariableValue(this, LINE_GRAPH_LABEL_CONFIG.fontSizeVar)); return { family: getCssVariableValue(this, LINE_GRAPH_LABEL_CONFIG.fontFamily), sizePx: Number.isFinite(sizePx) ? sizePx : 12, weight: getCssVariableValue(this, LINE_GRAPH_LABEL_CONFIG.fontWeightVar) }; } /** * Extent of the prepared data: one for x, one per y scale id. Each y axis * ranges from its own datasets, so a merged extent would label one axis * with another's values. */ dataExtents(prepared) { const x = { min: Infinity, max: -Infinity }; const y = /* @__PURE__ */ new Map(); const take = (extent, v) => { if (!Number.isFinite(v)) return; extent.min = Math.min(extent.min, v); extent.max = Math.max(extent.max, v); }; prepared.datasets.forEach((dataset) => { const id = dataset.yAxisID ?? this.primaryYAxisId; const extent = y.get(id) ?? { min: Infinity, max: -Infinity }; y.set(id, extent); dataset.data.forEach((point) => { if (typeof point === \"number\") take(extent, point); else if (point) { take(x, point.x); take(extent, point.y); } }); }); y.forEach((extent, id) => { if (!(extent.min <= extent.max)) y.delete(id); }); return { x: x.min <= x.max ? x : void 0, y }; } /** * Range the y labels describe. Below the threshold the axis runs on data * bounds, so its datasets' extent is exact and needs no chart to read from. */ yRangeBounds(extents) { let axis; let id = \"y\"; if (this.yAxes?.length) { const match = this.yAxes.findIndex((a) => (a.position ?? \"left\") === this.ySide); const index = match === -1 ? 0 : match; axis = this.yAxes[index]; id = axis.id ?? `y${index}`; } const extent = extents.get(id); const stackedScale = this.shouldStack() ? this.chart?.scales[id] : void 0; const min = axis?.min ?? stackedScale?.min ?? extent?.min; const max = axis?.max ?? stackedScale?.max ?? extent?.max; return min !== void 0 && max !== void 0 ? { min, max } : void 0; } /** First and last x label, or nothing when there is no span to label. */ xEdgeLabelTexts(prepared, extent) { if (!this.isNumericXAxis) { const labels = prepared.labels.map(String); const first = labels[0]; const last = labels[labels.length - 1]; return labels.length > 1 && first !== last ? [first, last] : []; } const min = this.xAxis?.min ?? extent?.min; const max = this.xAxis?.max ?? extent?.max; if (min === void 0 || max === void 0 || min === max) return []; const reference = this.timeDisplay === \"minutes\" ? this.computeTimeReference() : void 0; return [formatXValue(min, this.xValueMode, reference), formatXValue(max, this.xValueMode, reference)]; } /** * Recompute the range labels. A side with a slotted scale is labelled by * the scale, so it gets no text here; the y bounds are kept regardless, * since the scale's compact band is measured from them. */ refreshRangeLabels() { const cache = { y: [], x: [] }; if (this.isBelowThreshold() && (this.rangeLabelsY || this.rangeLabelsX)) { const prepared = this.prepareChartDataAndLabels(); const extents = this.dataExtents(prepared); if (this.rangeLabelsY) { cache.bounds = this.yRangeBounds(extents.y); if (cache.bounds && !this.hasSlottedScale(\"left\") && !this.hasSlottedScale(\"right\")) { const { min, max } = cache.bounds; cache.y = yRangeLabelValues(min, max).map((v) => formatRangeValue(v, min, max)); } } if (this.rangeLabelsX && !this.hasSlottedScale(\"top\") && !this.hasSlottedScale(\"bottom\")) cache.x = this.xEdgeLabelTexts(prepared, extents.x); } this.rangeLabelCache = cache; return cache; } /** * Value cursors drawn after the datasets, in the dataset's own colour, so no * annotation dependency is needed. A no-op while both markers are unset. */ createMarkersPlugin() { return { id: \"markers\", afterDatasetsDraw: (chart) => { this.lastMarkers = {}; if (!this.xMarker && !this.yMarker) return; const area = chart.chartArea; const ctx = chart.ctx; const datasetOf = (index = 0) => chart.data.datasets[index]; const yScaleOf = (ds) => chart.scales[ds?.yAxisID ?? this.primaryYAxisId]; const colorOf = (ds) => typeof ds?.borderColor === \"string\" ? ds.borderColor : getCssVariableValue(this, LINE_GRAPH_LABEL_CONFIG.fontColorVar); ctx.save(); ctx.beginPath(); ctx.rect(area.left, area.top, area.right - area.left, area.bottom - area.top); ctx.clip(); let dot; const xScale = chart.scales[\"x\"]; if (this.xMarker && xScale) { const ds = datasetOf(this.xMarker.datasetIndex); const xValue = this.isNumericXAxis ? normalizeXValue(this.xMarker.x, this.xValueMode) : typeof this.xMarker.x === \"number\" ? this.xMarker.x : (chart.data.labels ?? []).indexOf(this.xMarker.x); if (Number.isFinite(xValue) && (this.isNumericXAxis || xValue >= 0)) { const xPixel = xScale.getPixelForValue(xValue); const x = Math.round(xPixel) + .5; const hit = chart.getDatasetMeta(this.xMarker.datasetIndex ?? 0).dataset?.interpolate({ x: xPixel, y: 0 }, \"x\"); const hitY = (Array.isArray(hit) ? hit[0] : hit)?.y; const y = typeof hitY === \"number\" ? hitY : void 0; const color = colorOf(ds); ctx.strokeStyle = color; ctx.lineWidth = MARKER.lineWidth; ctx.setLineDash([]); ctx.beginPath(); ctx.moveTo(x, area.top); ctx.lineTo(x, y ?? area.top); ctx.stroke(); ctx.setLineDash([...MARKER.dash]); ctx.beginPath(); ctx.moveTo(x, y ?? area.top); ctx.lineTo(x, area.bottom); ctx.stroke(); ctx.setLineDash([]); if (y !== void 0 && xPixel >= area.left && xPixel <= area.right && y >= area.top && y <= area.bottom && (this.xMarker.showDot ?? true)) dot = { x, y, color }; this.lastMarkers.x = { x, y, dot: dot !== void 0 }; } } if (this.yMarker) { const ds = datasetOf(this.yMarker.datasetIndex); const yScale = yScaleOf(ds); if (yScale) { const y = yScale.getPixelForValue(this.yMarker.y); ctx.lineWidth = MARKER.lineWidth; ctx.strokeStyle = getCssVariableValue(this, MARKER.ringColorVar); ctx.beginPath(); ctx.moveTo(area.left, y + MARKER.valueLineWidth / 2 + .5); ctx.lineTo(area.right, y + MARKER.valueLineWidth / 2 + .5); ctx.stroke(); ctx.lineWidth = MARKER.valueLineWidth; ctx.strokeStyle = colorOf(ds); ctx.beginPath(); ctx.moveTo(area.left, y); ctx.lineTo(area.right, y); ctx.stroke(); this.lastMarkers.y = { y }; } } ctx.restore(); if (dot) { ctx.save(); ctx.beginPath(); ctx.arc(dot.x, dot.y, MARKER.dotRadius, 0, Math.PI * 2); ctx.fillStyle = dot.color; ctx.fill(); ctx.lineWidth = MARKER.dotRingWidth; ctx.strokeStyle = getCssVariableValue(this, MARKER.ringColorVar); ctx.stroke(); ctx.restore(); } } }; } /** * Paints min / 0 / max and first / last once Chart.js has drawn, inside the * gutters `getChartOptions()` reserved. The end labels sit flush with the * plot edges so no vertical padding is needed for them. */ createRangeLabelsPlugin() { return { id: \"rangeLabels\", afterDraw: (chart) => { this.lastRangeLabels = []; const { y: yTexts, x: xTexts, bounds } = this.rangeLabelCache; if (!yTexts.length && !xTexts.length) return; const area = chart.chartArea; const ctx = chart.ctx; const font = this.rangeLabelFont(); const lineHeight = rangeLabelLineHeight(font); ctx.save(); ctx.font = rangeLabelFontString(font); ctx.fillStyle = getCssVariableValue(this, LINE_GRAPH_LABEL_CONFIG.fontColorVar); const scale = chart.scales[this.primaryYAxisId]; if (yTexts.length && bounds && scale) { const onRight = this.ySide === \"right\"; const x = onRight ? area.right + 8 : area.left - 8; ctx.textAlign = onRight ? \"left\" : \"right\"; const values = yRangeLabelValues(bounds.min, bounds.max); const reversed = this.isYAxisReversed(this.ySide); for (let i = values.length - 1; i >= 0; i--) { const isMax = i === values.length - 1; const isMin = i === 0; const isEnd = isMax || isMin; const atTop = isMax !== reversed; const y = isEnd ? atTop ? area.top : area.bottom : scale.getPixelForValue(values[i]); if (!isMax && !isMin && (y - area.top < lineHeight || area.bottom - y < lineHeight)) continue; ctx.textBaseline = isEnd ? atTop ? \"top\" : \"bottom\" : \"middle\"; ctx.fillText(yTexts[i], x, y); this.lastRangeLabels.push({ axis: \"y\", text: yTexts[i], x, y }); } } if (xTexts.length === 2) { const y = area.bottom + 4; ctx.textBaseline = \"top\"; ctx.textAlign = \"left\"; ctx.fillText(xTexts[0], area.left, y); this.lastRangeLabels.push({ axis: \"x\", text: xTexts[0], x: area.left, y }); ctx.textAlign = \"right\"; ctx.fillText(xTexts[1], area.right, y); this.lastRangeLabels.push({ axis: \"x\", text: xTexts[1], x: area.right, y }); } ctx.restore(); } }; } /** * Check if a slotted scale element is actually visible (renders content). * For bar-vertical/bar-horizontal elements, checks hasBar and hasScale properties. */ hasVisibleScale(side) { return (this.slotFor(side)?.assignedElements() ?? []).some((el) => { const barEl = el; if (\"hasBar\" in barEl && \"hasScale\" in barEl) return barEl.hasBar === true || barEl.hasScale === true; return true; }); } computeRoundedCorners() { if (!this.borderRadiusPosition) return { topLeft: false, topRight: false, bottomLeft: false, bottomRight: false }; if (this.borderRadiusPosition === BorderRadiusPosition.middleChild) return { topLeft: false, topRight: false, bottomLeft: false, bottomRight: false }; if (this.borderRadiusPosition === BorderRadiusPosition.middleRoundedChild) return { topLeft: true, topRight: true, bottomLeft: true, bottomRight: true }; const hasLeft = this.hasVisibleScale(\"left\"); const hasRight = this.hasVisibleScale(\"right\"); const hasTop = this.hasVisibleScale(\"top\"); const hasBottom = this.hasVisibleScale(\"bottom\"); if (hasLeft && hasRight || hasTop && hasBottom) return { topLeft: false, topRight: false, bottomLeft: false, bottomRight: false }; const result = { topLeft: false, topRight: false, bottomLeft: false, bottomRight: false }; const isInner = this.borderRadiusPosition === BorderRadiusPosition.innerFirstChild; const isOuter = this.borderRadiusPosition === BorderRadiusPosition.outerLastChild; if (hasRight && hasBottom) { if (isInner) result.bottomRight = true; else if (isOuter) result.topLeft = true; } else if (hasRight && hasTop) { if (isInner) result.topRight = true; else if (isOuter) result.bottomLeft = true; } else if (hasLeft && hasBottom) { if (isInner) result.bottomLeft = true; else if (isOuter) result.topRight = true; } else if (hasLeft && hasTop) { if (isInner) result.topLeft = true; else if (isOuter) result.bottomRight = true; } else if (hasRight && !hasLeft) { if (isInner) { result.topLeft = true; result.bottomLeft = true; } else if (isOuter) { result.topRight = true; result.bottomRight = true; } } else if (hasLeft && !hasRight) { if (isInner) { result.topRight = true; result.bottomRight = true; } else if (isOuter) { result.topLeft = true; result.bottomLeft = true; } } else if (hasBottom && !hasTop) { if (isInner) { result.topLeft = true; result.topRight = true; } else if (isOuter) { result.bottomLeft = true; result.bottomRight = true; } } else if (hasTop && !hasBottom) { if (isInner) { result.bottomLeft = true; result.bottomRight = true; } else if (isOuter) { result.topLeft = true; result.topRight = true; } } return result; } /** * Create a Chart.js plugin that draws a border around the chart area with selective corner rounding * and clips content to that border. */ createBorderPlugin() { const corners = this.computeRoundedCorners(); const radius = this.currentBorderRadiusPx; let didApplyClip = false; const buildRoundedRectPath = (ctx, rect, cornerRadius) => { const { x, y, width, height } = rect; if (width <= 0 || height <= 0) return; const r = clamp(cornerRadius, 0, Math.max(0, Math.min(width, height) / 2)); ctx.moveTo(x + (corners.topLeft ? r : 0), y); ctx.lineTo(x + width - (corners.topRight ? r : 0), y); if (corners.topRight) ctx.arcTo(x + width, y, x + width, y + r, r); ctx.lineTo(x + width, y + height - (corners.bottomRight ? r : 0)); if (corners.bottomRight) ctx.arcTo(x + width, y + height, x + width - r, y + height, r); ctx.lineTo(x + (corners.bottomLeft ? r : 0), y + height); if (corners.bottomLeft) ctx.arcTo(x, y + height, x, y + height - r, r); ctx.lineTo(x, y + (corners.topLeft ? r : 0)); if (corners.topLeft) ctx.arcTo(x, y, x + r, y, r); }; return { id: \"chartAreaBorder\", beforeDatasetsDraw: (chart) => { const ctx = chart.ctx; const chartArea = chart.chartArea; if (!chartArea) return; const clipInset = 1; const { top, right, bottom, left } = chartArea; const rect = { x: left + clipInset, y: top + clipInset, width: right - left - 2, height: bottom - top - 2 }; const clipRadius = Math.max(0, radius - clipInset); ctx.save(); didApplyClip = true; ctx.beginPath(); buildRoundedRectPath(ctx, rect, clipRadius); ctx.closePath(); if (this.instrumentMode) { ctx.fillStyle = getCssVariableValue(this, CHART_AREA_BACKGROUND_COLOR_VAR); ctx.fill(); } ctx.clip(); }, afterDraw: (chart) => { const ctx = chart.ctx; const chartArea = chart.chartArea; if (!chartArea) return; const borderWidthPx = 1; const strokeInset = borderWidthPx / 2; const { top, right, bottom, left } = chartArea; const rect = { x: left + strokeInset, y: top + strokeInset, width: right - left - strokeInset * 2, height: bottom - top - strokeInset * 2 }; const strokeRadius = Math.max(0, radius - strokeInset); const skipTop = this.hasVisibleScale(\"top\"); const skipRight = this.hasVisibleScale(\"right\"); const skipBottom = this.hasVisibleScale(\"bottom\"); const skipLeft = this.hasVisibleScale(\"left\"); const borderColor = getCssVariableValue(this, \"--instrument-frame-tertiary-color\"); ctx.save(); ctx.strokeStyle = borderColor; ctx.lineWidth = borderWidthPx; const { x, y, width, height } = rect; const r = clamp(strokeRadius, 0, Math.max(0, Math.min(width, height) / 2)); if (!skipTop && !skipRight && !skipBottom && !skipLeft) { ctx.beginPath(); buildRoundedRectPath(ctx, rect, strokeRadius); ctx.closePath(); ctx.stroke(); } else { if (!skipTop) { ctx.beginPath(); if (!skipLeft && corners.topLeft) ctx.moveTo(x + r, y); else ctx.moveTo(x, y); if (!skipRight && corners.topRight) ctx.lineTo(x + width - r, y); else ctx.lineTo(x + width, y); ctx.stroke(); } if (!skipRight) { ctx.beginPath(); if (!skipTop && corners.topRight) ctx.moveTo(x + width, y + r); else ctx.moveTo(x + width, y); if (!skipBottom && corners.bottomRight) ctx.lineTo(x + width, y + height - r); else ctx.lineTo(x + width, y + height); ctx.stroke(); } if (!skipBottom) { ctx.beginPath(); if (!skipRight && corners.bottomRight) ctx.moveTo(x + width - r, y + height); else ctx.moveTo(x + width, y + height); if (!skipLeft && corners.bottomLeft) ctx.lineTo(x + r, y + height); else ctx.lineTo(x, y + height); ctx.stroke(); } if (!skipLeft) { ctx.beginPath(); if (!skipBottom && corners.bottomLeft) ctx.moveTo(x, y + height - r); else ctx.moveTo(x, y + height); if (!skipTop && corners.topLeft) ctx.lineTo(x, y + r); else ctx.lineTo(x, y); ctx.stroke(); } if (!skipTop && !skipLeft && corners.topLeft) { ctx.beginPath(); ctx.arc(x + r, y + r, r, Math.PI, Math.PI * 1.5); ctx.stroke(); } if (!skipTop && !skipRight && corners.topRight) { ctx.beginPath(); ctx.arc(x + width - r, y + r, r, Math.PI * 1.5, Math.PI * 2); ctx.stroke(); } if (!skipRight && !skipBottom && corners.bottomRight) { ctx.beginPath(); ctx.arc(x + width - r, y + height - r, r, 0, Math.PI * .5); ctx.stroke(); } if (!skipBottom && !skipLeft && corners.bottomLeft) { ctx.beginPath(); ctx.arc(x + r, y + height - r, r, Math.PI * .5, Math.PI); ctx.stroke(); } } ctx.restore(); if (this.showPoints) { ctx.save(); chart.data.datasets.forEach((_ds, datasetIndex) => { const meta = chart.getDatasetMeta(datasetIndex); if (!meta || meta.hidden) return; (meta.data ?? []).forEach((el) => { const point = el; if (point.skip) return; const r = point.options?.radius; if (typeof r === \"number\" && r <= 0) return; point.draw(ctx); }); }); ctx.restore(); } }, afterDatasetsDraw: (chart) => { if (didApplyClip) { chart.ctx.restore(); didApplyClip = false; } } }; } /** * Check if any external scales are slotted */ hasExternalScales() { const top = this.topScaleSlot?.assignedElements() ?? []; const bottom = this.bottomScaleSlot?.assignedElements() ?? []; const left = this.leftScaleSlot?.assignedElements() ?? []; const right = this.rightScaleSlot?.assignedElements() ?? []; return top.length > 0 || bottom.length > 0 || left.length > 0 || right.length > 0; } /** * Wait for all slotted scales to report their dimensions */ async waitForScaleDimensions() { if (!this.hasExternalScales()) { this.requestUpdate(); return; } const scaleElements = []; [ this.topScaleSlot, this.bottomScaleSlot, this.leftScaleSlot, this.rightScaleSlot ].forEach((slot) => { if (slot) { const assigned = slot.assignedElements(); scaleElements.push(...assigned); } }); const setScaleProps = (slot) => { if (!slot) return; slot.assignedElements().forEach((scale) => { scale.fixedAspectRatio = this.fixedAspectRatioScaling; scale.scaleReferenceSize = this.scaleReferenceSize; }); }; setScaleProps(this.leftScaleSlot); setScaleProps(this.rightScaleSlot); setScaleProps(this.topScaleSlot); setScaleProps(this.bottomScaleSlot); await Promise.all(scaleElements.map((el) => \"updateComplete\" in el && typeof el.updateComplete === \"object\" ? el.updateComplete : Promise.resolve())); if (this.externalScaleDimensions.size === 0 && scaleElements.length > 0) await new Promise((resolve) => setTimeout(resolve, 50)); this.syncScalesAndChart(); } /** * Synchronize scale and chart dimensions/data * This is the main coordination function */ syncScalesAndChart() { if (this.isUpdatingScales) return false; this.isUpdatingScales = true; try { const padding = this.computeChartPadding(); const effectiveWidth = this.getEffectiveWidth() - padding.left - padding.right; const effectiveHeight = this.getEffectiveHeight() - padding.top - padding.bottom; if (effectiveWidth <= 0 || effectiveHeight <= 0) { console.warn(\"[chart-line-base] Invalid effective dimensions\", { width: this.getEffectiveWidth(), height: this.getEffectiveHeight(), padding, effectiveWidth, effectiveHeight }); return false; } this.updateScaleProperties(padding); if (this.chart) this.chart.destroy(); this.createChart(); return true; } finally { this.isUpdatingScales = false; } } /** * Calculate chart padding from external scale dimensions. * * For sides without an external scale, falls back to `CHART_DIMENSIONS.CANVAS_PADDING` * (the chart's own padding to reserve room for axis tick labels). When * `hasLabelPadding=false` that fallback is 0 so the chart renders edge-to-edge, * and this same value is cascaded to slotted scales via `updateScaleProperties()` * — so the bar's main-axis padding (`paddingTop`/`paddingBottom` for vertical bars) * collapses with the chart's perpendicular padding and they stay visually aligned. */ calculatePaddingFromScales() { const defaultPadding = this.hasLabelPadding ? CHART_DIMENSIONS.CANVAS_PADDING : 0; return { top: this.externalScaleDimensions.get(\"top\") ?? defaultPadding, right: this.externalScaleDimensions.get(\"right\") ?? defaultPadding, bottom: this.externalScaleDimensions.get(\"bottom\") ?? defaultPadding, left: this.externalScaleDimensions.get(\"left\") ?? defaultPadding }; } /** * Range a slotted scale on the given side has to cover. * * A range pinned in the axis configuration is used as is: it is the source * of truth, and on the first sync there is no chart to read yet. Otherwise * the live Chart.js scale is read under the id `buildScalesConfig()` gives * it. A side with no axis of its own follows the first configured one. */ resolveAxisRange(side) { let id = side === \"x\" ? \"x\" : \"y\"; let configured; if (side === \"x\") configured = this.isNumericXAxis ? this.xAxis : void 0; else if (this.yAxes?.length) { const match = this.yAxes.findIndex((axis) => (axis.position ?? \"left\") === side); const index = match === -1 ? 0 : match; const axis = this.yAxes[index]; id = axis.id ?? `y${index}`; configured = axis; } if (configured?.min !== void 0 && configured.max !== void 0) return { min: configured.min, max: configured.max }; const scale = this.chart?.scales[id]; return { min: scale?.min ?? configured?.min ?? 0, max: scale?.max ?? configured?.max ?? 100 }; } /** * Range pushed to the top and bottom scales, or `undefined` to leave them * alone. A scale prints its values verbatim, and on a `time` axis the raw * range is epoch milliseconds. In `minutes` display the range is converted * to the minutes the chart's own labels show; `date` display has no numeric * equivalent, so the scale keeps its own range. */ resolveSlottedXRange() { const range = this.resolveAxisRange(\"x\"); if (this.xAxisType !== \"time\") return range; if (this.timeDisplay !== \"minutes\") { if (!this.warnedDateDisplayScale) { this.warnedDateDisplayScale = true; console.warn(\"[obc-chart] a slotted horizontal scale cannot label a time axis in 'date' display and keeps its own range; use timeDisplay='minutes' or a number axis.\"); } return; } const pinned = this.xAxis?.min !== void 0 && this.xAxis?.max !== void 0; const reference = this.computeTimeReference(); if (reference === void 0 || !this.chart && !pinned) return void 0; const minute = 6e4; return { min: (range.min - reference) / minute, max: (range.max - reference) / minute }; } /** * Update properties on slotted scale elements */ updateScaleProperties(padding) { const leftRange = this.resolveAxisRange(\"left\"); const rightRange = this.resolveAxisRange(\"right\"); const xRange = this.resolveSlottedXRange(); const effectiveWidth = this.getEffectiveWidth(); const effectiveHeight = this.getEffectiveHeight(); const aboveThreshold = effectiveWidth >= RECTANGULAR_CHART_DIMENSIONS.MIN_HEIGHT_WITH_LABELS && effectiveHeight >= RECTANGULAR_CHART_DIMENSIONS.MIN_HEIGHT_WITH_LABELS; const showLabels = this.hasLabelPadding && aboveThreshold; const compactY = !aboveThreshold && this.rangeLabelsY; const compactX = !aboveThreshold && this.rangeLabelsX; const compactYThickness = compactY ? this.compactLabelThickness(\"y\") : void 0; const compactXThickness = compactX ? this.compactLabelThickness(\"x\") : void 0; const mainLabelsFor = (scale, compact) => { if (compact) { if (!this.savedMainTickmarkLabels.has(scale)) this.savedMainTickmarkLabels.set(scale, scale.showMainTickmarkLabels ?? false); return true; } if (!this.savedMainTickmarkLabels.has(scale)) return void 0; const saved = this.savedMainTickmarkLabels.get(scale); this.savedMainTickmarkLabels.delete(scale); return saved; }; const bandFor = (scale, compact, thickness) => { if (compact) { if (thickness === void 0 || typeof scale.labelThickness !== \"number\") return; if (!this.savedLabelThickness.has(scale)) this.savedLabelThickness.set(scale, scale.labelThickness); return thickness; } const saved = this.savedLabelThickness.get(scale); this.savedLabelThickness.delete(scale); return saved; }; const verticalViewBoxPadding = this.fixedAspectRatioScaling ? { top: Math.round(padding.top * this.scaleReferenceSize / effectiveHeight), bottom: Math.round(padding.bottom * this.scaleReferenceSize / effectiveHeight) } : { top: padding.top, bottom: padding.bottom }; const horizontalViewBoxPadding = this.fixedAspectRatioScaling ? { left: Math.round(padding.left * this.scaleReferenceSize / effectiveWidth), right: Math.round(padding.right * this.scaleReferenceSize / effectiveWidth) } : { left: padding.left, right: padding.right }; const updates = []; /** Empty on a side whose slotted scale carries a range of its own. */ const rangeProps = (side, range) => this.ownsSlottedScaleRange(side) ? { minValue: range.min, maxValue: range.max, ...side === \"left\" || side === \"right\" ? { reverse: this.isYAxisReversed(side) } : {} } : {}; if (this.leftScaleSlot) this.leftScaleSlot.assignedElements().forEach((scale) => { const props = { ...rangeProps(\"left\", leftRange), height: effectiveHeight, paddingTop: verticalViewBoxPadding.top, paddingBottom: verticalViewBoxPadding.bottom, paddingStart: verticalViewBoxPadding.top, paddingEnd: verticalViewBoxPadding.bottom, showLabels: showLabels || compactY, fixedAspectRatio: this.fixedAspectRatioScaling, scaleReferenceSize: this.scaleReferenceSize, state: this.state, priority: this.priority, frameStyle: this.frameStyle, borderRadiusPosition: this.borderRadiusPositionExternalScales }; if (this.yStepSize !== void 0) props.primaryTickmarkInterval = this.yStepSize; const band = bandFor(scale, compactY, compactYThickness); const mainLabels = mainLabelsFor(scale, compactY); if (mainLabels !== void 0) props.showMainTickmarkLabels = mainLabels; if (band !== void 0) props.labelThickness = band; updates.push([ this.leftScaleSlot, scale, props ]); }); if (this.rightScaleSlot) this.rightScaleSlot.assignedElements().forEach((scale) => { const props = { ...rangeProps(\"right\", rightRange), height: effectiveHeight, paddingTop: verticalViewBoxPadding.top, paddingBottom: verticalViewBoxPadding.bottom, paddingStart: verticalViewBoxPadding.top, paddingEnd: verticalViewBoxPadding.bottom, showLabels: showLabels || compactY, fixedAspectRatio: this.fixedAspectRatioScaling, scaleReferenceSize: this.scaleReferenceSize, state: this.state, priority: this.priority, frameStyle: this.frameStyle, borderRadiusPosition: this.borderRadiusPositionExternalScales }; if (this.yStepSize !== void 0) props.primaryTickmarkInterval = this.yStepSize; const band = bandFor(scale, compactY, compactYThickness); const mainLabels = mainLabelsFor(scale, compactY); if (mainLabels !== void 0) props.showMainTickmarkLabels = mainLabels; if (band !== void 0) props.labelThickness = band; updates.push([ this.rightScaleSlot, scale, props ]); }); if (this.topScaleSlot) this.topScaleSlot.assignedElements().forEach((scale) => { const props = { ...xRange, width: effectiveWidth, paddingLeft: horizontalViewBoxPadding.left, paddingRight: horizontalViewBoxPadding.right, paddingStart: horizontalViewBoxPadding.left, paddingEnd: horizontalViewBoxPadding.right, showLabels: showLabels || compactX, fixedAspectRatio: this.fixedAspectRatioScaling, scaleReferenceSize: this.scaleReferenceSize, state: this.state, priority: this.priority, frameStyle: this.frameStyle, borderRadiusPosition: this.borderRadiusPositionExternalScales }; if (this.xStepSize !== void 0) props.primaryTickmarkInterval = this.xStepSize; const band = bandFor(scale, compactX, compactXThickness); const mainLabels = mainLabelsFor(scale, compactX); if (mainLabels !== void 0) props.showMainTickmarkLabels = mainLabels; if (band !== void 0) props.labelThickness = band; updates.push([ this.topScaleSlot, scale, props ]); }); if (this.bottomScaleSlot) this.bottomScaleSlot.assignedElements().forEach((scale) => { const props = { ...xRange, width: effectiveWidth, paddingLeft: horizontalViewBoxPadding.left, paddingRight: horizontalViewBoxPadding.right, paddingStart: horizontalViewBoxPadding.left, paddingEnd: horizontalViewBoxPadding.right, showLabels: showLabels || compactX, fixedAspectRatio: this.fixedAspectRatioScaling, scaleReferenceSize: this.scaleReferenceSize, state: this.state, priority: this.priority, frameStyle: this.frameStyle, borderRadiusPosition: this.borderRadiusPositionExternalScales }; if (this.xStepSize !== void 0) props.primaryTickmarkInterval = this.xStepSize; const band = bandFor(scale, compactX, compactXThickness); const mainLabels = mainLabelsFor(scale, compactX); if (mainLabels !== void 0) props.showMainTickmarkLabels = mainLabels; if (band !== void 0) props.labelThickness = band; updates.push([ this.bottomScaleSlot, scale, props ]); }); updates.forEach(([_slot, scale, props]) => { Object.assign(scale, props); }); } /** * Whether the chart's axis range is what a slotted scale on this side should * describe. A subclass that slots a scale of its own and gives it a separate * range returns false for that side, otherwise the sync below overwrites it. */ ownsSlottedScaleRange(_side) { return true; } /** * Push the current axis ranges to the slotted scales. The full * `updateScaleProperties()` cascade runs before the chart is (re)built and * so reads the previous chart's ranges; this closes that gap once the new * chart exists, and keeps auto-ranged scales in step with the data. */ syncSlottedScaleRanges() { const apply = (side, slot, range) => { if (!slot || !range || !this.ownsSlottedScaleRange(side)) return; slot.assignedElements().forEach((scale) => { scale.minValue = range.min; scale.maxValue = range.max; if (side === \"left\" || side === \"right\") scale.reverse = this.isYAxisReversed(side); }); }; apply(\"left\", this.leftScaleSlot, this.resolveAxisRange(\"left\")); apply(\"right\", this.rightScaleSlot, this.resolveAxisRange(\"right\")); const xRange = this.resolveSlottedXRange(); apply(\"top\", this.topScaleSlot, xRange); apply(\"bottom\", this.bottomScaleSlot, xRange); } hasAnyChanged(changed, props) { return props.some((prop) => changed.has(prop)); } /** * Apply fillMode rules to datasets. Must be called after the chart is created * so scales and pixel coordinates are available for gradient construction. * * NOTE: For non-threshold modes (solid, semitransparent), backgroundColor is already * set correctly in buildDataset(). This method now only handles threshold gradients * which require Chart.js scales to be available. * * @returns Whether it set gradients; they reach the drawn chart on its next update. */ applyFillModes() { if (!this.chart || !this.canvasEl || !this.canvasEl.isConnected) return false; const chart = this.chart; const ctx = chart.ctx; if (!ctx) return false; const fill = this.shouldApplyFill(); if (this.getFillMode() !== \"threshold\" || !fill) return false; let applied = false; chart.data.datasets.forEach((ds, _idx) => { const dataset = ds; if (dataset.fill === false || !fill) return; const yScaleId = dataset.yAxisID ?? \"y\"; const yScale = chart.scales[yScaleId]; if (!yScale) return; const dataValues = dataset.data.map((d) => typeof d === \"number\" ? d : d.y).filter((v) => Number.isFinite(v)); if (dataValues.length === 0) return; const thresholdVal = (Math.min(...dataValues) + Math.max(...dataValues)) / 2; const thresholdPixel = yScale.getPixelForValue(thresholdVal); const range = yScale.bottom - yScale.top; let stop = (thresholdPixel - yScale.top) / range; if (!Number.isFinite(stop) || range === 0) stop = .5; else stop = clamp(stop, 0, 1); const lowRaw = LINE_GRAPH_GRID_CONFIG.thresholdLowColorVar; const highRaw = LINE_GRAPH_GRID_CONFIG.thresholdHighColorVar; const createGradient = (lowAlpha, highAlpha) => { const low = applyAlphaToColor(this, lowRaw, lowAlpha); const high = applyAlphaToColor(this, highRaw, highAlpha); const grad = ctx.createLinearGradient(0, yScale.top, 0, yScale.bottom); grad.addColorStop(0, high); grad.addColorStop(stop, high); grad.addColorStop(stop, low); grad.addColorStop(1, low); return grad; }; const fillGradient = createGradient(.35, .35); const borderGradient = createGradient(.8, .8); dataset.backgroundColor = fillGradient; dataset.borderColor = borderGradient; applied = true; }); return applied; } updated(changed) { super.updated(changed); if (!this.hasAnyChanged(changed, LINE_GRAPH_WATCHED_PROP_NAMES)) return; if (this.hasAnyChanged(changed, LINE_GRAPH_DIMENSION_PROP_NAMES)) { if (this.updateComputedDimensions()) return; } const belowThreshold = this.isBelowThreshold(); const crossedThreshold = this.wasBelowThreshold !== void 0 && this.wasBelowThreshold !== belowThreshold; this.wasBelowThreshold = belowThreshold; if ((changed.has(\"hasLabelPadding\") || changed.has(\"rangeLabels\") || crossedThreshold) && this.hasExternalScales()) { this.syncScalesAndChart(); return; } if (this.hasAnyChanged(changed, LINE_GRAPH_RECREATE_PROP_NAMES)) { this.chart?.destroy(); this.createChart(); } else this.updateChart(); } async firstUpdated() { await this.waitForScaleDimensions(); if (!this.hasExternalScales()) this.createChart(); this.themeObserver = observeThemeChanges(() => { this.updateChartColors(); this.updateBorderRadius(); }); this.setupResizeObserver(); this.setupAspectRatioResizeObserver(); if (this.canvasEl) { if (!this.instrumentMode) this.borderRadiusObserver = startExternalScaleBorderRadiusObserver(this.canvasEl, this.updateBorderRadius); this.updateBorderRadius(); } } disconnectedCallback() { super.disconnectedCallback(); this.chart?.destroy(); this.themeObserver?.disconnect(); this.resizeObserver?.disconnect(); this.aspectRatioResizeObserver?.disconnect(); this.borderRadiusObserver?.disconnect(); if (this.dimensionUpdateTimer) clearTimeout(this.dimensionUpdateTimer); } /** * Crossing MIN_HEIGHT_WITH_LABELS changes the plugin set, so the chart is * rebuilt rather than updated. */ setupResizeObserver() { if (!this.canvasEl) return; this.resizeObserver = observeLabelThreshold(this.canvasEl, () => (this.canvasEl?.clientHeight ?? 0) >= RECTANGULAR_CHART_DIMENSIONS.MIN_HEIGHT_WITH_LABELS && (this.canvasEl?.clientWidth ?? 0) >= RECTANGULAR_CHART_DIMENSIONS.MIN_HEIGHT_WITH_LABELS, { rebuild: () => { this.chart?.destroy(); this.createChart(); }, update: () => this.updateChart() }); } /** * Setup resize observer for fixed aspect ratio scaling. * Observes the wrapper element and recalculates dimensions when parent size changes. */ setupAspectRatioResizeObserver() { const wrapper = this.renderRoot.querySelector(\".wrapper\"); if (!wrapper) return; this.updateComputedDimensions(); this.aspectRatioResizeObserver = new ResizeObserver(() => { if (!this.fixedAspectRatioScaling) return; this.updateComputedDimensions(); }); this.aspectRatioResizeObserver.observe(wrapper); } /** * Refresh `computedWidth` / `computedHeight`, the derived pixel size the * chart and its slotted scales are laid out from. * * In pixel mode they mirror `width` / `height`. Only in * `fixedAspectRatioScaling` mode are they derived — from the wrapper's * measured width and the aspect ratio the `width` / `height` pair defines — * and only then can this rebuild the chart. * * @returns `true` when the change was significant enough that the chart was * rebuilt here, so the caller must not rebuild it a second time. */ updateComputedDimensions() { if (!this.fixedAspectRatioScaling) { this.computedWidth = this.width; this.computedHeight = this.height; return false; } const wrapper = this.renderRoot.querySelector(\".wrapper\"); if (!wrapper) return false; const parentWidth = wrapper.clientWidth; if (parentWidth <= 0) return false; const aspectRatio = this.width / this.height; const newWidth = parentWidth; const newHeight = Math.round(parentWidth / aspectRatio); if (this.computedWidth !== newWidth || this.computedHeight !== newHeight) { this.computedWidth = newWidth; this.computedHeight = newHeight; if (this.hasExternalScales()) return this.syncScalesAndChart(); else if (this.chart) { this.chart.destroy(); this.createChart(); return true; } } return false; } /** * Get the effective width for chart rendering. * Returns computed width when fixedAspectRatioScaling is true, otherwise the width property. */ getEffectiveWidth() { return this.fixedAspectRatioScaling ? this.computedWidth : this.width; } /** * Get the effective height for chart rendering. * Returns computed height when fixedAspectRatioScaling is true, otherwise the height property. */ getEffectiveHeight() { return this.fixedAspectRatioScaling ? this.computedHeight : this.height; } /** * Get the scale factor for proportional scaling when fixedAspectRatioScaling is true. * Returns 1.0 when not in fixed aspect ratio mode. * The scale factor is based on computed width vs reference width (the width property). */ getScaleFactor() { if (!this.fixedAspectRatioScaling) return 1; return this.computedWidth / this.width; } /** * Build a complete dataset configuration with all styling properties. * Handles both new datasets (from values array) and existing datasets (normalization). * * @param data - Either numeric values array or existing dataset to normalize * @param index - Dataset index for color cycling * @param chartColors - Color palette array * @param totalCount - Total number of datasets (used for stacked divider logic) * @returns Fully configured Chart.js dataset */ buildDataset(data, index, chartColors, totalCount = 1) { const currentColor = chartColors[index % chartColors.length]; const existingDataset = Array.isArray(data) ? null : data; const values = Array.isArray(data) ? data : null; const borderColor = existingDataset?.borderColor ?? currentColor; const explicitFill = existingDataset?.fill; const fillFlag = explicitFill !== void 0 ? explicitFill !== false : this.shouldApplyFill(); const tension = this.lineMode === \"smooth\" ? this.DEFAULT_TENSION : 0; const needsDivider = this.shouldStack() && this.getFillMode() !== \"threshold\" && index < totalCount - 1; let backgroundColor = \"transparent\"; const fillMode = this.getFillMode(); if (fillFlag && fillMode) { const nextColor = chartColors[(index + 1) % chartColors.length]; if (fillMode === \"solid\") backgroundColor = String(borderColor); else if (fillMode === \"semitransparent\") backgroundColor = applyAlphaToColor(this, nextColor, .5); else if (fillMode === \"threshold\") backgroundColor = applyAlphaToColor(this, nextColor, .5); } return { ...existingDataset || {}, data: existingDataset?.data ?? values, yAxisID: existingDataset?.yAxisID ?? this.primaryYAxisId, borderColor, backgroundColor: existingDataset?.backgroundColor ?? backgroundColor, borderWidth: existingDataset?.borderWidth ?? 2, showLine: existingDataset?.showLine ?? true, tension: existingDataset?.tension ?? tension, pointRadius: existingDataset?.pointRadius ?? (this.showPoints ? this.POINT_RADIUS : 0), pointBackgroundColor: existingDataset?.pointBackgroundColor ?? \"#fff\", pointBorderColor: existingDataset?.pointBorderColor ?? borderColor, pointBorderWidth: existingDataset?.pointBorderWidth ?? 2, stepped: existingDataset?.stepped ?? this.lineMode === \"stepped\", fill: explicitFill === void 0 || explicitFill === true ? fillFlag ? \"start\" : false : explicitFill, spanGaps: existingDataset?.spanGaps ?? true, ...needsDivider && { segment: { borderColor: getCssVariableValue(this, LINE_GRAPH_GRID_CONFIG.stackedDividerColorVar), borderWidth: 1 } } }; } /** * Create threshold mode datasets: invisible baseline + main dataset with * above/below fills. Accepts plain values (category mode) or {x, y} points * (time/number mode); the baseline mirrors the input x-positions. */ createThresholdDatasets(values, chartColors) { const yValues = values.map((v) => typeof v === \"number\" ? v : v.y).filter((n) => Number.isFinite(n)); const threshold = ((yValues.length ? Math.min(...yValues) : 0) + (yValues.length ? Math.max(...yValues) : 100)) / 2; const baselineData = values.map((v) => typeof v === \"number\" ? threshold : { x: v.x, y: threshold }); const lowRaw = LINE_GRAPH_GRID_CONFIG.thresholdLowColorVar; const highRaw = LINE_GRAPH_GRID_CONFIG.thresholdHighColorVar; const highFill = applyAlphaToColor(this, highRaw, .35); const lowFill = applyAlphaToColor(this, lowRaw, .35); const baselineDataset = { label: \"threshold-baseline\", data: baselineData, yAxisID: this.primaryYAxisId, borderColor: \"transparent\", backgroundColor: \"transparent\", borderWidth: 0, pointRadius: 0, showLine: false, fill: false, spanGaps: true }; const main = this.buildDataset(values, 0, chartColors); main.fill = { target: 0, above: highFill, below: lowFill }; main.borderWidth = 2; return [baselineDataset, main]; } /** * Prepare normalized datasets for multi-series charts. * In time/number mode every point's x is normalized (epoch ms / number) * so strings, Dates and Temporal objects position correctly. */ prepareMultiSeriesDatasets() { const defaultPalette = this.priority === Priority.enhanced ? CHART_SECTOR_ENHANCED_COLORS : CHART_SECTOR_DEFAULT_COLORS; const chartColors = getChartColorsOrDefault(this, this.colors, defaultPalette); const normalized = this.datasets.map((ds) => this.normalizeDatasetX(ds)); if (this.isNumericXAxis) this.warnOnInvalidX(normalized.flatMap((ds) => (ds.data ?? []).map((pt) => pt && typeof pt === \"object\" ? pt.x : 0)), this.datasets); const totalCount = this.datasets.length; return normalized.map((ds, i) => this.buildDataset(ds, i, chartColors, totalCount)); } /** @internal - Return a copy of the dataset with normalized point x-values. */ normalizeDatasetX(ds) { if (!this.isNumericXAxis || !ds.data) return ds; const data = ds.data.map((pt) => pt && typeof pt === \"object\" && \"x\" in pt ? { ...pt, x: normalizeXValue(pt.x, this.xValueMode) } : pt); return { ...ds, data }; } /** * Prepare datasets for single-series charts. * Category mode: labels + numeric values (unchanged legacy path). * Time/number mode: normalized {x, y} points on a linear scale. * Handles both regular and threshold fill modes. */ prepareSingleSeriesDatasets() { const defaultPalette = this.priority === Priority.enhanced ? CHART_SECTOR_ENHANCED_COLORS : CHART_SECTOR_DEFAULT_COLORS; const chartColors = getChartColorsOrDefault(this, this.colors, defaultPalette); const fill = this.shouldApplyFill(); const fillMode = this.getFillMode(); if (this.isNumericXAxis) { const points = this.data.map((d) => ({ x: normalizeXValue(d.x ?? d.label ?? NaN, this.xValueMode), y: d.value })); this.warnOnInvalidX(points.map((p) => p.x), this.data); return { datasets: fill && fillMode === \"threshold\" ? this.createThresholdDatasets(points, chartColors) : [this.buildDataset(points, 0, chartColors)], labels: [] }; } const values = this.data.map((d) => d.value); const labels = this.data.map((d) => d.label ?? String(d.x ?? \"\")); return { datasets: fill && fillMode === \"threshold\" ? this.createThresholdDatasets(values, chartColors) : [this.buildDataset(values, 0, chartColors)], labels }; } /** * One padding source for the Chart.js layout and the slotted scales: two * sources painted the canvas over a scale and inset a scale inside a chart. */ computeChartPadding() { const isTooSmall = this.isBelowThreshold(); const scaleFactor = this.getScaleFactor(); const defaultPaddingScaled = !this.hasLabelPadding ? 0 : this.fixedAspectRatioScaling ? Math.round(CHART_DIMENSIONS.CANVAS_PADDING * scaleFactor) : CHART_DIMENSIONS.CANVAS_PADDING; const { y: yTexts, x: xTexts } = this.refreshRangeLabels(); const context = this.canvasEl?.getContext(\"2d\"); const gutters = (yTexts.length || xTexts.length) && context ? measureRangeLabelGutters(context, this.rangeLabelFont(), yTexts, xTexts) : { side: 0, bottom: 0 }; const scalePadding = this.calculatePaddingFromScales(); const freeSide = (side) => { if (!isTooSmall) return defaultPaddingScaled; if (side === \"bottom\") return gutters.bottom; return side === this.ySide ? gutters.side : 0; }; return { top: this.externalScaleDimensions.has(\"top\") ? scalePadding.top : freeSide(\"top\"), right: this.externalScaleDimensions.has(\"right\") ? scalePadding.right : freeSide(\"right\"), bottom: this.externalScaleDimensions.has(\"bottom\") ? scalePadding.bottom : freeSide(\"bottom\"), left: this.externalScaleDimensions.has(\"left\") ? scalePadding.left : freeSide(\"left\") }; } /** * Get Chart.js options with dynamic sizing and padding */ getChartOptions() { const effectiveWidth = this.getEffectiveWidth(); const effectiveHeight = this.getEffectiveHeight(); const isTooSmall = effectiveWidth < RECTANGULAR_CHART_DIMENSIONS.MIN_HEIGHT_WITH_LABELS || effectiveHeight < RECTANGULAR_CHART_DIMENSIONS.MIN_HEIGHT_WITH_LABELS; const padding = this.computeChartPadding(); if (this.fixedAspectRatioScaling) { this.style.setProperty(\"--chart-width\", \"100%\"); this.style.setProperty(\"--chart-height\", `${effectiveHeight}px`); } else { this.style.setProperty(\"--chart-width\", `${this.width}px`); this.style.setProperty(\"--chart-height\", `${this.height}px`); } const refTs = this.computeTimeReference(); const effectiveShowTickMarks = this.hasExternalScales() ? false : this.showTickMarks; return { responsive: true, maintainAspectRatio: false, layout: { padding }, plugins: { legend: { display: false, labels: { generateLabels: () => [] }, onClick: () => {} }, tooltip: { ...getChartTooltipOptions(this), enabled: !isTooSmall, callbacks: { title: () => \"\", label: (context) => { const value = typeof context.parsed === \"object\" && context.parsed !== null ? context.parsed.y : context.parsed; const numericValue = formatChartNumber(value, 1, false, 0); const unit = this.unit ? `${this.unit}` : \"\"; let label = context.label ?? \"\"; if (this.isNumericXAxis) { const x = typeof context.parsed === \"object\" && context.parsed !== null ? context.parsed.x : NaN; const relativeTo = this.timeDisplay === \"minutes\" ? refTs : void 0; label = formatXValue(x, this.xValueMode, relativeTo); } return `${label} ${numericValue}${unit}`; } } } }, animation: false, scales: this.buildScalesConfig(refTs, isTooSmall, effectiveShowTickMarks) }; } /** * Compute reference timestamp for time axis formatting. * Returns earliest timestamp for 'date' mode, latest for 'minutes' mode. * A pinned x range supplies the reference instead, so the axis edge stays * the reference while the data has not reached it yet. */ computeTimeReference() { if (this.xAxisType !== \"time\") return void 0; const pinned = this.timeDisplay === \"minutes\" ? this.xAxis?.max : this.xAxis?.min; if (pinned !== void 0 && Number.isFinite(pinned)) return pinned; const timestamps = []; if (this.datasets?.length) this.datasets.forEach((ds) => { if (!ds.data) return; ds.data.forEach((pt) => { if (pt && typeof pt === \"object\" && \"x\" in pt) { const ts = normalizeXValue(pt.x, XValueMode.time); if (Number.isFinite(ts)) timestamps.push(ts); } }); }); else if (this.data?.length) this.data.forEach((d) => { const ts = normalizeXValue(d.x ?? d.label ?? NaN, XValueMode.time); if (Number.isFinite(ts)) timestamps.push(ts); }); if (!timestamps.length && this.labels?.length) this.labels.forEach((l) => { if (typeof l === \"string\") { const ts = new Date(l).getTime(); if (Number.isFinite(ts)) timestamps.push(ts); } }); return timestamps.length ? this.timeDisplay === \"minutes\" ? Math.max(...timestamps) : Math.min(...timestamps) : void 0; } /** * Build Chart.js scale configuration with theme-aware styling. * Applies CSS variables for grid colors, tick colors, and label typography. * * @param minX - Reference timestamp for time-based x-axis (used for 'minutes' display) * @param isTooSmall - Whether chart is below 192px threshold (hides ticks when true) * @param showTickMarks - Whether to show tick marks (overridden to false when external scales present) * @returns Configured scales object for Chart.js options */ buildScalesConfig(minX, isTooSmall = false, showTickMarks = true) { const gridColor = getCssVariableValue(this, LINE_GRAPH_GRID_CONFIG.gridColorVar); const tickColor = getCssVariableValue(this, LINE_GRAPH_GRID_CONFIG.tickColorVar); const fontFamily = getCssVariableValue(this, LINE_GRAPH_LABEL_CONFIG.fontFamily); const fontSize = getCssVariableValue(this, LINE_GRAPH_LABEL_CONFIG.fontSizeVar); const fontWeight = getCssVariableValue(this, LINE_GRAPH_LABEL_CONFIG.fontWeightVar); const fontColor = getCssVariableValue(this, LINE_GRAPH_LABEL_CONFIG.fontColorVar); const showLabels = showTickMarks && !isTooSmall && this.hasLabelPadding; const showTicks = showTickMarks && !isTooSmall && this.hasLabelPadding; const fontConfig = { family: fontFamily, size: fontSize, weight: fontWeight }; const x = { type: this.xAxisType === \"category\" ? \"category\" : \"linear\", offset: false, grace: 0, bounds: \"data\", min: this.isNumericXAxis ? this.xAxis?.min : void 0, max: this.isNumericXAxis ? this.xAxis?.max : void 0, grid: { display: this.showGrid && this.showGridX, color: gridColor, offset: false, drawTicks: showTicks }, ticks: { display: showLabels, color: fontColor, font: fontConfig, maxRotation: 0, minRotation: 0, maxTicksLimit: this.xTicksLimit, stepSize: this.xStepSize, callback: (value) => { if (!this.isNumericXAxis) return String(value); const n = Number(value); if (!Number.isFinite(n)) return String(value); const relativeTo = this.timeDisplay === \"minutes\" ? minX : void 0; return formatXValue(n, this.xValueMode, relativeTo); } }, border: { display: showLabels, color: tickColor } }; const yAxesConfig = this.yAxes?.length ? this.yAxes.map((axis, i) => ({ id: axis.id ?? `y${i}`, position: axis.position ?? \"left\", min: axis.min, max: axis.max, reverse: axis.reverse ?? false, gridDisplay: axis.grid ?? (this.showGrid && this.showGridY) })) : [{ id: \"y\", position: this.yAxisPosition, min: void 0, max: void 0, reverse: false, gridDisplay: this.showGrid && this.showGridY }]; const scalesRecord = { x }; yAxesConfig.forEach(({ id, position, min, max, reverse, gridDisplay }) => { scalesRecord[id] = { type: \"linear\", display: true, position, reverse, stacked: this.shouldStack() && this.getFillMode() !== \"threshold\", grace: isTooSmall ? 0 : void 0, bounds: isTooSmall ? \"data\" : \"ticks\", grid: { display: gridDisplay, color: gridColor, drawTicks: showTicks }, ticks: { display: showLabels, color: fontColor, font: fontConfig, maxTicksLimit: this.yTicksLimit, stepSize: this.yStepSize }, border: { display: showLabels, color: tickColor }, min, max }; }); return scalesRecord; } /** * Prepare chart data and labels for both single and multi-series modes */ prepareChartDataAndLabels() { if (this.datasets?.length) return { datasets: this.prepareMultiSeriesDatasets(), labels: this.labels ?? [] }; return this.prepareSingleSeriesDatasets(); } createChart() { if (!this.canvasEl || !this.canvasEl.isConnected) return; const ctx = this.canvasEl.getContext(\"2d\"); if (!ctx) return; if (this.chart) { this.chart.destroy(); this.chart = void 0; } const { datasets, labels } = this.prepareChartDataAndLabels(); this.chart = new Chart(ctx, { type: \"line\", data: { labels, datasets }, options: this.getChartOptions(), plugins: [ ...this.borderRadiusPosition ? [this.createBorderPlugin()] : [], ...this.rangeLabels !== \"none\" ? [this.createRangeLabelsPlugin()] : [], this.createMarkersPlugin() ] }); requestAnimationFrame(() => this.updateLegend()); if (this.applyFillModes()) this.chart.update(\"none\"); this.syncSlottedScaleRanges(); } updateChart() { if (!this.chart || !this.canvasEl || !this.canvasEl.isConnected) return; const { datasets, labels } = this.prepareChartDataAndLabels(); this.chart.data.labels = labels; this.chart.data.datasets = datasets; Object.assign(this.chart.options, this.getChartOptions()); this.applyFillModes(); this.chart.update(); this.syncSlottedScaleRanges(); requestAnimationFrame(() => this.updateLegend()); } /** * Update only chart colors without recalculating layout * Used by theme observer for efficient theme changes */ updateChartColors() { if (!this.chart || !this.canvasEl || !this.canvasEl.isConnected) return; this.applyFillModes(); this.chart.update(\"none\"); requestAnimationFrame(() => this.updateLegend()); } /** * Update the legend HTML content */ updateLegend() { if (!this.legend || !this.legendDiv || !this.chart) return; if (!this.chart.data.datasets || this.chart.data.datasets.length === 0) { this.legendDiv.innerHTML = \"\"; return; } try { const legendItems = this.chart.data.datasets.map((ds, i) => { const meta = this.chart.getDatasetMeta(i); if (!meta || !meta.controller) return null; const style = meta.controller.getStyle(0, false); const dataset = ds; return { fillStyle: dataset.borderColor ?? style.borderColor ?? \"\", label: dataset.label || `Series ${i + 1}`, value: \"\", unit: \"\" }; }).filter((item) => item !== null); if (legendItems.length > 0) { const legendHTML = generateLegendHTML(legendItems); this.legendDiv.innerHTML = legendHTML; } } catch (error) { console.debug(\"[chart-line-base] updateLegend: error generating legend HTML\", error); } } render() { return html` <div class=\"wrapper\"> <div class=\"canvas-and-slots-container\"> <slot name=\"top-scale\" @slotchange=${this.handleSlotChange} @scale-dimensions-changed=${this.handleScaleDimensionsChanged} ></slot> <slot name=\"bottom-scale\" @slotchange=${this.handleSlotChange} @scale-dimensions-changed=${this.handleScaleDimensionsChanged} ></slot> <slot name=\"left-scale\" @slotchange=${this.handleSlotChange} @scale-dimensions-changed=${this.handleScaleDimensionsChanged} ></slot> <slot name=\"right-scale\" @slotchange=${this.handleSlotChange} @scale-dimensions-changed=${this.handleScaleDimensionsChanged} ></slot> <canvas></canvas> </div> ${this.legend ? html`<div class=\"legend\"></div>` : \"\"} </div> `; } static { this.styles = [ unsafeCSS(chart_line_base_default), unsafeCSS(chart_common_default), unsafeCSS(chart_legend_default), unsafeCSS(chart_debug_default) ]; } }",
|
|
3353
3353
|
"description": "Abstract base class for line and area chart components built on Chart.js.\n\n## Concrete implementations\n- `<obc-line-graph>`: Line chart (non-filled)\n- `<obc-area-graph>`: Area chart with fill modes (semitransparent, solid, threshold)\n\n## Features\n- **Single or multi-series**: Use `data` for simple single-series or `datasets` for multi-series charts\n- **Category, time and number axes**: `category` (labels, evenly spaced), `time` (epoch ms,\n ISO strings, `Date` or Temporal objects — positioned proportionally, so uneven intervals\n render unevenly) and `number` (plain numeric x-values on a linear scale)\n- **Line styles**: Choose `smooth` (curved), `straight`, or `stepped` line rendering\n- **Fill modes**: Area fills with `semitransparent`, `solid`, or `threshold` (red/blue above/below midpoint)\n- **Stacked charts**: Enable `stacked` for multi-series datasets to stack values on y-axis\n- **Flexible axes**: Single y-axis via `yAxisPosition` or multi-axis via `yAxes` for complex charts\n- **Theme-aware**: Automatically updates colors on theme changes using CSS variables\n- **Responsive sizing**: Fixed height with 1.5:1 aspect ratio (e.g., 320px height → 480px width)\n- **Grid & ticks**: Toggle grid lines (`showGrid`, `showGridX`, `showGridY`) and tick marks (`showTickMarks`)\n- **Legend support**: Optional HTML legend showing series labels with `legend` property\n- **External axis support**: via slots\n- **Color priority**: Set `priority` to `Priority.enhanced` to use the blue/enhanced\n color palette instead of the default gray/regular palette (default: `Priority.regular`)\n\n## Size Behavior\n- Above 192px: Shows labels, tick marks, and grid lines with standard padding\n- Below 192px: Hides labels/ticks and uses edge-to-edge rendering for compact display\n\n## Examples\n\nBasic single-series with category axis:\n```html\n<obc-line-graph></obc-line-graph>\n<script>\n const chart = document.querySelector('obc-line-graph');\n chart.data = [\n {label: 'Jan', value: 10},\n {label: 'Feb', value: 14},\n {label: 'Mar', value: 12}\n ];\n chart.unit = 'kW';\n chart.height = 256;\n<\\/script>\n```\n\nMulti-series with time axis and legend:\n```html\n<obc-line-graph></obc-line-graph>\n<script>\n const chart = document.querySelector('obc-line-graph');\n chart.xAxisType = 'time';\n chart.timeDisplay = 'date';\n chart.legend = true;\n chart.datasets = [\n {label: 'Temperature', data: [{x: '2025-01-01', y: 20}, {x: '2025-01-02', y: 22}]},\n {label: 'Humidity', data: [{x: '2025-01-01', y: 65}, {x: '2025-01-02', y: 68}]}\n ];\n<\\/script>\n```\n\nSingle-series with time axis (uneven intervals position proportionally;\nx accepts epoch ms, ISO strings, Date or Temporal objects):\n```html\n<obc-line-graph></obc-line-graph>\n<script>\n const chart = document.querySelector('obc-line-graph');\n chart.xAxisType = 'time';\n chart.timeDisplay = 'minutes';\n chart.data = [\n {x: '2026-07-06T10:00:00Z', value: 10},\n {x: new Date('2026-07-06T10:03:00Z'), value: 14},\n {x: Temporal.Instant.from('2026-07-06T10:15:00Z'), value: 12}\n ];\n<\\/script>\n```\n\nSingle-series with numeric x-axis:\n```html\n<obc-line-graph></obc-line-graph>\n<script>\n const chart = document.querySelector('obc-line-graph');\n chart.xAxisType = 'number';\n chart.data = [\n {x: 0, value: 2},\n {x: 2.5, value: 3},\n {x: 10, value: 6}\n ];\n<\\/script>\n```\n\nStacked area chart with solid fill:\n```html\n<obc-line-graph></obc-line-graph>\n<script>\n const chart = document.querySelector('obc-line-graph');\n chart.datasets = [\n {label: 'Series A', data: [2, 3, 4, 3, 5]},\n {label: 'Series B', data: [1, 2, 3, 2, 4]},\n {label: 'Series C', data: [3, 2, 1, 2, 3]}\n ];\n chart.fillMode = 'solid';\n chart.stacked = true;\n chart.legend = true;\n<\\/script>\n```\n\nThreshold fill (single-series only):\n```html\n<obc-line-graph></obc-line-graph>\n<script>\n const chart = document.querySelector('obc-line-graph');\n chart.data = [{label: '1', value: 20}, {label: '2', value: 45}, {label: '3', value: 35}];\n chart.fillMode = 'threshold';\n<\\/script>\n```\n\nMulti-axis chart with right-side y-axis:\n```html\n<obc-line-graph></obc-line-graph>\n<script>\n const chart = document.querySelector('obc-line-graph');\n chart.yAxes = [\n {id: 'y-temp', position: 'left', min: 0, max: 100},\n {id: 'y-pressure', position: 'right', min: 0, max: 10}\n ];\n chart.datasets = [\n {label: 'Temperature', data: [20, 25, 30], yAxisID: 'y-temp'},\n {label: 'Pressure', data: [2, 3, 2.5], yAxisID: 'y-pressure'}\n ];\n<\\/script>\n```"
|
|
3354
3354
|
}
|
|
3355
3355
|
],
|
|
@@ -10189,7 +10189,7 @@
|
|
|
10189
10189
|
{
|
|
10190
10190
|
"kind": "variable",
|
|
10191
10191
|
"name": "ObcWatchFlat",
|
|
10192
|
-
"default": "class ObcWatchFlat extends LitElement { constructor(..._args) { super(..._args); this.width = 352; this.height = 72; this.padding = 0; this.rotation = 0; this.tickmarkSpacing = 0; this.tickmarks = []; this.labels = []; this.FOVIndicator = []; this.trackHeight = 2 / 3 * this.height; this.ticksHeight = this.height - this.trackHeight; this.borderRadius = 8; this.bottomBar = false; this.barAreas = []; this.needles = []; this.rotPosition = LinearRotPosition.track; this.rotStartX = 0; this.rotEndX = 0; this.rotDotSpacing = 0; this.rotPriority = Priority.regular; this.rotPortStarboard = false; this.rotAtZeroDeadband = ROT_ZERO_DEADBAND_PX; this.rotDotAnimationFactor = 18; this._legacyRotationsPerMinute = 0; } /** * @deprecated Use `rateOfTurnDegreesPerMinute` (and optionally * `rotDotAnimationFactor`) instead. Takes effect only when * `rateOfTurnDegreesPerMinute` is `undefined`. */ set rotationsPerMinute(value) { this._legacyRotationsPerMinute = value; } get rotationsPerMinute() { return this._legacyRotationsPerMinute; } get _effectiveRpm() { if (this.rateOfTurnDegreesPerMinute != null) return this.rateOfTurnDegreesPerMinute / 360 * this.rotDotAnimationFactor; return this._legacyRotationsPerMinute; } get totalHeight() { return this.bottomBar ? this.height + this.ticksHeight : this.height; } renderClipPath(offsetY = 0) { return svg` <clipPath id=\"frameClipPath${offsetY === 0 ? \"\" : \"Tickmarks\"}\"> <rect x=\"${-this.width / 2}\" y=\"${-this.totalHeight / 2 + offsetY}\" width=\"${this.width}\" height=\"${this.totalHeight}\" rx=\"${this.borderRadius}\" /> </clipPath> `; } renderLabelMask() { return svg` <mask id=\"labelMask\"> <rect x=\"${-this.width / 2}\" y=\"${-70}\" width=\"${this.width}\" height=\"${32}\" /> <linearGradient id=\"fadeGradient\" gradientUnits=\"userSpaceOnUse\" x1=\"${-this.width / 2}\" y1=\"0\" x2=\"${this.width / 2}\" y2=\"0\"> <stop offset=\"0%\" style=\"stop-color:black; stop-opacity:1;\" /> <stop offset=\"10%\" style=\"stop-color:white; stop-opacity:1;\" /> <stop offset=\"50%\" style=\"stop-color:white; stop-opacity:1;\" /> <stop offset=\"90%\" style=\"stop-color:white; stop-opacity:1;\" /> <stop offset=\"100%\" style=\"stop-color:black; stop-opacity:1;\" /> </linearGradient> <rect x=\"${-this.width / 2}\" y=\"${-70}\" width=\"${this.width}\" height=\"${32}\" fill=\"url(#fadeGradient)\" /> </mask> `; } renderLabels(scale) { const labels = []; for (const l of this.labels) labels.push(svg`<g transform=\"translate(${-this.rotation * this.tickmarkSpacing}, ${-6 / scale})\"> <text x=${l.x} y=${l.y} class=\"label\" fill=${\"var(--instrument-tick-mark-secondary-color)\"}> ${l.text} </text> </g>`); return labels; } watchFace() { const strokeWidth = 1; const th = this.totalHeight; const topTicksY = -th / 2; return svg` ${this.renderClipPath()} ${this.renderClipPath(-40)} <g clip-path=\"url(#frameClipPath)\"> ${rect(\"frame-track\", { width: this.width, height: this.trackHeight, y: th / 2 - this.trackHeight - (this.bottomBar ? this.ticksHeight : 0), strokeWidth, strokeColor: \"var(--instrument-frame-secondary-color)\", strokePosition: \"inside\", fillColor: \"var(--instrument-frame-secondary-color)\", borderRadius: 0 })} ${rect(\"frame-ticks\", { width: this.width, height: this.ticksHeight, y: topTicksY, strokeWidth, strokeColor: \"var(--instrument-frame-primary-color)\", strokePosition: \"inside\", fillColor: \"var(--instrument-frame-primary-color)\", borderRadius: 0 })} ${this.bottomBar ? rect(\"frame-bottom-bar\", { width: this.width, height: this.ticksHeight, y: th / 2 - this.ticksHeight, strokeWidth, strokeColor: \"var(--instrument-frame-primary-color)\", strokePosition: \"inside\", fillColor: \"var(--instrument-frame-primary-color)\", borderRadius: 0 }) : nothing} </g> ${rect(\"frame-outline\", { width: this.width, height: th, strokeWidth, strokeColor: \"var(--instrument-frame-tertiary-color)\", strokePosition: \"inside\", fillColor: \"none\", borderRadius: this.borderRadius })} `; } /** Top edge of the track band in SVG user space. */ get trackBandY() { return this.totalHeight / 2 - this.trackHeight - (this.bottomBar ? this.ticksHeight : 0); } renderBandBars() { if (this.barAreas.length === 0) return nothing; return this.barAreas.map((bar) => svg` <rect x=\"${Math.min(bar.startX, bar.endX)}\" y=\"${this.trackBandY}\" width=\"${Math.abs(bar.endX - bar.startX)}\" height=\"${this.trackHeight}\" fill=${bar.fillColor} /> `); } renderBandNeedles() { if (this.needles.length === 0) return nothing; return this.needles.map((needle) => svg` <rect x=\"${needle.x - 4}\" y=\"${this.trackBandY}\" width=\"8\" height=\"${this.trackHeight}\" rx=\"4\" fill=${needle.fillColor} stroke=${needle.strokeColor} stroke-width=\"1\" vector-effect=\"non-scaling-stroke\" paint-order=\"stroke fill\" /> `); } getRotTrackY() { const th = this.totalHeight; if (this.rotPosition === LinearRotPosition.scale) return -th / 2 + this.ticksHeight / 2; if (this.bottomBar) return th / 2 - this.ticksHeight / 2; return this.height / 2 - this.trackHeight / 2; } getRotColors() { const isEnhanced = this.rotPriority === Priority.enhanced; if (this.rotPortStarboard) { const direction = this.rotType === RotType.bar ? this.rotEndX - this.rotStartX : this._effectiveRpm; if (direction > 0) return { dotColor: \"var(--instrument-starboard-secondary-color)\", barBgColor: \"var(--instrument-starboard-primary-color)\" }; if (direction < 0) return { dotColor: \"var(--instrument-port-secondary-color)\", barBgColor: \"var(--instrument-port-primary-color)\" }; } return { dotColor: isEnhanced ? \"var(--instrument-enhanced-tertiary-color)\" : \"var(--instrument-regular-tertiary-color)\", barBgColor: isEnhanced ? \"var(--instrument-enhanced-secondary-color)\" : \"var(--instrument-regular-secondary-color)\" }; } renderRot() { if (!this.rotType) return nothing; const trackY = this.getRotTrackY(); const { dotColor, barBgColor } = this.getRotColors(); const canAnimateDots = this.rotDotSpacing > 0; if (this.rotType === RotType.bar) { const span = Math.abs(this.rotEndX - this.rotStartX); const zeroDb = Number.isFinite(this.rotAtZeroDeadband) ? this.rotAtZeroDeadband : ROT_ZERO_DEADBAND_PX; if (span < Math.max(zeroDb, 8)) return renderLinearRotZeroPill(barBgColor, this.rotStartX, trackY); return svg` ${renderLinearRotBarStatic({ startX: this.rotStartX, endX: this.rotEndX, barColor: barBgColor, trackY, maskId: \"rot-bar-mask-linear\" })} ${canAnimateDots ? svg`<g clip-path=\"url(#rot-bar-mask-linear)\"> <g id=\"rot-spinner\"> ${renderLinearRotBarDots(dotColor, trackY, this.rotDotSpacing, this.width)} </g> </g>` : nothing} `; } let dotsColor = this.rotPriority === Priority.enhanced ? \"var(--instrument-enhanced-secondary-color)\" : \"var(--instrument-regular-secondary-color)\"; if (this.rotPortStarboard) { if (this._effectiveRpm > 0) dotsColor = \"var(--instrument-starboard-secondary-color)\"; else if (this._effectiveRpm < 0) dotsColor = \"var(--instrument-port-secondary-color)\"; } return canAnimateDots ? svg` <g id=\"rot-spinner\"> ${renderLinearRotDots(dotsColor, trackY, this.rotDotSpacing, this.width)} </g> ` : nothing; } updated(changed) { super.updated(changed); const el = this.rotType ? this.renderRoot.querySelector(\"#rot-spinner\") : null; if (!el) { this._rotController = disposeRotController(this, this._rotController); return; } const cyclePx = 360 * (this.rotDotSpacing / 72); if (!this._rotController || this._rotController.el !== el) { this._rotController = disposeRotController(this, this._rotController); this._rotController = new RateOfTurnController(this, el, this._effectiveRpm, cyclePx); } else this._rotController.cyclePx = cyclePx; if (changed.has(\"rateOfTurnDegreesPerMinute\") || changed.has(\"rotDotAnimationFactor\") || changed.has(\"rotationsPerMinute\")) this._rotController.rotationsPerMinute = this._effectiveRpm; } disconnectedCallback() { super.disconnectedCallback(); this._rotController = disposeRotController(this, this._rotController); } render() { const width = (this.width / 2 + this.padding) * 2; const th = this.totalHeight; const viewBox = `-${width / 2} -${th / 2} ${width} ${th}`; const scale = this.
|
|
10192
|
+
"default": "class ObcWatchFlat extends LitElement { constructor(..._args) { super(..._args); this.width = 352; this.height = 72; this.padding = 0; this.rotation = 0; this.tickmarkSpacing = 0; this.tickmarks = []; this.labels = []; this.FOVIndicator = []; this.trackHeight = 2 / 3 * this.height; this.ticksHeight = this.height - this.trackHeight; this.borderRadius = 8; this.bottomBar = false; this.barAreas = []; this.needles = []; this.rotPosition = LinearRotPosition.track; this.rotStartX = 0; this.rotEndX = 0; this.rotDotSpacing = 0; this.rotPriority = Priority.regular; this.rotPortStarboard = false; this.rotAtZeroDeadband = ROT_ZERO_DEADBAND_PX; this.rotDotAnimationFactor = 18; this._legacyRotationsPerMinute = 0; this._resizeController = new ResizeController(this, {}); } /** * @deprecated Use `rateOfTurnDegreesPerMinute` (and optionally * `rotDotAnimationFactor`) instead. Takes effect only when * `rateOfTurnDegreesPerMinute` is `undefined`. */ set rotationsPerMinute(value) { this._legacyRotationsPerMinute = value; } get rotationsPerMinute() { return this._legacyRotationsPerMinute; } get _effectiveRpm() { if (this.rateOfTurnDegreesPerMinute != null) return this.rateOfTurnDegreesPerMinute / 360 * this.rotDotAnimationFactor; return this._legacyRotationsPerMinute; } /** * Rendered px per user-space unit; the labels divide by it to keep their * on-screen size. 1:1 while the strip has no width yet (hidden, or not laid * out), until the ResizeController re-renders it. */ scaleFor(viewBoxWidth) { const scale = measureContainerPx(this).width / viewBoxWidth; return Number.isFinite(scale) && scale > 0 ? scale : 1; } get totalHeight() { return this.bottomBar ? this.height + this.ticksHeight : this.height; } renderClipPath(offsetY = 0) { return svg` <clipPath id=\"frameClipPath${offsetY === 0 ? \"\" : \"Tickmarks\"}\"> <rect x=\"${-this.width / 2}\" y=\"${-this.totalHeight / 2 + offsetY}\" width=\"${this.width}\" height=\"${this.totalHeight}\" rx=\"${this.borderRadius}\" /> </clipPath> `; } renderLabelMask() { return svg` <mask id=\"labelMask\"> <rect x=\"${-this.width / 2}\" y=\"${-70}\" width=\"${this.width}\" height=\"${32}\" /> <linearGradient id=\"fadeGradient\" gradientUnits=\"userSpaceOnUse\" x1=\"${-this.width / 2}\" y1=\"0\" x2=\"${this.width / 2}\" y2=\"0\"> <stop offset=\"0%\" style=\"stop-color:black; stop-opacity:1;\" /> <stop offset=\"10%\" style=\"stop-color:white; stop-opacity:1;\" /> <stop offset=\"50%\" style=\"stop-color:white; stop-opacity:1;\" /> <stop offset=\"90%\" style=\"stop-color:white; stop-opacity:1;\" /> <stop offset=\"100%\" style=\"stop-color:black; stop-opacity:1;\" /> </linearGradient> <rect x=\"${-this.width / 2}\" y=\"${-70}\" width=\"${this.width}\" height=\"${32}\" fill=\"url(#fadeGradient)\" /> </mask> `; } renderLabels(scale) { const labels = []; for (const l of this.labels) labels.push(svg`<g transform=\"translate(${-this.rotation * this.tickmarkSpacing}, ${-6 / scale})\"> <text x=${l.x} y=${l.y} class=\"label\" fill=${\"var(--instrument-tick-mark-secondary-color)\"}> ${l.text} </text> </g>`); return labels; } watchFace() { const strokeWidth = 1; const th = this.totalHeight; const topTicksY = -th / 2; return svg` ${this.renderClipPath()} ${this.renderClipPath(-40)} <g clip-path=\"url(#frameClipPath)\"> ${rect(\"frame-track\", { width: this.width, height: this.trackHeight, y: th / 2 - this.trackHeight - (this.bottomBar ? this.ticksHeight : 0), strokeWidth, strokeColor: \"var(--instrument-frame-secondary-color)\", strokePosition: \"inside\", fillColor: \"var(--instrument-frame-secondary-color)\", borderRadius: 0 })} ${rect(\"frame-ticks\", { width: this.width, height: this.ticksHeight, y: topTicksY, strokeWidth, strokeColor: \"var(--instrument-frame-primary-color)\", strokePosition: \"inside\", fillColor: \"var(--instrument-frame-primary-color)\", borderRadius: 0 })} ${this.bottomBar ? rect(\"frame-bottom-bar\", { width: this.width, height: this.ticksHeight, y: th / 2 - this.ticksHeight, strokeWidth, strokeColor: \"var(--instrument-frame-primary-color)\", strokePosition: \"inside\", fillColor: \"var(--instrument-frame-primary-color)\", borderRadius: 0 }) : nothing} </g> ${rect(\"frame-outline\", { width: this.width, height: th, strokeWidth, strokeColor: \"var(--instrument-frame-tertiary-color)\", strokePosition: \"inside\", fillColor: \"none\", borderRadius: this.borderRadius })} `; } /** Top edge of the track band in SVG user space. */ get trackBandY() { return this.totalHeight / 2 - this.trackHeight - (this.bottomBar ? this.ticksHeight : 0); } renderBandBars() { if (this.barAreas.length === 0) return nothing; return this.barAreas.map((bar) => svg` <rect x=\"${Math.min(bar.startX, bar.endX)}\" y=\"${this.trackBandY}\" width=\"${Math.abs(bar.endX - bar.startX)}\" height=\"${this.trackHeight}\" fill=${bar.fillColor} /> `); } renderBandNeedles() { if (this.needles.length === 0) return nothing; return this.needles.map((needle) => svg` <rect x=\"${needle.x - 4}\" y=\"${this.trackBandY}\" width=\"8\" height=\"${this.trackHeight}\" rx=\"4\" fill=${needle.fillColor} stroke=${needle.strokeColor} stroke-width=\"1\" vector-effect=\"non-scaling-stroke\" paint-order=\"stroke fill\" /> `); } getRotTrackY() { const th = this.totalHeight; if (this.rotPosition === LinearRotPosition.scale) return -th / 2 + this.ticksHeight / 2; if (this.bottomBar) return th / 2 - this.ticksHeight / 2; return this.height / 2 - this.trackHeight / 2; } getRotColors() { const isEnhanced = this.rotPriority === Priority.enhanced; if (this.rotPortStarboard) { const direction = this.rotType === RotType.bar ? this.rotEndX - this.rotStartX : this._effectiveRpm; if (direction > 0) return { dotColor: \"var(--instrument-starboard-secondary-color)\", barBgColor: \"var(--instrument-starboard-primary-color)\" }; if (direction < 0) return { dotColor: \"var(--instrument-port-secondary-color)\", barBgColor: \"var(--instrument-port-primary-color)\" }; } return { dotColor: isEnhanced ? \"var(--instrument-enhanced-tertiary-color)\" : \"var(--instrument-regular-tertiary-color)\", barBgColor: isEnhanced ? \"var(--instrument-enhanced-secondary-color)\" : \"var(--instrument-regular-secondary-color)\" }; } renderRot() { if (!this.rotType) return nothing; const trackY = this.getRotTrackY(); const { dotColor, barBgColor } = this.getRotColors(); const canAnimateDots = this.rotDotSpacing > 0; if (this.rotType === RotType.bar) { const span = Math.abs(this.rotEndX - this.rotStartX); const zeroDb = Number.isFinite(this.rotAtZeroDeadband) ? this.rotAtZeroDeadband : ROT_ZERO_DEADBAND_PX; if (span < Math.max(zeroDb, 8)) return renderLinearRotZeroPill(barBgColor, this.rotStartX, trackY); return svg` ${renderLinearRotBarStatic({ startX: this.rotStartX, endX: this.rotEndX, barColor: barBgColor, trackY, maskId: \"rot-bar-mask-linear\" })} ${canAnimateDots ? svg`<g clip-path=\"url(#rot-bar-mask-linear)\"> <g id=\"rot-spinner\"> ${renderLinearRotBarDots(dotColor, trackY, this.rotDotSpacing, this.width)} </g> </g>` : nothing} `; } let dotsColor = this.rotPriority === Priority.enhanced ? \"var(--instrument-enhanced-secondary-color)\" : \"var(--instrument-regular-secondary-color)\"; if (this.rotPortStarboard) { if (this._effectiveRpm > 0) dotsColor = \"var(--instrument-starboard-secondary-color)\"; else if (this._effectiveRpm < 0) dotsColor = \"var(--instrument-port-secondary-color)\"; } return canAnimateDots ? svg` <g id=\"rot-spinner\"> ${renderLinearRotDots(dotsColor, trackY, this.rotDotSpacing, this.width)} </g> ` : nothing; } firstUpdated(changed) { super.firstUpdated(changed); observeInnerBox(this._resizeController, this.renderRoot); } updated(changed) { super.updated(changed); const el = this.rotType ? this.renderRoot.querySelector(\"#rot-spinner\") : null; if (!el) { this._rotController = disposeRotController(this, this._rotController); return; } const cyclePx = 360 * (this.rotDotSpacing / 72); if (!this._rotController || this._rotController.el !== el) { this._rotController = disposeRotController(this, this._rotController); this._rotController = new RateOfTurnController(this, el, this._effectiveRpm, cyclePx); } else this._rotController.cyclePx = cyclePx; if (changed.has(\"rateOfTurnDegreesPerMinute\") || changed.has(\"rotDotAnimationFactor\") || changed.has(\"rotationsPerMinute\")) this._rotController.rotationsPerMinute = this._effectiveRpm; } disconnectedCallback() { super.disconnectedCallback(); this._rotController = disposeRotController(this, this._rotController); } render() { const width = (this.width / 2 + this.padding) * 2; const th = this.totalHeight; const viewBox = `-${width / 2} -${th / 2} ${width} ${th}`; const scale = this.scaleFor(width); const contentOffsetY = this.bottomBar ? -this.ticksHeight / 2 : 0; return html` <svg width=\"100%\" height=\"100%\" viewBox=${viewBox} style=\"--scale: ${scale}\" > ${this.watchFace()} ${this.renderLabelMask()} <g clip-path=\"url(#frameClipPath)\"> ${this.renderBandBars()} ${this.renderBandNeedles()} </g> <g transform=\"translate(0, ${contentOffsetY})\"> <g clip-path=\"url(#frameClipPath)\"> ${this.tickmarks.map((t) => svg` <g transform=\"translate(${-this.rotation * this.tickmarkSpacing}, 0)\"> ${tickmark(t.angle, t.type, TickmarkStyle.regular)} </g> `)} </g> <g mask=\"url(#labelMask)\">${this.renderLabels(scale)}</g> </g> ${this.FOVIndicator} <g clip-path=\"url(#frameClipPath)\">${this.renderRot()}</g> ${svg`<line x1=\"0\" y1=\"${-this.totalHeight / 2 + this.ticksHeight}\" x2=\"0\" y2=\"${this.totalHeight / 2}\" stroke=\"var(--instrument-frame-tertiary-color)\" stroke-width=\"1\" vector-effect=\"non-scaling-stroke\" />`} </svg> `; } static { this.styles = unsafeCSS(watch_flat_default); } }"
|
|
10193
10193
|
}
|
|
10194
10194
|
],
|
|
10195
10195
|
"exports": [
|
|
@@ -43563,6 +43563,11 @@
|
|
|
43563
43563
|
"kind": "method",
|
|
43564
43564
|
"name": "applyFillModes",
|
|
43565
43565
|
"privacy": "protected",
|
|
43566
|
+
"return": {
|
|
43567
|
+
"type": {
|
|
43568
|
+
"text": ""
|
|
43569
|
+
}
|
|
43570
|
+
},
|
|
43566
43571
|
"description": "Apply fillMode rules to datasets. Must be called after the chart is created\nso scales and pixel coordinates are available for gradient construction.\n\nNOTE: For non-threshold modes (solid, semitransparent), backgroundColor is already\nset correctly in buildDataset(). This method now only handles threshold gradients\nwhich require Chart.js scales to be available.",
|
|
43567
43572
|
"inheritedFrom": {
|
|
43568
43573
|
"name": "ObcChartLineBase",
|
|
@@ -45393,6 +45398,11 @@
|
|
|
45393
45398
|
"kind": "method",
|
|
45394
45399
|
"name": "applyFillModes",
|
|
45395
45400
|
"privacy": "protected",
|
|
45401
|
+
"return": {
|
|
45402
|
+
"type": {
|
|
45403
|
+
"text": ""
|
|
45404
|
+
}
|
|
45405
|
+
},
|
|
45396
45406
|
"description": "Apply fillMode rules to datasets. Must be called after the chart is created\nso scales and pixel coordinates are available for gradient construction.\n\nNOTE: For non-threshold modes (solid, semitransparent), backgroundColor is already\nset correctly in buildDataset(). This method now only handles threshold gradients\nwhich require Chart.js scales to be available.",
|
|
45397
45407
|
"inheritedFrom": {
|
|
45398
45408
|
"name": "ObcChartLineBase",
|
|
@@ -49289,6 +49299,11 @@
|
|
|
49289
49299
|
"kind": "method",
|
|
49290
49300
|
"name": "applyFillModes",
|
|
49291
49301
|
"privacy": "protected",
|
|
49302
|
+
"return": {
|
|
49303
|
+
"type": {
|
|
49304
|
+
"text": ""
|
|
49305
|
+
}
|
|
49306
|
+
},
|
|
49292
49307
|
"description": "Apply fillMode rules to datasets. Must be called after the chart is created\nso scales and pixel coordinates are available for gradient construction.\n\nNOTE: For non-threshold modes (solid, semitransparent), backgroundColor is already\nset correctly in buildDataset(). This method now only handles threshold gradients\nwhich require Chart.js scales to be available."
|
|
49293
49308
|
},
|
|
49294
49309
|
{
|
|
@@ -86048,6 +86063,11 @@
|
|
|
86048
86063
|
"kind": "method",
|
|
86049
86064
|
"name": "applyFillModes",
|
|
86050
86065
|
"privacy": "protected",
|
|
86066
|
+
"return": {
|
|
86067
|
+
"type": {
|
|
86068
|
+
"text": ""
|
|
86069
|
+
}
|
|
86070
|
+
},
|
|
86051
86071
|
"description": "Apply fillMode rules to datasets. Must be called after the chart is created\nso scales and pixel coordinates are available for gradient construction.\n\nNOTE: For non-threshold modes (solid, semitransparent), backgroundColor is already\nset correctly in buildDataset(). This method now only handles threshold gradients\nwhich require Chart.js scales to be available.",
|
|
86052
86072
|
"inheritedFrom": {
|
|
86053
86073
|
"name": "ObcChartLineBase",
|
|
@@ -98955,6 +98975,12 @@
|
|
|
98955
98975
|
},
|
|
98956
98976
|
"privacy": "private"
|
|
98957
98977
|
},
|
|
98978
|
+
{
|
|
98979
|
+
"kind": "field",
|
|
98980
|
+
"name": "_resizeController",
|
|
98981
|
+
"privacy": "private",
|
|
98982
|
+
"default": "new ResizeController(this, {})"
|
|
98983
|
+
},
|
|
98958
98984
|
{
|
|
98959
98985
|
"kind": "field",
|
|
98960
98986
|
"name": "_effectiveRpm",
|
|
@@ -98964,6 +98990,25 @@
|
|
|
98964
98990
|
"privacy": "private",
|
|
98965
98991
|
"readonly": true
|
|
98966
98992
|
},
|
|
98993
|
+
{
|
|
98994
|
+
"kind": "method",
|
|
98995
|
+
"name": "scaleFor",
|
|
98996
|
+
"privacy": "private",
|
|
98997
|
+
"return": {
|
|
98998
|
+
"type": {
|
|
98999
|
+
"text": "number"
|
|
99000
|
+
}
|
|
99001
|
+
},
|
|
99002
|
+
"parameters": [
|
|
99003
|
+
{
|
|
99004
|
+
"name": "viewBoxWidth",
|
|
99005
|
+
"type": {
|
|
99006
|
+
"text": "number"
|
|
99007
|
+
}
|
|
99008
|
+
}
|
|
99009
|
+
],
|
|
99010
|
+
"description": "Rendered px per user-space unit; the labels divide by it to keep their\non-screen size. 1:1 while the strip has no width yet (hidden, or not laid\nout), until the ResizeController re-renders it."
|
|
99011
|
+
},
|
|
98967
99012
|
{
|
|
98968
99013
|
"kind": "field",
|
|
98969
99014
|
"name": "totalHeight",
|
|
@@ -99090,6 +99135,23 @@
|
|
|
99090
99135
|
}
|
|
99091
99136
|
}
|
|
99092
99137
|
},
|
|
99138
|
+
{
|
|
99139
|
+
"kind": "method",
|
|
99140
|
+
"name": "firstUpdated",
|
|
99141
|
+
"return": {
|
|
99142
|
+
"type": {
|
|
99143
|
+
"text": "void"
|
|
99144
|
+
}
|
|
99145
|
+
},
|
|
99146
|
+
"parameters": [
|
|
99147
|
+
{
|
|
99148
|
+
"name": "changed",
|
|
99149
|
+
"type": {
|
|
99150
|
+
"text": "PropertyValues"
|
|
99151
|
+
}
|
|
99152
|
+
}
|
|
99153
|
+
]
|
|
99154
|
+
},
|
|
99093
99155
|
{
|
|
99094
99156
|
"kind": "method",
|
|
99095
99157
|
"name": "updated",
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"chart-object-vessel-button.d.ts","sourceRoot":"","sources":["../../../src/ar/chart-object-vessel-button/chart-object-vessel-button.ts"],"names":[],"mappings":"AAAA,OAAO,EAAC,UAAU,EAAsB,cAAc,EAAC,MAAM,KAAK,CAAC;AAOnE,OAAO,EACL,WAAW,EAEZ,MAAM,8CAA8C,CAAC;AAGtD,oBAAY,cAAc;IACxB,OAAO,YAAY;IACnB,GAAG,QAAQ;IACX,GAAG,QAAQ;IACX,KAAK,UAAU;IACf,QAAQ,aAAa;CACtB;AAED,oBAAY,KAAK;IACf,OAAO,YAAY;IACnB,MAAM,WAAW;IACjB,QAAQ,aAAa;IACrB,OAAO,YAAY;IACnB,OAAO,YAAY;IACnB,KAAK,UAAU;CAChB;AAED,oBAAY,IAAI;IACd,IAAI,SAAS;IACb,MAAM,WAAW;IACjB,SAAS,eAAe;IACxB,KAAK,UAAU;IACf,YAAY,mBAAmB;IAC/B,cAAc,qBAAqB;CACpC;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA0DG;AACH,qBACa,0BAA2B,SAAQ,UAAU;IAC9B,OAAO,SAAK;IACZ,MAAM,SAAK;IACX,cAAc,EAAE,cAAc,CAAsB;IACpD,QAAQ,SAAK;IACb,MAAM,EAAE,MAAM,GAAG,SAAS,CAAa;IACvC,IAAI,EAAE,MAAM,GAAG,SAAS,CAAa;IACrC,KAAK,EAAE,KAAK,CAAiB;IAC7B,IAAI,EAAE,IAAI,CAAa;IACtB,QAAQ,UAAS;IAClB,aAAa,EAAE,MAAM,GAAG,SAAS,CAAa;IAC7C,gBAAgB,EAAE,OAAO,CAAS;IACnC,WAAW,EAAE,WAAW,GAAG,IAAI,CAAQ;IACvC,eAAe,EAAE,MAAM,CAAM;IAE9C,MAAM;IA0Df,OAAO,CAAC,qBAAqB;IAyD7B,OAAO,CAAC,eAAe;
|
|
1
|
+
{"version":3,"file":"chart-object-vessel-button.d.ts","sourceRoot":"","sources":["../../../src/ar/chart-object-vessel-button/chart-object-vessel-button.ts"],"names":[],"mappings":"AAAA,OAAO,EAAC,UAAU,EAAsB,cAAc,EAAC,MAAM,KAAK,CAAC;AAOnE,OAAO,EACL,WAAW,EAEZ,MAAM,8CAA8C,CAAC;AAGtD,oBAAY,cAAc;IACxB,OAAO,YAAY;IACnB,GAAG,QAAQ;IACX,GAAG,QAAQ;IACX,KAAK,UAAU;IACf,QAAQ,aAAa;CACtB;AAED,oBAAY,KAAK;IACf,OAAO,YAAY;IACnB,MAAM,WAAW;IACjB,QAAQ,aAAa;IACrB,OAAO,YAAY;IACnB,OAAO,YAAY;IACnB,KAAK,UAAU;CAChB;AAED,oBAAY,IAAI;IACd,IAAI,SAAS;IACb,MAAM,WAAW;IACjB,SAAS,eAAe;IACxB,KAAK,UAAU;IACf,YAAY,mBAAmB;IAC/B,cAAc,qBAAqB;CACpC;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA0DG;AACH,qBACa,0BAA2B,SAAQ,UAAU;IAC9B,OAAO,SAAK;IACZ,MAAM,SAAK;IACX,cAAc,EAAE,cAAc,CAAsB;IACpD,QAAQ,SAAK;IACb,MAAM,EAAE,MAAM,GAAG,SAAS,CAAa;IACvC,IAAI,EAAE,MAAM,GAAG,SAAS,CAAa;IACrC,KAAK,EAAE,KAAK,CAAiB;IAC7B,IAAI,EAAE,IAAI,CAAa;IACtB,QAAQ,UAAS;IAClB,aAAa,EAAE,MAAM,GAAG,SAAS,CAAa;IAC7C,gBAAgB,EAAE,OAAO,CAAS;IACnC,WAAW,EAAE,WAAW,GAAG,IAAI,CAAQ;IACvC,eAAe,EAAE,MAAM,CAAM;IAE9C,MAAM;IA0Df,OAAO,CAAC,qBAAqB;IAyD7B,OAAO,CAAC,eAAe;IAiCvB,OAAO,CAAC,kBAAkB;IAqD1B,OAAO,CAAC,uBAAuB;IA4D/B,OAAO,CAAC,kBAAkB;IAmB1B,OAAgB,MAAM,0BAA2B;CAClD;AAED,OAAO,CAAC,MAAM,CAAC;IACb,UAAU,qBAAqB;QAC7B,gCAAgC,EAAE,0BAA0B,CAAC;KAC9D;CACF"}
|
|
@@ -153,7 +153,7 @@ var ObcChartObjectVesselButton = class ObcChartObjectVesselButton extends LitEle
|
|
|
153
153
|
}
|
|
154
154
|
getTurnRateIcon() {
|
|
155
155
|
if (!["button-speed-rot", "flat-speed-rot"].includes(this.type)) return nothing;
|
|
156
|
-
const deg = this.turnRate / 100 * 12;
|
|
156
|
+
const deg = (Number.isFinite(this.turnRate) ? this.turnRate : 0) / 100 * 12;
|
|
157
157
|
const R = 24;
|
|
158
158
|
const x = -24 * Math.cos(degToRad(deg)) + R + 3;
|
|
159
159
|
const y = R * Math.sin(degToRad(deg)) + 8;
|