Skip to content

A platform for community discussion. Free, open, simple.

FIX: improve color input hex autocomplete (#34218)

David Battersby3c82f1bf9874
diff --git a/app/assets/javascripts/admin/addon/components/color-input.gjs b/app/assets/javascripts/admin/addon/components/color-input.gjs
index f8d895b94c7..b2d81fe706e 100644
--- a/app/assets/javascripts/admin/addon/components/color-input.gjs
+++ b/app/assets/javascripts/admin/addon/components/color-input.gjs
@@ -34,14 +34,9 @@ export default class ColorInput extends Component {
if (!color.startsWith("#")) {
color = "#" + color;
}
- if (color.length === 4) {
- color =
- "#" +
- color
- .slice(1)
- .split("")
- .map((hex) => hex + hex)
- .join("");
+ // auto fill common hex codes like #F8F -> #F8F8F8 and #DDD -> #DDDDDD
+ if (color.length === 4 && color[1] === color[3]) {
+ color = "#" + color.slice(1).slice(0, 2).repeat(3);
}
}
return color;
diff --git a/app/assets/javascripts/discourse/tests/integration/components/color-input-test.gjs b/app/assets/javascripts/discourse/tests/integration/components/color-input-test.gjs
new file mode 100644
index 00000000000..581459feaf2
--- /dev/null
+++ b/app/assets/javascripts/discourse/tests/integration/components/color-input-test.gjs
@@ -0,0 +1,28 @@
+import { fillIn, render } from "@ember/test-helpers";
+import { module, test } from "qunit";
+import { setupRenderingTest } from "discourse/tests/helpers/component-test";
+import ColorInput from "admin/components/color-input";
+
+module("Integration | Component | ColorInput", function (hooks) {
+ setupRenderingTest(hooks);
+
+ test("autocompletes hex codes", async function (assert) {
+ let result;
+ const autocompleteHex = (color) => (result = color.replace("#", ""));
+
+ await render(
+ <template><ColorInput @onChangeColor={{autocompleteHex}} /></template>
+ );
+
+ await fillIn(".hex-input", "000");
+ assert.strictEqual(result, "000000", "black text");
+ await fillIn(".hex-input", "fff");
+ assert.strictEqual(result, "ffffff", "white text");
+ await fillIn(".hex-input", "f2f");
+ assert.strictEqual(result, "f2f2f2", "2 digit sequence");
+ await fillIn(".hex-input", "DDD");
+ assert.strictEqual(result, "DDDDDD", "3 digit sequence");
+ await fillIn(".hex-input", "0f8");
+ assert.strictEqual(result, "0f8", "with no sequence");
+ });
+});