0
Fork 0
mirror of https://github.com/penpot/penpot.git synced 2025-01-06 14:50:20 -05:00

Restrict token naming

This commit is contained in:
Florian Schroedl 2024-06-26 16:01:41 +02:00
parent 5c5b378262
commit f9530c5a10
2 changed files with 54 additions and 1 deletions

View file

@ -22,6 +22,30 @@
;; Schemas ---------------------------------------------------------------------
(def valid-token-name-regexp
"Only allow letters and digits for token names.
Also allow one `.` for a namespace separator.
Caution: This will allow a trailing dot like `token-name.`,
But we will trim that in the `finalize-name`,
to not throw too many errors while the user is editing."
#"([a-zA-Z0-9]+\.?)*")
(def valid-token-name-schema
(m/-simple-schema
{:type :token/invalid-token-name
:pred #(re-matches valid-token-name-regexp %)
:type-properties {:error/fn #(str (:value %) " is not a valid token name.
Token names should only contain letters and digits separated by . characters.")}}))
(comment
(m/validate valid-token-name-schema "Hey [1]")
(m/valid? valid-token-name-schema "Hey")
(m/validate valid-token-name-schema "Hey.foo.")
(m/validate valid-token-name-schema "🤣")
(m/validate valid-token-name-schema ".")
nil)
(defn token-name-schema
"Generate a dynamic schema validation to check if a token name already exists.
`existing-token-names` should be a set of strings."
@ -35,6 +59,7 @@
(m/schema
[:and
[:string {:min 1 :max 255}]
valid-token-name-schema
non-existing-token-schema])))
(def token-description-schema
@ -44,7 +69,9 @@
;; Helpers ---------------------------------------------------------------------
(defn finalize-name [name]
(str/trim name))
(-> (str/trim name)
;; Remove trailing dots
(str/replace #"\.+$" "")))
(defn valid-name? [name]
(seq (finalize-name (str name))))

View file

@ -0,0 +1,26 @@
;; This Source Code Form is subject to the terms of the Mozilla Public
;; License, v. 2.0. If a copy of the MPL was not distributed with this
;; file, You can obtain one at http://mozilla.org/MPL/2.0/.
;;
;; Copyright (c) KALEIDOS INC
(ns token-tests.token-form-test
(:require
[app.main.ui.workspace.tokens.form :as wtf]
[cljs.test :as t :include-macros true]
[malli.core :as m]))
(t/deftest test-valid-token-name-schema
;; Allow regular namespace token names
(t/is (some? (m/validate wtf/valid-token-name-schema "Foo")))
(t/is (some? (m/validate wtf/valid-token-name-schema "foo")))
(t/is (some? (m/validate wtf/valid-token-name-schema "FOO")))
(t/is (some? (m/validate wtf/valid-token-name-schema "Foo.Bar.Baz")))
;; Allow trailing tokens
(t/is (nil? (m/validate wtf/valid-token-name-schema "Foo.Bar.Baz....")))
;; Disallow multiple separator dots
(t/is (nil? (m/validate wtf/valid-token-name-schema "Foo..Bar.Baz")))
;; Disallow any special characters
(t/is (nil? (m/validate wtf/valid-token-name-schema "Hey Foo.Bar")))
(t/is (nil? (m/validate wtf/valid-token-name-schema "Hey😈Foo.Bar")))
(t/is (nil? (m/validate wtf/valid-token-name-schema "Hey%Foo.Bar"))))