Merge remote-tracking branch 'origin/staging' into develop

This commit is contained in:
Andrey Antukh 2026-11-24 12:22:16 +01:00
commit 2da9bddd05
35 changed files with 1509 additions and 155 deletions

View File

@ -5,6 +5,7 @@
- The Plugin API is a public facade over internal frontend/common data. Do not expect Plugin API property names, value shapes, or behavior boundaries to match internal CLJS attrs or helper APIs; inspect the relevant proxy and internal code path before using Plugin API observations in production internals or tests.
- `plugins/libs/plugin-types/index.d.ts` contains TypeScript declarations only. Runtime objects are CLJS proxies built under `frontend/src/app/plugins/*.cljs` with `obj/reify`.
- `shape.cljs` builds shape proxies with hidden ids and per-property CLJS implementations. `library.cljs` builds library proxies such as `LibraryComponentProxy`.
- A new or changed proxy member needs its type in `plugins/libs/plugin-types/index.d.ts`, a `plugins/CHANGELOG.md` entry and a Plugin API test suite test: see `mem:plugins/core`.
- `shape.cljs`, `library.cljs`, and related namespaces break circular dependencies with mutable nil vars patched from `app.plugins` at load time. If a proxy constructor appears nil, check the patching path in `frontend/src/app/plugins.cljs`.
## Key Domain Namespaces

View File

@ -3,4 +3,5 @@
- `plugins/README.md` covers local development; `plugins/package.json` defines the commands. For test design see `mem:testing`; for local checks see `mem:scripts/ci`.
- `libs/plugin-types/index.d.ts` declares the public Plugin API; it does not implement it. For Penpot's CLJS proxies, permissions and event behavior, see `mem:frontend/plugin-api-to-cljs-binding`. For sandbox startup and plugin lifetime in `libs/plugins-runtime`, see `mem:plugins/runtime`.
- Update `plugins/CHANGELOG.md` for public type or runtime changes. Label entries with `**plugin-types:**` for declarations and `**plugins-runtime:**` for runtime behavior.
- Every new or changed Plugin API member needs a test in `apps/plugin-api-test-suite/src/tests/` when the suite can reach the case. Read its README first; call the API through `ctx.penpot` or `ctx.penpotMgmt`, tag backend-dependent tests `skipIfMocked`, and rerun `gen:api` plus Prettier on `src/generated/api-surface.json` after changing `libs/plugin-types/index.d.ts`.
- Keep `libs/plugins-styles/styles.css` at the package root. When pnpm links the workspace source instead of the published package, `@penpot/plugin-styles/styles.css` must still resolve to the same styles that `plugins/tools/scripts/build-css.mjs` publishes.

View File

@ -309,13 +309,15 @@
broken (break-frame ctx)
calls (atom 0)
before (repair-count :unrepaired)
out (with-redefs [cfr/repair-file (fn [_ _ _]
(swap! calls inc)
[])]
out (with-redefs [cfr/repair-error (fn [_ _ _ _]
(swap! calls inc)
{:redo-changes []})]
(update-file (:id profile) file-id (:revn broken)
[(set-attr page-id shape-b :name "renamed")]))]
(t/is (not (th/success? out)))
(t/is (= :referential-integrity (:code (ex-data (:error out)))))
;; `calls` counts repairs, one per error; `break-frame` yields a
;; single error, so one call means one pass.
(t/is (= 1 @calls))
(t/is (= 1.0 (- (repair-count :unrepaired) before)))))))

View File

@ -296,7 +296,20 @@
(when head
(println head))
(doseq [line (if trace-length (take trace-length tail) tail)]
(println line)))))))
(println line))))
;; The cause holds the original failure, e.g. the WASM trap behind a
;; `:wasm-error` (`RuntimeError: unreachable`, `Aborted(OOM)`). Its
;; message is printed on its own: only V8 starts `.stack` with it.
(when-let [inner (ex-cause cause)]
(let [message (if (ex-data inner) (ex-message inner) (str inner))]
(println)
(println "Caused by:")
(println "--------------------")
(println (truncate message max-message-length))
(when (or (ex-data inner) (.-stack inner))
(println)
(print (format-throwable inner :trace-length trace-length))))))))
(defn first-line
[s]

View File

@ -523,7 +523,10 @@
mk-undo-change
(fn [undo-changes shape]
(let [prev-sibling (cfh/get-prev-sibling objects (:id shape))]
;; Use the shape as it is in the objects, as the sibling lookup
;; does: the given map may predate earlier moves in these changes
(let [shape (get objects (:id shape) shape)
prev-sibling (cfh/get-prev-sibling objects (:id shape))]
(conj undo-changes
(cond-> {:type :mov-objects
:page-id (::page-id (meta changes))

View File

@ -311,37 +311,49 @@
(defmethod repair-error :ref-shape-not-found
[_ {:keys [shape page-id] :as error} file-data libraries]
(let [lost-main (let [page (ctpl/get-page file-data page-id)]
(find-lost-main file-data (ctn/get-component-shape (:objects page) shape)))
(let [;; An earlier repair of the same pass may have removed the shape, or
;; fixed the reference (e.g. pointed the component back to its main).
current (let [page (ctpl/get-page file-data page-id)]
(get (:objects page) (:id shape)))
matching-shape (let [page (ctpl/get-page file-data page-id)
root-shape (ctn/get-component-shape (:objects page) shape)
component-file (if (= (:component-file root-shape) (:id file-data))
file-data
(-> (get libraries (:component-file root-shape)) :data))
component (when component-file
(ctkl/get-component component-file (:component-id root-shape) true))
component-shapes (ctf/get-component-shapes file-data component)]
ref-shape (when (some? current)
(ctf/find-ref-shape {:id (:id file-data) :data file-data}
(ctpl/get-page file-data page-id) libraries current
:include-deleted? true))
;; Check if the shape points to the remote main. If so, reassign to the near main.
(if-let [near-shape-1 (d/seek #(= (:shape-ref %) (:shape-ref shape)) component-shapes)]
near-shape-1
;; Check if it points to any random shape in the page. If so, try to find a matchng
;; shape in the near main component.
(when-let [random-shape (ctn/get-shape page (:shape-ref shape))]
(if-let [near-shape-2 (d/seek #(= (:id %) (:shape-ref random-shape)) component-shapes)]
near-shape-2
;; If not, check if it's a fostered copy and find a direct main.
(let [head-shape (ctn/get-head-shape (:objects page) shape)
component-file (if (= (:component-file head-shape) (:id file-data))
file-data
(-> (get libraries (:component-file head-shape)) :data))
component (when component-file
(ctkl/get-component component-file (:component-id head-shape) true))
component-shapes (ctf/get-component-shapes file-data component)]
(if-let [near-shape-3 (d/seek #(= (:id %) (:shape-ref random-shape)) component-shapes)]
near-shape-3
nil))))))
lost-main (when (some? current)
(let [page (ctpl/get-page file-data page-id)]
(find-lost-main file-data (ctn/get-component-shape (:objects page) shape))))
matching-shape (when (some? current)
(let [page (ctpl/get-page file-data page-id)
root-shape (ctn/get-component-shape (:objects page) shape)
component-file (if (= (:component-file root-shape) (:id file-data))
file-data
(-> (get libraries (:component-file root-shape)) :data))
component (when component-file
(ctkl/get-component component-file (:component-id root-shape) true))
component-shapes (ctf/get-component-shapes file-data component)]
;; Check if the shape points to the remote main. If so, reassign to the near main.
(if-let [near-shape-1 (d/seek #(= (:shape-ref %) (:shape-ref shape)) component-shapes)]
near-shape-1
;; Check if it points to any random shape in the page. If so, try to find a matchng
;; shape in the near main component.
(when-let [random-shape (ctn/get-shape page (:shape-ref shape))]
(if-let [near-shape-2 (d/seek #(= (:id %) (:shape-ref random-shape)) component-shapes)]
near-shape-2
;; If not, check if it's a fostered copy and find a direct main.
(let [head-shape (ctn/get-head-shape (:objects page) shape)
component-file (if (= (:component-file head-shape) (:id file-data))
file-data
(-> (get libraries (:component-file head-shape)) :data))
component (when component-file
(ctkl/get-component component-file (:component-id head-shape) true))
component-shapes (ctf/get-component-shapes file-data component)]
(if-let [near-shape-3 (d/seek #(= (:id %) (:shape-ref random-shape)) component-shapes)]
near-shape-3
nil)))))))
reassign-shape
(fn [shape]
(log/debug :hint " -> reassign shape-ref to" :shape-ref (:id matching-shape))
@ -357,6 +369,11 @@
;; and link to it. If not, detach the shape.
(log/debug :hint "repairing shape :ref-shape-not-found" :id (:id shape) :name (:name shape) :page-id page-id)
(cond
(or (nil? current) (some? ref-shape))
(do
(log/debug :hint " -> shape removed or ref shape found, nothing to repair")
(pcb/empty-changes nil page-id))
(some? lost-main)
(do
(log/debug :hint " -> assign main-instance-id" :main-instance-id (:id lost-main))
@ -882,19 +899,29 @@
(log/error :hint "Unknown error code, don't know how to repair" :code (:code error))
file)
(defn repair-file
[{:keys [data id] :as file} libraries errors]
(defn- repair-file*
"Repair `errors` in `file`. Return `{:data data' :changes redo-changes}`.
Each repair is built on the data left by the previous ones, so two
repairs that write the same component or shape attribute do not undo
each other. The `:shape` of each error is still the one taken by the
validation."
[{:keys [data id]} libraries errors]
(log/debug :hint "repairing file" :id (str id) :errors (count errors))
(let [{:keys [redo-changes]}
(reduce (fn [changes error]
(pcb/concat-changes changes
(repair-error (:code error)
error
data
libraries)))
(pcb/empty-changes nil)
errors)]
redo-changes))
(reduce (fn [{:keys [data] :as result} error]
(let [{:keys [redo-changes]} (repair-error (:code error) error data libraries)]
(cond-> result
(seq redo-changes)
(-> (assoc :data (cfc/process-changes data redo-changes))
(update :changes into redo-changes)))))
{:data data :changes []}
errors))
(defn repair-file
"Return the redo changes that repair `errors` in `file`. Applied in
order to the file data, they give the repaired data."
[file libraries errors]
(:changes (repair-file* file libraries errors)))
(defn- error-fingerprint
[errors]
@ -938,8 +965,7 @@
:errors (not-empty errors)}
:else
(let [batch (repair-file file libraries errors)
data' (cfc/process-changes (:data file) batch)]
(let [{data' :data batch :changes} (repair-file* file libraries errors)]
(if (= data' (:data file))
{:file file
:changes applied

View File

@ -2995,11 +2995,13 @@
[changes objects shape file page libraries id-new-component
index target-cell keep-props-values ignore-swapped?]
(let [;; When we keep the touched properties, we can't delete the
;; swapped children (we will keep them too)
;; swapped children (we will keep them too). That includes the
;; children swapped in an outer main, above the main of the shape
ignore-swapped-fn
(if ignore-swapped?
#(-> (get objects %)
(ctk/get-swap-slot))
(let [outer-swaps (ctf/get-outer-swaps (ctn/make-container page :page) libraries shape)]
#(or (some? (ctk/get-swap-slot (get objects %)))
(contains? outer-swaps %)))
(constantly false))
;; In the cases where the swapped shape was the first element of the masked group it would make the group to loose the

View File

@ -110,6 +110,33 @@
[[] {}]
shapes))))
(defn- move-to-root-first
"Adds, before all the `changes` of a switch, a move of `shape` to the root,
so it is not deleted with the original copy (its undo, run last, puts it
back once the original copy is restored)."
[changes page shape]
(-> (pcb/empty-changes)
(pcb/with-page page)
(pcb/with-objects (:objects page))
(pcb/change-parent uuid/zero [shape] 0 {:allow-altering-copies true})
(pcb/concat-changes changes)
;; Keep the other keys of the switch changes, as :origin or :undo-group
(merge (dissoc changes :redo-changes :undo-changes))))
(defn- drop-swapped-item
"As part of the keep-touched process on a switch, delete a child on the
original copy that was swapped (orig-swapped-child) and has no related
shape on the new copy."
[changes orig-swapped-child ldata page]
(let [changes (move-to-root-first changes page orig-swapped-child)]
;; These are the page objects with the child moved to the root. The
;; delete replays all the changes on them, so the working objects end
;; as the ones after the switch, for the next steps.
(-> (cls/generate-delete-shapes changes ldata page (pcb/get-objects changes)
(d/ordered-set (:id orig-swapped-child))
{:allow-altering-copies true})
second)))
(defn- keep-swapped-item
"As part of the keep-touched process on a switch, given a child on the original
copy that was swapped (orig-swapped-child), and its related shape on the new copy
@ -120,15 +147,7 @@
orig-swapped-child follows its parent through its constraints and, if the
user didn't move it, takes the place of related-shape-in-new."
[changes related-shape-in-new orig-swapped-child ldata page swap-ref-id]
(let [;; Before to the swap, temporary move the previous
;; shape to the root panel to avoid problems when
;; the previous parent is deleted.
before-changes (-> (pcb/empty-changes)
(pcb/with-page page)
(pcb/with-objects (:objects page))
(pcb/change-parent uuid/zero [orig-swapped-child] 0 {:allow-altering-copies true}))
objects (pcb/get-objects changes)
(let [objects (pcb/get-objects changes)
page-objects (:objects page)
prev-swap-slot (ctk/get-swap-slot orig-swapped-child)
current-parent (get objects (:parent-id related-shape-in-new))
@ -140,7 +159,7 @@
#(gpt/subtract (grc/rect->point (:selrect related-shape-in-new))
(grc/rect->point (:selrect %))))]
(-> (pcb/concat-changes before-changes changes)
(-> (move-to-root-first changes page orig-swapped-child)
;; Move the previous shape to the new parent
(pcb/change-parent (:parent-id related-shape-in-new) [orig-swapped-child] pos {:allow-altering-copies true})
@ -167,8 +186,9 @@
second)))
(defn- child-of-swapped?
"Check if any ancestor of a shape (between base-parent-id and shape) was swapped"
[shape objects base-parent-id]
"Check if any ancestor of a shape (between base-parent-id and shape) was swapped,
in the copy itself or in an outer main (`outer-swaps`, by head id)"
[shape objects base-parent-id outer-swaps]
(let [ancestors (->> (ctn/get-parent-heads objects shape)
;; Ignore ancestors ahead of base-parent
(drop-while #(not= base-parent-id (:id %)))
@ -177,7 +197,29 @@
;; Ignore first and last (base-parent and shape)
ancestors (when (and ancestors (<= 3 num-ancestors))
(subvec (vec ancestors) 1 (dec num-ancestors)))]
(some ctk/get-swap-slot ancestors)))
(some #(or (ctk/get-swap-slot %) (contains? outer-swaps (:id %))) ancestors)))
(defn- repoint-outer-swapped
"A head swapped in an outer main (`orig-head`, `level` levels up its ref chain)
has been moved into the new copy, in the place of `related-shape-in-new`.
Make it and its children point to the swapped component instead of the
outer main, and give the head the slot of `related-shape-in-new`."
[changes page libraries orig-head level related-shape-in-new]
(let [refs (ctf/get-advanced-refs nil (ctn/make-container page :page) libraries
(:id orig-head) level orig-head)]
;; The working objects of `changes` lost the head when the original copy
;; was deleted, so take the shapes from the page
(->> (-> (pcb/empty-changes)
(pcb/with-page page)
(pcb/with-objects (:objects page))
(pcb/update-shapes (keys refs)
(fn [shape]
(let [{:keys [shape-ref touched]} (get refs (:id shape))]
(cond-> (assoc shape :shape-ref shape-ref :touched touched)
(= (:id shape) (:id orig-head))
(ctk/set-swap-slot (:shape-ref related-shape-in-new)))))
{:ignore-touched true}))
(pcb/concat-changes changes))))
(defn- find-shape-ref-child-of
"Get the shape referenced by the shape-ref of the near main of the shape,
@ -218,18 +260,29 @@
container (ctn/make-container page :page)
page-objects (:objects page)
;; Get the touched children of the original-shape
;; The original-shape is in a copy. For the relation rules, we need the referenced
;; shape on the main component
orig-base-ref-shape (ctf/find-remote-shape container libraries original-shape {:with-context? true})
orig-ref-objects (:objects (:container (meta orig-base-ref-shape)))
;; Heads swapped in an outer main (when the original-shape is nested
;; in another copy), with no swap of their own, by id: [level slot]
outer-swaps (ctf/get-outer-swaps container libraries original-shape)
;; Get the touched children of the original-shape, and the ones
;; swapped in an outer main.
;; Ignore children of swapped items, because
;; they will be moved without change when
;; managing their swapped ancestor
orig-touched (->> original-shapes
;; Add to each shape also the touched of its ref chain
(map #(add-touched-from-ref-chain container libraries %))
(filter (comp seq :touched))
(filter #(or (seq (:touched %)) (contains? outer-swaps (:id %))))
(remove
#(child-of-swapped? %
page-objects
(:id original-shape))))
(:id original-shape)
outer-swaps)))
;; Adds a :shape-path attribute to the children of the new-shape,
;; that contains the type of its ancestors and its name
@ -240,11 +293,6 @@
;; Creates a map to quickly find a child of the new-shape by its shape-path
new-shapes-map (into {} (map (juxt :shape-path identity)) new-shapes-w-path)
;; The original-shape is in a copy. For the relation rules, we need the referenced
;; shape on the main component
orig-base-ref-shape (ctf/find-remote-shape container libraries original-shape {:with-context? true})
orig-ref-objects (:objects (:container (meta orig-base-ref-shape)))
;; Adds a :shape-path attribute to the children of the orig-ref-shape,
;; that contains the type of its ancestors and its name
o-ref-shapes-wp (add-unique-path
@ -259,8 +307,10 @@
[changes parents-of-swapped]
(reduce
(fn [[changes parent-of-swapped] orig-child-touched]
(let [;; If the orig-child-touched was swapped, get its swap-slot
swap-slot (ctk/get-swap-slot orig-child-touched)
(let [;; If the orig-child-touched was swapped, get its swap-slot.
;; If it was swapped in an outer main, outer-swap is [level slot]
outer-swap (get outer-swaps (:id orig-child-touched))
swap-slot (or (ctk/get-swap-slot orig-child-touched) (second outer-swap))
;; orig-child-touched is in a copy. Get the referenced shape on the main component
;; If there is a swap slot, we will get the referenced shape in another way
@ -268,8 +318,14 @@
(find-shape-ref-child-of container libraries orig-child-touched (:id orig-base-ref-shape)))
orig-ref-id (if swap-slot
;; If there is a swap slot, find the referenced shape id
(ctf/find-ref-id-for-swapped orig-child-touched container libraries)
;; If there is a swap slot, find the referenced shape id,
;; looking from the match of its parent on the main component
(let [parent (get page-objects (:parent-id orig-child-touched))
parent-head (ctn/get-head-shape page-objects parent)
parent-ref (find-shape-ref-child-of container libraries parent-head
(:id orig-base-ref-shape))]
(when parent-ref
(ctf/find-next-related-swap-shape-id parent-ref swap-slot libraries)))
;; If there is not a swap slot, get the id from the orig-ref-shape
(:id orig-ref-shape))
@ -285,16 +341,30 @@
parent-of-swapped)
;; If there is a related shape, keep its data
changes
(if related-shape-in-new
(cond
(and swap-slot
(nil? related-shape-in-new)
(not= (:id orig-child-touched) (:id original-shape)))
;; The swapped child has no place on the new copy
(drop-swapped-item changes orig-child-touched ldata page)
related-shape-in-new
(if swap-slot
;; If the orig-child-touched was swapped, keep it
(keep-swapped-item changes related-shape-in-new orig-child-touched
ldata page orig-ref-id)
(cond-> (keep-swapped-item changes related-shape-in-new orig-child-touched
ldata page orig-ref-id)
;; If it was swapped in an outer main, point it to the swapped component
(some? outer-swap)
(repoint-outer-swapped page libraries
(get page-objects (:id orig-child-touched))
(first outer-swap) related-shape-in-new))
;; If the orig-child-touched wasn't swapped, copy
;; the touched attributes into it
(cll/update-attrs-on-switch
changes related-shape-in-new orig-child-touched
new-shape original-shape orig-ref-shape container))
:else
changes)]
[changes parents-of-swapped]))
[changes []]

View File

@ -550,7 +550,7 @@
(or (= slot-main slot-inst)
(= (:id shape-main) slot-inst)))))
(defn- find-next-related-swap-shape-id
(defn find-next-related-swap-shape-id
"Go up from the chain of references shapes that will eventually lead to the shape
with swap-slot-id as id. Returns the next shape on the chain"
[parent swap-slot-id libraries]
@ -1311,6 +1311,25 @@
(recur (inc level) ref (:container (meta ref)))
max-levels))))
(defn find-outer-swap
"Returns [level slot] for the first shape in the ref chain of `shape`,
excluding itself, that has been swapped there (level 1 is the ref shape).
Returns nil if the chain ends, or reaches a shape under `base-id`
first, so swaps made inside `base-id` are not returned."
[container libraries shape base-id]
(loop [level 1
current shape
container container]
(when-let [ref (find-ref-shape nil container libraries current
:include-deleted? true
:with-context? true)]
(let [ref-container (:container (meta ref))]
(when-not (->> (cfh/get-parents-with-self (:objects ref-container) (:id ref))
(some #(= base-id (:id %))))
(if-let [slot (ctk/get-swap-slot ref)]
[level slot]
(recur (inc level) ref ref-container)))))))
(defn get-touched-from-ref-chain-until-target-ref
"Returns a set with the :touched of all the items on the shape
ref chain until target-ref, including itself"
@ -1320,4 +1339,47 @@
:always (map :touched)
:always (reduce set/union #{})
remove-slots? (remove ctk/swap-slot?))]
(set/union (or (:touched shape) #{}) (set more-touched))))
(set/union (or (:touched shape) #{}) (set more-touched))))
(defn get-outer-swaps
"Map from id to [level slot] (see `find-outer-swap`) of the nested heads
inside the copy `head`, with no swap slot of their own, that were swapped
in an outer main, above the main of `head`. This happens when `head` is
nested in another copy."
[container libraries head]
(let [base-id (:id (find-remote-shape container libraries head))]
(into {}
(keep (fn [shape]
(when (and (ctk/instance-head? shape)
(nil? (ctk/get-swap-slot shape)))
(when-let [outer-swap (find-outer-swap container libraries shape base-id)]
[(:id shape) outer-swap]))))
(cfh/get-children (:objects container) (:id head)))))
(defn get-advanced-refs
"Map from id to the new :shape-ref and :touched of `shape` and its children,
advanced by `level-delta` levels in the ref chain. A nested head swapped in
one of the levels dropped advances only up to there, as the swap already
points it to the swapped-in main. The swap slots of the chain are removed
only for the head `head-id`. A shape whose ref does not change, or whose
chain cannot be resolved (e.g. a missing library), is left out."
[file container libraries head-id level-delta shape]
(let [level-delta (if (ctk/instance-head? shape)
(get-swap-level container libraries shape level-delta)
level-delta)]
(if (pos? level-delta)
(let [new-shape-ref (advance-shape-ref file container libraries shape level-delta
:include-deleted? true)
refs (if (and (some? new-shape-ref)
(not= new-shape-ref (:shape-ref shape)))
{(:id shape)
{:shape-ref new-shape-ref
:touched (get-touched-from-ref-chain-until-target-ref
container libraries shape new-shape-ref
:remove-slots? (= (:id shape) head-id))}}
{})]
(reduce #(merge %1 (get-advanced-refs file container libraries head-id level-delta
(get (:objects container) %2)))
refs
(:shapes shape)))
{})))

View File

@ -50,6 +50,26 @@
(t/is (some? msg))
(t/is (<= (count msg) (+ ex/max-message-length 16))))))
#?(:cljs
(t/deftest format-throwable-includes-the-cause-test
(let [cause (js/Error. "memory access out of bounds")
out (ex/format-throwable (ex-info "WASM Error (wasm-critical)"
{:type :wasm-error}
cause))]
(t/is (str/includes? out "Caused by:"))
(t/is (str/includes? out "memory access out of bounds")))))
#?(:cljs
(t/deftest format-throwable-includes-a-non-error-cause-test
(let [out (ex/format-throwable (ex-info "outer" {} "Aborted(OOM)"))]
(t/is (str/includes? out "Caused by:"))
(t/is (str/includes? out "Aborted(OOM)")))))
#?(:cljs
(t/deftest format-throwable-omits-the-cause-block-without-a-cause-test
(t/is (not (str/includes? (ex/format-throwable (ex-info "boom" {}))
"Caused by:")))))
#?(:cljs
(t/deftest format-throwable-honors-trace-length-test
(let [full (ex/format-throwable (ex-info "boom" {}))

View File

@ -0,0 +1,46 @@
;; 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 common-tests.files.changes-builder-test
(:require
[app.common.files.changes-builder :as pcb]
[app.common.test-helpers.compositions :as tho]
[app.common.test-helpers.files :as thf]
[app.common.test-helpers.ids-map :as thi]
[app.common.test-helpers.shapes :as ths]
[clojure.test :as t]))
(t/use-fixtures :each thi/test-fixture)
(t/deftest test-change-parent-undo-uses-parent-in-objects
(let [;; ==== Setup
file (-> (thf/sample-file :file1)
(tho/add-frame :parent1)
(tho/add-frame :parent2)
(tho/add-frame :parent3)
(tho/add-rect :rect0 :parent-label :parent1)
(tho/add-rect :rect1 :parent-label :parent1)
(tho/add-rect :rect2 :parent-label :parent1))
page (thf/current-page file)
;; The map of the shape as it is before both moves
rect1 (ths/get-shape file :rect1)
;; ==== Action
changes (-> (pcb/empty-changes nil (:id page))
(pcb/with-objects (:objects page))
(pcb/change-parent (thi/id :parent2) [rect1])
(pcb/change-parent (thi/id :parent3) [rect1]))
file' (thf/apply-changes file changes)
file'' (thf/apply-undo-changes file' changes)]
(t/is (= (thi/id :parent3) (:parent-id (ths/get-shape file' :rect1))))
;; The undo of the second move, run first, takes the shape back to
;; :parent2, where the first move left it, not to the parent in the map
(t/is (= (thi/id :parent2) (:parent-id (first (:undo-changes changes)))))
;; The whole undo puts the shape back in its place in :parent1
(t/is (= (thi/id :parent1) (:parent-id (ths/get-shape file'' :rect1))))
(t/is (= (:shapes (ths/get-shape file :parent1))
(:shapes (ths/get-shape file'' :parent1))))))

View File

@ -171,6 +171,101 @@
(t/is (= "Value2, ValueB" (:variant-name root2'))))))
(t/deftest repair-two-errors-on-one-variant-component-in-one-pass
(t/testing "the properties fix and the variant id fix of the same component both survive one repair pass"
(let [file (-> (thf/sample-file :file1 :page-label :page1)
(thv/add-variant :variant1 :component1 :root1 :component2 :root2)
;; The first child of the container is root2, so component2 sets the
;; property names. Component1 has an extra property and a variant id
;; that does not point to the container.
(thc/update-component :component1 {:variant-id (uuid/next)
:variant-properties [{:name "Property 1" :value "Value1"}
{:name "Extra" :value "x"}]})
(ths/update-shape :root1 :variant-name "Value1, x"))
errors (cfv/validate-file file {})
changes (cfr/repair-file file {} errors)
file' (thf/apply-changes file {:redo-changes changes} :validate? false)
errors' (cfv/validate-file file' {})
comp1' (thc/get-component file' :component1)]
(t/is (= [:invalid-variant-properties :variant-component-bad-id] (mapv :code errors)))
(t/is (nil? errors'))
(t/is (= (thi/id :variant1) (:variant-id comp1')))
(t/is (= [{:name "Property 1" :value "Value1"}] (:variant-properties comp1'))))))
(t/deftest repair-two-errors-on-one-component-in-any-order
(let [stray-id (uuid/next)
file (-> (thf/sample-file :file1 :page-label :page1)
(thv/add-variant :variant1 :component1 :root1 :component2 :root2)
(thc/update-component :component1 {:variant-id (uuid/next)
:objects {stray-id {:id stray-id :type :rect :name "Stray"}}}))
errors (cfv/validate-file file {})]
(t/is (= [:variant-component-bad-id :non-deleted-component-cannot-have-objects]
(mapv :code errors)))
;; Both repairs rewrite the whole component: whichever runs last must
;; keep the fix of the other one.
(doseq [errors [errors (reverse errors)]]
(t/testing (str "both fixes survive with the errors in order " (mapv :code errors))
(let [changes (cfr/repair-file file {} errors)
file' (thf/apply-changes file {:redo-changes changes} :validate? false)
comp1' (thc/get-component file' :component1)]
(t/is (nil? (cfv/validate-file file' {})))
(t/is (not (contains? comp1' :objects)))
(t/is (= (thi/id :variant1) (:variant-id comp1'))))))))
(t/deftest repair-errors-on-shapes-removed-by-an-earlier-repair
(t/testing "repairs on shapes that an earlier repair of the same pass removed change nothing"
(let [file (-> (thf/sample-file :file1 :page-label :page1)
(thv/add-variant :variant1 :component1 :root1 :component2 :root2)
;; A variant that is not a main: its repair removes it with its children
(ths/add-sample-shape :stray :type :frame :parent-label :variant1
:variant-id (thi/id :variant1) :variant-name "Value3")
(ths/add-sample-shape :inner :parent-label :stray)
(ths/update-shape :inner :frame-id (uuid/next)))
errors (cfv/validate-file file {})
removed #{(thi/id :stray) (thi/id :inner)}
later (->> errors
(drop-while #(not= :variant-not-main (:code %)))
(rest))
changes (cfr/repair-file file {} errors)
file' (thf/apply-changes file {:redo-changes changes} :validate? false)
errors' (cfv/validate-file file' {})]
(t/is (some #(= :frame-not-found (:code %)) later))
(t/is (every? #(contains? removed (:shape-id %)) later))
(t/is (nil? errors'))
(t/is (nil? (ths/get-shape file' :stray)))
(t/is (nil? (ths/get-shape file' :inner)))
(t/is (not-any? removed (:shapes (ths/get-shape file' :variant1))))))
;; Guards against a crash, not a lost fix: without the removed-shape check
;; in the :ref-shape-not-found repair, its lookups throw on the removed
;; root1. Removing the variant's main here is the behaviour #13257 tracks;
;; revisit this fixture when that issue changes it.
(t/testing ":ref-shape-not-found on a shape that an earlier repair of the same pass removed"
(let [file (-> (thf/sample-file :file1 :page-label :page1)
(thv/add-variant :variant1 :component1 :root1 :component2 :root2)
(ths/update-shape :root1 :main-instance nil))
errors (cfv/validate-file file {})
result (cfr/repair-file-until-valid
file {}
(fn [file _] (cfv/validate-file file {})))]
(t/is (= [[:variant-not-main (thi/id :root1)]
[:invalid-main-instance (thi/id :root1)]
[:ref-shape-not-found (thi/id :root1)]]
(mapv (juxt :code :shape-id) errors)))
(t/is (= 1 (:iterations result)))
(t/is (nil? (:errors result))))))
(t/deftest repair-variant-not-main
(t/testing "detect and repair a non-main-instance shape inside a variant container"
(let [file (-> (thf/sample-file :file1 :page-label :page1)
@ -530,6 +625,15 @@
(t/is (= uuid/zero (:parent-id shape2')))
(t/is (= #{(thi/id :shape1) (thi/id :shape2)} (set (:shapes root')))))))
(defn- stub-repair-error
"Stand-in for `cfr/repair-error` that returns `(f)` as the redo changes.
Multi-arity on purpose: the JS build calls the multimethod through its
`cljs$core$IFn$_invoke$arity$4` property, which a single-arity fn lacks."
[f]
(fn
([_ _ _ _] {:redo-changes (f)})
([_ _ _ _ & _] {:redo-changes (f)})))
(defn- broken-frame-file
[]
(-> (thf/sample-file :file1 :page-label :page1)
@ -587,7 +691,7 @@
(t/testing "an empty repair batch stops after one iteration"
(let [file (broken-frame-file)
errors (cfv/validate-file file {})]
(with-redefs [cfr/repair-file (fn [_ _ _] [])]
(with-redefs [cfr/repair-error (stub-repair-error (constantly []))]
(let [result (cfr/repair-file-until-valid
file {}
(fn [file _] (cfv/validate-file file {})))]
@ -596,8 +700,8 @@
(t/is (= (mapv :code errors) (mapv :code (:errors result)))))))))
(t/deftest repair-file-until-valid-repairs-several-errors-on-one-shape
(t/testing "three missing children of one frame are all removed although
every pass reports the same [code shape-id]"
(t/testing "three missing children of one frame are all removed in one pass,
although the three errors write the same :shapes attribute"
(let [file (-> (thf/sample-file :file1 :page-label :page1)
(ths/add-sample-shape :frame1 :type :frame)
(ths/update-shape :frame1 :shapes [(uuid/next) (uuid/next) (uuid/next)]))
@ -608,6 +712,7 @@
frame1' (ths/get-shape (:file result) :frame1 :page-label :page1)]
(t/is (= [:child-not-found :child-not-found :child-not-found] (mapv :code errors)))
(t/is (= #{(thi/id :frame1)} (into #{} (map :shape-id) errors)))
(t/is (= 1 (:iterations result)))
(t/is (nil? (:errors result)))
(t/is (nil? (cfv/validate-file (:file result) {})))
(t/is (= [] (:shapes frame1'))))))
@ -618,12 +723,13 @@
shape-id (thi/id :shape1)
page-id (thi/id :page1)
cur-name (:name (ths/get-shape file :shape1 :page-label :page1))]
(with-redefs [cfr/repair-file
(fn [_ _ _]
[{:type :mod-obj
:id shape-id
:page-id page-id
:operations [{:type :set :attr :name :val cur-name}]}])]
(with-redefs [cfr/repair-error
(stub-repair-error
(fn []
[{:type :mod-obj
:id shape-id
:page-id page-id
:operations [{:type :set :attr :name :val cur-name}]}]))]
(let [result (cfr/repair-file-until-valid
file {}
(fn [_ _] [{:code :frame-not-found :shape-id shape-id}])
@ -642,14 +748,15 @@
:shape-id shape-id
:hint "stuck"
:args {:x 1}}]
(with-redefs [cfr/repair-file
(fn [_ _ _]
[{:type :mod-obj
:id shape-id
:page-id page-id
:operations [{:type :set
:attr :name
:val (str "pass-" (swap! pass inc))}]}])]
(with-redefs [cfr/repair-error
(stub-repair-error
(fn []
[{:type :mod-obj
:id shape-id
:page-id page-id
:operations [{:type :set
:attr :name
:val (str "pass-" (swap! pass inc))}]}]))]
(let [result (cfr/repair-file-until-valid
file {}
(fn [_ _] [sticky])
@ -664,14 +771,15 @@
pass (atom 0)
shape-id (thi/id :shape1)
page-id (thi/id :page1)]
(with-redefs [cfr/repair-file
(fn [_ _ _]
[{:type :mod-obj
:id shape-id
:page-id page-id
:operations [{:type :set
:attr :name
:val (str "pass-" (swap! pass inc))}]}])]
(with-redefs [cfr/repair-error
(stub-repair-error
(fn []
[{:type :mod-obj
:id shape-id
:page-id page-id
:operations [{:type :set
:attr :name
:val (str "pass-" (swap! pass inc))}]}]))]
(let [result (cfr/repair-file-until-valid
file {}
(fn [_ _]

View File

@ -12,6 +12,7 @@
[app.common.geom.shapes :as gsh]
[app.common.logic.libraries :as cll]
[app.common.logic.shapes :as cls]
[app.common.logic.variants :as clv]
[app.common.math :as mth]
[app.common.test-helpers.components :as thc]
[app.common.test-helpers.compositions :as tho]
@ -21,6 +22,7 @@
[app.common.test-helpers.variants :as thv]
[app.common.types.component :as ctk]
[app.common.types.modifiers :as ctm]
[app.common.uuid :as uuid]
[clojure.set :as set]
[clojure.string :as string]
[clojure.test :as t]))
@ -1562,6 +1564,506 @@
;; The width of copy-cp02-rect' is 25 (change is preserved)
(t/is (= (:width copy-cp02-rect') 25))))
(defn- switch-with-changes
"Switches the copy `shape-tag` to the variant `component-tag` keeping the
touched changes, as `tho/swap-component-in-shape` does, and returns the new
file and the changes."
[file shape-tag component-tag]
(let [page (thf/current-page file)
shape (ths/get-shape file shape-tag)
libraries {(:id file) file}
orig-shapes (cfh/get-children-with-self (:objects page) (:id shape))
[new-shape _ changes]
(cll/generate-component-swap (pcb/empty-changes)
(:objects page)
shape
(:data file)
page
libraries
(:id (thc/get-component file component-tag))
0
nil
(select-keys shape ctk/swap-keep-attrs)
true)
[changes _] (clv/generate-keep-touched changes new-shape shape orig-shapes
page libraries (:data file))]
[(thf/apply-changes file changes) changes]))
(defn- check-switch-undone
"Undoes the switch `changes` on `file'` and checks that every shape of the
copy `shape-tag` is as it was in `file`, and that a redo gives `file'`
again."
[file file' changes shape-tag]
(let [file'' (thf/apply-undo-changes file' changes)
file''' (thf/apply-changes file'' changes)
objects (:objects (thf/current-page file))
objects'' (:objects (thf/current-page file''))]
(doseq [shape (cfh/get-children-with-self objects (thi/id shape-tag))]
(t/is (= shape (get objects'' (:id shape)))))
(t/is (= (:objects (thf/current-page file'))
(:objects (thf/current-page file'''))))))
(defn- setup-copy-with-swapped-child
"Variants `:c01` / `:c02` holding a copy of `:external01`, and a copy
`:copy01` of `:c01` whose `:external01` copy is swapped for `:external02`
(labelled `:copy-cp02`)."
[]
(-> (thf/sample-file :file1)
(tho/add-simple-component :external01 :external01-root :external01-child)
(tho/add-simple-component :external02 :external02-root :external02-child)
(thv/add-variant-with-copy :v01 :c01 :m01 :c02 :m02 :cp01 :cp02 :external01)
(thc/instantiate-component :c01 :copy01 :children-labels [:copy-cp01])
(tho/swap-component-in-shape :copy-cp01 :external02 {:new-shape-label :copy-cp02
:keep-touched? false})))
(t/deftest test-switch-variant-undo-keeps-swapped-child
(let [;; ==== Setup
file (setup-copy-with-swapped-child)
;; ==== Action
[file' changes] (switch-with-changes file :copy01 :c02)]
;; The new variant copy keeps the swapped child
(t/is (= (:shapes (ths/get-shape file' :copy01)) [(thi/id :copy-cp02)]))
;; Undo restores the old variant copy with the swapped child
(check-switch-undone file file' changes :copy01)))
(t/deftest test-switch-variant-undo-keeps-swapped-child-without-match
(let [;; ==== Setup
file (-> (setup-copy-with-swapped-child)
;; The :external01 copy in :c02 gets another name, so
;; the swapped child has no related shape in :c02
(tho/change-shape :cp02 #(assoc % :name "Other child")))
;; ==== Action
[file' changes] (switch-with-changes file :copy01 :c02)]
;; The swapped child is removed, and nothing is left on the root
(t/is (nil? (ths/get-shape-by-id file' (thi/id :copy-cp02))))
(t/is (= (set (:shapes (ths/get-shape-by-id file uuid/zero)))
(set (:shapes (ths/get-shape-by-id file' uuid/zero)))))
;; Undo restores the old variant copy with the swapped child
(check-switch-undone file file' changes :copy01)))
(defn- label-child-by-name
"Gives the label `label` to the child named `child-name` of the shape
`parent-tag`."
[file parent-tag child-name label]
(let [child (->> (:shapes (ths/get-shape file parent-tag))
(map #(ths/get-shape-by-id file %))
(filter #(= child-name (:name %)))
first)]
(assert child (str "no child named " child-name))
(thi/set-id! label (:id child))
file))
(t/deftest test-switch-variant-undo-keeps-kept-and-dropped-swapped-children
(let [;; ==== Setup
file (-> (thf/sample-file :file1)
(tho/add-simple-component :external01 :external01-root :external01-child)
(tho/add-simple-component :external02 :external02-root :external02-child)
(thv/add-variant-with-copy :v01 :c01 :m01 :c02 :m02 :cp01 :cp02 :external01)
;; A second :external01 copy in each variant, with other
;; names, so the one in :c01 has no related shape in :c02
(thc/instantiate-component :external01 :second-in-m01 :parent-label :m01)
(thc/instantiate-component :external01 :second-in-m02 :parent-label :m02)
(tho/change-shape :cp01 #(assoc % :name "First child"))
(tho/change-shape :cp02 #(assoc % :name "First child"))
(tho/change-shape :second-in-m01 #(assoc % :name "Second child"))
(tho/change-shape :second-in-m02 #(assoc % :name "Other child"))
(thc/instantiate-component :c01 :copy01)
(label-child-by-name :copy01 "First child" :first-in-copy)
(label-child-by-name :copy01 "Second child" :second-in-copy)
(tho/swap-component-in-shape :first-in-copy :external02
{:new-shape-label :first-swapped
:keep-touched? false})
(tho/swap-component-in-shape :second-in-copy :external02
{:new-shape-label :second-swapped
:keep-touched? false}))
;; ==== Action
[file' changes] (switch-with-changes file :copy01 :c02)
copy01' (ths/get-shape file' :copy01)]
;; The swaps put each new child first, so the one to be removed comes
;; first in the copy, and the switch processes it before the kept one
(t/is (= [(thi/id :second-swapped) (thi/id :first-swapped)]
(:shapes (ths/get-shape file :copy01))))
;; The first swapped child is kept, in the place of the first child of
;; :c02, and the second one is removed
(t/is (= 2 (count (:shapes copy01'))))
(t/is (= (thi/id :first-swapped) (first (:shapes copy01'))))
(t/is (nil? (ths/get-shape-by-id file' (thi/id :second-swapped))))
;; Undo restores the old variant copy with both swapped children
(check-switch-undone file file' changes :copy01)))
(defn- swap-at-index
"Swaps the shape `shape-tag` for a copy of `component-tag` in the same
place of its parent, as the workspace does (`tho/swap-component-in-shape`
puts it first). The new copy keeps the id, and so the label, of the shape."
[file shape-tag component-tag]
(let [page (thf/current-page file)
shape (ths/get-shape file shape-tag)
parent (get (:objects page) (:parent-id shape))
index (first (keep-indexed #(when (= %2 (:id shape)) %1) (:shapes parent)))
[_ _ changes] (cll/generate-component-swap (pcb/empty-changes)
(:objects page)
shape
(:data file)
page
{(:id file) file}
(:id (thc/get-component file component-tag))
index
nil
(select-keys shape ctk/swap-keep-attrs)
false)]
(thf/apply-changes file changes)))
(t/deftest test-switch-variant-undo-keeps-order-of-kept-and-dropped-swapped-children
(let [;; ==== Setup
file (-> (thf/sample-file :file1)
(tho/add-simple-component :external01 :external01-root :external01-child)
(tho/add-simple-component :external02 :external02-root :external02-child)
(thv/add-variant-with-copy :v01 :c01 :m01 :c02 :m02 :cp01 :cp02 :external01)
;; :c01 holds a plain child, then one with no related
;; shape in :c02, then one that matches the second
;; child of :c02
(thc/instantiate-component :external01 :second-in-m01 :parent-label :m01)
(thc/instantiate-component :external01 :third-in-m01 :parent-label :m01)
(thc/instantiate-component :external01 :second-in-m02 :parent-label :m02)
(tho/change-shape :cp01 #(assoc % :name "Plain child"))
(tho/change-shape :second-in-m01 #(assoc % :name "Dropped child"))
(tho/change-shape :third-in-m01 #(assoc % :name "Kept child"))
(tho/change-shape :cp02 #(assoc % :name "Plain child"))
(tho/change-shape :second-in-m02 #(assoc % :name "Kept child"))
(thc/instantiate-component :c01 :copy01)
(label-child-by-name :copy01 "Plain child" :plain-in-copy)
(label-child-by-name :copy01 "Dropped child" :dropped-in-copy)
(label-child-by-name :copy01 "Kept child" :kept-in-copy)
(swap-at-index :dropped-in-copy :external02)
(swap-at-index :kept-in-copy :external02))
;; ==== Action
[file' changes] (switch-with-changes file :copy01 :c02)
copy01' (ths/get-shape file' :copy01)]
;; The swapped children keep their place in the copy
(t/is (= [(thi/id :plain-in-copy) (thi/id :dropped-in-copy) (thi/id :kept-in-copy)]
(:shapes (ths/get-shape file :copy01))))
;; The kept child takes the place of the second child of :c02, and the
;; other swapped child is removed
(t/is (= 2 (count (:shapes copy01'))))
(t/is (= (thi/id :kept-in-copy) (second (:shapes copy01'))))
(t/is (nil? (ths/get-shape-by-id file' (thi/id :dropped-in-copy))))
;; Undo restores the old variant copy, with its children in their order
(check-switch-undone file file' changes :copy01)))
(t/deftest test-nested-switch-in-copy-twice-keeps-copy
(let [;; ==== Setup
file (-> (thf/sample-file :file1)
(thv/add-variant :v01 :c01 :m01 :c02 :m02)
(tho/add-frame :m03)
(thc/instantiate-component :c01 :nested01 :parent-label :m03)
(thc/make-component :c03 :m03)
(thc/instantiate-component :c03 :nested02 :children-labels [:child01])
;; After this switch the copy has a swap slot
(tho/swap-component-in-shape :child01 :c02 {:keep-touched? true}))
c01 (thc/get-component file :c01)
;; ==== Action
[file' changes] (switch-with-changes file :child01 :c01)
child01' (ths/get-shape file' :child01)]
(t/is (some? (ctk/get-swap-slot (ths/get-shape file :child01))))
;; The second switch keeps the copy, now of :c01
(t/is (= (:component-id child01') (:id c01)))
;; Undo restores the copy of :c02
(check-switch-undone file file' changes :child01)))
(defn- setup-variant-with-copy-in-outer
"Variants `:c01` / `:c02` holding a copy of `:external01`, and a component
`:outer` whose main holds a copy of `:c01`. A copy of `:outer` is placed,
with its nested variant copy labelled `:c01-in-copy`, the child of that one
`:child-in-copy` and its child `:child-child`.
`swap-in` says where the `:external01` copy is swapped for `:external02`:
`:copy` (in the nested variant copy of the copy of `:outer`),
`:outer-main` (in the main of `:outer`) or `:variant-main` (in `:m01`).
With `delete-outer`, `:outer` is deleted after the swap.
With `outer-main-fills` (and `swap-in` `:outer-main`), the rect of the
swapped child in the main of `:outer` (labelled `:rect-in-outer-main`)
gets those fills.
With `outer-of-outer`, the copy of `:outer` is not placed on its own but
inside a copy of a component `:outer2`, whose main holds a copy of `:outer`.
With `nested-swap-in-copy`, `:external02` holds a copy of `:z01`, and the one
inside `:child-in-copy` (labelled `:z-in-copy`) is swapped in the copy for
`:z02` (new label `:z-swapped-in-copy`)."
[& {:keys [swap-in delete-outer outer-of-outer nested-swap-in-copy outer-main-fills]}]
(let [file (-> (thf/sample-file :file1)
(tho/add-simple-component :external01 :external01-root :external01-child)
(tho/add-simple-component :external02 :external02-root :external02-child))
file (cond-> file
nested-swap-in-copy
(-> (tho/add-simple-component :z01 :z01-root :z01-child)
(tho/add-simple-component :z02 :z02-root :z02-child)
(thc/instantiate-component :z01 :z01-in-external02
:parent-label :external02-root)))
file (thv/add-variant-with-copy file
:v01 :c01 :m01 :c02 :m02 :cp01 :cp02 :external01)
file (cond-> file
(= swap-in :variant-main)
(tho/swap-component-in-shape :cp01 :external02 {:new-shape-label :cp01-swapped
:keep-touched? false}))
file (-> file
(tho/add-simple-component :outer :outer-root :outer-child)
(thc/instantiate-component :c01
:c01-in-outer-main
:children-labels [:child-in-outer-main]
:parent-label :outer-root))
;; Nothing propagates main changes to existing copies here, so the
;; swap in the main of :outer must happen before its copy is placed
file (cond-> file
(= swap-in :outer-main)
(tho/swap-component-in-shape :child-in-outer-main :external02
{:new-shape-label :swapped-in-outer-main
:keep-touched? false}))
file (if outer-main-fills
(let [page (thf/current-page file)
rect (-> (ths/get-shape file :swapped-in-outer-main) :shapes first)]
(thi/set-id! :rect-in-outer-main rect)
(thf/apply-changes file
(cls/generate-update-shapes (pcb/empty-changes nil (:id page))
#{rect}
#(assoc % :fills outer-main-fills)
(:objects page)
{})))
file)
file (if outer-of-outer
(-> file
(tho/add-simple-component :outer2 :outer2-root :outer2-child)
(thc/instantiate-component :outer :outer-in-outer2-main
:parent-label :outer2-root)
(thc/instantiate-component :outer2
:outer2-copy
:children-labels [:outer2-copy-rect :outer-copy
:outer-copy-rect :c01-in-copy
:child-in-copy :child-child
:z-in-copy]))
(thc/instantiate-component file
:outer
:outer-copy
:children-labels [:outer-copy-rect :c01-in-copy
:child-in-copy :child-child
:z-in-copy]))
file (cond-> file
(= swap-in :copy)
(tho/swap-component-in-shape :child-in-copy :external02
{:new-shape-label :swapped-in-copy
:keep-touched? false})
nested-swap-in-copy
(tho/swap-component-in-shape :z-in-copy :z02
{:new-shape-label :z-swapped-in-copy
:keep-touched? false}))]
(cond-> file
delete-outer
(tho/delete-shape :outer-root))))
(defn- switch-nested-variant
"Switches `:c01-in-copy` to `:c02` keeping the touched changes, and
returns the new file, the first child of the new variant copy and the
changes. The new copy keeps the id, and so the label, of the old one."
[file]
(let [[file' changes] (switch-with-changes file :c01-in-copy :c02)
c02-in-copy (ths/get-shape file' :c01-in-copy)]
[file' (ths/get-shape-by-id file' (-> c02-in-copy :shapes first)) changes]))
(t/deftest test-switch-nested-variant-keeps-swap-made-in-copy
(let [;; ==== Setup
file (setup-variant-with-copy-in-outer :swap-in :copy)
external02 (thc/get-component file :external02)
swapped (ths/get-shape file :swapped-in-copy)
;; ==== Action
[file' new-child' changes] (switch-nested-variant file)]
;; The child of the nested variant copy was swapped for :external02
(t/is (= (:component-id swapped) (:id external02)))
;; The new variant copy keeps the swapped child, in the slot of the
;; :external01 copy in :c02
(t/is (= (:id new-child') (:id swapped)))
(t/is (= (:component-id new-child') (:id external02)))
(t/is (= (ctk/get-swap-slot new-child') (thi/id :cp02)))
;; Undo restores the old variant copy with the swapped child
(check-switch-undone file file' changes :c01-in-copy)))
(t/deftest test-switch-nested-variant-keeps-swap-made-in-copy-of-deleted-outer
(let [;; ==== Setup
file (setup-variant-with-copy-in-outer :swap-in :copy :delete-outer true)
external02 (thc/get-component file :external02)
swapped (ths/get-shape file :swapped-in-copy)
;; ==== Action
[_ new-child'] (switch-nested-variant file)]
;; The outer component is deleted
(t/is (nil? (thc/get-component file :outer)))
(t/is (some? (thc/get-component file :outer :include-deleted? true)))
;; The child of the nested variant copy was swapped for :external02
(t/is (= (:component-id swapped) (:id external02)))
;; The new variant copy keeps the swapped child, in the slot of the
;; :external01 copy in :c02
(t/is (= (:id new-child') (:id swapped)))
(t/is (= (:component-id new-child') (:id external02)))
(t/is (= (ctk/get-swap-slot new-child') (thi/id :cp02)))))
(defn- get-rect-child
"The rect child of `shape`, not a nested copy that :external02 may also hold"
[file shape]
(->> (:shapes shape)
(map #(ths/get-shape-by-id file %))
(remove :component-id)
first))
(defn- check-swap-from-outer-main-kept
[file' new-child']
(let [external02 (thc/get-component file' :external02)
new-child-child' (get-rect-child file' new-child')]
;; The new variant copy shows :external02 instead of its default child
(t/is (= (:component-id new-child') (:id external02)))
;; It points to the main of :external02, and takes the slot of the
;; :external01 copy in :c02
(t/is (= (:shape-ref new-child') (thi/id :external02-root)))
(t/is (= (ctk/get-swap-slot new-child') (thi/id :cp02)))
;; The slots of its ref chain are not kept
(t/is (= 1 (count (filter ctk/swap-slot? (:touched new-child')))))
;; Its rect child points to the child of the main of :external02
(t/is (= (:shape-ref new-child-child') (thi/id :external02-child)))))
(t/deftest test-switch-nested-variant-keeps-swap-made-in-outer-main
(let [;; ==== Setup
file (setup-variant-with-copy-in-outer :swap-in :outer-main)
external02 (thc/get-component file :external02)
child-in-copy (ths/get-shape file :child-in-copy)
;; ==== Action
[file' new-child' changes] (switch-nested-variant file)]
;; The copy of :outer inherits the swap from its main
(t/is (= (:component-id child-in-copy) (:id external02)))
(check-swap-from-outer-main-kept file' new-child')
;; Undo restores the old variant copy with the swapped child
(check-switch-undone file file' changes :c01-in-copy)))
(t/deftest test-switch-nested-variant-keeps-swap-made-in-deleted-outer-main
(let [;; ==== Setup
file (setup-variant-with-copy-in-outer :swap-in :outer-main :delete-outer true)
external02 (thc/get-component file :external02)
child-in-copy (ths/get-shape file :child-in-copy)
;; ==== Action
[file' new-child'] (switch-nested-variant file)]
;; The outer component is deleted
(t/is (nil? (thc/get-component file :outer)))
(t/is (some? (thc/get-component file :outer :include-deleted? true)))
;; The copy of :outer inherits the swap from its main
(t/is (= (:component-id child-in-copy) (:id external02)))
(check-swap-from-outer-main-kept file' new-child')))
(t/deftest test-switch-nested-variant-keeps-override-made-in-outer-main
(let [;; ==== Setup
fills (ths/sample-fills-color :fill-color "#fabada")
file (setup-variant-with-copy-in-outer :swap-in :outer-main
:outer-main-fills fills)
rect-in-outer-main (ths/get-shape file :rect-in-outer-main)
;; ==== Action
[file' new-child'] (switch-nested-variant file)
new-child-child' (get-rect-child file' new-child')]
;; The rect of the swapped child was overridden in the main of :outer
(t/is (contains? (:touched rect-in-outer-main) :fill-group))
(check-swap-from-outer-main-kept file' new-child')
;; The moved rect keeps the override, and it is still marked as touched
;; now that it points to the child of the main of :external02
(t/is (= (:fills new-child-child') fills))
(t/is (contains? (:touched new-child-child') :fill-group))))
(t/deftest test-switch-nested-variant-drops-swap-made-in-variant-main
(let [;; ==== Setup
file (setup-variant-with-copy-in-outer :swap-in :variant-main)
external01 (thc/get-component file :external01)
external02 (thc/get-component file :external02)
child-in-copy (ths/get-shape file :child-in-copy)
;; ==== Action
[_ new-child'] (switch-nested-variant file)]
;; The swap is part of the definition of :c01
(t/is (= (:component-id child-in-copy) (:id external02)))
;; So the new variant copy shows the child of :c02
(t/is (= (:component-id new-child') (:id external01)))
(t/is (= (:shape-ref new-child') (thi/id :cp02)))))
(t/deftest test-switch-nested-variant-keeps-swap-made-in-outer-of-outer-main
(let [;; ==== Setup
file (setup-variant-with-copy-in-outer :swap-in :outer-main
:outer-of-outer true)
external02 (thc/get-component file :external02)
child-in-copy (ths/get-shape file :child-in-copy)
;; ==== Action
[file' new-child'] (switch-nested-variant file)]
;; The swap comes from the main of :outer, two levels up the ref chain
(t/is (= (:component-id child-in-copy) (:id external02)))
(check-swap-from-outer-main-kept file' new-child')))
(t/deftest test-switch-nested-variant-keeps-nested-swap-made-in-copy
(let [;; ==== Setup
file (setup-variant-with-copy-in-outer :swap-in :outer-main
:nested-swap-in-copy true)
z02 (thc/get-component file :z02)
z-swapped (ths/get-shape file :z-swapped-in-copy)
;; ==== Action
[file' new-child'] (switch-nested-variant file)
z-swapped' (ths/get-shape file' :z-swapped-in-copy)]
(check-swap-from-outer-main-kept file' new-child')
;; The copy of :z02 swapped inside the moved child moves with it, and
;; keeps pointing to :z02, with the same slot
(t/is (= (:parent-id z-swapped') (:id new-child')))
(t/is (= (:component-id z-swapped') (:id z02)))
(t/is (= (:shape-ref z-swapped') (thi/id :z02-root)))
(t/is (= (ctk/get-swap-slot z-swapped') (ctk/get-swap-slot z-swapped)))))
(t/deftest test-switch-nested-variant-drops-swap-made-in-outer-main-without-match
(let [;; ==== Setup
file (-> (setup-variant-with-copy-in-outer :swap-in :outer-main)
;; The :external01 copy in :c02 gets another name, so
;; the swapped child has no related shape in :c02
(tho/change-shape :cp02 #(assoc % :name "Other child")))
external01 (thc/get-component file :external01)
;; ==== Action
[file' new-child' changes] (switch-nested-variant file)]
;; The new variant copy shows the child of :c02
(t/is (= (:component-id new-child') (:id external01)))
(t/is (= (:shape-ref new-child') (thi/id :cp02)))
;; The swapped child is removed with the old variant copy
(t/is (nil? (ths/get-shape-by-id file' (thi/id :child-in-copy))))
;; Undo restores the old variant copy with the swapped child
(check-switch-undone file file' changes :c01-in-copy)))
;; ============================================================
;; TOUCHED PARENT (switch without touched but with touched parent)
;; ============================================================

View File

@ -33,6 +33,7 @@
[common-tests.files-migrations-0038-test]
[common-tests.files-migrations-0039-test]
[common-tests.files-migrations-test]
[common-tests.files.changes-builder-test]
[common-tests.files.comp-processors-test]
[common-tests.files.helpers-test]
[common-tests.files.page-diff-test]
@ -160,6 +161,7 @@
'common-tests.files-migrations-0038-test
'common-tests.files-migrations-0039-test
'common-tests.files-migrations-test
'common-tests.files.changes-builder-test
'common-tests.files.comp-processors-test
'common-tests.files.helpers-test
'common-tests.files.page-diff-test

View File

@ -95,3 +95,55 @@
(t/is (= 1 (swap-level file :effects-copy 1)))
;; With no levels to look at, not even the shape itself is checked
(t/is (= 0 (swap-level file :effects-in-mid 0)))))
(defn- outer-swap
[file label base-label]
(let [page (thf/current-page file)]
(ctf/find-outer-swap (ctn/make-container page :page)
{(:id file) file}
(ths/get-shape file label)
(thi/id base-label))))
(t/deftest test-find-outer-swap-up-the-ref-chain
(let [file (setup-file)]
;; Level 1 is the ref shape
(t/is (= [1 (thi/id :plain-in-inner)] (outer-swap file :effects-in-top :frame-inner)))
(t/is (= [2 (thi/id :plain-in-inner)] (outer-swap file :effects-copy :frame-inner)))))
(t/deftest test-find-outer-swap-excludes-the-shape-itself
(let [file (setup-file)]
;; :effects-in-mid is swapped, but its ref chain has no swap
(t/is (nil? (outer-swap file :effects-in-mid :frame-inner)))))
(t/deftest test-find-outer-swap-stops-at-base
(let [file (setup-file)]
;; The swap is made inside :frame-mid
(t/is (nil? (outer-swap file :effects-copy :frame-mid)))))
(t/deftest test-find-outer-swap-none-found
(let [file (setup-file)]
;; The ref chain of the copy has no swap and reaches the main
(t/is (nil? (outer-swap file :inner-copy :frame-base)))
;; The base main has no ref chain at all
(t/is (nil? (outer-swap file :frame-base :frame-inner)))))
(t/deftest test-find-outer-swap-in-deleted-component
(let [file (-> (setup-file)
(tho/delete-shape :frame-mid))]
(t/is (nil? (thc/get-component file :mid)))
(t/is (= [2 (thi/id :plain-in-inner)] (outer-swap file :effects-copy :frame-inner)))))
(defn- outer-swaps
[file label]
(let [page (thf/current-page file)]
(ctf/get-outer-swaps (ctn/make-container page :page)
{(:id file) file}
(ths/get-shape file label))))
(t/deftest test-get-outer-swaps
(let [file (setup-file)]
;; :effects-copy was swapped in :frame-mid, outside the main of :inner-copy
(t/is (= {(thi/id :effects-copy) [2 (thi/id :plain-in-inner)]}
(outer-swaps file :inner-copy)))
;; but inside the main of :mid-copy, so it is part of its definition
(t/is (= {} (outer-swaps file :mid-copy)))))

View File

@ -70,42 +70,19 @@
[potok.v2.core :as ptk]
[promesa.core :as p]))
(defn- advance-shape
[file libraries page level-delta head-id objects shape]
(let [new-shape-ref (ctf/advance-shape-ref file page libraries shape level-delta {:include-deleted? true})
container (ctn/make-container page :page)
;; The head becomes a root copy, which cannot carry a swap slot, so
;; strip inherited slots only for it. Nested sub-heads keep them so
;; they still pair with the children of the new near main.
head? (= (:id shape) head-id)
new-touched (ctf/get-touched-from-ref-chain-until-target-ref
container libraries shape new-shape-ref :remove-slots? head?)]
(cond-> objects
(and (some? new-shape-ref) (not= new-shape-ref (:shape-ref shape)))
(update (:id shape) assoc :shape-ref new-shape-ref :touched new-touched))))
(defn- advance-subtree
"Advance the shape and its children. A head swapped in one of the levels
being dropped already points to the new component main from that level,
so it and its children advance only up to there."
[file libraries page head-id level-delta objects shape]
(let [level-delta (if (ctk/instance-head? shape)
(ctf/get-swap-level (ctn/make-container page :page)
libraries shape level-delta)
level-delta)]
(if (pos? level-delta)
(reduce #(advance-subtree file libraries page head-id level-delta %1
(get %1 %2))
(advance-shape file libraries page level-delta head-id objects shape)
(:shapes shape))
objects)))
(defn- advance-copy
"Advance the refs of the copy and its children. The head becomes a root
copy, which cannot carry a swap slot, so only the head loses the inherited
slots. Nested sub-heads keep them so they still pair with the children of
the new near main."
[file libraries page objects shape]
(if (and (ctk/instance-head? shape) (not (ctk/main-instance? shape)))
(advance-subtree file libraries page (:id shape)
(ctn/get-nesting-level-delta (:objects page) shape uuid/zero)
objects shape)
(reduce-kv (fn [objects id refs]
(update objects id merge refs))
objects
(ctf/get-advanced-refs file (ctn/make-container page :page) libraries (:id shape)
(ctn/get-nesting-level-delta (:objects page) shape uuid/zero)
shape))
objects))
(defn advance-copies

View File

@ -260,7 +260,7 @@
last-vern-ref (mf/use-ref nil)
;; WASM grid overlay was visible last run (`hover-grid?` true). Used so `clear-grid`
;; (expensive: `_hide_grid` + full `request-render`) runs only when hiding the overlay.
;; runs only when hiding the overlay.
prev-hover-grid-shown?-ref (mf/use-ref false)
;; STATE REFS

View File

@ -13,6 +13,7 @@
[app.common.uuid :as uuid]
[app.config :as cf]
[app.main.data.exports.files :as exports.files]
[app.main.data.helpers :as dsh]
[app.main.data.plugins :as dp]
[app.main.data.workspace :as dw]
[app.main.data.workspace.versions :as dwv]
@ -28,7 +29,8 @@
[app.plugins.utils :as u]
[app.util.http :as http]
[app.util.object :as obj]
[beicon.v2.core :as rx]))
[beicon.v2.core :as rx]
[clojure.set :as set]))
(defn file-version-proxy?
[proxy]
@ -129,6 +131,19 @@
:deleted-at nil)))))
reject))))))))))
(defn get-file-features
"Sorted features of the open file `file-id`: its stored features plus
the features active in the session. `render-wasm/v1` comes from the
session alone, so it is present only when the WebGL renderer draws the
file. Returns nil when `file-id` is not the open file."
[state file-id]
(when (= file-id (:current-file-id state))
(let [file (dsh/lookup-file state file-id)]
(-> (set (:features file))
(disj "render-wasm/v1")
(set/union (:features state))
(sort)))))
(defn file-proxy? [p]
(obj/type-of? p "FileProxy"))
@ -148,6 +163,9 @@
:revn
{:get #(-> (u/locate-file id) :revn)}
:features
{:get #(some->> (get-file-features @st/state id) (apply array))}
:pages
{:this true
:get #(.getPages ^js %)}

View File

@ -2582,6 +2582,7 @@
(p/rejected cause))))))
(defn show-grid
"Show the grid overlay for `id`. The WASM call re-presents the last frame."
[id]
(when (initialized?)
(let [buffer (uuid/get-u32 id)]
@ -2589,8 +2590,7 @@
(aget buffer 0)
(aget buffer 1)
(aget buffer 2)
(aget buffer 3)))
(request-render "show-grid")))
(aget buffer 3)))))
(defn set-rulers-visible!
[visible?]
@ -2629,10 +2629,10 @@
(sr-clr/hex->u32argb accent-hex 1))))
(defn clear-grid
"Hide the hover grid overlay. The WASM call re-presents the last frame."
[]
(when (initialized?)
(h/call wasm/internal-module "_hide_grid")
(request-render "clear-grid")))
(h/call wasm/internal-module "_hide_grid")))
;; Ruler guides ----------------------------------------------------------------

View File

@ -265,16 +265,20 @@
(dm/str (u/join cf/public-uri "fonts/" asset-id))))
(defn font-stored?
"True when the face is already in the WASM font store. Returns nil/false
while the GL/WASM context is not live (e.g. mid page-switch teardown), so
callers never hit `_is_font_uploaded` against a null resource pool."
[font-data emoji?]
(when-let [id-buffer (uuid/get-u32 (:wasm-id font-data))]
(not= 0 (h/call wasm/internal-module "_is_font_uploaded"
(aget id-buffer 0)
(aget id-buffer 1)
(aget id-buffer 2)
(aget id-buffer 3)
(:weight font-data)
(:style font-data)
emoji?))))
(when (wasm/live?)
(when-let [id-buffer (uuid/get-u32 (:wasm-id font-data))]
(not= 0 (h/call wasm/internal-module "_is_font_uploaded"
(aget id-buffer 0)
(aget id-buffer 1)
(aget id-buffer 2)
(aget id-buffer 3)
(:weight font-data)
(:style font-data)
emoji?)))))
(defn font-failed?
"Returns true when the face behind `font-key` failed to load, so WASM lays

View File

@ -131,3 +131,30 @@
(.-label pinned)))
(t/is (false? (.-isAutosave pinned)))
(t/is (identical? created-at (.-createdAt pinned))))))))
(t/deftest open-file-features-add-the-session-features
(let [file-id (uuid/next)
state {:current-file-id file-id
:features #{"render-wasm/v1" "components/v2"}
:files {file-id {:id file-id
:features #{"variants/v1" "components/v2"}}}}]
(t/is (= ["components/v2" "render-wasm/v1" "variants/v1"]
(file/get-file-features state file-id)))))
(t/deftest open-file-features-take-the-renderer-from-the-session
(let [file-id (uuid/next)
state {:current-file-id file-id
:features #{"components/v2"}
:files {file-id {:id file-id
:features #{"render-wasm/v1" "components/v2"}}}}]
(t/is (= ["components/v2"]
(file/get-file-features state file-id)))))
(t/deftest other-file-features-are-nil
(let [file-id (uuid/next)
other-id (uuid/next)
state {:current-file-id file-id
:features #{"render-wasm/v1"}
:files {other-id {:id other-id
:features #{"variants/v1" "components/v2"}}}}]
(t/is (nil? (file/get-file-features state other-id)))))

View File

@ -0,0 +1,45 @@
;; 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.render-wasm.fonts-test
"font-stored? must not call into WASM while the GL context is not live
(page-switch teardown), otherwise `_is_font_uploaded` aborts on a null
resource pool (#13205)."
(:require
[app.common.render-wasm.wasm :as wasm]
[app.common.uuid :as uuid]
[app.render-wasm.api.fonts :as fonts]
[cljs.test :as t :include-macros true]))
(defn- font-data
[]
{:wasm-id (uuid/next)
:weight 400
:style 0})
(defn- module-with-is-font-uploaded
[on-call]
#js {"_is_font_uploaded" (fn [& args]
(on-call args)
1)})
(t/deftest font-stored-skips-wasm-when-not-live
(let [called? (atom false)
module (module-with-is-font-uploaded
(fn [_] (reset! called? true)))]
(with-redefs [wasm/live? (constantly false)
wasm/internal-module module]
(t/is (nil? (fonts/font-stored? (font-data) false)))
(t/is (false? @called?)))))
(t/deftest font-stored-queries-wasm-when-live
(let [called? (atom false)
module (module-with-is-font-uploaded
(fn [_] (reset! called? true)))]
(with-redefs [wasm/live? (constantly true)
wasm/internal-module module]
(t/is (true? (fonts/font-stored? (font-data) false)))
(t/is (true? @called?)))))

View File

@ -126,6 +126,7 @@
[frontend-tests.render-dimensions-test]
[frontend-tests.render-wasm.call-test]
[frontend-tests.render-wasm.modifiers-test]
[frontend-tests.render-wasm.fonts-test]
[frontend-tests.render-wasm.process-objects-test]
[frontend-tests.render-wasm.serialization-test]
[frontend-tests.render-wasm.shape-proxy-test]
@ -367,6 +368,7 @@
'frontend-tests.plugins.wait-for-save-test
'frontend-tests.render-wasm.call-test
'frontend-tests.render-wasm.modifiers-test
'frontend-tests.render-wasm.fonts-test
'frontend-tests.render-wasm.process-objects-test
'frontend-tests.render-wasm.serialization-test
'frontend-tests.render-wasm.shape-proxy-test

View File

@ -161,3 +161,23 @@ test("findShapes — excludes the root shape itself from the results", () => {
assert.ok(!result.includes(root as any));
});
test("isWasmRenderer — true when the open file has render-wasm/v1", () => {
(globalThis as any).penpot = { currentFile: { features: ["components/v2", "render-wasm/v1"] } };
assert.equal(PenpotUtils.isWasmRenderer(), true);
});
test("isWasmRenderer — false when the open file lacks render-wasm/v1", () => {
(globalThis as any).penpot = { currentFile: { features: ["components/v2"] } };
assert.equal(PenpotUtils.isWasmRenderer(), false);
});
test("isWasmRenderer — throws when no file is open", () => {
(globalThis as any).penpot = { currentFile: null };
assert.throws(() => PenpotUtils.isWasmRenderer(), /No file is open/);
});
test("isWasmRenderer — throws when the file features are not exposed", () => {
(globalThis as any).penpot = { currentFile: {} };
assert.throws(() => PenpotUtils.isWasmRenderer(), /does not expose the file features/);
});

View File

@ -186,6 +186,25 @@ export class PenpotUtils {
return this.findPage((page) => page.name.toLowerCase() === name.toLowerCase());
}
/**
* Checks whether the new render engine (WebGL, `render-wasm/v1`) draws the open file.
* When it returns false, the file renders with the SVG engine.
*
* @returns true iff the open file has the `render-wasm/v1` feature active
* @throws Error if no file is open or the Penpot version does not expose the file features
*/
public static isWasmRenderer(): boolean {
const file = penpot.currentFile;
if (!file) {
throw new Error("No file is open");
}
const features = file.features;
if (!Array.isArray(features)) {
throw new Error("This Penpot version does not expose the file features");
}
return features.includes("render-wasm/v1");
}
public static getPageForShape(shape: Shape): Page | null {
for (const page of penpot.currentFile!.pages) {
if (page.getShapeById(shape.id)) {

View File

@ -0,0 +1,152 @@
import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import test from "node:test";
import { createContext, runInContext, type Context } from "node:vm";
import ts from "typescript";
import * as ErrorUtils from "./ErrorUtils.ts";
import * as VersionCompatibility from "./VersionCompatibility.ts";
/** Compiles a plugin source file for a simulated plugin context. */
function compile(name: string) {
return ts.transpileModule(readFileSync(new URL(name, import.meta.url), "utf8"), {
compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2020 },
}).outputText;
}
/** Exports of a compiled module run in the given context, which it shares with the plugin bundle. */
function compiledModule(name: string, context: Context) {
const exports = {};
context.exports = exports;
runInContext(compile(name), context);
return exports;
}
/**
* Plugin task request handling with a task that waits until the test releases it.
*
* Closing the plugin replaces the plugin globals with `undefined`, as the plugin runtime does
* when it closes a plugin: SES reads a removed global as `undefined` instead of throwing.
*/
function pluginWithPendingTask(outcome: "success" | "failure") {
const responses: any[] = [];
const errors: unknown[][] = [];
let release!: () => void;
const released = new Promise<void>((resolve) => {
release = resolve;
});
let onMessage!: (message: any) => void;
const context: Context = createContext({
console: {
log() {},
error: (...args: unknown[]) => {
errors.push(args);
},
warn() {},
info() {},
},
penpot: {
theme: "dark",
ui: {
open() {},
onMessage: (handler: (message: any) => void) => {
onMessage = handler;
},
sendMessage: (message: any) => {
if (message.type === "task-response") {
responses.push(message.response);
}
},
},
on() {},
},
mcp: undefined,
});
const taskModule = compiledModule("TaskHandler.ts", context);
context.require = (name: string) => {
if (name === "./task-handlers/ExecuteCodeTaskHandler") {
return {
ExecuteCodeTaskHandler: class {
isApplicableTo(task: any) {
return task.taskType === "executeCode";
}
async handle(task: any) {
await released;
if (outcome === "failure") {
throw new Error("code failed");
}
task.sendSuccess({ result: 1 });
}
},
};
}
if (name === "./TaskHandler") return taskModule;
if (name === "./ErrorUtils") return ErrorUtils;
if (name === "./VersionCompatibility") return VersionCompatibility;
if (name === "./RollbackLog") {
return {
LocalStorageRollbackStore: class {},
RollbackLog: class {
listen() {}
pending() {
return [];
}
acknowledge() {}
},
};
}
throw new Error(`Unexpected import: ${name}`);
};
context.exports = {};
runInContext(compile("plugin.ts"), context);
return {
responses,
errors,
start: () => onMessage({ id: "task-1", task: "executeCode", params: { code: "" } }),
close: () => {
for (const name of ["console", "penpot", "penpotMgmt", "mcp"]) {
context[name] = undefined;
}
},
release,
};
}
/** Unhandled rejections raised while the given action and its follow-up work run. */
async function unhandledRejections(action: () => void | Promise<void>): Promise<unknown[]> {
const rejections: unknown[] = [];
const listener = (reason: unknown) => rejections.push(reason);
process.on("unhandledRejection", listener);
try {
await action();
await new Promise((resolve) => setTimeout(resolve, 20));
} finally {
process.off("unhandledRejection", listener);
}
return rejections;
}
for (const outcome of ["success", "failure"] as const) {
test(`a task ending in ${outcome} after the plugin closed raises no error`, async () => {
const plugin = pluginWithPendingTask(outcome);
const rejections = await unhandledRejections(() => {
plugin.start();
plugin.close();
plugin.release();
});
assert.deepEqual(rejections, []);
assert.deepEqual(plugin.responses, []);
assert.deepEqual(plugin.errors, []);
});
}
test("a task failing while the plugin is open sends an error response", async () => {
const plugin = pluginWithPendingTask("failure");
const rejections = await unhandledRejections(() => {
plugin.start();
plugin.release();
});
assert.deepEqual(rejections, []);
assert.equal(plugin.responses.length, 1);
assert.equal(plugin.responses[0].success, false);
assert.match(plugin.responses[0].error, /code failed/);
});

View File

@ -18,6 +18,12 @@ const isIntegratedRemoteMcp = !!mcp;
*/
const management = typeof penpotMgmt === "undefined" ? null : penpotMgmt;
/**
* the console of the plugin context, kept for task errors reported after the plugin is closed,
* when the runtime has removed the `console` global
*/
const pluginConsole = console;
let uiInitialized = false;
/**
@ -119,7 +125,7 @@ penpot.ui.onMessage<
} else if (typeof message === "object" && message.task && message.id) {
// Handle plugin tasks submitted by the MCP server
handlePluginTaskRequest(message).catch((error) => {
console.error("Error in handlePluginTaskRequest:", error);
pluginConsole.error("Error in handlePluginTaskRequest:", error);
});
}
});
@ -156,6 +162,15 @@ function sendWorkspaceContext(): void {
management?.on("workspacechange", sendWorkspaceContext);
/**
* Whether the plugin runtime has closed this plugin.
* Closing removes the plugin globals, which then read as undefined, but a task that was already
* running goes on and fails at its next use of them.
*/
function isPluginClosed(): boolean {
return typeof penpot === "undefined";
}
/**
* Handles plugin task requests received from the MCP server via WebSocket.
*
@ -182,6 +197,10 @@ async function handlePluginTaskRequest(request: { id: string; task: string; para
console.log("Task handled successfully:", task);
} catch (error) {
if (isPluginClosed()) {
// no way to answer: the MCP server fails the task when the plugin connection closes
return;
}
console.error("Error handling task:", error);
task.sendError(`Error handling task: ${formatTaskError(error)}`);
}

View File

@ -38,6 +38,7 @@ Penpot:
currentUser: User;
activeUsers: ActiveUser[];
theme: Theme;
location: PenpotLocation;
localStorage: LocalStorage;
selection: Shape[];
shapesColors(shapes: Shape[]): (Color & ColorShapeInfo)[];
@ -309,6 +310,20 @@ Penpot:
const currentTheme = context.theme;
console.log(currentTheme);
```
location: |-
```
readonly location: PenpotLocation
```
The Penpot instance URL and the current address in the app, in the
dashboard as well as in the workspace. Requires `content:read` permission.
Example
```
const { baseUrl, href, params } = penpot.location;
console.log(baseUrl); // "https://design.penpot.app/"
console.log(params['file-id']);
```
localStorage: |-
```
readonly localStorage: LocalStorage
@ -5917,6 +5932,7 @@ Context:
currentUser: User;
activeUsers: ActiveUser[];
theme: Theme;
location: PenpotLocation;
localStorage: LocalStorage;
selection: Shape[];
shapesColors(shapes: Shape[]): (Color & ColorShapeInfo)[];
@ -6120,6 +6136,20 @@ Context:
const currentTheme = context.theme;
console.log(currentTheme);
```
location: |-
```
readonly location: PenpotLocation
```
The Penpot instance URL and the current address in the app, in the
dashboard as well as in the workspace. Requires `content:read` permission.
Example
```
const { baseUrl, href, params } = penpot.location;
console.log(baseUrl); // "https://design.penpot.app/"
console.log(params['file-id']);
```
localStorage: |-
```
readonly localStorage: LocalStorage
@ -8390,6 +8420,7 @@ File:
id: string;
name: string;
revn: number;
features: string[] | null;
pages: Page[];
export(
exportType: "penpot" | "zip",
@ -8437,6 +8468,24 @@ File:
```
The `revn` will change for every document update
features: |-
```
readonly features: string[] | null
```
The features of the open file, sorted by name, e.g. `"components/v2"`
or `"variants/v1"`. It also lists the features active in the session,
such as `"render-wasm/v1"` when the new render engine (WebGL) draws the
file. Each read returns a new array.
Only `penpot.currentFile` answers it: for any other file, such as a
library, or a `File` kept after the user opens another file, it is
`null`.
Example
```
const webgl = penpot.currentFile.features.includes('render-wasm/v1');
```
pages: |-
```
readonly pages: Page[]
@ -14204,6 +14253,51 @@ LibraryTypography:
const sharedKeys = shape.getSharedPluginDataKeys('exampleNamespace');
console.log(sharedKeys);
```
PenpotLocation:
overview: |-
Interface PenpotLocation
========================
The Penpot instance URL and the current address in the app.
Each read of `penpot.location` returns a new snapshot.
Query params that carry secrets (`share-id`, any param ending in
`token`, `secret` or `password`, and the OAuth params `request`,
`code` and `state`) are left out of `params` and `href`.
```
interface PenpotLocation {
baseUrl: string;
href: string;
params: Record<string, string>;
}
```
Referenced by: Context, Penpot
members:
Properties:
baseUrl: |-
```
readonly baseUrl: string
```
The public URL of the Penpot instance, ending in `/`,
e.g. `"https://design.penpot.app/"`.
href: |-
```
readonly href: string
```
The URL of the current screen, e.g. the open file and page:
`"https://design.penpot.app/?screen=workspace&team-id=…&file-id=…&page-id=…"`.
Use it to link to what the user is looking at.
params: |-
```
readonly params: Record<string, string>
```
The query params of the current URL, e.g. `screen`, `team-id`,
`file-id` and `page-id`. A param repeated in the URL keeps its last value.
LocalStorage:
overview: |-
Interface LocalStorage

View File

@ -209,6 +209,8 @@ A key object for navigating the currently active Penpot file is the `penpot` obj
* `penpot.location` gives the Penpot instance URL (`baseUrl`), the link to what the user is viewing (`href`, e.g. the open file and page)
and the query params of that link (`params`, e.g. `params["file-id"]`). Use `href` when you need a link to the open file;
never guess the instance domain or build the link by hand.
* `penpot.currentFile.features` lists the features active for the open file (e.g. `"components/v2"`, `"render-wasm/v1"`);
it is null on any other `File` object.
Members of `penpot` (e.g. `penpot.currentFile` and `penpot.root`) will be null no Penpot file is currently opened.
You can use `penpotMgmt` to navigate to a file if needed (see below).
@ -236,6 +238,8 @@ CRITICAL: The `penpotUtils` object provides essential utilities - USE THESE INST
General-purpose utility for analyzing/validating descendants
Calls evaluator on each descendant; collects non-null/undefined results
Powerful pattern: evaluator can return corrector functions or diagnostic data
* isWasmRenderer(): boolean
Returns true iff the new render engine (WebGL) draws the open file; false means the SVG engine.
* Further functions for specific tasks (described in the sections below)
General pointers for working with Penpot designs:

View File

@ -6,6 +6,7 @@
- **plugin-types, plugins-runtime:** `penpotMgmt` returns `Team`, `Project` and `ProjectFile` objects. Assigning `name` renames teams, projects and files, `project.pinned` pins a project and `file.shared` shares a file as a team library; `createProject`, `createFile`, `moveTo`, `duplicate`, `remove` and `restore` live on the objects. Added `penpotMgmt.listTeams`, `penpotMgmt.createTeam`, `penpotMgmt.getFile`, `listDeletedProjects` and `listDeletedFiles`, and the `manage:projects`, `manage:teams` and `manage:delete` permissions. Restoration uses the dashboard's Trash operation; projects need recoverable files and empty projects cannot be restored; the API exposes no permanent deletion method. Team deletion is not exposed.
- **plugins-runtime, plugin-types**: Added global plugins (`scope: "global"`) that remain active across dashboard and workspace navigation until closed or logged out, with `penpotMgmt` for project and file discovery, file navigation and workspace events. Global scope adds the `allow:global` permission, which users must accept when installing the plugin.
- **plugin-types, plugins-runtime:** Added `penpot.location` with the instance base URL (`baseUrl`), the URL of the current screen (`href`) and its query params (`params`), in the dashboard and the workspace. Params that carry secrets are left out. Requires `content:read`. Closes #13013.
- **plugin-types:** Added `file.features`, the sorted features of the open file, including the features active in the session, such as `render-wasm/v1` when the new render engine (WebGL) draws the file. It is `null` for any other file. Closes #13167.
- **plugin-types:** Added the `contentrollback` event and the `ContentRollback` type. The event fires after the backend rejected some changes and the workspace undid them, with the ids of the files, pages and shapes affected. It fires once the undone data is in the workspace, also when the workspace has to reload the file to undo the changes.
### 🩹 Fixes

View File

@ -152,6 +152,7 @@
"Export": ["scale", "skipChildren", "suffix", "type"],
"File": [
"export",
"features",
"findVersions",
"id",
"name",
@ -3141,6 +3142,12 @@
"type": null,
"array": false
},
"features": {
"decl": "File",
"kind": "get",
"type": null,
"array": true
},
"pages": {
"decl": "File",
"kind": "get",

View File

@ -22,6 +22,20 @@ describe('File', () => {
}
});
test('currentFile lists its features sorted', (ctx) => {
const file = ctx.penpot.currentFile;
expect(file).not.toBeNull();
if (file) {
const { features } = file;
expect(features).not.toBeNull();
if (!features) return;
expect(features.every((f) => typeof f === 'string')).toBe(true);
expect(features).toContain('components/v2');
expect(features).toEqual([...features].sort());
expect(file.features === features).toBe(false);
}
});
test('file lists its pages', (ctx) => {
const file = ctx.penpot.currentFile;
if (file) {

View File

@ -430,6 +430,19 @@ describe('Management', () => {
expect(finished).toContain(other.id);
});
test('features is null on a file that is not open', async (ctx) => {
const home = ctx.penpot.currentFile;
expect(home).not.toBeNull();
if (!home) return;
expect(home.features).not.toBeNull();
const other = await temporaryFile(ctx, 'Features');
await inFile(ctx, other, () => {
expect(home.features).toBeNull();
expect(ctx.penpot.currentFile?.features).toContain('components/v2');
});
});
test('off stops workspacechange notifications', async (ctx) => {
const other = await temporaryFile(ctx, 'Unsubscribed');
let count = 0;

View File

@ -1968,6 +1968,23 @@ export interface File extends PluginData {
*/
readonly revn: number;
/**
* The features of the open file, sorted by name, e.g. `"components/v2"`
* or `"variants/v1"`. It also lists the features active in the session,
* such as `"render-wasm/v1"` when the new render engine (WebGL) draws the
* file. Each read returns a new array.
*
* Only `penpot.currentFile` answers it: for any other file, such as a
* library, or a `File` kept after the user opens another file, it is
* `null`.
*
* @example
* ```js
* const webgl = penpot.currentFile.features.includes('render-wasm/v1');
* ```
*/
readonly features: string[] | null;
/**
* List all the pages for the current file
*/

View File

@ -240,15 +240,26 @@ pub extern "C" fn set_grid_cells() -> Result<()> {
Ok(())
}
/// Hover only changes the grid overlay on the UI surface. Re-present the last
/// frame so the lines update without a tile pass. A full render clears the
/// canvas and walks every visible tile.
fn present_grid_overlay() {
with_state!(state, {
state.present_frame();
});
}
#[no_mangle]
pub extern "C" fn show_grid(a: u32, b: u32, c: u32, d: u32) {
let id = uuid_from_u32_quartet(a, b, c, d);
get_render_state().show_grid = Some(id);
present_grid_overlay();
}
#[no_mangle]
pub extern "C" fn hide_grid() {
get_render_state().show_grid = None;
present_grid_overlay();
}
#[no_mangle]