🐛 Dont allow hex values without # prefix

This commit is contained in:
Florian Schroedl 2025-02-14 12:50:56 +01:00 committed by Andrés Moya
parent 6cbaacf1e0
commit 6b773d6b74
2 changed files with 35 additions and 6 deletions

View file

@ -9,6 +9,7 @@
(:require (:require
[app.common.colors :as c] [app.common.colors :as c]
[app.common.data :as d] [app.common.data :as d]
[app.common.data.macros :as dm]
[app.common.types.tokens-lib :as ctob] [app.common.types.tokens-lib :as ctob]
[app.main.data.modal :as modal] [app.main.data.modal :as modal]
[app.main.data.tokens :as dt] [app.main.data.tokens :as dt]
@ -321,9 +322,15 @@
on-update-value (mf/use-fn on-update-value (mf/use-fn
(mf/deps on-update-value-debounced) (mf/deps on-update-value-debounced)
(fn [e] (fn [e]
(let [value (dom/get-target-val e)] (let [value (dom/get-target-val e)
(reset! value-ref value) ;; Automatically add # for hex values
(on-update-value-debounced value)))) value' (if (and color? (tinycolor/hex-without-hash-prefix? value))
(let [hex (dm/str "#" value)]
(dom/set-value! (mf/ref-val value-input-ref) hex)
hex)
value)]
(reset! value-ref value')
(on-update-value-debounced value'))))
on-update-color (mf/use-fn on-update-color (mf/use-fn
(mf/deps on-update-value-debounced) (mf/deps on-update-value-debounced)
(fn [hex-value alpha] (fn [hex-value alpha]

View file

@ -4,14 +4,36 @@
This library was chosen as it is already used by StyleDictionary, This library was chosen as it is already used by StyleDictionary,
so there is no extra dependency cost and there was no clojure alternatives with all the necessary features." so there is no extra dependency cost and there was no clojure alternatives with all the necessary features."
(:require (:require
["tinycolor2$default" :as tinycolor])) ["tinycolor2$default" :as tinycolor]
[cuerdas.core :as str]))
(defn tinycolor? [^js x] (defn tinycolor? [^js x]
(and (instance? tinycolor x) (.isValid x))) (and (instance? tinycolor x) (.isValid x)))
(defn valid-color [color-str] (defn hex? [^js tc]
(str/starts-with? (.getFormat tc) "hex"))
(defn valid-color
"Checks if `color-str` is a valid css color."
[color-str]
(let [tc (tinycolor color-str)] (let [tc (tinycolor color-str)]
(when (.isValid tc) tc))) (when (and (.isValid tc)
;; Invalid CSS color strings will return `false` for `.getFormat`
(.getFormat tc)
;; Values like `1111` will still return `hex8` as format which are non-valid css colors,
;; so we reject hex values without a # prefix
(if (hex? tc)
(str/starts-with? (.getOriginalInput tc) "#")
true))
tc)))
(defn hex-without-hash-prefix? [color-str]
(when (not= "#" (first color-str))
(let [tc (tinycolor color-str)]
(str/starts-with? (.getFormat tc) "hex"))))
(defn ->string [^js tc]
(.toString tc))
(defn ->hex-string [^js tc] (defn ->hex-string [^js tc]
(assert (tinycolor? tc)) (assert (tinycolor? tc))