import { html, css, LitElement, PropertyValues } from 'lit' import { repeat } from 'lit/directives/repeat.js' import { customElement, property, query, state } from 'lit/decorators.js' import { ValueDisplayConfiguration } from './definition-schema.js' type Dataseries = Exclude[number] & { needleValue?: number } type Data = Exclude[number] type Theme = { theme_name: string theme_object: any } // No locale and no time zone given: both are the viewer's own. const localDateTime = new Intl.DateTimeFormat(undefined, { year: 'numeric', month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' }) // A bound timestamp column arrives as epoch milliseconds; a string column or a // static subtitle may hold ISO 8601 instead. Anything else is not a point in // time and comes back undefined, so the caller can show it as given. const toDate = (value: unknown): Date | undefined => { if (value === null || value === undefined || value === '') return undefined const ms = /^\s*-?\d+(\.\d+)?\s*$/.test(String(value)) ? Number(value) : Date.parse(String(value)) return Number.isFinite(ms) ? new Date(ms) : undefined } // A finite number, or undefined for null, '', NaN and anything else that is not numeric. const toNumber = (value: unknown): number | undefined => { if (value === null || value === undefined || value === '') return undefined const number = typeof value === 'number' ? value : Number(value) return Number.isFinite(number) ? number : undefined } // Decimals for toFixed(), which throws outside 0-100. const fractionDigits = (precision: unknown): number => { const digits = Math.floor(Number(precision)) return Number.isFinite(digits) ? Math.min(100, Math.max(0, digits)) : 0 } /** * When a readout's value goes stale, in epoch milliseconds: the newest row's * timestamp plus Maximum Latency. Undefined when it never does, because no * latency is set or the newest row (the last one: rows arrive oldest first) has * no readable timestamp. */ const staleAt = (rows: Data[], maxLatency: unknown): number | undefined => { const seconds = toNumber(maxLatency) const tsp = toDate(rows[rows.length - 1]?.tsp) return seconds === undefined || !tsp ? undefined : tsp.getTime() + seconds * 1000 } @customElement('widget-value-versionplaceholder') export class WidgetValue extends LitElement { @property({ type: Object }) inputData?: ValueDisplayConfiguration @property({ type: Object }) theme?: Theme @state() private dataSets: Map = new Map() @state() private textActive: boolean = true @state() private themeTitleColor?: string @state() private themeSubtitleColor?: string @query('.value-container') valueContainer?: HTMLDivElement @query('.sizing-container') sizingContainer?: HTMLDivElement version: string = 'versionplaceholder' private resizeObserver: ResizeObserver private lastLargerWidthTime?: number private origWidth: number = 0 private origHeight: number = 0 // Re-runs transformData when the next readout's data passes Maximum Latency. // Studio sends no new inputData while a device is silent, so without it the // last value would stay on screen however old it gets. private staleTimer?: ReturnType constructor() { super() this.resizeObserver = new ResizeObserver(this.applyData.bind(this)) } connectedCallback() { super.connectedCallback() // Observed on every attach, not once: Studio moves a tile by detaching and // re-attaching it, and disconnectedCallback stops observing. this.resizeObserver.observe(this) // Back after a move: re-check the data's age, which also re-arms the stale timer. if (this.hasUpdated) this.transformData() } disconnectedCallback() { super.disconnectedCallback() this.resizeObserver.disconnect() clearTimeout(this.staleTimer) this.staleTimer = undefined } protected update(changedProperties: PropertyValues): void { // Before the render, so the first render already has the theme's colours. if (changedProperties.has('theme') || !this.hasUpdated) this.registerTheme(this.theme) if (changedProperties.has('inputData')) this.transformData() super.update(changedProperties) } protected updated(changedProperties: PropertyValues) { if (changedProperties.has('inputData')) this.sizingSetup() // After every render, not only after new data: a render rewrites the text's // style attributes, which also carry the font sizes applyData sets, so a // theme change used to leave the default sizes until the next data update. this.applyData() super.updated(changedProperties) } registerTheme(theme?: Theme) { // The host's --re-tile-background-color / --re-text-color are not read // through getComputedStyle here. That snapshots them, and this only runs // on a `theme` property change, so a board style edit — which changes the // custom property and nothing else — left the tile painting the previous // colour until it was reloaded. What these fields hold is a var() chain // with the theme's own colour as the fallback, so the host property keeps // winning over the theme, and the browser resolves it on every repaint // without the widget being told anything. const themeBg = this.theme?.theme_object?.backgroundColor const themeText = this.theme?.theme_object?.title?.textStyle?.color const themeSubtext = this.theme?.theme_object?.title?.subtextStyle?.color || themeText this.themeTitleColor = `var(--re-text-color, ${themeText ?? 'inherit'})` this.themeSubtitleColor = `var(--re-text-color, ${themeSubtext ?? 'inherit'})` } subTitleText() { const subTitle = this.inputData?.subTitle if (this.inputData?.subTitleType !== 'timestamp') return subTitle const date = toDate(subTitle) return date ? localDateTime.format(date) : subTitle } sizingSetup() { const boxes = Array.from( this.sizingContainer?.querySelectorAll('.single-value') as NodeListOf ) let width = 0 let height = 0 for (const box of boxes) { const dims = box.getBoundingClientRect() width = Math.max(dims.width, width) height = Math.max(dims.height, height) } if (width < this.origWidth) { if (!this.lastLargerWidthTime || Date.now() - this.lastLargerWidthTime > 5000) { this.origWidth = width } } else { this.origWidth = width this.lastLargerWidthTime = Date.now() } this.origHeight = height } applyData() { if (!this.valueContainer) return const userWidth = this.valueContainer.getBoundingClientRect().width const userHeight = this.valueContainer.getBoundingClientRect().height const count = this.dataSets.size const width = this.origWidth const height = this.origHeight if (!userWidth || !userHeight || !width || !height) return const fits = [] for (let c = 1; c <= count; c++) { const r = Math.ceil(count / c) const uwgap = userWidth - 12 * (c - 1) const uhgap = userHeight - 12 * (r - 1) const m = uwgap / width / c const size = m * m * width * height * count if (r * m * height <= uhgap) fits.push({ r, c, m, size, width, height, userWidth, userHeight }) } for (let r = 1; r <= count; r++) { const c = Math.ceil(count / r) const uwgap = userWidth - 12 * (c - 1) const uhgap = userHeight - 12 * (r - 1) const m = uhgap / height / r const size = m * m * width * height * count if (c * m * width <= uwgap) fits.push({ r, c, m, size, width, height, userWidth, userHeight }) } const maxSize = fits.reduce((p, c) => (c.size < p ? p : c.size), 0) const fit = fits.find((f) => f.size === maxSize) if (!fit) return const modifier = fit.m ?? 1 // console.log('FITS', fits, 'modifier', modifier, 'cols',fit?.c, 'rows', fit?.r, 'new size', fit?.size.toFixed(0), 'total space', (userWidth* userHeight).toFixed(0)) const boxes = Array.from( this.valueContainer?.querySelectorAll('.single-value') as NodeListOf ) this.valueContainer.style.gridTemplateColumns = `repeat(${fit.c}, 1fr)` for (const box of boxes) { box.setAttribute( 'style', `width:${modifier * width}px; height:${modifier * height}px; padding:${modifier * 6}px` ) const label: string | null = box.getAttribute('label') const ds: Dataseries | undefined = this.dataSets.get(label ?? '') const labelText = box.querySelector('.label') as HTMLDivElement labelText.setAttribute( 'style', `font-size: ${26 * modifier}px; color: ${ds?.styling?.labelColor || this.themeTitleColor};` ) const numberText = box.querySelector('.current-value') as HTMLDivElement numberText.setAttribute( 'style', `font-size: ${32 * modifier}px; color: ${ds?.styling?.valueColor || this.theme?.theme_object?.color?.[0] || this.themeTitleColor};` ) const unitText = box.querySelector('.unit') as HTMLDivElement unitText.setAttribute('style', `font-size: ${26 * modifier}px;`) } this.textActive = true } transformData() { this.dataSets = new Map() // Skip null list slots, and read anything but a list as no list: hand-written // board templates have both, and reading a field of null would throw. const list = this.inputData?.dataseries const dataseries = Array.isArray(list) ? list.filter((ds) => !!ds && typeof ds === 'object') : [] dataseries.forEach((ds) => { const rows = Array.isArray(ds.data) ? ds.data.filter((d): d is Data => !!d && typeof d === 'object') : [] // pivot data const distincts = ds.multiChart ? ([...new Set(rows.map((d) => d.pivot))].sort() as string[]) : [''] distincts.forEach((piv) => { const prefix = piv ?? '' const label = ds.label ?? '' const pds: Dataseries = { label: prefix + (!!prefix && !!label ? ' - ' : '') + label, order: ds.order, unit: ds.unit, precision: ds.precision, advanced: ds.advanced, styling: ds.styling, multiChart: ds.multiChart, value: ds.value, data: distincts.length === 1 ? rows : rows.filter((d) => d.pivot === piv), needleValue: undefined } this.dataSets.set(pds.label ?? '', pds) }) }) // filter latest values and calculate average const now = Date.now() // the earliest moment a readout that is fresh now goes stale let nextStaleAt = Infinity this.dataSets.forEach((ds) => { // ds.advanced is the host's own object (shared with other tiles): read the // settings into locals, never write a default back into it. const n = toNumber(ds.advanced?.averageLatest) const averageLatest = n !== undefined && n >= 1 ? Math.floor(n) : 1 if (!ds.multiChart) { ds.needleValue = toNumber(ds.value) } else { const data = ds.data?.slice(-averageLatest) ?? [] // A missing, empty or non-numeric reading is no reading: skip it rather // than average it in as 0 (Number(null)) or as NaN. const values = data.map((d) => toNumber(d.value)).filter((v): v is number => v !== undefined) ds.needleValue = values.length ? values.reduce((p, c) => p + c, 0) / values.length : undefined // Hide data older than Maximum Latency. The newest row sits at the END of // the data array; rows without a readable tsp opt out, since their age // cannot be judged. const expiresAt = staleAt(data, ds.advanced?.maxLatency) if (expiresAt !== undefined && now > expiresAt) ds.needleValue = undefined else if (expiresAt !== undefined) nextStaleAt = Math.min(nextStaleAt, expiresAt) } }) this.scheduleStaleCheck(nextStaleAt) } /** Runs transformData again just after `at` (epoch ms), when the next readout goes stale. */ private scheduleStaleCheck(at: number) { clearTimeout(this.staleTimer) this.staleTimer = undefined // Nothing goes stale, or detached: connectedCallback re-checks on return. if (!Number.isFinite(at) || !this.isConnected) return // setTimeout fires at once for delays above 2^31 - 1 ms (about 24.8 days); // a capped wait only re-checks and re-arms. const delay = Math.min(Math.max(at - Date.now(), 0) + 1, 2 ** 31 - 1) this.staleTimer = setTimeout(() => { this.staleTimer = undefined this.transformData() }, delay) } static styles = css` :host { display: block; font-family: sans-serif; box-sizing: border-box; position: relative; margin: auto; overflow: hidden; container-type: size; } .paging:not([active]) { display: none !important; } .wrapper { display: flex; flex-direction: column; height: 100%; width: 100%; padding: 2cqh 2cqw; box-sizing: border-box; } h3 { margin: 0; max-width: 300px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } p { margin: 10px 0 0 0; max-width: 300px; font-size: 14px; line-height: 17px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } .value-container { display: grid; line-height: 0.9; flex: 1; overflow: hidden; position: relative; gap: 12px; } .single-value { overflow: hidden; position: relative; align-items: end; padding: 6px; box-sizing: border-box; } .current-value { font-size: 32px; font-weight: 600; white-space: nowrap; } .label, .unit { font-weight: 300; font-size: 26px; white-space: nowrap; } .sizing-container { position: absolute; left: 100000px; line-height: 0.9; overflow: hidden; gap: 12px; } .no-data { font-size: 20px; display: flex; height: 100%; width: 100%; text-align: center; align-items: center; justify-content: center; } ` render() { return html`

${this.inputData?.title}

${this.subTitleText()}

${repeat( this.dataSets, ([label]) => label, ([label, ds]) => { return html`
${label}
${ds.needleValue === undefined || ds.needleValue === null || isNaN(ds.needleValue) ? '' : ds.needleValue.toFixed(fractionDigits(ds.precision))} ${ds.unit}
` } )}
No Data
${repeat( [...this.dataSets.entries()].sort(), ([label]) => label, ([label, ds]) => { return html`
${label}
${ds.needleValue === undefined || ds.needleValue === null || isNaN(ds.needleValue) ? '' : ds.needleValue.toFixed(fractionDigits(ds.precision))} ${ds.unit}
` } )}
` } }