/** * TaskMate Points Graph Card * Line graph tracking points earned per day or cumulative total. * Configurable time range, per-child or combined view, toggle between modes. * * Version: 1.0.0 * Last Updated: 2026-03-18 */ const LitElement = customElements.get("hui-masonry-view") ? Object.getPrototypeOf(customElements.get("hui-masonry-view")) : Object.getPrototypeOf(customElements.get("hui-view")); const html = LitElement.prototype.html; const css = LitElement.prototype.css; const _safeColor = (c, d) => (typeof c === "string" && /^#[0-9a-fA-F]{3,8}$/.test(c) ? c : d); // Child colors — matches the streak/jackpot palette const CHILD_COLORS = [ { line: "#9b59b6", fill: "rgba(155,89,182,0.15)" }, { line: "#3498db", fill: "rgba(52,152,219,0.15)" }, { line: "#2ecc71", fill: "rgba(46,204,113,0.15)" }, { line: "#e67e22", fill: "rgba(230,126,34,0.15)" }, { line: "#e74c3c", fill: "rgba(231,76,60,0.15)" }, { line: "#1abc9c", fill: "rgba(26,188,156,0.15)" }, ]; class TaskMateGraphCard extends LitElement { static get properties() { return { hass: { type: Object }, config: { type: Object }, _mode: { type: String }, // "daily" | "cumulative" | "career" }; } shouldUpdate(changedProps) { if (changedProps.has("hass")) { return window.__taskmate_hasChanged ? window.__taskmate_hasChanged(changedProps.get("hass"), this.hass, this.config?.entity) : true; } return true; } constructor() { super(); this._mode = "daily"; } _t(key, params) { const fn = window.__taskmate_localize; return fn ? fn(this.hass, key, params) : key; } static get styles() { const base = css` :host { display: block; --gr-purple: #9b59b6; --gr-purple-light: #a569bd; --gr-gold: #f1c40f; --gr-green: #2ecc71; --gr-blue: #3498db; } ha-card { overflow: hidden; } .card-header { display: flex; align-items: center; justify-content: space-between; padding: 14px 18px; background: var(--taskmate-header-bg, #d35400); color: white; gap: 12px; } .header-left { display: flex; align-items: center; gap: 10px; min-width: 0; } .header-icon { --mdc-icon-size: 26px; opacity: 0.9; flex-shrink: 0; } .header-title { font-size: 1.15rem; font-weight: 600; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } .mode-toggle { display: flex; background: rgba(255,255,255,0.12); border-radius: 20px; padding: 3px; gap: 2px; flex-shrink: 0; } .mode-btn { background: none; border: none; color: rgba(255,255,255,0.6); padding: 4px 10px; border-radius: 16px; font-size: 0.75rem; font-weight: 600; cursor: pointer; transition: all 0.2s ease; white-space: nowrap; } .mode-btn.active { background: rgba(255,255,255,0.2); color: white; } .mode-btn:hover:not(.active) { color: rgba(255,255,255,0.85); } .card-content { padding: 16px; display: flex; flex-direction: column; gap: 12px; } /* Legend */ .legend { display: flex; flex-wrap: wrap; gap: 8px 16px; padding: 0 4px; } .legend-item { display: flex; align-items: center; gap: 6px; font-size: 0.8rem; color: var(--secondary-text-color); font-weight: 500; } .legend-dot { width: 10px; height: 10px; border-radius: 50%; flex-shrink: 0; } /* SVG chart container */ .chart-wrap { position: relative; width: 100%; min-height: 180px; } /* Tooltip */ .tooltip { position: absolute; background: var(--card-background-color, #fff); border: 1px solid var(--divider-color, #e0e0e0); border-radius: 8px; padding: 8px 12px; font-size: 0.8rem; color: var(--primary-text-color); box-shadow: 0 4px 16px rgba(0,0,0,0.15); pointer-events: none; z-index: 10; white-space: nowrap; display: none; } .tooltip.visible { display: block; } .tooltip-date { font-weight: 700; margin-bottom: 4px; color: var(--secondary-text-color); font-size: 0.75rem; } .tooltip-row { display: flex; align-items: center; gap: 6px; margin: 2px 0; } .tooltip-dot { width: 8px; height: 8px; border-radius: 50%; flex-shrink: 0; } /* Empty / error */ .error-state, .empty-state { display: flex; flex-direction: column; align-items: center; justify-content: center; padding: 40px 20px; color: var(--secondary-text-color); text-align: center; } .error-state { color: var(--error-color, #f44336); } .error-state ha-icon, .empty-state ha-icon { --mdc-icon-size: 48px; margin-bottom: 12px; opacity: 0.5; } .empty-state .message { font-size: 1rem; color: var(--primary-text-color); } .empty-state .submessage { font-size: 0.85rem; margin-top: 4px; } @media (max-width: 480px) { .card-header { padding: 12px 14px; flex-wrap: wrap; row-gap: 8px; } .header-title { font-size: 1rem; } .mode-toggle { flex-shrink: 1; } .mode-btn { padding: 3px 8px; font-size: 0.7rem; } .card-content { padding: 12px; } } /* ── Designed styles (shared .tmd kit comes from taskmate-design.js) ── */ .tmg-chips { gap: 6px; margin-bottom: 11px; } .tmg-plot { margin-bottom: 4px; } .tmg-plot-pl { background: var(--tmd-surface-2); border-radius: 16px; padding: 12px 10px 6px; } .tmg-plot-cn { background: #0b1424; border: 1px solid var(--tmd-border); border-radius: 8px; padding: 12px 10px 6px; } .tmg-plot-cp { padding: 2px 2px 0; } .tmg-xaxis { justify-content: space-between; font-size: 10.5px; font-weight: 600; margin-top: 4px; } .tmg-plot-cn .tmg-xaxis { font-size: 9.5px; } .tmg-legend { gap: 14px; justify-content: center; margin-top: 11px; font-size: 12px; font-weight: 700; flex-wrap: wrap; } .tmg-plot-cp ~ .tmg-legend { justify-content: flex-start; font-weight: 600; } .tmg-dot { font-size: 0.9em; } `; const tokens = window.__taskmate_design && window.__taskmate_design.styles ? window.__taskmate_design.styles() : null; return tokens ? [tokens, base] : base; } setConfig(config) { if (!config.entity) throw new Error("Please define an entity"); this.config = { title: "", child_id: null, days: 14, header_color: '#d35400', ...config, }; } getCardSize() { return 4; } static getConfigElement() { return document.createElement("taskmate-graph-card-editor"); } static getStubConfig() { return { entity: "sensor.taskmate_overview", title: "Points Graph", days: 14 }; } render() { const design = window.__taskmate_design ? window.__taskmate_design.apply(this, this.hass, this.config, this.config?.entity) : "classic"; if (design !== "classic") { try { return this._renderDesigned(design); } catch (e) { console.error("[TaskMateGraph] Designed render error:", e); return html`
${this._t('graph.graph_error', { message: e.message })}
`; } } try { return this._render(); } catch(e) { console.error("[TaskMateGraph] Render error:", e); return html`
${this._t('graph.graph_error', { message: e.message })}
`; } } _render() { if (!this.hass || !this.config) return html``; const entity = this.hass.states[this.config.entity]; if (!entity) { return html`
${this._t('common.entity_not_found', { entity: this.config.entity })}
`; } if (entity.state === "unavailable" || entity.state === "unknown") { return html`
${this._t('common.unavailable')}
`; } const tz = this.hass?.config?.time_zone || Intl.DateTimeFormat().resolvedOptions().timeZone; const attrs = (window.__taskmate_attrs && window.__taskmate_attrs(this.hass, this.config.entity)) || entity.attributes || {}; let children = attrs.children || []; const pointsIcon = attrs.points_icon || "mdi:star"; const pointsName = attrs.points_name || this._t('common.points'); const days = Math.max(3, Math.min(90, this.config.days || 14)); // Filter to specific child if configured if (this.config.child_id) { children = children.filter(c => c.id === this.config.child_id); } // Get all completions (approved only for points) const allCompletions = [ ...(attrs.recent_completions || attrs.todays_completions || []), ].filter(c => c.approved); // Get manual transactions const allTransactions = attrs.recent_transactions || []; // Build chore points map const chorePointsMap = {}; (attrs.chores || []).forEach(ch => { chorePointsMap[ch.id] = ch.points || 0; }); // Build date range const dateRange = this._buildDateRange(days, tz); // Build career score history lookup const careerHistory = attrs.career_score_history || {}; // Build per-child data series const series = children.map((child, idx) => { const color = CHILD_COLORS[idx % CHILD_COLORS.length]; const dailyPoints = this._buildDailyPoints( child.id, dateRange, allCompletions, allTransactions, chorePointsMap, tz ); const cumulativePoints = this._buildCumulative(dailyPoints); const careerPoints = this._buildCareerSeries(child, careerHistory[child.id] || [], dateRange, allCompletions, allTransactions, chorePointsMap, tz); return { child, color, dailyPoints, cumulativePoints, careerPoints }; }); if (series.length === 0) { return html`
${this._t('common.no_children')}
`; } const dataKey = this._mode === "daily" ? "dailyPoints" : this._mode === "career" ? "careerPoints" : "cumulativePoints"; const hasData = series.some(s => s[dataKey].some(v => v > 0)); const baseTitle = this.config.title || this._t('graph.default_title'); const filterLabel = this.config.child_id ? (series[0]?.child?.name || '') : this._t('graph.all_children'); const headerTitle = this.config.title ? baseTitle : (filterLabel ? `${baseTitle} — ${filterLabel}` : baseTitle); return html`
${headerTitle}
${series.length > 1 ? html`
${series.map(s => html`
${s.child.name}
`)}
` : ''} ${hasData ? this._renderChart(series, dateRange, dataKey, pointsName) : html`
${this._t('graph.no_data_yet')}
${this._t('graph.no_data_submessage')}
`}
`; } /* ══════════════════════════════════════════════════════════════════════ DESIGNED STYLES (playroom / console / cleanpro) — see taskmate-design.js Ported from docs/design/redesigns/frag/07-graph.html. Reuses the SAME series/data computation as the classic chart. ══════════════════════════════════════════════════════════════════════ */ _designTone(i) { return `var(--tmd-c${(i % 6) + 1})`; } // Reuse the classic data pipeline to produce per-child series + the active key. _computeSeries() { const entity = this.hass.states[this.config.entity]; const tz = this.hass?.config?.time_zone || Intl.DateTimeFormat().resolvedOptions().timeZone; const attrs = (window.__taskmate_attrs && window.__taskmate_attrs(this.hass, this.config.entity)) || entity.attributes || {}; let children = attrs.children || []; const pointsName = attrs.points_name || this._t('common.points'); const days = Math.max(3, Math.min(90, this.config.days || 14)); if (this.config.child_id) { children = children.filter(c => c.id === this.config.child_id); } const allCompletions = [ ...(attrs.recent_completions || attrs.todays_completions || []), ].filter(c => c.approved); const allTransactions = attrs.recent_transactions || []; const chorePointsMap = {}; (attrs.chores || []).forEach(ch => { chorePointsMap[ch.id] = ch.points || 0; }); const dateRange = this._buildDateRange(days, tz); const careerHistory = attrs.career_score_history || {}; const series = children.map((child, idx) => { const color = CHILD_COLORS[idx % CHILD_COLORS.length]; const tone = this._designTone(idx); const dailyPoints = this._buildDailyPoints(child.id, dateRange, allCompletions, allTransactions, chorePointsMap, tz); const cumulativePoints = this._buildCumulative(dailyPoints); const careerPoints = this._buildCareerSeries(child, careerHistory[child.id] || [], dateRange, allCompletions, allTransactions, chorePointsMap, tz); return { child, color, tone, dailyPoints, cumulativePoints, careerPoints }; }); const dataKey = this._mode === "daily" ? "dailyPoints" : this._mode === "career" ? "careerPoints" : "cumulativePoints"; return { series, dateRange, dataKey, pointsName }; } // Build SVG point string for a data array, mapped into a 0..VW × 0..VH box. _svgPoints(data, niceMax, VW, VH) { const n = data.length; return data.map((v, i) => { const x = (i / Math.max(n - 1, 1)) * VW; const y = VH - (Math.max(0, v) / niceMax) * VH; return `${x.toFixed(1)},${y.toFixed(1)}`; }).join(" "); } _renderDesigned(design) { if (!this.hass || !this.config) return html``; const hd = _safeColor(this.config.header_color, '#d35400'); const entity = this.hass.states[this.config.entity]; const header = (sub) => html`
${design === "console" ? "⌁" : design === "cleanpro" ? "◔" : "📈"} ${this.config.title || this._t('graph.default_title')}${sub ? html`${sub}` : ""} ${design === "console" ? html`LIVE` : ""}
`; if (!entity) { return html`${header()}
${this._t('common.entity_not_found', { entity: this.config.entity })}
`; } if (entity.state === "unavailable" || entity.state === "unknown") { return html`${header()}
${this._t('common.unavailable')}
`; } const { series, dateRange, dataKey } = this._computeSeries(); if (series.length === 0) { return html`${header()}
${this._t('common.no_children')}
`; } // Match classic: surface the active child filter (or "all children") as a subline. const filterLabel = this.config.child_id ? (series[0]?.child?.name || '') : this._t('graph.all_children'); const hasData = series.some(s => s[dataKey].some(v => v > 0)); // Mode chips wired to the SAME handler/state as the classic toggle. const chip = (mode, label) => html` ${label}`; const chips = html`
${chip("daily", this._t('graph.daily'))} ${chip("cumulative", this._t('graph.total'))} ${chip("career", this._t('graph.career_growth'))}
`; const legend = html`
${series.map(s => html` ${s.child.name}`)}
`; const empty = html`
${this._t('graph.no_data_yet')}
`; const body = design === "console" ? this._graphConsole(series, dateRange, dataKey, chips, legend, hasData, empty) : design === "cleanpro" ? this._graphCleanpro(series, dateRange, dataKey, chips, legend, hasData, empty) : this._graphPlayroom(series, dateRange, dataKey, chips, legend, hasData, empty); return html`${header(filterLabel)}
${body}
`; } // Shared SVG chart builder; per-style flags tweak fills/glow/stroke width. // Built as a string parsed via