Florian Schrödl 3c4ae62db5
⚡ Resolve tokens incrementally with tokenscript (#12437)
With the tokenscript flag every resolution rebuilt the whole library:
each sidebar render, each propagation and each keystroke in a token
form. The adapter now keeps the interpreter state of the last
resolutions and updates it with set-sets, so only the tokens that
changed and their dependents are re-resolved and converted. Every other
output token stays the same object.

- common/deps.edn moves penpot/tokenscript-interpreter to v0.3.0:
  token readers and writers and a set-sets that looks only into changed
  sets (#1), on top of the DTCG import and export (#4) Penpot already
  uses.
- The sidebar, token propagation, token application and the plugin API
  pass the active sets unmerged (cfo/get-active-token-sets and its
  force variant); the interpreter merges them. The plugin API's own
  resolution cache is gone.
- The adapter hands Penpot's token records to the interpreter with a
  reader (value and DTCG type, an error for a token without a value)
  and a writer (the conversion to :resolved-value or :errors), which
  runs only for the re-resolved names.
- The cache resolves new sets from the last resolution with the same
  set ids, else from one sharing a set id, else from scratch.
- The token form controls resolve the draft in a set of its own on top
  of the library's sets, the selected set last
  (cfo/get-token-sets-for-edit). The form leaves the edited token's old
  name out of them (cfo/without-token). A keystroke re-resolves only
  the draft and its dependents. The last draft is cached apart, so
  typing doesn't evict the sidebar's resolutions. Without the flag the
  controls don't build these sets. The plugin API's token name and
  value setters validate the candidate the same way.
- The token form hint shows resolved font families as a name list.
- Tests cover the unmerged set helpers, a plugin rename to a name below
  the old one (which needs the old name left out), and compare renames,
  with and without updating the references, against StyleDictionary.

Signed-off-by: Florian Schroedl <flo.schroedl@gmail.com>
2026-11-20 13:54:15 +01:00

1478 lines
77 KiB
Clojure

;; 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 SUBSIDIARY SL
(ns frontend-tests.plugins.tokens-test
(:require
[app.common.files.tokens :as cfo]
[app.common.test-helpers.compositions :as ctho]
[app.common.test-helpers.files :as cthf]
[app.common.test-helpers.ids-map :as cthi]
[app.common.test-helpers.tokens :as ctht]
[app.common.types.token :as ctt]
[app.common.types.tokens-lib :as ctob]
[app.common.types.tokens-status :as ctos]
[app.common.uuid :as uuid]
[app.main.data.tokenscript :as ts]
[app.main.data.workspace.shapes :as dwsh]
[app.main.data.workspace.tokens.library-edit :as dwtl]
[app.main.data.workspace.undo :as dwu]
[app.main.store :as st]
[app.plugins.api :as api]
[app.plugins.library :as library]
[app.plugins.register :as r]
[app.plugins.tokens :as ptok]
[app.plugins.utils :as u]
[app.util.object :as obj]
[cljs.test :as t :include-macros true]
[clojure.datafy :refer [datafy]]
[frontend-tests.helpers.async :as async]
[frontend-tests.helpers.mock :as mock]
[frontend-tests.helpers.state :as ths]
[frontend-tests.helpers.wasm :as thw]
[frontend-tests.tokens.helpers.state :as tohs]
[potok.v2.core :as ptk]))
(t/use-fixtures :each
{:before (fn []
(cthi/reset-idmap!)
(thw/setup-wasm-mocks!))
:after thw/teardown-wasm-mocks!})
(def ^:private get-resolved-value @#'ptok/get-resolved-value)
(t/deftest ^:async stroke-property-edits-only-remove-related-token-bindings
(let [tokens {:stroke-color "border.color"
:stroke-width-top "border.top"
:stroke-width-right "border.right"
:stroke-width-bottom "border.bottom"
:stroke-width-left "border.left"}
cases [[0 "strokeWidthTop" 8 #{:stroke-width-top}]
[0 "strokeWidthRight" 8 #{:stroke-width-right}]
[0 "strokeWidthBottom" 8 #{:stroke-width-bottom}]
[0 "strokeWidthLeft" 8 #{:stroke-width-left}]
[0 "strokeWidth" 8 ctt/per-side-stroke-width-keys]
[0 "strokeColor" "#ff0000" #{:stroke-color}]
[0 "strokeOpacity" 0.5 #{:stroke-color}]
[0 "strokeStyle" "dashed" #{}]
[0 "strokeAlignment" "center" #{}]
[1 "strokeWidthTop" 8 #{}]
[1 "strokeWidth" 8 #{}]
[1 "strokeColor" "#ff0000" #{}]]]
(doseq [[index property value removed] cases]
(t/testing (str "stroke " index " property " property)
(let [store (ths/setup-store (cthf/sample-file :file1 :page-label :page1))
_ (set! st/state store)
^js ctx (api/create-context "00000000-0000-0000-0000-000000000000")
^js rect (.createRectangle ctx)
id (obj/get rect "$id")
path [:files (:current-file-id @store) :data :pages-index
(:current-page-id @store) :objects id :applied-tokens]]
(set! (.-strokes rect)
#js [#js {:strokeColor "#000000" :strokeWidth 1 :strokeWidthRight 2}
#js {:strokeColor "#000000" :strokeWidth 1}])
(ptk/emit! store (dwsh/update-shapes [id] #(assoc % :applied-tokens tokens)))
(obj/set! (aget (.-strokes rect) index) property value)
(await (async/settle))
(t/is (= (apply dissoc tokens removed) (get-in @store path)))
(t/is (= value (obj/get (aget (.-strokes rect) index) property))))))))
(t/deftest ^:async stroke-gradient-edits-preserve-width-token-bindings
(let [store (ths/setup-store (cthf/sample-file :file1 :page-label :page1))
_ (set! st/state store)
^js ctx (api/create-context "00000000-0000-0000-0000-000000000000")
^js rect (.createRectangle ctx)
id (obj/get rect "$id")
path [:files (:current-file-id @store) :data :pages-index
(:current-page-id @store) :objects id :applied-tokens]
tokens {:stroke-color "border.color"
:stroke-width-top "border.width"
:stroke-width-right "border.width"
:stroke-width-bottom "border.width"
:stroke-width-left "border.width"}]
(set! (.-strokes rect)
#js [#js {:strokeWidth 1
:strokeColorGradient
#js {:type "linear" :startX 0 :startY 0 :endX 1 :endY 1 :width 1
:stops #js [#js {:color "#000000" :opacity 1 :offset 0}
#js {:color "#ffffff" :opacity 1 :offset 1}]}}])
(ptk/emit! store (dwsh/update-shapes [id] #(assoc % :applied-tokens tokens)))
(let [^js gradient (obj/get (aget (.-strokes rect) 0) "strokeColorGradient")]
(set! (.-startX gradient) 0.5)
(await (async/settle))
(t/is (= (dissoc tokens :stroke-color) (get-in @store path)))
(t/is (= 0.5 (obj/get (obj/get (aget (.-strokes rect) 0) "strokeColorGradient") "startX")))
(ptk/emit! store (dwsh/update-shapes [id] #(assoc % :applied-tokens tokens)))
(obj/set! (aget (.-stops gradient) 0) "color" "#ff0000")
(await (async/settle))
(t/is (= (dissoc tokens :stroke-color) (get-in @store path)))
(t/is (= "#ff0000" (obj/get (aget (obj/get (obj/get (aget (.-strokes rect) 0) "strokeColorGradient") "stops") 0) "color"))))))
(defn- token-source-file
[file-label]
(let [set-id (uuid/next)]
(ctht/sample-file-with-tokens
:file-id file-label
:lib-fn #(-> %
(ctob/add-set (ctob/make-token-set :id set-id :name "Core"))
(ctob/add-theme (ctob/make-token-theme :name "Light"
:group "Mode"
:sets #{"Core"}))
(ctob/add-token set-id (ctob/make-token :name "color.primary"
:type :color
:value "#FF0000")))
:status-fn #(ctos/set-tokens-status % #{} #{set-id}))))
(defn- with-active-theme
"The tokens status of `file` with its first visible theme activated."
[file]
(let [tokens-lib (ctht/get-tokens-lib file)
theme-id (:id (first (remove ctob/hidden-theme? (ctob/get-themes tokens-lib))))]
(cfo/activate-theme (ctht/get-tokens-status file) tokens-lib theme-id)))
(defn- tokens-unchanged?
"True when the token attributes of `file` in the store are the original ones."
[store file]
(let [attrs [:tokens-lib :tokens-status :tokens-source]]
(= (select-keys (:data file) attrs)
(select-keys (get-in @store [:files (:id file) :data]) attrs))))
(defn- record-not-valid
"A `u/not-valid` stub that collects each call into `errors`."
[errors]
(mock/stub (fn [plugin-id code value] (swap! errors conj [plugin-id code value]))))
(t/deftest ^:async library-tokens-source-switches-to-connected-library
(let [file (token-source-file :local)
source (token-source-file :source)
store (ths/setup-store file {:libraries [source]})
^js context (library/library-subcontext (str uuid/zero))
source-proxy (library/library-proxy (str uuid/zero) (:id source))]
(await
(mock/with-mocks* {st/state store st/stream (ptk/input-stream store)}
(t/is (= (str (:id file)) (.. context -tokensSource -id)))
(set! (.-tokensSource context) source-proxy)
(await (async/wait-for-store store #(= (:id source) (get-in @store [:files (:id file) :data :tokens-source]))
"library token source"))
(t/is (= (str (:id source)) (.. context -tokensSource -id)))
(t/is (= (datafy (ctht/get-tokens-status source))
(datafy (get-in @store [:files (:id file) :data :tokens-status]))))
(t/is (= (ctht/get-tokens-lib source) (u/locate-tokens-lib (:id file))))
(t/is (false? (.. context -local -tokens -isEditableTokens)))
(t/is (= (ctht/get-tokens-lib file)
(get-in @store [:files (:id file) :data :tokens-lib])))
(t/is (tokens-unchanged? store source))))))
(t/deftest ^:async library-tokens-source-restores-local-tokens
(let [source (token-source-file :source)
file (-> (token-source-file :local)
(assoc-in [:data :tokens-source] (:id source))
(assoc-in [:data :tokens-status] (with-active-theme source)))
store (ths/setup-store file {:libraries [source]})
^js context (library/library-subcontext (str uuid/zero))]
(await
(mock/with-mocks* {st/state store st/stream (ptk/input-stream store)}
(set! (.-tokensSource context) (.-local context))
(await (async/wait-for-store store #(nil? (get-in @store [:files (:id file) :data :tokens-source]))
"local token source"))
(let [^js catalog (.. context -local -tokens)]
(t/is (= (str (:id file)) (.. context -tokensSource -id)))
(t/is (true? (.-isEditableTokens catalog)))
(t/is (= (ctht/get-tokens-lib file) (u/locate-tokens-lib (:id file))))
(t/is (= #{} (ctos/get-active-set-ids (get-in @store [:files (:id file) :data :tokens-status]))))
(t/is (not-any? #(.-active ^js %) (.-themes catalog))))))))
(t/deftest ^:async library-tokens-source-supports-undo-and-redo
(let [file (token-source-file :local)
source (token-source-file :source)
store (ths/setup-store file {:libraries [source]})
^js context (library/library-subcontext (str uuid/zero))
source-proxy (library/library-proxy (str uuid/zero) (:id source))]
(await
(mock/with-mocks* {st/state store st/stream (ptk/input-stream store)}
(st/emit! (tohs/watch-undo-stack))
(set! (.-tokensSource context) source-proxy)
(await (async/wait-for-store store #(seq (get-in @store [:workspace-undo :items]))
"token source undo entry"))
(st/emit! dwu/undo)
(await (async/wait-for-store store #(nil? (get-in @store [:files (:id file) :data :tokens-source]))
"undo token source"))
(t/is (= (datafy (ctht/get-tokens-status file))
(datafy (get-in @store [:files (:id file) :data :tokens-status]))))
(st/emit! dwu/redo)
(await (async/wait-for-store store #(= (:id source) (get-in @store [:files (:id file) :data :tokens-source]))
"redo token source"))
(t/is (= (datafy (ctht/get-tokens-status source))
(datafy (get-in @store [:files (:id file) :data :tokens-status]))))))))
(t/deftest ^:async library-tokens-source-keeps-status-when-source-is-unchanged
(let [source (token-source-file :source)
file (-> (token-source-file :local)
(assoc-in [:data :tokens-source] (:id source)))
store (ths/setup-store file {:libraries [source]})
^js context (library/library-subcontext (str uuid/zero))
source-proxy (library/library-proxy (str uuid/zero) (:id source))]
(await
(mock/with-mocks* {st/state store st/stream (ptk/input-stream store)}
(set! (.-tokensSource context) source-proxy)
(await (async/settle))
(t/is (tokens-unchanged? store file))))))
(t/deftest ^:async library-tokens-source-rejects-invalid-libraries
(let [file (token-source-file :local)
empty-lib (ctht/sample-file-with-tokens :file-id :empty)
indirect (-> (token-source-file :indirect)
(assoc-in [:data :tokens-source] (uuid/next)))
store (ths/setup-store file {:libraries [empty-lib indirect]})
plugin-id (str uuid/zero)
^js context (library/library-subcontext plugin-id)
errors (atom [])]
(await
(mock/with-mocks* {st/state store
st/stream (ptk/input-stream store)
u/not-valid (record-not-valid errors)}
(doseq [[label value message]
[["not a library" "invalid" "invalid"]
["not connected" (library/library-proxy plugin-id (uuid/next)) "Library is not connected"]
["without own tokens" (library/library-proxy plugin-id (:id empty-lib)) "Library must have its own tokens"]
["with another tokens source" (library/library-proxy plugin-id (:id indirect)) "Library must have its own tokens"]]]
(t/testing label
(reset! errors [])
(set! (.-tokensSource context) value)
(t/is (= [[plugin-id :tokensSource message]] @errors))))
(await (async/settle))
(t/is (tokens-unchanged? store file))))))
(t/deftest ^:async external-catalogs-reject-tokens-changes
(let [source (token-source-file :source)
other (token-source-file :other)
file (-> (token-source-file :local)
(assoc-in [:data :tokens-source] (:id source)))
store (ths/setup-store file {:libraries [source other]})
plugin-id (str uuid/zero)]
(swap! store assoc-in [:plugins :flags plugin-id :throw-validation-errors] true)
(await
(mock/with-mocks* {st/state store st/stream (ptk/input-stream store)}
(doseq [[catalog-label ^js catalog]
[["local catalog" (.. (library/library-subcontext plugin-id) -local -tokens)]
["source catalog" (.. (library/library-subcontext plugin-id) -tokensSource -tokens)]
["other connected catalog" (.-tokens (library/library-proxy plugin-id (:id other)))]]]
(t/testing catalog-label
(let [^js token-set (aget (.-sets catalog) 0)
^js token (aget (.-tokens token-set) 0)
^js theme (aget (.-themes catalog) 0)]
(t/is (false? (.-isEditableTokens catalog)))
(doseq [[label mutate]
[["create set" #(.addSet catalog #js {:name "New"})]
["rename set" #(set! (.-name token-set) "Renamed")]
["duplicate set" #(.duplicate token-set)]
["remove set" #(.remove token-set)]
["create token" #(.addToken token-set #js {:name "color.new" :type "color" :value "#00FF00"})]
["rename token" #(set! (.-name token) "color.renamed")]
["change token value" #(set! (.-value token) "#00FF00")]
["change token description" #(set! (.-description token) "New description")]
["duplicate token" #(.duplicate token)]
["remove token" #(.remove token)]
["create theme" #(.addTheme catalog #js {:name "Dark" :group "Mode"})]
["rename theme" #(set! (.-name theme) "Dark")]
["change theme group" #(set! (.-group theme) "Other")]
["add set to theme" #(.addSet theme token-set)]
["remove set from theme" #(.removeSet theme token-set)]
["duplicate theme" #(.duplicate theme)]
["remove theme" #(.remove theme)]]]
(t/testing label
(t/is (thrown-with-msg? js/Error #"Cannot modify tokens in an external library"
(mutate)))
(await (async/settle))
(t/is (tokens-unchanged? store file))
(t/is (tokens-unchanged? store source))
(t/is (tokens-unchanged? store other)))))))))))
(t/deftest ^:async external-catalogs-reject-status-changes
(let [source (token-source-file :source)
other (token-source-file :other)
file (-> (token-source-file :local)
(assoc-in [:data :tokens-source] (:id source))
(assoc-in [:data :tokens-status] (with-active-theme source)))
store (ths/setup-store file {:libraries [source other]})
plugin-id (str uuid/zero)
message "Cannot change activation through a connected library; use penpot.library.local.tokens"
errors (atom [])]
(await
(mock/with-mocks* {st/state store
st/stream (ptk/input-stream store)
u/not-valid (record-not-valid errors)}
(let [^js context (library/library-subcontext plugin-id)]
(t/is (true? (.-active ^js (aget (.. context -local -tokens -themes) 0))))
(doseq [[catalog-label ^js catalog]
[["source catalog" (.. context -tokensSource -tokens)]
["other connected catalog" (.-tokens (library/library-proxy plugin-id (:id other)))]]]
(t/testing catalog-label
(let [^js token-set (aget (.-sets catalog) 0)
^js theme (aget (.-themes catalog) 0)]
(t/testing "reports the status of its own file"
(t/is (true? (.-active token-set)))
(t/is (false? (.-active theme))))
(reset! errors [])
(set! (.-active token-set) false)
(.toggleActive token-set)
(set! (.-active theme) true)
(.toggleActive theme)
(await (async/settle))
(t/is (= [[plugin-id :active message]
[plugin-id :toggleActive message]
[plugin-id :active message]
[plugin-id :toggleActive message]]
@errors))
(t/is (tokens-unchanged? store file))
(t/is (tokens-unchanged? store source))
(t/is (tokens-unchanged? store other))))))))))
(t/deftest ^:async external-token-source-allows-set-activation
(let [source (token-source-file :source)
file (-> (token-source-file :local)
(assoc-in [:data :tokens-source] (:id source))
(assoc-in [:data :tokens-status] (ctht/get-tokens-status source)))
store (ths/setup-store file {:libraries [source]})]
(await
(mock/with-mocks* {st/state store st/stream (ptk/input-stream store)}
(let [^js catalog (.. (library/library-subcontext (str uuid/zero)) -local -tokens)
^js token-set (aget (.-sets catalog) 0)]
(t/is (true? (.-active token-set)))
(set! (.-active token-set) false)
(await (async/wait-for #(false? (.-active token-set)) "deactivate set"))
(.toggleActive token-set)
(await (async/wait-for #(true? (.-active token-set)) "toggle set"))
(t/is (= (ctht/get-tokens-lib file) (get-in @store [:files (:id file) :data :tokens-lib])))
(t/is (tokens-unchanged? store source)))))))
(t/deftest ^:async external-token-source-allows-theme-activation
(let [source (token-source-file :source)
file (-> (token-source-file :local)
(assoc-in [:data :tokens-source] (:id source))
(assoc-in [:data :tokens-status] (ctht/get-tokens-status source)))
store (ths/setup-store file {:libraries [source]})]
(await
(mock/with-mocks* {st/state store st/stream (ptk/input-stream store)}
(let [^js catalog (.. (library/library-subcontext (str uuid/zero)) -local -tokens)
^js theme (aget (.-themes catalog) 0)]
(t/is (false? (.-active theme)))
(set! (.-active theme) true)
(await (async/wait-for #(true? (.-active theme)) "activate theme"))
(.toggleActive theme)
(await (async/wait-for #(false? (.-active theme)) "toggle theme"))
(t/is (= (ctht/get-tokens-lib file) (get-in @store [:files (:id file) :data :tokens-lib])))
(t/is (tokens-unchanged? store source)))))))
(t/deftest ^:async external-token-source-theme-toggle-supports-undo
(let [source (token-source-file :source)
status (with-active-theme source)
file (-> (token-source-file :local)
(assoc-in [:data :tokens-source] (:id source))
(assoc-in [:data :tokens-status] status))
store (ths/setup-store file {:libraries [source]})]
(await
(mock/with-mocks* {st/state store st/stream (ptk/input-stream store)}
(let [^js catalog (.. (library/library-subcontext (str uuid/zero)) -local -tokens)
^js theme (aget (.-themes catalog) 0)]
(st/emit! (tohs/watch-undo-stack))
(.toggleActive theme)
(await (async/wait-for-store store #(seq (get-in @store [:workspace-undo :items]))
"theme toggle undo entry"))
(t/is (false? (.-active theme)))
(st/emit! dwu/undo)
(await (async/wait-for-store store #(= (datafy status)
(datafy (get-in @store [:files (:id file) :data :tokens-status])))
"undo external theme toggle"))
(t/is (tokens-unchanged? store source)))))))
(t/deftest ^:async external-token-source-allows-applying-tokens-to-shapes
(let [source (token-source-file :source)
file (-> (token-source-file :local)
(assoc-in [:data :tokens-source] (:id source))
(assoc-in [:data :tokens-status] (ctht/get-tokens-status source))
(ctho/add-rect :rect1)
(ctho/add-rect :rect2)
(ctho/add-rect :rect3))
store (ths/setup-store file {:libraries [source]})
page-id (cthf/current-page-id file)]
(swap! store assoc-in [:workspace-local :selected] #{(cthi/id :rect3)})
(await
(mock/with-mocks* {st/state store st/stream (ptk/input-stream store)}
(let [^js context (api/create-context (str uuid/zero))
^js page (.-currentPage context)
^js catalog (.. context -library -local -tokens)
^js token-set (aget (.-sets catalog) 0)
^js token (aget (.-tokens token-set) 0)
^js rect1 (.getShapeById page (str (cthi/id :rect1)))
^js rect2 (.getShapeById page (str (cthi/id :rect2)))]
(.applyToken rect1 token #js ["fill"])
(.applyToShapes token #js [rect2] #js ["fill"])
(.applyToSelected token #js ["fill"])
(doseq [label [:rect1 :rect2 :rect3]]
(let [shape-path [:files (:id file) :data :pages-index page-id :objects (cthi/id label)]]
(await (async/wait-for-store store #(= "color.primary" (get-in @store (conj shape-path :applied-tokens :fill)))
(str "apply external token to " label)))
(await (async/wait-for-store store #(= "#ff0000" (get-in @store (conj shape-path :fills 0 :fill-color)))
(str "resolve external token on " label)))))
(t/is (= (ctht/get-tokens-lib file) (get-in @store [:files (:id file) :data :tokens-lib])))
(t/is (= (datafy (ctht/get-tokens-status file))
(datafy (get-in @store [:files (:id file) :data :tokens-status]))))
(t/is (tokens-unchanged? store source)))))))
(t/deftest ^:async library-tokens-source-requires-content-write-permission
(let [file (token-source-file :local)
source (token-source-file :source)
plugin-id "read-only-plugin"
store (ths/setup-store file {:libraries [source]})
^js context (library/library-subcontext plugin-id)
source-proxy (library/library-proxy plugin-id (:id source))
errors (atom [])]
(await
(mock/with-mocks* {st/state store
st/stream (ptk/input-stream store)
u/not-valid (record-not-valid errors)}
(set! (.-tokensSource context) source-proxy)
(t/is (= [[plugin-id :tokensSource "Plugin doesn't have 'content:write' permission"]] @errors))
(await (async/settle))
(t/is (tokens-unchanged? store file))))))
;; Regression coverage for issue #9162.
;;
;; Plugin code calling `shape.applyToken(token, ["fill"])` or
;; `token.applyToShapes([rect], ["fill"])` from JavaScript supplies a JS
;; array of strings. Penpot's plugin proxies expect a Clojure set of
;; keywords. Two coupled defects made these calls silently no-op (or, with
;; `throwValidationErrors` enabled, throw a "check error"):
;;
;; 1. `token-attr-plugin->token-attr` only consulted its alias map when
;; the input was already a keyword — string inputs like "fill" or
;; "border-radius-top-left" fell through to the identity branch
;; unchanged, so the downstream `cto/token-attr?` predicate (which
;; checks against a set of keywords) returned false.
;; 2. The `applyToken` / `applyToShapes` / `applyToSelected` schemas used
;; plain `[:set ...]`, which does not have a `:decode/json`
;; transformer for the JS array → Clojure set coercion. Penpot's
;; custom `[::sm/set ...]` does. Switching to the registered set type
;; lets the standard JSON decoder pipeline turn the JS argument into
;; a set of strings, after which the `[:and ::sm/keyword [:fn
;; token-attr?]]` element schema coerces each string to a keyword and
;; validates it.
;;
;; These helper-level tests pin the string-friendly conversion contract;
;; the schema-level fix is covered by the existing plugin integration
;; suite that exercises `applyToken` end-to-end.
(t/deftest token-attr-plugin->token-attr-passes-canonical-form-through
;; Both already-canonical short names and unaliased names pass through
;; unchanged.
(t/is (= :fill (ptok/token-attr-plugin->token-attr :fill)))
(t/is (= :stroke-color (ptok/token-attr-plugin->token-attr :stroke-color)))
(t/is (= :r1 (ptok/token-attr-plugin->token-attr :r1)))
(t/is (= :p2 (ptok/token-attr-plugin->token-attr :p2))))
(t/deftest token-attr-plugin->token-attr-resolves-verbose-plugin-aliases
;; Plugin-side verbose names (e.g. `:border-radius-top-left`) map to
;; their canonical short internal form (`:r1`) so plugin authors can
;; spell the corner explicitly without the engine having to know both.
(t/is (= :r1 (ptok/token-attr-plugin->token-attr :border-radius-top-left)))
(t/is (= :r2 (ptok/token-attr-plugin->token-attr :border-radius-top-right)))
(t/is (= :r3 (ptok/token-attr-plugin->token-attr :border-radius-bottom-right)))
(t/is (= :r4 (ptok/token-attr-plugin->token-attr :border-radius-bottom-left))))
(t/deftest token-attr-plugin->token-attr-resolves-padding-margin-side-aliases
(t/is (= :p1 (ptok/token-attr-plugin->token-attr :padding-top)))
(t/is (= :p2 (ptok/token-attr-plugin->token-attr :padding-right)))
(t/is (= :p3 (ptok/token-attr-plugin->token-attr :padding-bottom)))
(t/is (= :p4 (ptok/token-attr-plugin->token-attr :padding-left)))
(t/is (= :m1 (ptok/token-attr-plugin->token-attr :margin-top)))
(t/is (= :m2 (ptok/token-attr-plugin->token-attr :margin-right)))
(t/is (= :m3 (ptok/token-attr-plugin->token-attr :margin-bottom)))
(t/is (= :m4 (ptok/token-attr-plugin->token-attr :margin-left))))
(t/deftest token-attr-plugin->token-attr-resolves-font-family-alias
;; Plugin-facing `fontFamilies` (kebab-cased to `:font-families` by the
;; schema layer) maps to the canonical internal `:font-family`.
(t/is (= :font-family (ptok/token-attr-plugin->token-attr :font-families)))
(t/is (= :font-family (ptok/token-attr-plugin->token-attr "font-families"))))
(t/deftest token-attr->token-attr-plugin-resolves-font-family-alias
;; Symmetric direction: the canonical internal attribute maps to the
;; plural plugin-facing name so applied-token readback serializes as
;; camelCase `fontFamilies`, not the undocumented singular `fontFamily`.
(t/is (= :font-families (ptok/token-attr->token-attr-plugin :font-family))))
(t/deftest token-attr-plugin->token-attr-coerces-string-input
;; This is the actual regression — JS plugin calls supply strings.
(t/is (= :fill (ptok/token-attr-plugin->token-attr "fill")))
(t/is (= :stroke-color (ptok/token-attr-plugin->token-attr "stroke-color")))
;; Verbose plugin aliases work via the string path too.
(t/is (= :r1 (ptok/token-attr-plugin->token-attr "border-radius-top-left")))
(t/is (= :m3 (ptok/token-attr-plugin->token-attr "margin-bottom"))))
(t/deftest token-attr?-accepts-keyword-input
(t/is (true? (boolean (ptok/token-attr? :fill))))
(t/is (true? (boolean (ptok/token-attr? :stroke-color))))
(t/is (true? (boolean (ptok/token-attr? :r1))))
(t/is (true? (boolean (ptok/token-attr? :p2)))))
(t/deftest token-attr?-accepts-string-input
;; Same JS-array-of-strings reproducer as the issue, exercised at the
;; predicate layer the plugin schemas call into.
(t/is (true? (boolean (ptok/token-attr? "fill"))))
(t/is (true? (boolean (ptok/token-attr? "stroke-color"))))
(t/is (true? (boolean (ptok/token-attr? "r1"))))
(t/is (true? (boolean (ptok/token-attr? "m3")))))
(t/deftest token-attr?-accepts-per-side-stroke-width
;; Accepts the uniform width alias and side attributes as keywords or strings.
(t/is (true? (boolean (ptok/token-attr? :stroke-width))))
(t/is (true? (boolean (ptok/token-attr? "stroke-width"))))
(t/is (true? (boolean (ptok/token-attr? :stroke-width-top))))
(t/is (true? (boolean (ptok/token-attr? "stroke-width-left")))))
(t/deftest expand-token-attrs-expands-uniform-stroke-width
(t/testing "the uniform alias becomes the four per-side attributes"
(t/is (= ctt/per-side-stroke-width-keys
(ptok/expand-token-attrs #{:stroke-width})))
(t/is (= ctt/per-side-stroke-width-keys
(ptok/expand-token-attrs #{"stroke-width"}))))
(t/testing "per-side and unrelated attributes pass through unchanged"
(t/is (= #{:stroke-width-top} (ptok/expand-token-attrs #{:stroke-width-top})))
(t/is (= #{:fill} (ptok/expand-token-attrs #{:fill})))
(t/is (= #{} (ptok/expand-token-attrs nil)))))
(t/deftest per-side-stroke-attrs?-distinguishes-sides-from-the-uniform-alias
(t/testing "the uniform alias is not per-side"
(t/is (false? (ptok/per-side-stroke-attrs? #{:stroke-width})))
(t/is (false? (ptok/per-side-stroke-attrs? #{"stroke-width"}))))
(t/testing "each explicit side is per-side, as keyword or string"
(t/is (true? (ptok/per-side-stroke-attrs? #{:stroke-width-top})))
(t/is (true? (ptok/per-side-stroke-attrs? #{:stroke-width-right})))
(t/is (true? (ptok/per-side-stroke-attrs? #{:stroke-width-bottom})))
(t/is (true? (ptok/per-side-stroke-attrs? #{:stroke-width-left})))
(t/is (true? (ptok/per-side-stroke-attrs? #{"stroke-width-left"}))))
(t/testing "unrelated and empty attrs are not per-side"
(t/is (false? (ptok/per-side-stroke-attrs? #{:fill})))
(t/is (false? (ptok/per-side-stroke-attrs? #{})))
(t/is (false? (ptok/per-side-stroke-attrs? nil)))))
(t/deftest shape-apply-token-accepts-padding-top
(t/async
done
(let [set-id (cthi/new-id! :token-set)
token-id (cthi/new-id! :spacing-token)
theme-id (cthi/new-id! :theme)
file (-> (ctht/sample-file-with-tokens
:file-id :file1
:lib-fn #(-> %
(ctob/add-set
(ctob/make-token-set :id set-id
:name "spacing"))
(ctob/add-theme
(ctob/make-token-theme :id theme-id
:name "theme"
:sets #{"spacing"}))
(ctob/add-token
set-id
(ctob/make-token :id token-id
:name "spacing.medium"
:type :spacing
:value "16")))
:status-fn #(ctos/set-tokens-status % #{theme-id} #{set-id}))
(ctho/add-frame :frame1 {:layout :flex}))
store (ths/setup-store file)
_ (set! st/state store)
_ (set! st/stream (ptk/input-stream store))
^js context (api/create-context "00000000-0000-0000-0000-000000000000")
^js page (.-currentPage context)
^js shape (.getShapeById page (str (cthi/id :frame1)))
^js library (.-library context)
^js local (.-local library)
^js catalog (.-tokens local)
^js token-set (.getSetById catalog (str set-id))
^js token (.getTokenById token-set (str token-id))]
(.applyToken shape token #js ["paddingTop"])
(js/setTimeout
(fn []
(let [shape-id (cthi/id :frame1)
page-id (cthf/current-page-id file)]
(t/is (= "spacing.medium" (.. shape -tokens -paddingTop)))
(t/is (= "spacing.medium"
(get-in @store
[:files (:id file) :data :pages-index page-id
:objects shape-id :applied-tokens :p1])))
(done)))
0))))
(t/deftest shape-apply-token-accepts-font-families
(t/async
done
(let [theme-id (cthi/new-id! :token-theme)
set-id (cthi/new-id! :token-set)
token-id (cthi/new-id! :font-family-token)
file (-> (cthf/sample-file :file1 :page-label :page1)
(ctho/add-text :text1 "Hello World!")
(ctht/add-tokens-lib)
(ctht/update-tokens-lib
#(-> %
(ctob/add-set
(ctob/make-token-set :id set-id
:name "fonts"))
(ctob/add-theme
(ctob/make-token-theme :name "theme"
:sets #{"fonts"}))
(ctob/add-token
set-id
(ctob/make-token :id token-id
:name "font.primary"
:type :font-family
:value ["Inter"]))))
(ctht/update-tokens-status
#(ctos/set-tokens-status % #{theme-id} #{set-id})))
store (ths/setup-store file)
_ (set! st/state store)
_ (set! st/stream (ptk/input-stream store))
^js context (api/create-context "00000000-0000-0000-0000-000000000000")
^js page (.-currentPage context)
^js shape (.getShapeById page (str (cthi/id :text1)))
^js library (.-library context)
^js local (.-local library)
^js catalog (.-tokens local)
^js token-set (.getSetById catalog (str set-id))
^js token (.getTokenById token-set (str token-id))]
(.applyToken shape token #js ["fontFamilies"])
(js/setTimeout
(fn []
(let [shape-id (cthi/id :text1)
page-id (cthf/current-page-id file)]
;; Plugin readback exposes the documented plural key.
(t/is (= "font.primary" (.. shape -tokens -fontFamilies)))
;; The undocumented singular spelling must not leak.
(t/is (undefined? (.. shape -tokens -fontFamily)))
;; Internal state keeps the canonical `:font-family` key.
(t/is (= "font.primary"
(get-in @store
[:files (:id file) :data :pages-index page-id
:objects shape-id :applied-tokens :font-family])))
(done)))
0))))
;; Regression coverage for issue #12319.
;;
;; Per-side stroke widths are only supported on boards and rectangles, and the
;; `strokes` setter already rejects them elsewhere. The token path did not:
;; `shape.applyToken` / `token.applyToShapes` / `token.applyToSelected` bound a
;; per-side width token to an ellipse and left the stroke in the per-side state
;; the strokes setter refuses. The token path now rejects the four explicit side
;; properties on unsupported shapes while keeping the uniform `strokeWidth`
;; alias working.
(t/deftest ^:async apply-token-rejects-per-side-stroke-width-on-unsupported-shape
(let [plugin-id "00000000-0000-0000-0000-000000000000"
set-id (cthi/new-id! :token-set)
token-id (cthi/new-id! :stroke-width-token)
theme-id (cthi/new-id! :theme)
file (-> (ctht/sample-file-with-tokens
:file-id :file1
:lib-fn #(-> %
(ctob/add-set
(ctob/make-token-set :id set-id
:name "widths"))
(ctob/add-theme
(ctob/make-token-theme :id theme-id
:name "theme"
:sets #{"widths"}))
(ctob/add-token
set-id
(ctob/make-token :id token-id
:name "width.sm"
:type :stroke-width
:value 10)))
:status-fn #(ctos/set-tokens-status % #{theme-id} #{set-id})))
store (ths/setup-store file)
_ (set! st/state store)
_ (set! st/stream (ptk/input-stream store))
^js context (api/create-context plugin-id)
^js ellipse (.createEllipse context)
id (obj/get ellipse "$id")
^js library (.-library context)
^js local (.-local library)
^js catalog (.-tokens local)
^js token-set (.getSetById catalog (str set-id))
^js token (.getTokenById token-set (str token-id))
path [:files (:id file) :data :pages-index (cthf/current-page-id file)
:objects id :applied-tokens]]
(swap! store assoc-in [:plugins :flags plugin-id :throw-validation-errors] true)
(t/testing "shape.applyToken rejects an explicit per-side width"
(t/is (thrown? js/Error (.applyToken ellipse token #js ["strokeWidthTop"])))
(t/is (nil? (get-in @store path))))
(t/testing "token.applyToShapes rejects an explicit per-side width"
(t/is (thrown? js/Error (.applyToShapes token #js [ellipse] #js ["strokeWidthLeft"])))
(t/is (nil? (get-in @store path))))
(t/testing "token.applyToSelected rejects an explicit per-side width"
(swap! store assoc-in [:workspace-local :selected] #{id})
(t/is (thrown? js/Error (.applyToSelected token #js ["strokeWidthRight"])))
(t/is (nil? (get-in @store path))))
;; The uniform alias stays valid: it expands to the four sides with the same
;; token and resolves to a uniform width, which the strokes setter accepts.
(t/testing "the uniform strokeWidth alias is still accepted"
(.applyToken ellipse token #js ["strokeWidth"])
(await (async/wait-for-store store
#(= "width.sm" (get-in @store (conj path :stroke-width-top)))
"uniform stroke width token applied"))
(t/is (= "width.sm" (get-in @store (conj path :stroke-width-top)))))))
(t/deftest token-attr?-rejects-unknown-input
(t/is (false? (boolean (ptok/token-attr? :not-a-real-attr))))
(t/is (false? (boolean (ptok/token-attr? "not-a-real-attr"))))
(t/is (false? (boolean (ptok/token-attr? nil)))))
;; Regression coverage for issue #10070.
;;
;; The Plugin API's `addToken` rejected reference tokens whose target
;; lives in an *inactive* token set, even though the referenced token
;; exists structurally. The proxy `:fn` resolved the new token against
;; active sets only (`get-tokens-in-active-sets`), so a reference into an
;; inactive set never resolved and fell into the generic `not-valid`
;; error path.
;;
;; The fix resolves against *all* tokens in the library (inactive sets
;; included), mirroring the workspace token-creation form. These tests
;; reproduce the exact `tokens-tree` construction from both the buggy and
;; the fixed `addToken` `:fn` and assert resolution behaviour directly —
;; the proxy `:fn` itself drives the global store and `st/emit!`, so it is
;; not unit-testable, but the resolve step it gates on is.
(defn- inactive-set-library
"A library with `primitives` (holding `color.gray.50`) left inactive and
an active, empty `semantic` set — the repro from the issue."
[]
(-> (ctob/make-tokens-lib)
(ctob/add-set (ctob/make-token-set :id (cthi/new-id! :primitives)
:name "primitives"))
(ctob/add-set (ctob/make-token-set :id (cthi/new-id! :semantic)
:name "semantic"))
(ctob/add-token (cthi/id :primitives)
(ctob/make-token {:name "color.gray.50"
:value "#fafafa"
:type :color}))
;; `add-set` does not activate sets, so activate only `semantic`,
;; leaving `primitives` (the reference target) inactive.
(ctob/toggle-set-in-theme ctob/hidden-theme-id "semantic")))
(t/deftest add-token-active-sets-only-fails-to-resolve-cross-set-reference
;; Demonstrates the bug: resolving the new token against active sets
;; only leaves the reference unresolved.
(let [tokens-lib (inactive-set-library)
tokens-status (cfo/make-tokens-status-from-lib tokens-lib)
token (ctob/make-token {:name "color.bg.default"
:value "{color.gray.50}"
:type :color})
tokens-tree (-> (cfo/get-tokens-in-active-sets tokens-status tokens-lib)
(assoc (:name token) token))
resolved (ts/resolve-tokens tokens-tree)
{:keys [errors resolved-value]} (get resolved (:name token))]
(t/is (nil? resolved-value))
(t/is (seq errors))))
(t/deftest add-token-resolves-cross-set-reference-into-inactive-set
;; The fix: resolving against all tokens in the library (inactive sets
;; included) resolves the reference even though `primitives` is inactive.
(let [tokens-lib (inactive-set-library)
token (ctob/make-token {:name "color.bg.default"
:value "{color.gray.50}"
:type :color})
tokens-tree (-> (merge (ctob/get-all-tokens-map tokens-lib)
(ctob/get-tokens tokens-lib (cthi/id :semantic)))
(assoc (:name token) token))
resolved (ts/resolve-tokens tokens-tree)
{:keys [errors resolved-value]} (get resolved (:name token))]
(t/is (some? resolved-value))
(t/is (empty? errors))))
(t/deftest add-token-still-fails-for-references-missing-from-every-set
;; A reference to a token that exists in *no* set must still fail, even
;; with the all-tokens resolution.
(let [tokens-lib (inactive-set-library)
token (ctob/make-token {:name "color.bg.default"
:value "{color.does.not.exist}"
:type :color})
tokens-tree (-> (merge (ctob/get-all-tokens-map tokens-lib)
(ctob/get-tokens tokens-lib (cthi/id :semantic)))
(assoc (:name token) token))
resolved (ts/resolve-tokens tokens-tree)
{:keys [errors resolved-value]} (get resolved (:name token))]
(t/is (nil? resolved-value))
(t/is (seq errors))))
(t/deftest token-set-duplicate-returns-the-duplicated-set
(let [file-id (cthi/new-id! :file)
set-id (cthi/new-id! :set)
dup-id (cthi/new-id! :dup)]
(with-redefs [u/locate-tokens-lib (constantly nil)
r/check-permission (constantly true)
u/check-editable-tokens (constantly nil)
dwtl/duplicate-token-set
(mock/stub (fn [id {:keys [id-ref]}]
(t/is (= set-id id))
(reset! id-ref dup-id)
:duplicate-token-set))
st/emit! mock/noop]
(let [proxy (ptok/token-set-proxy "plugin-id" file-id set-id)
dup (.duplicate proxy)]
(t/is (ptok/token-set-proxy? dup))
(t/is (= (str dup-id) (.-id dup)))))))
(t/deftest theme-add-set-and-remove-set-use-the-set-name
(let [file-id (cthi/new-id! :file)
theme-id (cthi/new-id! :theme)
set-id (cthi/new-id! :set)
captured (atom [])]
(with-redefs [u/locate-tokens-lib (constantly nil)
r/check-permission (constantly true)
u/check-editable-tokens (constantly nil)
u/locate-token-theme
(fn [_file _theme]
(ctob/make-token-theme :id theme-id
:name "Theme"
:sets #{"Primitives"}))
dwtl/update-token-theme
(fn [id theme]
(swap! captured conj {:id id :theme theme})
:update-token-theme)
st/emit! mock/noop]
(let [set (ptok/token-set-proxy "plugin-id" file-id set-id "Primitives")
theme (ptok/token-theme-proxy "plugin-id" file-id theme-id)]
(.addSet theme set)
(.removeSet theme set)
(t/is (= [theme-id theme-id] (mapv :id @captured)))
(t/is (contains? (-> @captured first :theme :sets) "Primitives"))
(t/is (not (contains? (-> @captured second :theme :sets) "Primitives")))))))
(t/deftest font-family-token-value-accepts-a-string
;; The setter validates the candidate token against the file tokens library,
;; so the token has to live in a real library.
(let [set-id (cthi/new-id! :token-set)
token-id (cthi/new-id! :font-token)
file (-> (cthf/sample-file :file1 :page-label :page1)
(ctht/add-tokens-lib)
(ctht/update-tokens-lib
#(-> %
(ctob/add-set
(ctob/make-token-set :id set-id
:name "fonts"))
(ctob/add-token
set-id
(ctob/make-token :id token-id
:name "font.primary"
:type :font-family
:value ["Inter"])))))
store (ths/setup-store file)
_ (set! st/state store)
_ (set! st/stream (ptk/input-stream store))
file-id (:id file)
captured (atom nil)]
(with-redefs [r/check-permission (constantly true)
u/check-editable-tokens (constantly nil)
dwtl/update-token (mock/stub (fn [set-id token-id attrs]
(reset! captured {:set-id set-id
:token-id token-id
:attrs attrs})
:update-token))
st/emit! mock/noop]
(let [token (ptok/token-proxy "plugin-id" file-id set-id token-id)]
(set! (.-value token) "Inter, Arial")
(t/is (= set-id (:set-id @captured)))
(t/is (= token-id (:token-id @captured)))
(t/is (= ["Inter" "Arial"] (get-in @captured [:attrs :value])))))))
(t/deftest shadow-token-value-round-trips
(let [set-id (cthi/new-id! :token-set)
token-id (cthi/new-id! :shadow-token)
shadow [{:offset-x "1" :offset-y "2" :blur "4" :spread "0" :color "#000000" :inset false}]
file (-> (cthf/sample-file :file1 :page-label :page1)
(ctht/add-tokens-lib)
(ctht/update-tokens-lib
#(-> %
(ctob/add-set
(ctob/make-token-set :id set-id
:name "shadows"))
(ctob/add-token
set-id
(ctob/make-token :id token-id
:name "shadow.card"
:type :shadow
:value shadow)))))
store (ths/setup-store file)
_ (set! st/state store)
_ (set! st/stream (ptk/input-stream store))
file-id (:id file)
captured (atom nil)]
(with-redefs [r/check-permission (constantly true)
u/check-editable-tokens (constantly nil)
dwtl/update-token (mock/stub (fn [_ _ attrs]
(reset! captured attrs)
:update-token))
st/emit! mock/noop]
(let [token (ptok/token-proxy "plugin-id" file-id set-id token-id)]
(set! (.-value token) (.-value token))
(t/is (= shadow (:value @captured)))))))
(t/deftest token-setters-validate-the-candidate-resolution
;; The candidate resolves against the library without the token's
;; current name, so references to it can't validate it.
(let [set-id (cthi/new-id! :token-set)
size-id (cthi/new-id! :size-token)
double-id (cthi/new-id! :double-token)
file (-> (cthf/sample-file :file1 :page-label :page1)
(ctht/add-tokens-lib)
(ctht/update-tokens-lib
#(-> %
(ctob/add-set (ctob/make-token-set :id set-id :name "core"))
(ctob/add-token set-id (ctob/make-token :id size-id :name "size" :type :sizing :value "4"))
(ctob/add-token set-id (ctob/make-token :id double-id :name "double" :type :sizing :value "{size} * 2")))))
store (ths/setup-store file)
_ (set! st/state store)
_ (set! st/stream (ptk/input-stream store))
file-id (:id file)
updates (atom [])
invalid (atom [])]
(with-redefs [r/check-permission (constantly true)
u/check-editable-tokens (constantly nil)
u/not-valid (fn [_ code value] (swap! invalid conj [code value]))
dwtl/update-token (mock/stub (fn [_ _ attrs] (swap! updates conj attrs) {:attrs attrs}))
st/emit! mock/noop]
(let [size (ptok/token-proxy "plugin-id" file-id set-id size-id)
double (ptok/token-proxy "plugin-id" file-id set-id double-id)]
(set! (.-value double) "{size} * 3")
(set! (.-value double) "{missing} * 2")
(set! (.-value double) "{double} * 2")
(set! (.-name size) "space")
(t/is (= [{:value "{size} * 3"} {:name "space"}] @updates))
(t/is (= [[:value "{missing} * 2"] [:value "{double} * 2"]] @invalid))))))
(t/deftest token-name-setter-accepts-a-name-below-the-old-name
;; The candidate resolves without the token's current name: with the
;; old `size` left in, `size.small` would be a token below another
;; token, a name collision.
(let [set-id (cthi/new-id! :token-set)
size-id (cthi/new-id! :size-token)
file (-> (cthf/sample-file :file1 :page-label :page1)
(ctht/add-tokens-lib)
(ctht/update-tokens-lib
#(-> %
(ctob/add-set (ctob/make-token-set :id set-id :name "core"))
(ctob/add-token set-id (ctob/make-token :id size-id :name "size" :type :sizing :value "4")))))
store (ths/setup-store file)
_ (set! st/state store)
_ (set! st/stream (ptk/input-stream store))
file-id (:id file)
updates (atom [])
invalid (atom [])]
(with-redefs [r/check-permission (constantly true)
u/check-editable-tokens (constantly nil)
u/not-valid (fn [_ code value] (swap! invalid conj [code value]))
dwtl/update-token (mock/stub (fn [_ _ attrs] (swap! updates conj attrs) {:attrs attrs}))
st/emit! mock/noop]
(let [size (ptok/token-proxy "plugin-id" file-id set-id size-id)]
(set! (.-name size) "size.small")
(t/is (= [{:name "size.small"}] @updates))
(t/is (= [] @invalid))))))
(t/deftest typography-token-resolved-value-is-plugin-array-shape
(let [token (ctob/make-token
{:name "type.body"
:type :typography
:value {:font-family ["Inter" "Arial"]
:font-size "16px"
:font-weight "600"
:line-height "20px"
:letter-spacing "1"
:text-case "uppercase"
:text-decoration "underline"}})
result (get-resolved-value token [[nil {(:name token) token}]])
entry (aget result 0)]
(t/is (array? result))
(t/is (= ["Inter" "Arial"] (vec (aget entry "fontFamilies"))))
(t/is (= 16 (aget entry "fontSizes")))
(t/is (= "600" (aget entry "fontWeights")))
(t/is (= 20 (aget entry "lineHeight")))
(t/is (= "uppercase" (aget entry "textCase")))
(t/is (= "underline" (aget entry "textDecoration")))))
(t/deftest shadow-token-resolved-value-is-plugin-array-shape
(let [token (ctob/make-token
{:name "shadow.card"
:type :shadow
:value [{:offset-x "1px"
:offset-y "2px"
:blur "3px"
:spread "4px"
:color "#000000"
:inset false}]})
result (get-resolved-value token [[nil {(:name token) token}]])
entry (aget result 0)]
(t/is (array? result))
(t/is (= 1 (aget entry "offsetX")))
(t/is (= 2 (aget entry "offsetY")))
(t/is (= 3 (aget entry "blur")))
(t/is (= 4 (aget entry "spread")))))
(t/deftest font-family-token-resolved-value-is-string-array
(let [token (ctob/make-token
{:name "font.primary"
:type :font-family
:value ["Inter" "Arial"]})
result (get-resolved-value token [[nil {(:name token) token}]])]
(t/is (array? result))
(t/is (= ["Inter" "Arial"] (vec result)))))
(t/deftest font-family-token-resolved-value-keeps-multi-word-families
;; An unquoted family whose name has several words resolves to a list of word
;; symbols, so the family name is the string form of each entry.
(let [token (ctob/make-token
{:name "font.body"
:type :font-family
:value ["Hanken Grotesk" "IBM Plex Mono"]})
result (get-resolved-value token [[nil {(:name token) token}]])]
(t/is (array? result))
(t/is (= ["Hanken Grotesk" "IBM Plex Mono"] (vec result)))))
(t/deftest typography-token-resolved-value-keeps-multi-word-families
(let [token (ctob/make-token
{:name "type.body"
:type :typography
:value {:font-family ["Hanken Grotesk" "Arial"]
:font-size "16px"}})
result (get-resolved-value token [[nil {(:name token) token}]])
entry (aget result 0)]
(t/is (= ["Hanken Grotesk" "Arial"] (vec (aget entry "fontFamilies"))))))
(t/deftest font-family-token-resolved-value-keeps-names-with-expression-words
;; Words like `Red` or `Black` read as colors and `2P` as a number and a word
;; when tokenscript parses the family name.
(let [families ["Red Hat Display" "Crimson Pro" "Archivo Black"
"Press Start 2P" "M PLUS 1p" "Crimson"]
token (ctob/make-token
{:name "font.display"
:type :font-family
:value families})
result (get-resolved-value token [[nil {(:name token) token}]])]
(t/is (= families (vec result)))))
(t/deftest font-family-token-resolved-value-mixes-references-and-names
(let [base (ctob/make-token
{:name "font.base"
:type :font-family
:value ["Red Hat Text"]})
token (ctob/make-token
{:name "font.stack"
:type :font-family
:value ["{font.base}" "Rock 3D"]})
result (get-resolved-value token [[nil {(:name base) base
(:name token) token}]])]
(t/is (= ["Red Hat Text" "Rock 3D"] (vec result)))))
(t/deftest font-family-token-resolved-value-keeps-quoted-names
(let [token (ctob/make-token
{:name "font.quoted"
:type :font-family
:value ["\"Red Hat Mono\"" "'Black Ops One'"]})
result (get-resolved-value token [[nil {(:name token) token}]])]
(t/is (= ["Red Hat Mono" "Black Ops One"] (vec result)))))
(t/deftest typography-token-resolved-value-keeps-names-with-expression-words
(let [token (ctob/make-token
{:name "type.display"
:type :typography
:value {:font-family ["Red Hat Display" "Press Start 2P"]
:font-size "16px"}})
result (get-resolved-value token [[nil {(:name token) token}]])
entry (aget result 0)]
(t/is (= ["Red Hat Display" "Press Start 2P"]
(vec (aget entry "fontFamilies"))))))
(t/deftest token-theme-add-set-accepts-token-set-id
(let [plugin-id "plugin-id"
file-id (uuid/next)
theme-id (uuid/next)
set-id (uuid/next)
token-set (ctob/make-token-set :id set-id :name "Core")
theme (ctob/make-token-theme :id theme-id :group "mode" :name "Light")
emitted (atom [])
invalid (atom [])]
(with-redefs [r/check-permission (constantly true)
u/locate-tokens-lib (constantly nil)
u/locate-token-set (fn [_ id] (when (= id set-id) token-set))
u/locate-token-theme (fn [_ id] (when (= id theme-id) theme))
u/check-editable-tokens (constantly nil)
u/not-valid (fn [_ code value] (swap! invalid conj [code value]))
dwtl/update-token-theme (fn [id theme] {:id id :theme theme})
st/emit! (fn ([event] (swap! emitted conj event) nil)
([event & _] (swap! emitted conj event) nil))]
(let [theme-proxy (ptok/token-theme-proxy plugin-id file-id theme-id)]
(.addSet theme-proxy (str set-id))
(t/is (= #{"Core"} (-> @emitted first :theme :sets)))
(t/is (empty? @invalid))))))
(t/deftest token-theme-add-set-accepts-token-set-proxy
(let [plugin-id "plugin-id"
file-id (uuid/next)
theme-id (uuid/next)
set-id (uuid/next)
token-set (ctob/make-token-set :id set-id :name "Core")
theme (ctob/make-token-theme :id theme-id :group "mode" :name "Light")
emitted (atom [])
invalid (atom [])]
(with-redefs [r/check-permission (constantly true)
u/locate-tokens-lib (constantly nil)
u/locate-token-set (fn [_ id] (when (= id set-id) token-set))
u/locate-token-theme (fn [_ id] (when (= id theme-id) theme))
u/check-editable-tokens (constantly nil)
u/not-valid (fn [_ code value] (swap! invalid conj [code value]))
dwtl/update-token-theme (fn [id theme] {:id id :theme theme})
st/emit! (fn ([event] (swap! emitted conj event) nil)
([event & _] (swap! emitted conj event) nil))]
(let [theme-proxy (ptok/token-theme-proxy plugin-id file-id theme-id)
set-proxy (ptok/token-set-proxy plugin-id file-id set-id "Core")]
(.addSet theme-proxy set-proxy)
(t/is (= #{"Core"} (-> @emitted first :theme :sets)))
(t/is (empty? @invalid))))))
(t/deftest token-theme-add-set-rejects-invalid-arguments
(let [plugin-id "plugin-id"
file-id (uuid/next)
theme-id (uuid/next)
theme (ctob/make-token-theme :id theme-id :group "mode" :name "Light")
emitted (atom [])
invalid (atom [])]
(with-redefs [u/locate-tokens-lib (constantly nil)
u/locate-token-set (constantly nil)
u/throw-validation-errors? (constantly true)
u/locate-token-theme (fn [_ id] (when (= id theme-id) theme))
u/check-editable-tokens (constantly nil)
u/handle-error (fn [plugin-id]
(fn [cause]
(u/not-valid plugin-id :error (str cause))))
dwtl/update-token-theme (fn [id theme] {:id id :theme theme})
st/emit! (fn ([event] (swap! emitted conj event) nil)
([event & _] (swap! emitted conj event) nil))]
(let [theme-proxy (ptok/token-theme-proxy plugin-id file-id theme-id)]
(try (.addSet theme-proxy 42) (catch :default e (swap! invalid conj e)))
(try (.removeSet theme-proxy nil) (catch :default e (swap! invalid conj e)))
(t/is (empty? @emitted))
(t/is (= 2 (count @invalid)))
(t/is (every? #(instance? js/Error %) @invalid))))))
;; ═══════════════════════════════════════════════════════════════
;; Permission check tests (T9-F-01)
;; ═══════════════════════════════════════════════════════════════
;; Note: token-proxy-name-setter-checks-permission test removed because
;; schema validation runs before the permission check, making it impossible
;; to test the permission check directly for setters with schemas.
(t/deftest token-proxy-value-setter-checks-permission
(let [plugin-id "test-plugin"
file-id (uuid/next)
set-id (uuid/next)
token-id (uuid/next)
errors (atom [])]
(with-redefs [u/locate-token (constantly {:id token-id :name "test" :type :color})
u/locate-tokens-lib (constantly nil)
u/not-valid (mock/stub (fn [pid prop msg] (swap! errors conj [pid prop msg])))
r/check-permission (constantly false)
st/emit! mock/noop]
(let [proxy (ptok/token-proxy plugin-id file-id set-id token-id)]
(set! (.-value proxy) "#ff0000")
(t/is (= 1 (count @errors)))
(t/is (= [plugin-id :value "Plugin doesn't have 'content:write' permission"] (first @errors)))))))
(t/deftest token-proxy-description-setter-checks-permission
(let [plugin-id "test-plugin"
file-id (uuid/next)
set-id (uuid/next)
token-id (uuid/next)
errors (atom [])]
(with-redefs [u/locate-token (constantly {:id token-id :name "test"})
u/not-valid (mock/stub (fn [pid prop msg] (swap! errors conj [pid prop msg])))
r/check-permission (constantly false)
st/emit! mock/noop]
(let [proxy (ptok/token-proxy plugin-id file-id set-id token-id)]
(set! (.-description proxy) "A description")
(t/is (= 1 (count @errors)))
(t/is (= [plugin-id :description "Plugin doesn't have 'content:write' permission"] (first @errors)))))))
(t/deftest token-proxy-duplicate-checks-permission
(let [plugin-id "test-plugin"
file-id (uuid/next)
set-id (uuid/next)
token-id (uuid/next)
errors (atom [])]
(with-redefs [u/locate-token (constantly {:id token-id :name "test" :type :color :value "#000"})
u/not-valid (mock/stub (fn [pid prop msg] (swap! errors conj [pid prop msg])))
r/check-permission (constantly false)
st/emit! mock/noop]
(let [proxy (ptok/token-proxy plugin-id file-id set-id token-id)]
(.duplicate proxy)
(t/is (= 1 (count @errors)))
(t/is (= [plugin-id :duplicate "Plugin doesn't have 'content:write' permission"] (first @errors)))))))
(t/deftest token-proxy-remove-checks-permission
(let [plugin-id "test-plugin"
file-id (uuid/next)
set-id (uuid/next)
token-id (uuid/next)
errors (atom [])]
(with-redefs [u/not-valid (mock/stub (fn [pid prop msg] (swap! errors conj [pid prop msg])))
r/check-permission (constantly false)
st/emit! mock/noop]
(let [proxy (ptok/token-proxy plugin-id file-id set-id token-id)]
(.remove proxy)
(t/is (= 1 (count @errors)))
(t/is (= [plugin-id :remove "Plugin doesn't have 'content:write' permission"] (first @errors)))))))
(t/deftest token-set-proxy-name-setter-checks-permission
(let [plugin-id "test-plugin"
file-id (uuid/next)
set-id (uuid/next)
errors (atom [])]
(with-redefs [u/locate-token-set (constantly {:id set-id :name "core"})
u/locate-tokens-lib (constantly (ctob/make-tokens-lib))
u/not-valid (mock/stub (fn [pid prop msg] (swap! errors conj [pid prop msg])))
r/check-permission (constantly false)
st/emit! mock/noop]
(let [proxy (ptok/token-set-proxy plugin-id file-id set-id "core")]
(set! (.-name proxy) "new-core")
(t/is (= 1 (count @errors)))
(t/is (= [plugin-id :name "Plugin doesn't have 'content:write' permission"] (first @errors)))))))
(t/deftest token-set-proxy-active-setter-checks-permission
(let [plugin-id "test-plugin"
file-id (uuid/next)
set-id (uuid/next)
errors (atom [])]
(with-redefs [u/locate-token-set (constantly {:id set-id :name "core"})
u/locate-tokens-lib (constantly (ctob/make-tokens-lib))
u/not-valid (mock/stub (fn [pid prop msg] (swap! errors conj [pid prop msg])))
r/check-permission (constantly false)
st/emit! mock/noop]
(let [proxy (ptok/token-set-proxy plugin-id file-id set-id "core")]
(set! (.-active proxy) true)
(t/is (= 1 (count @errors)))
(t/is (= [plugin-id :active "Plugin doesn't have 'content:write' permission"] (first @errors)))))))
(t/deftest token-set-proxy-toggle-active-checks-permission
(let [plugin-id "test-plugin"
file-id (uuid/next)
set-id (uuid/next)
errors (atom [])]
(with-redefs [u/locate-token-set (constantly {:id set-id :name "core"})
u/locate-tokens-lib (constantly (ctob/make-tokens-lib))
u/not-valid (mock/stub (fn [pid prop msg] (swap! errors conj [pid prop msg])))
r/check-permission (constantly false)
st/emit! mock/noop]
(let [proxy (ptok/token-set-proxy plugin-id file-id set-id "test-plugin")]
(.toggleActive proxy)
(t/is (= 1 (count @errors)))
(t/is (= [plugin-id :toggleActive "Plugin doesn't have 'content:write' permission"] (first @errors)))))))
(t/deftest token-set-proxy-add-token-checks-permission
(let [plugin-id "test-plugin"
file-id (uuid/next)
set-id (uuid/next)
tokens-lib (-> (ctob/make-tokens-lib)
(ctob/add-set (ctob/make-token-set :id set-id :name "core")))
errors (atom [])]
(with-redefs [u/locate-token-set (constantly {:id set-id :name "core"})
u/locate-tokens-lib (constantly tokens-lib)
u/not-valid (mock/stub (fn [pid prop msg] (swap! errors conj [pid prop msg])))
r/check-permission (constantly false)
st/emit! mock/noop]
(let [proxy (ptok/token-set-proxy plugin-id file-id set-id "core")]
(t/is (fn? (.-addToken proxy)))
(.addToken proxy #js {"type" "color" "name" "color.test" "value" "#FF0000"})
(t/is (= 1 (count @errors)))
(t/is (= [plugin-id :addToken "Plugin doesn't have 'content:write' permission"] (first @errors)))))))
(t/deftest token-set-proxy-duplicate-checks-permission
(let [plugin-id "test-plugin"
file-id (uuid/next)
set-id (uuid/next)
errors (atom [])]
(with-redefs [u/not-valid (mock/stub (fn [pid prop msg] (swap! errors conj [pid prop msg])))
r/check-permission (constantly false)
st/emit! mock/noop]
(let [proxy (ptok/token-set-proxy plugin-id file-id set-id)]
(.duplicate proxy)
(t/is (= 1 (count @errors)))
(t/is (= [plugin-id :duplicate "Plugin doesn't have 'content:write' permission"] (first @errors)))))))
(t/deftest token-set-proxy-remove-checks-permission
(let [plugin-id "test-plugin"
file-id (uuid/next)
set-id (uuid/next)
errors (atom [])]
(with-redefs [u/not-valid (mock/stub (fn [pid prop msg] (swap! errors conj [pid prop msg])))
r/check-permission (constantly false)
st/emit! mock/noop]
(let [proxy (ptok/token-set-proxy plugin-id file-id set-id)]
(.remove proxy)
(t/is (= 1 (count @errors)))
(t/is (= [plugin-id :remove "Plugin doesn't have 'content:write' permission"] (first @errors)))))))
(t/deftest token-theme-proxy-group-setter-checks-permission
(let [plugin-id "test-plugin"
file-id (uuid/next)
theme-id (uuid/next)
errors (atom [])]
(with-redefs [u/locate-token-theme (constantly {:id theme-id :name "Light" :group "mode"})
u/locate-tokens-lib (constantly nil)
u/not-valid (mock/stub (fn [pid prop msg] (swap! errors conj [pid prop msg])))
r/check-permission (constantly false)
st/emit! mock/noop]
(let [proxy (ptok/token-theme-proxy plugin-id file-id theme-id)]
(set! (.-group proxy) "new-group")
(t/is (= 1 (count @errors)))
(t/is (= [plugin-id :group "Plugin doesn't have 'content:write' permission"] (first @errors)))))))
(t/deftest token-theme-proxy-name-setter-checks-permission
(let [plugin-id "test-plugin"
file-id (uuid/next)
theme-id (uuid/next)
errors (atom [])]
(with-redefs [u/locate-token-theme (constantly {:id theme-id :name "Light" :group "mode"})
u/locate-tokens-lib (constantly nil)
u/not-valid (mock/stub (fn [pid prop msg] (swap! errors conj [pid prop msg])))
r/check-permission (constantly false)
st/emit! mock/noop]
(let [proxy (ptok/token-theme-proxy plugin-id file-id theme-id)]
(set! (.-name proxy) "Dark")
(t/is (= 1 (count @errors)))
(t/is (= [plugin-id :name "Plugin doesn't have 'content:write' permission"] (first @errors)))))))
(t/deftest token-theme-proxy-active-setter-checks-permission
(let [plugin-id "test-plugin"
file-id (uuid/next)
theme-id (uuid/next)
errors (atom [])]
(with-redefs [u/locate-tokens-lib (constantly (ctob/make-tokens-lib))
u/not-valid (mock/stub (fn [pid prop msg] (swap! errors conj [pid prop msg])))
r/check-permission (constantly false)
st/emit! mock/noop]
(let [proxy (ptok/token-theme-proxy plugin-id file-id theme-id)]
(set! (.-active proxy) true)
(t/is (= 1 (count @errors)))
(t/is (= [plugin-id :active "Plugin doesn't have 'content:write' permission"] (first @errors)))))))
(t/deftest token-theme-proxy-toggle-active-checks-permission
(let [plugin-id "test-plugin"
file-id (uuid/next)
theme-id (uuid/next)
errors (atom [])]
(with-redefs [u/not-valid (mock/stub (fn [pid prop msg] (swap! errors conj [pid prop msg])))
r/check-permission (constantly false)
st/emit! mock/noop]
(let [proxy (ptok/token-theme-proxy plugin-id file-id theme-id)]
(.toggleActive proxy)
(t/is (= 1 (count @errors)))
(t/is (= [plugin-id :toggleActive "Plugin doesn't have 'content:write' permission"] (first @errors)))))))
(t/deftest token-theme-proxy-add-set-checks-permission
(let [plugin-id "test-plugin"
file-id (uuid/next)
theme-id (uuid/next)
set-id (uuid/next)
errors (atom [])]
(with-redefs [u/locate-token-theme (constantly {:id theme-id :name "Light" :sets #{}})
u/locate-token-set (constantly {:id set-id :name "core"})
u/not-valid (mock/stub (fn [pid prop msg] (swap! errors conj [pid prop msg])))
r/check-permission (constantly false)
st/emit! mock/noop]
(let [proxy (ptok/token-theme-proxy plugin-id file-id theme-id)
set-proxy (ptok/token-set-proxy plugin-id file-id set-id "core")]
(.addSet proxy set-proxy)
(t/is (= 1 (count @errors)))
(t/is (= [plugin-id :addSet "Plugin doesn't have 'content:write' permission"] (first @errors)))))))
(t/deftest token-theme-proxy-remove-set-checks-permission
(let [plugin-id "test-plugin"
file-id (uuid/next)
theme-id (uuid/next)
set-id (uuid/next)
errors (atom [])]
(with-redefs [u/locate-token-theme (constantly {:id theme-id :name "Light" :sets #{"core"}})
u/locate-token-set (constantly {:id set-id :name "core"})
u/not-valid (mock/stub (fn [pid prop msg] (swap! errors conj [pid prop msg])))
r/check-permission (constantly false)
st/emit! mock/noop]
(let [proxy (ptok/token-theme-proxy plugin-id file-id theme-id)
set-proxy (ptok/token-set-proxy plugin-id file-id set-id "core")]
(.removeSet proxy set-proxy)
(t/is (= 1 (count @errors)))
(t/is (= [plugin-id :removeSet "Plugin doesn't have 'content:write' permission"] (first @errors)))))))
(t/deftest token-theme-proxy-duplicate-checks-permission
(let [plugin-id "test-plugin"
file-id (uuid/next)
theme-id (uuid/next)
errors (atom [])]
(with-redefs [u/locate-token-theme (constantly {:id theme-id :name "Light" :group "mode"})
u/not-valid (mock/stub (fn [pid prop msg] (swap! errors conj [pid prop msg])))
r/check-permission (constantly false)
st/emit! mock/noop]
(let [proxy (ptok/token-theme-proxy plugin-id file-id theme-id)]
(.duplicate proxy)
(t/is (= 1 (count @errors)))
(t/is (= [plugin-id :duplicate "Plugin doesn't have 'content:write' permission"] (first @errors)))))))
(t/deftest token-theme-proxy-remove-checks-permission
(let [plugin-id "test-plugin"
file-id (uuid/next)
theme-id (uuid/next)
errors (atom [])]
(with-redefs [u/not-valid (mock/stub (fn [pid prop msg] (swap! errors conj [pid prop msg])))
r/check-permission (constantly false)
st/emit! mock/noop]
(let [proxy (ptok/token-theme-proxy plugin-id file-id theme-id)]
(.remove proxy)
(t/is (= 1 (count @errors)))
(t/is (= [plugin-id :remove "Plugin doesn't have 'content:write' permission"] (first @errors)))))))
(t/deftest tokens-catalog-add-theme-checks-permission
(let [plugin-id "test-plugin"
file-id (uuid/next)
errors (atom [])]
(with-redefs [u/locate-tokens-lib (constantly (ctob/make-tokens-lib))
u/not-valid (mock/stub (fn [pid prop msg] (swap! errors conj [pid prop msg])))
r/check-permission (constantly false)
st/emit! mock/noop]
(let [catalog (ptok/tokens-catalog plugin-id file-id)]
(.addTheme catalog #js {"name" "NewTheme" "group" "mode"})
(t/is (= 1 (count @errors)))
(t/is (= [plugin-id :addTheme "Plugin doesn't have 'content:write' permission"] (first @errors)))))))
(t/deftest tokens-catalog-add-set-checks-permission
(let [plugin-id "test-plugin"
file-id (uuid/next)
errors (atom [])]
(with-redefs [u/locate-tokens-lib (constantly (ctob/make-tokens-lib))
u/not-valid (mock/stub (fn [pid prop msg] (swap! errors conj [pid prop msg])))
r/check-permission (constantly false)
st/emit! mock/noop]
(let [catalog (ptok/tokens-catalog plugin-id file-id)]
(.addSet catalog #js {"name" "NewSet"})
(t/is (= 1 (count @errors)))
(t/is (= [plugin-id :addSet "Plugin doesn't have 'content:write' permission"] (first @errors)))))))