Skip to content

Commit e3b6b26

Browse files
authored
FIX: Do not break the whole app if color is invalid (#48)
This ensure we only log console warnings when the configuration uses unsupported colors.
1 parent 370b20c commit e3b6b26

3 files changed

Lines changed: 19 additions & 1 deletion

File tree

javascripts/discourse/initializers/tag-icons.js

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@ function iconTagRenderer(tag, params) {
3333
tagElement.prepend(iconElement);
3434
tagElement.classList.add("discourse-tag--tag-icons-style");
3535
tagElement.style.setProperty("--color1", color ?? "");
36+
3637
tagElement.style.setProperty("--color2", color ? contrastColor(color) : "");
3738

3839
return tagElement.outerHTML;

javascripts/discourse/lib/colors.js

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,9 @@ const hexToRgb = (hex) => {
1313
}
1414

1515
if (!/^[0-9a-fA-F]{6}$/.test(value)) {
16-
throw new Error(`Invalid hex color: ${hex}`);
16+
// eslint-disable-next-line no-console
17+
console.warn(`Invalid hex color: ${hex}`);
18+
return false;
1719
}
1820

1921
const num = parseInt(value, 16);
@@ -32,5 +34,8 @@ const luminance = (rgb) => {
3234

3335
export const contrastColor = (hexColor) => {
3436
const rgb = hexToRgb(hexColor);
37+
if (!rgb) {
38+
return "";
39+
}
3540
return luminance(rgb) >= 0.45 ? "#000d" : "#fffd";
3641
};

test/acceptance/tag-icons-test.js

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -67,4 +67,16 @@ acceptance("Topic with tags", function (needs) {
6767
const el = queryAll(".discourse-tags a.discourse-tag .tag-icon .d-icon")[0];
6868
assert.ok(el.classList.contains("d-icon-star"), "tag matches correct icon");
6969
});
70+
71+
test("Ensure non-HEX colors do not throw an error", async function (assert) {
72+
settings.tag_icon_list = "Tag2,star,rgba(0,0,0)";
73+
74+
await visit("/t/internationalization-localization/280");
75+
76+
assert.ok(queryAll(".title-wrapper .discourse-tags"), "it has tags");
77+
assert.ok(
78+
queryAll(".discourse-tags a.discourse-tag .tag-icon").length,
79+
"it has tag icon"
80+
);
81+
});
7082
});

0 commit comments

Comments
 (0)