A platform for community discussion. Free, open, simple.
FIX: Resolve theme colors before passing them to charts (#44241)
Kris3f2bf92368c7
diff --git a/frontend/discourse/admin/components/admin-report-chart.gjs b/frontend/discourse/admin/components/admin-report-chart.gjsindex 37d684d06a0..56dcab7713e 100644--- a/frontend/discourse/admin/components/admin-report-chart.gjs+++ b/frontend/discourse/admin/components/admin-report-chart.gjs@@ -1,5 +1,7 @@import Component from "@glimmer/component";import Report from "discourse/admin/models/report";+import { dimColor } from "discourse/lib/chart-legend-icon";+import { getCSSColors } from "discourse/lib/css-color";import { number } from "discourse/lib/formatter";import { makeArray } from "discourse/lib/helpers";import { i18n } from "discourse-i18n";@@ -7,12 +9,6 @@ import Chart from "./chart.gjs";const DOTTED_LINE = [5, 5];-function getCSSColor(varName) {- return getComputedStyle(document.documentElement)- .getPropertyValue(varName)- .trim();-}-export function isInCurrentPeriod(timestamp, grouping) {// Report data uses UTC dates, so compare in UTCconst date = moment.utc(timestamp);@@ -54,10 +50,16 @@ export default class AdminReportChart extends Component {options.chartGrouping);- const incompleteColor = getCSSColor("--primary-medium");- const tertiaryRgb = getCSSColor("--tertiary-rgb");- const primaryColor = `rgb(${tertiaryRgb})`;- const secondaryColor = `rgba(${tertiaryRgb}, 0.1)`;+ const colors = getCSSColors([+ "--primary",+ "--primary-low",+ "--primary-medium",+ "--secondary",+ "--tertiary",+ ]);+ const incompleteColor = colors["--primary-medium"];+ const primaryColor = colors["--tertiary"];+ const secondaryColor = dimColor(primaryColor, 0.1);let pointColors = primaryColor;let segment;@@ -115,10 +117,10 @@ export default class AdminReportChart extends Component {options: {plugins: {tooltip: {- backgroundColor: getCSSColor("--primary"),- titleColor: getCSSColor("--secondary"),- bodyColor: getCSSColor("--secondary"),- footerColor: getCSSColor("--secondary"),+ backgroundColor: colors["--primary"],+ titleColor: colors["--secondary"],+ bodyColor: colors["--secondary"],+ footerColor: colors["--secondary"],titleMarginBottom: 16,footerMarginTop: 16,padding: {@@ -173,7 +175,7 @@ export default class AdminReportChart extends Component {text: model.y_axis_title,},- grid: { color: getCSSColor("--primary-low") },+ grid: { color: colors["--primary-low"] },ticks: {callback: (label) => number(label),sampleSize: 5,diff --git a/frontend/discourse/admin/components/admin-report-stacked-chart.gjs b/frontend/discourse/admin/components/admin-report-stacked-chart.gjsindex 5fb3b4a80a0..aed838aab57 100644--- a/frontend/discourse/admin/components/admin-report-stacked-chart.gjs+++ b/frontend/discourse/admin/components/admin-report-stacked-chart.gjs@@ -1,18 +1,13 @@import Component from "@glimmer/component";import Report from "discourse/admin/models/report";import { buildLegendIcon, dimColor } from "discourse/lib/chart-legend-icon";+import { getCSSColors } from "discourse/lib/css-color";import { number } from "discourse/lib/formatter";import { makeArray } from "discourse/lib/helpers";import { remToPx } from "discourse/lib/rem-to-px";import I18n, { i18n } from "discourse-i18n";import Chart from "./chart.gjs";-function getCSSColor(varName) {- return getComputedStyle(document.documentElement)- .getPropertyValue(varName)- .trim();-}-function hexToRgba(hex, alpha) {const r = parseInt(hex.slice(1, 3), 16);const g = parseInt(hex.slice(3, 5), 16);@@ -78,6 +73,13 @@ export default class AdminReportStackedChart extends Component {const chartOptions = options || {};chartOptions.hiddenLabels ??= [];+ const colors = getCSSColors([+ "--primary",+ "--primary-high",+ "--primary-very-low",+ "--secondary",+ ]);+const sourceData = makeArray(model.chartData || model.data);const chartGrouping =chartOptions.chartGrouping ||@@ -151,7 +153,7 @@ export default class AdminReportStackedChart extends Component {padding: remToPx(1),font: { size: remToPx(0.75) },generateLabels: (chart) => {- const textColor = getCSSColor("--primary-high");+ const textColor = colors["--primary-high"];return chart.data.datasets.map((dataset, i) => {const isVisible = chart.isDatasetVisible(i);return {@@ -168,10 +170,10 @@ export default class AdminReportStackedChart extends Component {tooltip: {mode: "index",intersect: false,- backgroundColor: getCSSColor("--primary"),- titleColor: getCSSColor("--secondary"),- bodyColor: getCSSColor("--secondary"),- footerColor: getCSSColor("--secondary"),+ backgroundColor: colors["--primary"],+ titleColor: colors["--secondary"],+ bodyColor: colors["--secondary"],+ footerColor: colors["--secondary"],titleMarginBottom: 16,footerMarginTop: 16,padding: {@@ -211,7 +213,7 @@ export default class AdminReportStackedChart extends Component {stacked: true,display: true,grid: {- color: getCSSColor("--primary-very-low"),+ color: colors["--primary-very-low"],display: !chartOptions.hideYAxisGridLines,},ticks: {diff --git a/frontend/discourse/app/components/topic-map/topic-views-chart.gjs b/frontend/discourse/app/components/topic-map/topic-views-chart.gjsindex 1f3105c3ec4..746b64945fc 100644--- a/frontend/discourse/app/components/topic-map/topic-views-chart.gjs+++ b/frontend/discourse/app/components/topic-map/topic-views-chart.gjs@@ -2,6 +2,7 @@ import Component from "@glimmer/component";import { tracked } from "@glimmer/tracking";import { action } from "@ember/object";import didInsert from "@ember/render-modifiers/modifiers/did-insert";+import { getCSSColors } from "discourse/lib/css-color";import loadChartJS from "discourse/lib/load-chart-js";import I18n, { i18n } from "discourse-i18n";@@ -115,13 +116,13 @@ export default class TopicViewsChart extends Component {const topicMapElement = document.querySelector(".topic-map");// grab colors from CSS- const lineColor =- getComputedStyle(topicMapElement).getPropertyValue("--chart-line-color");- const pointColor = getComputedStyle(topicMapElement).getPropertyValue(- "--chart-point-color"- );- const predictionColor = getComputedStyle(topicMapElement).getPropertyValue(- "--chart-prediction-color"+ const {+ "--chart-line-color": lineColor,+ "--chart-point-color": pointColor,+ "--chart-prediction-color": predictionColor,+ } = getCSSColors(+ ["--chart-line-color", "--chart-point-color", "--chart-prediction-color"],+ { context: topicMapElement });if (this.chart) {diff --git a/frontend/discourse/app/lib/css-color.ts b/frontend/discourse/app/lib/css-color.tsnew file mode 100644index 00000000000..7b9e73b1ab3--- /dev/null+++ b/frontend/discourse/app/lib/css-color.ts@@ -0,0 +1,46 @@+export interface CSSColorOptions {+ /** Element whose custom properties are resolved. Defaults to `document.body`. */+ context?: HTMLElement;+}++/**+ * Reads theme CSS custom properties as concrete colors.+ *+ * Unlike `getComputedStyle().getPropertyValue()`, which returns the raw token+ * stream, this resolves each value through a real CSS `color` property so+ * functions like `light-dark()` and nested `var()` compute before canvas-based+ * consumers, which can't resolve them, receive the value (e.g. `rgb(31, 31, 31)`).+ *+ * Names that aren't set in `context` resolve to an empty string.+ */+export function getCSSColors<T extends string>(+ names: readonly T[],+ { context = document.body }: CSSColorOptions = {}+): Record<T, string> {+ const contextStyle = getComputedStyle(context);+ const probe = document.createElement("span");+ probe.style.display = "none";+ context.append(probe);+ const probeStyle = getComputedStyle(probe);++ const colors = {} as Record<T, string>;+ for (const name of names) {+ if (!contextStyle.getPropertyValue(name).trim()) {+ colors[name] = "";+ continue;+ }+ probe.style.color = `var(${name})`;+ colors[name] = probeStyle.color;+ }++ probe.remove();+ return colors;+}++/**+ * Reads a single theme CSS custom property as a concrete color.+ * Prefer {@link getCSSColors} when reading several at once.+ */+export function getCSSColor(name: string, options?: CSSColorOptions): string {+ return getCSSColors([name], options)[name];+}diff --git a/frontend/discourse/tests/unit/lib/css-color-test.js b/frontend/discourse/tests/unit/lib/css-color-test.jsnew file mode 100644index 00000000000..c91b69068c1--- /dev/null+++ b/frontend/discourse/tests/unit/lib/css-color-test.js@@ -0,0 +1,92 @@+import { module, test } from "qunit";+import { getCSSColor, getCSSColors } from "discourse/lib/css-color";++const TEST_VAR = "--css-color-test";+const OTHER_VAR = "--css-color-test-other";++module("Unit | Lib | cssColor", function (hooks) {+ let originalColorScheme;++ hooks.beforeEach(function () {+ document.documentElement.style.setProperty(+ TEST_VAR,+ "light-dark(#1f1f1f, #f8f5ee)"+ );+ originalColorScheme = document.documentElement.style.colorScheme;+ });++ hooks.afterEach(function () {+ document.documentElement.style.removeProperty(TEST_VAR);+ document.documentElement.style.removeProperty(OTHER_VAR);+ document.documentElement.style.colorScheme = originalColorScheme;+ });++ test("resolves light-dark() to a concrete color for the active scheme", function (assert) {+ document.documentElement.style.colorScheme = "light";+ assert.strictEqual(+ getCSSColor(TEST_VAR),+ "rgb(31, 31, 31)",+ "light scheme resolves to the light-dark() light value"+ );++ document.documentElement.style.colorScheme = "dark";+ assert.strictEqual(+ getCSSColor(TEST_VAR),+ "rgb(248, 245, 238)",+ "dark scheme resolves to the light-dark() dark value"+ );+ });++ test("returns a concrete color for a plain var() value", function (assert) {+ document.documentElement.style.setProperty(TEST_VAR, "#336699");+ assert.strictEqual(+ getCSSColor(TEST_VAR),+ "rgb(51, 102, 153)",+ "plain hex values pass through resolved"+ );+ });++ test("returns an empty string for an unset property", function (assert) {+ assert.strictEqual(+ getCSSColor("--css-color-test-unset"),+ "",+ "doesn't fall back to the inherited text color"+ );+ });++ test("resolves several properties at once", function (assert) {+ document.documentElement.style.colorScheme = "light";+ document.documentElement.style.setProperty(OTHER_VAR, "#336699");++ assert.deepEqual(+ getCSSColors([TEST_VAR, OTHER_VAR, "--css-color-test-unset"]),+ {+ [TEST_VAR]: "rgb(31, 31, 31)",+ [OTHER_VAR]: "rgb(51, 102, 153)",+ "--css-color-test-unset": "",+ },+ "each name maps to its resolved color"+ );+ });++ test("resolves properties scoped to a context element", function (assert) {+ const context = document.createElement("div");+ context.style.setProperty(OTHER_VAR, "#336699");+ document.body.append(context);++ try {+ assert.strictEqual(+ getCSSColor(OTHER_VAR, { context }),+ "rgb(51, 102, 153)",+ "reads the property from the context element"+ );+ assert.strictEqual(+ getCSSColor(OTHER_VAR),+ "",+ "the property isn't visible outside the context"+ );+ } finally {+ context.remove();+ }+ });+});diff --git a/plugins/discourse-ai/admin/assets/javascripts/discourse/components/doughnut-chart.gjs b/plugins/discourse-ai/admin/assets/javascripts/discourse/components/doughnut-chart.gjsindex 61cb81ba0e7..00d93bcd933 100644--- a/plugins/discourse-ai/admin/assets/javascripts/discourse/components/doughnut-chart.gjs+++ b/plugins/discourse-ai/admin/assets/javascripts/discourse/components/doughnut-chart.gjs@@ -1,11 +1,13 @@import Component from "@glimmer/component";import Chart from "discourse/admin/components/chart";import { buildLegendIcon, dimColor } from "discourse/lib/chart-legend-icon";+import { getCSSColor } from "discourse/lib/css-color";import { remToPx } from "discourse/lib/rem-to-px";export default class DoughnutChart extends Component {get config() {const totalScore = this.args.totalScore || "";+ const textColor = getCSSColor("--primary-high");return {type: "doughnut",@@ -32,9 +34,6 @@ export default class DoughnutChart extends Component {padding: remToPx(1),font: { size: remToPx(0.75) },generateLabels: (chart) => {- const textColor = getComputedStyle(document.documentElement)- .getPropertyValue("--primary-high")- .trim();const backgroundColor =chart.data.datasets[0]?.backgroundColor || [];return chart.data.labels.map((label, index) => {@@ -59,10 +58,6 @@ export default class DoughnutChart extends Component {{id: "centerText",afterDraw: function (chart) {- const cssVarColor =- getComputedStyle(document.documentElement).getPropertyValue(- "--primary-high"- ) || "#000";const cssFontSize =getComputedStyle(document.documentElement).getPropertyValue("--font-up-4"@@ -79,7 +74,7 @@ export default class DoughnutChart extends Component {ctx.restore();ctx.textAlign = "center";ctx.textBaseline = "middle";- ctx.fillStyle = cssVarColor.trim();+ ctx.fillStyle = textColor || "#000";ctx.font = `bold ${cssFontSize.trim()} ${cssFontFamily.trim()}`;ctx.fillText(totalScore, centerX, centerY);diff --git a/plugins/poll/assets/javascripts/lib/chart-colors.js b/plugins/poll/assets/javascripts/lib/chart-colors.jsindex 55aba01bef7..222264d8e21 100644--- a/plugins/poll/assets/javascripts/lib/chart-colors.js+++ b/plugins/poll/assets/javascripts/lib/chart-colors.js@@ -1,9 +1,4 @@-function getCSSColor(varName) {- const value = getComputedStyle(document.documentElement)- .getPropertyValue(varName)- .trim();- return value || null;-}+import { getCSSColors } from "discourse/lib/css-color";function generateGradientColors(count, palette) {palette = palette || "cool";@@ -76,13 +71,11 @@ function generateGradientColors(count, palette) {}export function getColors(count, palette) {- const cssColors = [];- for (let i = 1; i <= count; i++) {- const color = getCSSColor(`--poll-pie-color-${i}`);- if (color) {- cssColors.push(color);- }- }+ const names = Array.from(+ { length: count },+ (_, i) => `--poll-pie-color-${i + 1}`+ );+ const cssColors = Object.values(getCSSColors(names)).filter(Boolean);if (cssColors.length >= count) {return cssColors.slice(0, count);diff --git a/plugins/poll/test/javascripts/unit/chart-colors-test.js b/plugins/poll/test/javascripts/unit/chart-colors-test.jsindex d84e43562a0..a8644471085 100644--- a/plugins/poll/test/javascripts/unit/chart-colors-test.js+++ b/plugins/poll/test/javascripts/unit/chart-colors-test.js@@ -1,20 +1,22 @@import { module, test } from "qunit";import { getColors } from "discourse/plugins/poll/lib/chart-colors";-module("Unit | Utility | chart-colors", function (hooks) {- hooks.beforeEach(function () {- this.originalGetComputedStyle = window.getComputedStyle;- });+const POLL_VARS = [1, 2, 3, 4, 5].map((i) => `--poll-pie-color-${i}`);+module("Unit | Utility | chart-colors", function (hooks) {hooks.afterEach(function () {- window.getComputedStyle = this.originalGetComputedStyle;+ POLL_VARS.forEach((name) =>+ document.documentElement.style.removeProperty(name)+ );});- test("returns gradient colors when no CSS variables defined", function (assert) {- window.getComputedStyle = () => ({- getPropertyValue: () => "",- });+ function setPollColors(...colors) {+ colors.forEach((color, i) =>+ document.documentElement.style.setProperty(POLL_VARS[i], color)+ );+ }+ test("returns gradient colors when no CSS variables defined", function (assert) {const colors = getColors(3);assert.strictEqual(colors.length, 3, "returns 3 colors");@@ -25,39 +27,33 @@ module("Unit | Utility | chart-colors", function (hooks) {});test("returns CSS colors when all are defined", function (assert) {- const cssColors = {- "--poll-pie-color-1": "red",- "--poll-pie-color-2": "blue",- "--poll-pie-color-3": "green",- };-- window.getComputedStyle = () => ({- getPropertyValue: (varName) => cssColors[varName] || "",- });+ setPollColors("red", "blue", "green");const colors = getColors(3);- assert.strictEqual(colors.length, 3, "returns 3 colors");- assert.strictEqual(colors[0], "red", "first color is red");- assert.strictEqual(colors[1], "blue", "second color is blue");- assert.strictEqual(colors[2], "green", "third color is green");+ assert.deepEqual(+ colors,+ ["rgb(255, 0, 0)", "rgb(0, 0, 255)", "rgb(0, 128, 0)"],+ "returns the resolved CSS colors in order"+ );});test("mixes CSS and gradient colors when partially defined", function (assert) {- const cssColors = {- "--poll-pie-color-1": "hotpink",- "--poll-pie-color-2": "cyan",- };-- window.getComputedStyle = () => ({- getPropertyValue: (varName) => cssColors[varName] || "",- });+ setPollColors("hotpink", "cyan");const colors = getColors(5);assert.strictEqual(colors.length, 5, "returns 5 colors");- assert.strictEqual(colors[0], "hotpink", "first color is from CSS");- assert.strictEqual(colors[1], "cyan", "second color is from CSS");+ assert.strictEqual(+ colors[0],+ "rgb(255, 105, 180)",+ "first color is from CSS"+ );+ assert.strictEqual(+ colors[1],+ "rgb(0, 255, 255)",+ "second color is from CSS"+ );assert.true(colors[2].startsWith("rgb("), "third color is from gradient");assert.true(colors[3].startsWith("rgb("), "fourth color is from gradient");assert.true(colors[4].startsWith("rgb("), "fifth color is from gradient");