A platform for community discussion. Free, open, simple.
FEATURE: Add FormKit Color control for color picker fields (#37238)
Régis Hanol986f91418e7d
diff --git a/app/assets/stylesheets/common/form-kit/_control-color.scss b/app/assets/stylesheets/common/form-kit/_control-color.scssnew file mode 100644index 00000000000..3611823b937--- /dev/null+++ b/app/assets/stylesheets/common/form-kit/_control-color.scss@@ -0,0 +1,134 @@+@use "lib/viewport";++.form-kit__control-color {+ display: flex;+ flex-direction: column;+ gap: 0.5em;+ width: 100%;+}++.form-kit__control-color-input {+ display: flex;+ align-items: center;+ gap: 0.25em;+}++.form-kit__control-color-input-prefix {+ border: 1px solid var(--primary-low-mid);+ border-right: 0;+ padding-inline: 0.5em;+ height: 2em;+ box-sizing: border-box;+ background: var(--primary-low);+ display: flex;+ align-items: center;+ margin-right: -0.25em;+ border-radius: var(--d-input-border-radius) 0 0 var(--d-input-border-radius);++ @include viewport.until(sm) {+ height: 2.25em;+ }+}++.form-kit__control-color-input-hex {+ @include default-input;+ width: 5.5em;+ min-width: auto !important;++ .form-kit__control-color-input-prefix + & {+ border-radius: 0 var(--d-input-border-radius) var(--d-input-border-radius) 0;+ border-left: none;+ }++ // Wider when no prefix (named colors mode) to accommodate longer values+ &:first-child {+ width: 8em;+ }++ .form-kit__field.has-error & {+ border-color: var(--danger);+ }+}++.form-kit__control-color-input-picker {+ width: 2em;+ height: 2em;+ padding: 0;+ border: 1px solid var(--primary-low-mid);+ border-radius: var(--d-input-border-radius);+ cursor: pointer;++ @include viewport.until(sm) {+ height: 2.25em;+ }++ &::-webkit-color-swatch-wrapper {+ padding: 2px;+ }++ &::-webkit-color-swatch {+ border: none;+ border-radius: calc(var(--d-input-border-radius) - 2px);+ }++ &::-moz-color-swatch {+ border: none;+ border-radius: calc(var(--d-input-border-radius) - 2px);+ }++ &:focus,+ &:focus-visible {+ &:not(:disabled) {+ border-color: var(--tertiary);+ outline: 2px solid var(--tertiary);+ outline-offset: -2px;+ }+ }++ &:disabled {+ cursor: not-allowed;+ opacity: 0.5;+ }+}++.form-kit__control-color-swatches {+ display: flex;+ flex-wrap: wrap;+ gap: 0.25em;+}++.form-kit__control-color-swatch {+ width: 1.25em;+ height: 1.25em;+ padding: 0;+ border: 1px solid var(--primary-medium);+ border-radius: 2px;+ cursor: pointer;+ display: flex;+ align-items: center;+ justify-content: center;+ color: white;++ .d-icon {+ display: none;+ font-size: var(--font-down-2);+ }++ &.is-used .d-icon {+ display: inline-flex;+ opacity: 0.8;+ }++ &:hover {+ transform: scale(1.1);+ }++ &:disabled {+ cursor: not-allowed;+ opacity: 0.5;++ &:hover {+ transform: none;+ }+ }+}diff --git a/app/assets/stylesheets/common/form-kit/_index.scss b/app/assets/stylesheets/common/form-kit/_index.scssindex b426bea1967..c99008e4c90 100644--- a/app/assets/stylesheets/common/form-kit/_index.scss+++ b/app/assets/stylesheets/common/form-kit/_index.scss@@ -9,6 +9,7 @@@import "_container";@import "_control-checkbox";@import "_control-code";+@import "_control-color";@import "_control-composer";@import "_control-icon";@import "_control-password";diff --git a/frontend/discourse/admin/components/admin-welcome-banner-form.gjs b/frontend/discourse/admin/components/admin-welcome-banner-form.gjsindex ed3c549d47c..c26695f5d14 100644--- a/frontend/discourse/admin/components/admin-welcome-banner-form.gjs+++ b/frontend/discourse/admin/components/admin-welcome-banner-form.gjs@@ -4,7 +4,6 @@ import { fn, hash } from "@ember/helper";import { action } from "@ember/object";import { service } from "@ember/service";import { htmlSafe } from "@ember/template";-import ColorInput from "discourse/admin/components/color-input";import ConditionalLoadingSpinner from "discourse/components/conditional-loading-spinner";import DMultiSelect from "discourse/components/d-multi-select";import Form from "discourse/components/form";@@ -413,14 +412,7 @@ export default class AdminWelcomeBannerForm extends Component {@format="large"as |field|>- <field.Custom>- <ColorInput- @hexValue={{readonly field.value}}- @onlyHex={{false}}- @styleSelection={{false}}- @onChangeColor={{field.set}}- />- </field.Custom>+ <field.Color @allowNamedColors={{true}} /></form.Field><form.Fielddiff --git a/frontend/discourse/admin/components/color-input.gjs b/frontend/discourse/admin/components/color-input.gjsindex 140c47be3c9..f4dbebf86b1 100644--- a/frontend/discourse/admin/components/color-input.gjs+++ b/frontend/discourse/admin/components/color-input.gjs@@ -5,6 +5,7 @@ import { action, computed } from "@ember/object";import { classNames } from "@ember-decorators/component";import { observes } from "@ember-decorators/object";import TextField from "discourse/components/text-field";+import { isValidHex } from "discourse/lib/color-transformations";/**An input field for a color.@@ -63,7 +64,7 @@ export default class ColorInput extends Component {@actiononPickerInput(event) {- this.set("hexValue", event.target.value.replace("#", ""));+ this.set("hexValue", event.target.value.replace(/^#/, ""));}@action@@ -93,7 +94,7 @@ export default class ColorInput extends Component {}_valid(color = this.hexValue) {- return /^#?([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/.test(color);+ return isValidHex(color);}<template>diff --git a/frontend/discourse/admin/components/color-palette-editor.gjs b/frontend/discourse/admin/components/color-palette-editor.gjsindex b3a72c301ea..f6c262b2256 100644--- a/frontend/discourse/admin/components/color-palette-editor.gjs+++ b/frontend/discourse/admin/components/color-palette-editor.gjs@@ -8,6 +8,7 @@ import { service } from "@ember/service";import DButton from "discourse/components/d-button";import concatClass from "discourse/helpers/concat-class";import icon from "discourse/helpers/d-icon";+import { isValidHex, normalizeHex } from "discourse/lib/color-transformations";import { or } from "discourse/truth-helpers";import { i18n } from "discourse-i18n";@@ -22,13 +23,13 @@ const Picker = class extends Component {@actiononInput(event) {- const color = event.target.value.replace("#", "");+ const color = event.target.value.replace(/^#/, "");this.args.onChange(color);}@actiononChange(event) {- const color = event.target.value.replace("#", "");+ const color = event.target.value.replace(/^#/, "");this.args.onChange(color);}@@ -36,7 +37,7 @@ const Picker = class extends Component {onTextChange(event) {let color = event.target.value;- if (!this.isValidHex(color)) {+ if (!isValidHex(color)) {event.preventDefault();this.invalid = true;this.toasts.error({@@ -50,7 +51,7 @@ const Picker = class extends Component {}this.invalid = false;- color = this.ensureSixDigitsHex(color);+ color = normalizeHex(color);this.args.onChange(color);}@@ -117,8 +118,8 @@ const Picker = class extends Component {.trim().replace(/^#/, "");- if (this.isValidHex(content)) {- this.args.onChange(this.ensureSixDigitsHex(content));+ if (isValidHex(content)) {+ this.args.onChange(normalizeHex(content));} else {this.toasts.error({data: {@@ -132,14 +133,14 @@ const Picker = class extends Component {get displayedColor() {const color = this.args.color.hex;- return this.ensureSixDigitsHex(color);+ return normalizeHex(color);}get activeValue() {const color = this.args.color.hex;if (color) {- return `#${this.ensureSixDigitsHex(color)}`;+ return `#${normalizeHex(color)}`;}}@@ -150,20 +151,6 @@ const Picker = class extends Component {return i18n("admin.config_areas.color_palettes.blocked_edit_for_system");}- ensureSixDigitsHex(hex) {- if (hex.length === 3) {- return hex- .split("")- .map((digit) => `${digit}${digit}`)- .join("");- }- return hex;- }-- isValidHex(hex) {- return !!hex?.match(/^([0-9A-Fa-f]{3}|[0-9A-Fa-f]{6})$/);- }-<template><divclass={{concatClassdiff --git a/frontend/discourse/admin/components/edit-category-general.gjs b/frontend/discourse/admin/components/edit-category-general.gjsindex 4b39bd6c375..ad37c3f58a8 100644--- a/frontend/discourse/admin/components/edit-category-general.gjs+++ b/frontend/discourse/admin/components/edit-category-general.gjs@@ -1,11 +1,9 @@import Component from "@glimmer/component";import { cached } from "@glimmer/tracking";-import { fn, hash } from "@ember/helper";+import { hash } from "@ember/helper";import { action } from "@ember/object";import { service } from "@ember/service";import { htmlSafe } from "@ember/template";-import ColorInput from "discourse/admin/components/color-input";-import ColorPicker from "discourse/components/color-picker";import DecoratedHtml from "discourse/components/decorated-html";import PluginOutlet from "discourse/components/plugin-outlet";import categoryBadge from "discourse/helpers/category-badge";@@ -127,25 +125,16 @@ export default class EditCategoryGeneral extends Component {}@action- updateColor(field, newColor) {- const color = newColor.replace("#", "");+ setBackgroundColor(value, { set }) {+ const color = value?.replace(/^#/, "") ?? "";- if (color === field.value) {- return;- }+ set("color", color);- if (field.name === "color") {- const whiteDiff = this.colorDifference(color, CATEGORY_TEXT_COLORS[0]);- const blackDiff = this.colorDifference(color, CATEGORY_TEXT_COLORS[1]);- const colorIndex = whiteDiff > blackDiff ? 0 : 1;+ const whiteDiff = this.colorDifference(color, CATEGORY_TEXT_COLORS[0]);+ const blackDiff = this.colorDifference(color, CATEGORY_TEXT_COLORS[1]);+ const colorIndex = whiteDiff > blackDiff ? 0 : 1;- this.args.form.setProperties({- color,- text_color: CATEGORY_TEXT_COLORS[colorIndex],- });- } else {- field.set(color);- }+ set("text_color", CATEGORY_TEXT_COLORS[colorIndex]);}@action@@ -363,28 +352,13 @@ export default class EditCategoryGeneral extends Component {@format="full"@validate={{this.validateColor}}@validation="required"+ @onSet={{this.setBackgroundColor}}as |field|>- <field.Custom>- <div class="category-color-editor">- <div class="colorpicker-wrapper edit-background-color">- <ColorInput- @hexValue={{readonly field.value}}- @valid={{@category.colorValid}}- @ariaLabelledby="background-color-label"- @onChangeColor={{fn this.updateColor field}}- @skipNormalize={{true}}- />- <ColorPicker- @colors={{this.backgroundColors}}- @usedColors={{this.usedBackgroundColors}}- @value={{readonly field.value}}- @ariaLabel={{i18n "category.predefined_colors"}}- @onSelectColor={{fn this.updateColor field}}- />- </div>- </div>- </field.Custom>+ <field.Color+ @colors={{this.backgroundColors}}+ @usedColors={{this.usedBackgroundColors}}+ /></@form.Field><@form.Field@@ -395,24 +369,7 @@ export default class EditCategoryGeneral extends Component {@validation="required"as |field|>- <field.Custom>- <div class="category-color-editor">- <div class="colorpicker-wrapper edit-text-color">- <ColorInput- @hexValue={{readonly field.value}}- @ariaLabelledby="foreground-color-label"- @onChangeColor={{fn this.updateColor field}}- @skipNormalize={{true}}- />- <ColorPicker- @colors={{CATEGORY_TEXT_COLORS}}- @value={{readonly field.value}}- @ariaLabel={{i18n "category.predefined_colors"}}- @onSelectColor={{fn this.updateColor field}}- />- </div>- </div>- </field.Custom>+ <field.Color @colors={{CATEGORY_TEXT_COLORS}} /></@form.Field></@form.Section></div>diff --git a/frontend/discourse/admin/lib/hex-to-rgba.js b/frontend/discourse/admin/lib/hex-to-rgba.jsindex 96702b49bb2..6195659606f 100644--- a/frontend/discourse/admin/lib/hex-to-rgba.js+++ b/frontend/discourse/admin/lib/hex-to-rgba.js@@ -1,9 +1,7 @@-export default function hexToRGBA(hexCode, opacity) {- let hex = hexCode.replace("#", "");+import { normalizeHex } from "discourse/lib/color-transformations";- if (hex.length === 3) {- hex = hex[0] + hex[0] + hex[1] + hex[1] + hex[2] + hex[2];- }+export default function hexToRGBA(hexCode, opacity) {+ const hex = normalizeHex(hexCode);const r = parseInt(hex.substring(0, 2), 16);const g = parseInt(hex.substring(2, 4), 16);diff --git a/frontend/discourse/admin/models/color-scheme-color.js b/frontend/discourse/admin/models/color-scheme-color.jsindex 888cb64f220..63239bd99c6 100644--- a/frontend/discourse/admin/models/color-scheme-color.js+++ b/frontend/discourse/admin/models/color-scheme-color.js@@ -1,6 +1,7 @@import { tracked } from "@glimmer/tracking";import EmberObject from "@ember/object";import { observes, on } from "@ember-decorators/object";+import { isValidHex, normalizeHex } from "discourse/lib/color-transformations";import { propertyNotEqual } from "discourse/lib/computed";import discourseComputed from "discourse/lib/decorators";import { i18n } from "discourse-i18n";@@ -84,15 +85,7 @@ export default class ColorSchemeColor extends EmberObject {@discourseComputed("hex")brightness(hex) {if (hex.length === 6 || hex.length === 3) {- if (hex.length === 3) {- hex =- hex.slice(0, 1) +- hex.slice(0, 1) +- hex.slice(1, 2) +- hex.slice(1, 2) +- hex.slice(2, 3) +- hex.slice(2, 3);- }+ hex = normalizeHex(hex);return Math.round((parseInt(hex.slice(0, 2), 16) * 299 +parseInt(hex.slice(2, 4), 16) * 587 +@@ -111,6 +104,6 @@ export default class ColorSchemeColor extends EmberObject {@discourseComputed("hex")valid(hex) {- return hex.match(/^([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/) !== null;+ return isValidHex(hex);}}diff --git a/frontend/discourse/app/components/modal/create-invite.gjs b/frontend/discourse/app/components/modal/create-invite.gjsindex c810bc25727..02ba47de380 100644--- a/frontend/discourse/app/components/modal/create-invite.gjs+++ b/frontend/discourse/app/components/modal/create-invite.gjs@@ -380,7 +380,7 @@ export default class CreateInvite extends Component {as |field|><field.Input- type="number"+ @type="number"min="1"max={{this.maxRedemptionsAllowedLimit}}/>diff --git a/frontend/discourse/app/form-kit/components/fk/control-wrapper.gjs b/frontend/discourse/app/form-kit/components/fk/control-wrapper.gjsindex 2fc2e7115da..452b9795078 100644--- a/frontend/discourse/app/form-kit/components/fk/control-wrapper.gjs+++ b/frontend/discourse/app/form-kit/components/fk/control-wrapper.gjs@@ -108,6 +108,9 @@ export default class FKControlWrapper extends Component {@expandedDatePickerOnDesktop={{@expandedDatePickerOnDesktop}}@selection={{@selection}}@includeNone={{@includeNone}}+ @colors={{@colors}}+ @usedColors={{@usedColors}}+ @allowNamedColors={{@allowNamedColors}}@onControlWidthChange={{fn (mut this.controlWidth)}}id={{@field.id}}name={{@field.name}}diff --git a/frontend/discourse/app/form-kit/components/fk/control/color.gjs b/frontend/discourse/app/form-kit/components/fk/control/color.gjsnew file mode 100644index 00000000000..5f5da624ecd--- /dev/null+++ b/frontend/discourse/app/form-kit/components/fk/control/color.gjs@@ -0,0 +1,134 @@+import Component from "@glimmer/component";+import { fn } from "@ember/helper";+import { on } from "@ember/modifier";+import { action } from "@ember/object";+import { htmlSafe } from "@ember/template";+import concatClass from "discourse/helpers/concat-class";+import icon from "discourse/helpers/d-icon";+import {+ isValidHex,+ normalizeHex,+ resolveColor,+} from "discourse/lib/color-transformations";+import { i18n } from "discourse-i18n";++function isColorUsed(usedColors, color) {+ const normalizedColor = color.toUpperCase();+ return usedColors?.some((c) => c.toUpperCase() === normalizedColor);+}++function colorStyle(color) {+ return htmlSafe(`background-color: #${color};`);+}++function colorLabel(usedColors, color) {+ const usedText = isColorUsed(usedColors, color)+ ? ` ${i18n("category.color_used")}`+ : "";+ return `#${color}${usedText}`;+}++export default class FKControlColor extends Component {+ static controlType = "color";++ get showPrefix() {+ return !this.args.allowNamedColors;+ }++ get maxLength() {+ return this.args.allowNamedColors ? null : 6;+ }++ get normalizedValueForPicker() {+ const value = this.args.field.value;+ if (!value) {+ return "#000000";+ }++ if (isValidHex(value)) {+ return `#${normalizeHex(value)}`;+ }++ if (this.args.allowNamedColors) {+ return resolveColor(value) ?? "#000000";+ }++ return "#000000";+ }++ @action+ handleTextInput(event) {+ this.args.field.set(event.target.value);+ }++ @action+ handlePickerInput(event) {+ this.args.field.set(event.target.value.replace(/^#/, ""));+ }++ @action+ handlePaste(event) {+ event.preventDefault();+ const colorCode = event.clipboardData.getData("text/plain") ?? "";+ this.args.field.set(colorCode.replace(/^#/, ""));+ }++ @action+ selectColor(color) {+ this.args.field.set(color);+ }++ <template>+ <div class="form-kit__control-color">+ <div class="form-kit__control-color-input">+ {{#if this.showPrefix}}+ <span class="form-kit__control-color-input-prefix">#</span>+ {{/if}}+ <input+ type="text"+ value={{@field.value}}+ maxlength={{this.maxLength}}+ class="form-kit__control-color-input-hex"+ disabled={{@field.disabled}}+ {{on "input" this.handleTextInput}}+ {{on "paste" this.handlePaste}}+ ...attributes+ />+ <input+ type="color"+ value={{this.normalizedValueForPicker}}+ class="form-kit__control-color-input-picker"+ disabled={{@field.disabled}}+ {{on "input" this.handlePickerInput}}+ />+ </div>++ {{#if @colors}}+ <div class="form-kit__control-color-swatches" role="group">+ {{#each @colors as |color|}}+ <button+ type="button"+ style={{colorStyle color}}+ class={{concatClass+ "form-kit__control-color-swatch"+ (if (isColorUsed @usedColors color) "is-used")+ }}+ title={{if+ (isColorUsed @usedColors color)+ (i18n "category.already_used")+ }}+ aria-label={{colorLabel @usedColors color}}+ data-color={{color}}+ disabled={{@field.disabled}}+ {{on "click" (fn this.selectColor color)}}+ >+ {{#if (isColorUsed @usedColors color)}}+ {{icon "check"}}+ {{/if}}+ </button>+ {{/each}}+ </div>+ {{/if}}+ </div>+ </template>+}diff --git a/frontend/discourse/app/form-kit/components/fk/field.gjs b/frontend/discourse/app/form-kit/components/fk/field.gjsindex 2d999be3bd1..58adeda2d65 100644--- a/frontend/discourse/app/form-kit/components/fk/field.gjs+++ b/frontend/discourse/app/form-kit/components/fk/field.gjs@@ -6,6 +6,7 @@ import curryComponent from "ember-curry-component";import FKControlCalendar from "discourse/form-kit/components/fk/control/calendar";import FKControlCheckbox from "discourse/form-kit/components/fk/control/checkbox";import FKControlCode from "discourse/form-kit/components/fk/control/code";+import FKControlColor from "discourse/form-kit/components/fk/control/color";import FKControlComposer from "discourse/form-kit/components/fk/control/composer";import FKControlCustom from "discourse/form-kit/components/fk/control/custom";import FKControlEmoji from "discourse/form-kit/components/fk/control/emoji";@@ -100,6 +101,7 @@ export default class FKField extends Component {Question=(this.componentFor FKControlQuestion field)Textarea=(this.componentFor FKControlTextarea field)Checkbox=(this.componentFor FKControlCheckbox field)+ Color=(this.componentFor FKControlColor field)Image=(this.componentFor FKControlImage field)Password=(this.componentFor FKControlPassword field)Composer=(this.componentFor FKControlComposer field)diff --git a/frontend/discourse/app/lib/color-transformations.js b/frontend/discourse/app/lib/color-transformations.jsindex acce7a56a08..62f39e4edea 100644--- a/frontend/discourse/app/lib/color-transformations.js+++ b/frontend/discourse/app/lib/color-transformations.js@@ -1,10 +1,21 @@// replicates colors transformations from variables.scss// so we can generate transformed colors from color schemes in JS-// currently only generates primary-low and tertiary-low-// normalize hex color to 6 digits-function normalizeHex(hex) {- hex = hex.replace("#", "");+export function resolveColor(color) {+ if (!color) {+ return null;+ }++ const ctx = document.createElement("canvas").getContext("2d");+ ctx.fillStyle = "#000001"; // Set to something other than black+ ctx.fillStyle = color;++ // If it's still #000001, the color was invalid+ return ctx.fillStyle === "#000001" ? null : ctx.fillStyle;+}++export function normalizeHex(hex) {+ hex = hex.replace(/^#/, "");if (hex.length === 3) {return hex.split("")@@ -14,7 +25,10 @@ function normalizeHex(hex) {return hex;}-// matches dc-color-brightness from variables.scss+export function isValidHex(hex) {+ return hex && /^#?([0-9a-f]{3}|[0-9a-f]{6})$/i.test(hex);+}+function colorBrightness(color) {const hex = normalizeHex(color);const r = parseInt(hex.substring(0, 2), 16);@@ -24,7 +38,6 @@ function colorBrightness(color) {return r * 0.299 + g * 0.587 + b * 0.114;}-// convert RGB to HSLfunction rgbToHsl(r, g, b) {r /= 255;g /= 255;@@ -58,7 +71,6 @@ function rgbToHsl(r, g, b) {return [h, s, l];}-// HSL to RGBfunction hslToRgb(h, s, l) {let r, g, b;@@ -94,14 +106,13 @@ function hslToRgb(h, s, l) {return [Math.round(r * 255), Math.round(g * 255), Math.round(b * 255)];}-// scale color lightness (approximates sass' scale-color)+// approximates sass' scale-colorfunction scaleColorLightness(color, lightness) {const hex = normalizeHex(color);const r = parseInt(hex.substring(0, 2), 16);const g = parseInt(hex.substring(2, 4), 16);const b = parseInt(hex.substring(4, 6), 16);- // convert to HSLconst [h, s, l] = rgbToHsl(r, g, b);// scale lightness similar to sass@@ -151,7 +162,6 @@ export function getPreviewColor(scheme, colorName) {return base;}-// generate CSS custom propertiesexport function getColorSchemeStyles(scheme) {const primaryLow = getPreviewColor(scheme, "primary");const tertiaryLow = getPreviewColor(scheme, "tertiary");diff --git a/frontend/discourse/app/lib/hashtag-decorator.js b/frontend/discourse/app/lib/hashtag-decorator.jsindex f2a8765d788..93ed2add88b 100644--- a/frontend/discourse/app/lib/hashtag-decorator.js+++ b/frontend/discourse/app/lib/hashtag-decorator.js@@ -38,7 +38,7 @@ export function linkSeenHashtagsInContext(return [];}const slugs = [- ...hashtagSpans.map((span) => span.innerText.replace("#", "")),+ ...hashtagSpans.map((span) => span.innerText.replace(/^#/, "")),];hashtagSpans.forEach((hashtagSpan, index) => {diff --git a/frontend/discourse/tests/acceptance/category-new-test.js b/frontend/discourse/tests/acceptance/category-new-test.jsindex 384608125d6..548ad53e213 100644--- a/frontend/discourse/tests/acceptance/category-new-test.js+++ b/frontend/discourse/tests/acceptance/category-new-test.js@@ -5,6 +5,7 @@ import { CATEGORY_TEXT_COLORS } from "discourse/lib/constants";import { cloneJSON } from "discourse/lib/object";import DiscourseURL from "discourse/lib/url";import { fixturesByUrl } from "discourse/tests/helpers/create-pretender";+import formKit from "discourse/tests/helpers/form-kit-helper";import { acceptance } from "discourse/tests/helpers/qunit-helpers";import selectKit from "discourse/tests/helpers/select-kit-helper";import { i18n } from "discourse-i18n";@@ -136,16 +137,20 @@ acceptance("Category text color", function (needs) {test("Category text color is set based on contrast", async function (assert) {await visit("/new-category");- assert- .dom(".edit-text-color .hex-input")- .hasValue(CATEGORY_TEXT_COLORS[0], "has the default text color");+ assert.strictEqual(+ formKit().field("text_color").value(),+ CATEGORY_TEXT_COLORS[0],+ "has the default text color"+ );await fillIn("input.category-name", "testing");- await fillIn(".category-color-editor .hex-input", "EEEEEE");+ await formKit().field("color").fillIn("EEEEEE");- assert- .dom(".edit-text-color .hex-input")- .hasValue(CATEGORY_TEXT_COLORS[1], "sets the contrast text color");+ assert.strictEqual(+ formKit().field("text_color").value(),+ CATEGORY_TEXT_COLORS[1],+ "sets the contrast text color"+ );});});@@ -162,7 +167,7 @@ acceptance("New category preview", function (needs) {assert.strictEqual(previewBadgeColor, "#0088CC");- await fillIn(".hex-input", "FF00FF");+ await formKit().field("color").fillIn("FF00FF");previewBadgeColor = document.querySelector(".category-style .badge-category")diff --git a/frontend/discourse/tests/helpers/form-kit-assertions.js b/frontend/discourse/tests/helpers/form-kit-assertions.jsindex 947179a5f72..4fd1c464c7f 100644--- a/frontend/discourse/tests/helpers/form-kit-assertions.js+++ b/frontend/discourse/tests/helpers/form-kit-assertions.js@@ -94,6 +94,10 @@ class FieldHelper {case "select": {return this.element.querySelector(".form-kit__control-select").value;}+ case "color": {+ return this.element.querySelector(".form-kit__control-color-input-hex")+ .value;+ }case "menu": {return this.element.querySelector(".form-kit__control-menu-trigger").dataset.value;diff --git a/frontend/discourse/tests/helpers/form-kit-helper.js b/frontend/discourse/tests/helpers/form-kit-helper.jsindex 2ad174ad364..9f2befaaa87 100644--- a/frontend/discourse/tests/helpers/form-kit-helper.js+++ b/frontend/discourse/tests/helpers/form-kit-helper.js@@ -36,6 +36,8 @@ class Field {return this.element.querySelector("button");case "select":return this.element.querySelector("select");+ case "color":+ return this.element.querySelector(".form-kit__control-color-input-hex");default:throw new Error(`Unsupported control type: ${this.controlType}`);}@@ -43,8 +45,23 @@ class Field {value() {switch (this.controlType) {- case "input-text":+ case "input-number":return parseInt(this.inputElement.value, 10);+ // String-based controls fall through to return raw value+ case "input-text":+ case "password":+ case "code":+ case "textarea":+ case "composer":+ case "color":+ case "select":+ return this.inputElement.value;+ // Boolean-based controls return checked state+ case "checkbox":+ case "toggle":+ return this.inputElement.checked;+ default:+ throw new Error(`Unsupported control type: ${this.controlType}`);}}@@ -117,6 +134,40 @@ class Field {await fillIn(this.element.querySelector("input[type='time']"), time);}+ isDisabled() {+ return this.inputElement.disabled;+ }++ hasPrefix() {+ if (this.controlType !== "color") {+ throw new Error(`Unsupported control type: ${this.controlType}`);+ }+ return !!this.element.querySelector(+ ".form-kit__control-color-input-prefix"+ );+ }++ get pickerElement() {+ if (this.controlType !== "color") {+ throw new Error(`Unsupported control type: ${this.controlType}`);+ }+ return this.element.querySelector(".form-kit__control-color-input-picker");+ }++ swatches() {+ if (this.controlType !== "color") {+ throw new Error(`Unsupported control type: ${this.controlType}`);+ }+ const swatchElements = this.element.querySelectorAll(+ ".form-kit__control-color-swatch"+ );+ return [...swatchElements].map((swatch) => ({+ color: swatch.dataset.color,+ isUsed: swatch.classList.contains("is-used"),+ isDisabled: swatch.disabled,+ }));+ }+async select(value) {switch (this.element.dataset.controlType) {case "icon":@@ -149,6 +200,14 @@ class Field {);await click(radio);break;+ case "color":+ const swatch = this.element.querySelector(+ `.form-kit__control-color-swatch[data-color="${value.toUpperCase()}"]`+ );+ if (swatch) {+ await click(swatch);+ }+ break;default:throw new Error("Unsupported field type");}diff --git a/frontend/discourse/tests/integration/components/color-input-test.gjs b/frontend/discourse/tests/integration/components/color-input-test.gjsindex 3beff5094e9..0006f3cf429 100644--- a/frontend/discourse/tests/integration/components/color-input-test.gjs+++ b/frontend/discourse/tests/integration/components/color-input-test.gjs@@ -8,7 +8,7 @@ module("Integration | Component | ColorInput", function (hooks) {test("updates hex codes on blur", async function (assert) {let result;- const expandHex = (color) => (result = color.replace("#", ""));+ const expandHex = (color) => (result = color.replace(/^#/, ""));await render(<template><ColorInput @onBlur={{expandHex}} /></template>);diff --git a/frontend/discourse/tests/integration/components/form-kit/controls/color-test.gjs b/frontend/discourse/tests/integration/components/form-kit/controls/color-test.gjsnew file mode 100644index 00000000000..a7f230a146f--- /dev/null+++ b/frontend/discourse/tests/integration/components/form-kit/controls/color-test.gjs@@ -0,0 +1,170 @@+import { render } from "@ember/test-helpers";+import { module, test } from "qunit";+import Form from "discourse/components/form";+import { setupRenderingTest } from "discourse/tests/helpers/component-test";+import formKit from "discourse/tests/helpers/form-kit-helper";++module(+ "Integration | Component | FormKit | Controls | Color",+ function (hooks) {+ setupRenderingTest(hooks);++ test("default", async function (assert) {+ let data = { color: "FF0000" };+ const mutateData = (x) => (data = x);++ await render(+ <template>+ <Form @onSubmit={{mutateData}} @data={{data}} as |form|>+ <form.Field @name="color" @title="Color" as |field|>+ <field.Color />+ </form.Field>+ </Form>+ </template>+ );++ assert.strictEqual(formKit().field("color").value(), "FF0000");++ await formKit().field("color").fillIn("00FF00");+ await formKit().submit();++ assert.strictEqual(data.color, "00FF00");+ });++ test("shows # prefix by default", async function (assert) {+ await render(+ <template>+ <Form as |form|>+ <form.Field @name="color" @title="Color" as |field|>+ <field.Color />+ </form.Field>+ </Form>+ </template>+ );++ assert.true(formKit().field("color").hasPrefix());+ });++ test("hides # prefix when @allowNamedColors is true", async function (assert) {+ await render(+ <template>+ <Form as |form|>+ <form.Field @name="color" @title="Color" as |field|>+ <field.Color @allowNamedColors={{true}} />+ </form.Field>+ </Form>+ </template>+ );++ assert.false(formKit().field("color").hasPrefix());+ });++ test("with predefined colors", async function (assert) {+ const colors = ["FF0000", "00FF00", "0000FF"];+ let data = { color: null };+ const mutateData = (x) => (data = x);++ await render(+ <template>+ <Form @onSubmit={{mutateData}} @data={{data}} as |form|>+ <form.Field @name="color" @title="Color" as |field|>+ <field.Color @colors={{colors}} />+ </form.Field>+ </Form>+ </template>+ );++ const swatches = formKit().field("color").swatches();+ assert.strictEqual(swatches.length, 3);++ await formKit().field("color").select("00FF00");+ await formKit().submit();++ assert.strictEqual(data.color, "00FF00");+ });++ test("marks used colors", async function (assert) {+ const colors = ["FF0000", "00FF00", "0000FF"];+ const usedColors = ["00FF00"];++ await render(+ <template>+ <Form as |form|>+ <form.Field @name="color" @title="Color" as |field|>+ <field.Color @colors={{colors}} @usedColors={{usedColors}} />+ </form.Field>+ </Form>+ </template>+ );++ const swatches = formKit().field("color").swatches();+ assert.false(swatches[0].isUsed);+ assert.true(swatches[1].isUsed);+ assert.false(swatches[2].isUsed);+ });++ test("when disabled", async function (assert) {+ const colors = ["FF0000", "00FF00"];++ await render(+ <template>+ <Form as |form|>+ <form.Field+ @name="color"+ @title="Color"+ @disabled={{true}}+ as |field|+ >+ <field.Color @colors={{colors}} />+ </form.Field>+ </Form>+ </template>+ );++ const field = formKit().field("color");+ assert.true(field.isDisabled());+ assert.true(field.pickerElement.disabled);+ assert.true(field.swatches().every((s) => s.isDisabled));+ });++ test("native color picker updates field", async function (assert) {+ let data = { color: "FF0000" };+ const mutateData = (x) => (data = x);++ await render(+ <template>+ <Form @onSubmit={{mutateData}} @data={{data}} as |form|>+ <form.Field @name="color" @title="Color" as |field|>+ <field.Color />+ </form.Field>+ </Form>+ </template>+ );++ const picker = formKit().field("color").pickerElement;+ picker.value = "#00FF00";+ picker.dispatchEvent(new Event("input", { bubbles: true }));++ await formKit().submit();++ assert.strictEqual(data.color, "00ff00");+ });++ test("picker displays named colors correctly", async function (assert) {+ let data = { color: "purple" };++ await render(+ <template>+ <Form @data={{data}} as |form|>+ <form.Field @name="color" @title="Color" as |field|>+ <field.Color @allowNamedColors={{true}} />+ </form.Field>+ </Form>+ </template>+ );++ const picker = formKit().field("color").pickerElement;+ assert.strictEqual(picker.value, "#800080");+ });+ }+);diff --git a/plugins/styleguide/assets/javascripts/discourse/components/sections/atoms/05-forms.gjs b/plugins/styleguide/assets/javascripts/discourse/components/sections/atoms/05-forms.gjsindex 19f678f2ca1..e694937912d 100644--- a/plugins/styleguide/assets/javascripts/discourse/components/sections/atoms/05-forms.gjs+++ b/plugins/styleguide/assets/javascripts/discourse/components/sections/atoms/05-forms.gjs@@ -200,6 +200,50 @@ export default class Forms extends Component {</template>`;}+ get colorCode() {+ return `import Form from "discourse/components/form";++<template>+ <Form as |form|>+ <form.Field @title="Color" @name="color" as |field|>+ <field.Color placeholder="RRGGBB" />+ </form.Field>+ </Form>+</template>`;+ }++ get colorWithSwatchesCode() {+ return `import { array } from "@ember/helper";+import Form from "discourse/components/form";++const COLORS = ["FF0000", "00FF00", "0000FF", "FFFF00", "FF00FF", "00FFFF"];+const USED_COLORS = ["00FF00"];++<template>+ <Form as |form|>+ <form.Field @title="Color" @name="color" as |field|>+ <field.Color+ @colors={{COLORS}}+ @usedColors={{USED_COLORS}}+ placeholder="RRGGBB"+ />+ </form.Field>+ </Form>+</template>`;+ }++ get colorNamedCode() {+ return `import Form from "discourse/components/form";++<template>+ <Form as |form|>+ <form.Field @title="Color" @name="color" as |field|>+ <field.Color @allowNamedColors={{true}} placeholder="red, FF0000" />+ </form.Field>+ </Form>+</template>`;+ }+get sectionCode() {return `import Form from "discourse/components/form";@@ -516,6 +560,47 @@ import Form from "discourse/components/form";</Form></StyleguideExample>+ <StyleguideExample @title="Color" @code={{this.colorCode}}>+ <Form as |form|>+ <form.Field @title="Color" @name="color" as |field|>+ <field.Color placeholder="RRGGBB" />+ </form.Field>+ </Form>+ </StyleguideExample>++ <StyleguideExample+ @title="Color with swatches"+ @code={{this.colorWithSwatchesCode}}+ >+ <Form as |form|>+ <form.Field @title="Color" @name="color" as |field|>+ <field.Color+ @colors={{array+ "FF0000"+ "00FF00"+ "0000FF"+ "FFFF00"+ "FF00FF"+ "00FFFF"+ }}+ @usedColors={{array "00FF00"}}+ placeholder="RRGGBB"+ />+ </form.Field>+ </Form>+ </StyleguideExample>++ <StyleguideExample+ @title="Color with named colors"+ @code={{this.colorNamedCode}}+ >+ <Form as |form|>+ <form.Field @title="Color" @name="color" as |field|>+ <field.Color @allowNamedColors={{true}} placeholder="red, FF0000" />+ </form.Field>+ </Form>+ </StyleguideExample>+<h2>Layout</h2><StyleguideExample @title="Section" @code={{this.sectionCode}}>diff --git a/spec/system/edit_category_general_spec.rb b/spec/system/edit_category_general_spec.rbindex 764a303ee7e..f2768cc15e1 100644--- a/spec/system/edit_category_general_spec.rb+++ b/spec/system/edit_category_general_spec.rb@@ -11,19 +11,19 @@ describe "Edit Category General", type: :system doit "displays an error when the hex code is invalid" docategory_page.visit_general(category)- form.field("color").component.find("input.hex-input").fill_in(with: "ABZ")+ form.field("color").fill_in("ABZ")category_page.save_settingsexpect(form.field("color")).to have_errors(I18n.t("js.category.color_validations.non_hexdecimal"),)- form.field("color").component.find("input.hex-input").fill_in(with: "")+ form.field("color").fill_in("")category_page.save_settingsexpect(form.field("color")).to have_errors(I18n.t("js.category.color_validations.cant_be_empty"),)- form.field("color").component.find("input.hex-input").fill_in(with: "A")+ form.field("color").fill_in("A")category_page.save_settingsexpect(form.field("color")).to have_errors(I18n.t("js.category.color_validations.incorrect_length"),@@ -33,7 +33,7 @@ describe "Edit Category General", type: :system doit "saves successfully when the hex code is valid" docategory_page.visit_general(category)- form.field("color").component.find("input.hex-input").fill_in(with: "AB1")+ form.field("color").fill_in("AB1")category_page.save_settingsexpect(form.field("color")).to have_no_errorsend@@ -43,19 +43,19 @@ describe "Edit Category General", type: :system doit "displays an error when the hex code is invalid" docategory_page.visit_general(category)- form.field("text_color").component.find("input.hex-input").fill_in(with: "ABZ")+ form.field("text_color").fill_in("ABZ")category_page.save_settingsexpect(form.field("text_color")).to have_errors(I18n.t("js.category.color_validations.non_hexdecimal"),)- form.field("text_color").component.find("input.hex-input").fill_in(with: "")+ form.field("text_color").fill_in("")category_page.save_settingsexpect(form.field("text_color")).to have_errors(I18n.t("js.category.color_validations.cant_be_empty"),)- form.field("text_color").component.find("input.hex-input").fill_in(with: "A")+ form.field("text_color").fill_in("A")category_page.save_settingsexpect(form.field("text_color")).to have_errors(I18n.t("js.category.color_validations.incorrect_length"),@@ -65,7 +65,7 @@ describe "Edit Category General", type: :system doit "saves successfully when the hex code is valid" docategory_page.visit_general(category)- form.field("text_color").component.find("input.hex-input").fill_in(with: "AB1")+ form.field("text_color").fill_in("AB1")category_page.save_settingsexpect(form.field("text_color")).to have_no_errorsenddiff --git a/spec/system/page_objects/components/form_kit.rb b/spec/system/page_objects/components/form_kit.rbindex 80dc89f26fa..32f0d7a2c7b 100644--- a/spec/system/page_objects/components/form_kit.rb+++ b/spec/system/page_objects/components/form_kit.rb@@ -33,6 +33,8 @@ module PageObjectscase control_typewhen /input-/, "password"component.find("input").value+ when "color"+ component.find("input[type='text']").valuewhen "icon", "multi-select"picker = PageObjects::Components::SelectKit.new(component)picker.value@@ -114,6 +116,8 @@ module PageObjectscase control_typewhen "input-text", "password", "input-date", "input-number"component.find("input").fill_in(with: value)+ when "color"+ component.find("input[type='text']").fill_in(with: value)when "textarea", "composer"component.find("textarea").fill_in(with: value, visible: :all)when "code"