diff --git a/common/test/common_tests/files_builder_test.cljc b/common/test/common_tests/files_builder_test.cljc index 9658f51b28..f0c633be30 100644 --- a/common/test/common_tests/files_builder_test.cljc +++ b/common/test/common_tests/files_builder_test.cljc @@ -123,6 +123,88 @@ shape (fb/get-shape state shape-id)] (t/is (= "Group / Subgroup / Name" (:name shape))))) +(t/deftest add-shape-uniquifies-default-names + (let [file-id (uuid/next) + page-id (uuid/next) + board-a (uuid/next) + board-b (uuid/next) + state (-> (fb/create-state) + (fb/add-file {:id file-id :name "Test file"}) + (fb/add-page {:id page-id :name "Page 1"}) + (fb/add-board {:id board-a :x 0 :y 0 :width 10 :height 10}) + (fb/add-board {:id board-b :x 20 :y 0 :width 10 :height 10}))] + (t/is (= "Board" (:name (fb/get-shape state board-a)))) + (t/is (= "Board-1" (:name (fb/get-shape state board-b)))))) + +(t/deftest add-shape-uniquifies-names-that-clean-to-the-same-path + (let [file-id (uuid/next) + page-id (uuid/next) + shape-a (uuid/next) + shape-b (uuid/next) + state (-> (fb/create-state) + (fb/add-file {:id file-id :name "Test file"}) + (fb/add-page {:id page-id :name "Page 1"}) + (fb/add-shape {:id shape-a :type :frame :name "Group/Name" + :x 0 :y 0 :width 10 :height 10}) + (fb/add-shape {:id shape-b :type :frame :name "Group / Name" + :x 20 :y 0 :width 10 :height 10}))] + (t/is (= "Group / Name" (:name (fb/get-shape state shape-a)))) + (t/is (= "Group / Name-1" (:name (fb/get-shape state shape-b)))))) + +(t/deftest add-shape-uniquifies-names-used-by-component-roots + (let [file-id (uuid/next) + page-id (uuid/next) + frame-id (uuid/next) + component-id (uuid/next) + shape-id (uuid/next) + state (-> (fb/create-state) + (fb/add-file {:id file-id :name "Test file"}) + (fb/add-page {:id page-id :name "Page 1"}) + (fb/add-board {:id frame-id :name "Draft" + :x 0 :y 0 :width 10 :height 10}) + (fb/add-component {:component-id component-id + :name "Button" + :path "Forms"}) + (fb/close-board) + (fb/add-shape {:id shape-id :type :frame :name "Forms/Button" + :x 20 :y 0 :width 10 :height 10}))] + (t/is (= "Forms / Button" (:name (fb/get-shape state frame-id)))) + (t/is (= "Forms / Button-1" (:name (fb/get-shape state shape-id)))))) + +(t/deftest add-shape-keeps-unique-names-per-page + (let [file-id (uuid/next) + page-a (uuid/next) + page-b (uuid/next) + board-a (uuid/next) + board-b (uuid/next) + state (-> (fb/create-state) + (fb/add-file {:id file-id :name "Test file"}) + (fb/add-page {:id page-a :name "Page 1"}) + (fb/add-board {:id board-a :x 0 :y 0 :width 10 :height 10}) + (fb/add-page {:id page-b :name "Page 2"}) + (fb/add-board {:id board-b :x 0 :y 0 :width 10 :height 10})) + name-of (fn [page-id shape-id] + (get-in state [::fb/files file-id :data :pages-index + page-id :objects shape-id :name]))] + (t/is (= "Board" (name-of page-a board-a))) + (t/is (= "Board" (name-of page-b board-b))))) + +(t/deftest add-component-without-name-is-anonymous + (let [file-id (uuid/next) + page-id (uuid/next) + frame-id (uuid/next) + component-id (uuid/next) + state (-> (fb/create-state) + (fb/add-file {:id file-id :name "Test file"}) + (fb/add-page {:id page-id :name "Page 1"}) + (fb/add-board {:id frame-id :name "Draft" + :x 0 :y 0 :width 10 :height 10}) + (fb/add-component {:component-id component-id})) + component (get-in state [::fb/files file-id :data + :components component-id])] + (t/is (= "anonymous" (:name component))) + (t/is (= "anonymous" (:name (fb/get-shape state frame-id)))))) + (t/deftest add-component-renames-frame-to-match-component (t/testing "the main instance frame name is aligned with the component's path+name" (let [file-id (uuid/next) diff --git a/frontend/src/app/main/data/plugins.cljs b/frontend/src/app/main/data/plugins.cljs index 4d3f8b5ef5..7e489d1351 100644 --- a/frontend/src/app/main/data/plugins.cljs +++ b/frontend/src/app/main/data/plugins.cljs @@ -63,7 +63,7 @@ [plugin] (when (and (preg/global-requested? plugin) (not (preg/global-allowed? plugin))) - (log/warn :hint "Global plugins can only be loaded from localhost" + (log/warn :hint "Global plugins are not allowed from this host" :plugin-id (:plugin-id plugin) :host (:host plugin)) (st/emit! (ntf/warn (tr "workspace.plugins.error.global-not-allowed"))) diff --git a/frontend/src/app/main/data/workspace/shape_layout.cljs b/frontend/src/app/main/data/workspace/shape_layout.cljs index 0a5c7b4cfe..6f6cfba59d 100644 --- a/frontend/src/app/main/data/workspace/shape_layout.cljs +++ b/frontend/src/app/main/data/workspace/shape_layout.cljs @@ -112,7 +112,8 @@ update-positions-stream (if (d/not-empty? ids) (let [modif-tree (dwm/create-modif-tree ids (ctm/reflow-modifiers))] - (if (features/active-feature? state "render-wasm/v1") + (if (and (features/active-feature? state "render-wasm/v1") + (= page-id (:current-page-id state))) (rx/of (dwm/apply-wasm-modifiers modif-tree :stack-undo? true :undo-group undo-group diff --git a/frontend/src/app/plugins/api.cljs b/frontend/src/app/plugins/api.cljs index 3043ff510b..4220978faa 100644 --- a/frontend/src/app/plugins/api.cljs +++ b/frontend/src/app/plugins/api.cljs @@ -43,6 +43,7 @@ [app.plugins.history :as history] [app.plugins.library :as library] [app.plugins.local-storage :as local-storage] + [app.plugins.location :as location] [app.plugins.management :as management] [app.plugins.page :as page] [app.plugins.parser :as parser] @@ -114,6 +115,9 @@ {:this true :get #(.getTheme ^js %)} + :location + {:get (fn [] (clj->js (location/location @st/state)))} + :localStorage {:this true :get diff --git a/frontend/src/app/plugins/location.cljs b/frontend/src/app/plugins/location.cljs new file mode 100644 index 0000000000..59434fb636 --- /dev/null +++ b/frontend/src/app/plugins/location.cljs @@ -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 app.plugins.location + "The app URL as plugins see it: the instance base URL and the current + route's query params, without the params that carry secrets." + (:require + [app.common.data.macros :as dm] + [app.common.uri :as u] + [app.config :as cf] + [app.main.router :as rt])) + +(def ^:private secret-params + "Query params that grant access or carry auth state." + #{:share-id :request :code :state}) + +(defn- secret-param? + [k] + (or (contains? secret-params k) + (some? (re-find #"(?i)(token|secret|password)$" (name k))))) + +(defn- public-params + "Return the current route's query params without secrets. A key + repeated in the URL keeps its last value, as the app reads it." + [state] + (let [params (rt/get-params state)] + (into {} + (comp (remove (comp secret-param? key)) + (map (fn [[k _]] [k (rt/get-query-param params k)]))) + params))) + +(defn location + "Return `{:baseUrl :href :params}` for the current route in `state`. + `href` is rebuilt from the public params, so it never carries a secret." + [state] + (let [base-url (dm/str cf/public-uri) + params (public-params state)] + {:baseUrl base-url + :href (if (empty? params) + base-url + (dm/str base-url "?" (u/map->query-string params))) + :params (update-keys params name)})) diff --git a/frontend/src/app/plugins/register.cljs b/frontend/src/app/plugins/register.cljs index 5c7c4b4fe6..d1ab6ea5ac 100644 --- a/frontend/src/app/plugins/register.cljs +++ b/frontend/src/app/plugins/register.cljs @@ -34,14 +34,25 @@ (def global-permissions #{"allow:global" "manage:projects" "manage:teams" "manage:delete"}) -(def ^:private local-hosts +;; Loopback hosts that may serve global plugins over any scheme +(def ^:private trusted-hosts #{"localhost" "127.0.0.1" "[::1]" "::1"}) -(defn- local-url? - "True when the url host is a loopback name, ignoring case and a - trailing dot." +;; Domains whose https subdomains may serve global plugins +(def ^:private trusted-domains + #{"penpot.dev" "penpot.app"}) + +(defn- trusted-url? + "True when the url host is one of `trusted-hosts`, or the url uses + https and its host is a subdomain of one of `trusted-domains`. Hosts + are compared ignoring case and a trailing dot." [url] - (contains? local-hosts (some-> url u/uri :host str/lower (str/rtrim ".")))) + (let [uri (some-> url u/uri) + host (some-> uri :host str/lower (str/rtrim "."))] + (or (contains? trusted-hosts host) + (and (= "https" (some-> uri :scheme str/lower)) + (some? host) + (boolean (some #(str/ends-with? host (str "." %)) trusted-domains)))))) (defn global-requested? "True when the plugin asks for global scope or a management permission." @@ -52,10 +63,10 @@ (defn global-allowed? "True when the plugin may run with global scope and use the management API. The feature is still in progress, so only the bundled MCP plugin - and plugins served from localhost get it." + and plugins served from a trusted url get it." [{:keys [plugin-id host]}] (or (= plugin-id mcp-plugin-id) - (local-url? host))) + (trusted-url? host))) ;; Promise that resolves when plugins runtime is initialized. ;; Lives here to avoid circular dependency: workspace.mcp -> app.plugins -> app.plugins.api -> workspace @@ -155,7 +166,7 @@ (and (global-requested? manifest) (not (global-allowed? manifest))) - (throw (ex-info "Global plugins can only be loaded from localhost" + (throw (ex-info "Global plugins are not allowed from this host" {:type ::global-not-allowed :host origin})) diff --git a/frontend/test/frontend_tests/data/workspace_layout_other_page_test.cljs b/frontend/test/frontend_tests/data/workspace_layout_other_page_test.cljs new file mode 100644 index 0000000000..ac0cc0db6f --- /dev/null +++ b/frontend/test/frontend_tests/data/workspace_layout_other_page_test.cljs @@ -0,0 +1,57 @@ +;; 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.data.workspace-layout-other-page-test + "Regression test for #13015: with render-wasm/v1 active, a `:layout/update` + for a page other than the current one must still lay out its shapes." + (:require + [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.shapes :as cths] + [app.main.data.workspace.shape-layout :as dwsl] + [cljs.test :as t :include-macros true] + [frontend-tests.helpers.state :as ths] + [frontend-tests.helpers.wasm :as thw])) + +(t/use-fixtures :each + {:before thw/setup-wasm-mocks! + :after thw/teardown-wasm-mocks!}) + +(defn- setup-file + [] + (-> (cthf/sample-file :file1 :page-label :page-a) + (cthf/add-sample-page :page-b) + (ctho/add-frame :board + :x 0 :y 0 :width 500 :height 300 + :layout :flex + :layout-flex-dir :column + :layout-align-items :start + :layout-padding-type :multiple + :layout-padding {:p1 50 :p2 50 :p3 50 :p4 50}) + (cths/add-sample-shape :child + :type :rect + :parent-label :board + :x 50 :y 50 :width 100 :height 20 + :layout-item-h-sizing :fill) + (cthf/switch-to-page :page-a))) + +(t/deftest layout-update-on-another-page-resizes-fill-children + (t/async + done + (let [file (setup-file) + store (ths/setup-store file) + event (#'dwsl/update-layout-positions {:page-id (cthi/id :page-b) + :ids [(cthi/id :board)]})] + (ths/run-store + store done [event] + (fn [new-state] + (let [file' (ths/get-file-from-state new-state) + child (cths/get-shape file' :child :page-label :page-b)] + (t/is (= 400 (:width child)) + "the fill child takes the board width minus its padding") + (t/is (zero? (thw/call-count :propagate-modifiers)) + "WASM only holds the current page, so it must not lay out another one"))))))) diff --git a/frontend/test/frontend_tests/plugins/location_test.cljs b/frontend/test/frontend_tests/plugins/location_test.cljs new file mode 100644 index 0000000000..7ac6601b4c --- /dev/null +++ b/frontend/test/frontend_tests/plugins/location_test.cljs @@ -0,0 +1,73 @@ +;; 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.location-test + (:require + [app.common.data.macros :as dm] + [app.common.uri :as u] + [app.config :as cf] + [app.plugins.location :as location] + [cljs.test :as t :include-macros true])) + +(defn- state-with-query + [query-params] + {:route {:data {:name (keyword (:screen query-params))} + :params {:path {} :query query-params} + :query-params query-params}}) + +(defn- href-params + [href] + (-> (u/uri href) :query u/query-string->map)) + +(t/deftest base-url-is-the-public-uri + (let [result (location/location (state-with-query {:screen "dashboard-recent"}))] + (t/is (= (dm/str cf/public-uri) (:baseUrl result))))) + +(t/deftest workspace-params-are-exposed + (let [query {:screen "workspace" + :team-id "t1" + :file-id "f1" + :page-id "p1" + :layout "layers"} + result (location/location (state-with-query query))] + (t/is (= {"screen" "workspace" + "team-id" "t1" + "file-id" "f1" + "page-id" "p1" + "layout" "layers"} + (:params result))) + (t/is (= query (href-params (:href result)))) + (t/is (= (dm/str cf/public-uri) (subs (:href result) 0 (count (dm/str cf/public-uri))))))) + +(t/deftest custom-params-are-exposed + (let [result (location/location (state-with-query {:screen "workspace" :my-plugin "on"}))] + (t/is (= "on" (get-in result [:params "my-plugin"]))))) + +(t/deftest secret-params-are-left-out + (let [query {:screen "workspace" + :file-id "f1" + :token "s1" + :invitation-token "s2" + :share-id "s3" + :request "s4" + :code "s5" + :state "s6" + :client-secret "s7" + :password "s8"} + result (location/location (state-with-query query))] + (t/is (= {"screen" "workspace" "file-id" "f1"} (:params result))) + (t/is (= {:screen "workspace" :file-id "f1"} (href-params (:href result)))) + (t/is (not (re-find #"s\d" (:href result)))))) + +(t/deftest repeated-params-keep-the-last-value + (let [result (location/location (state-with-query {:screen "workspace" :page-id ["p1" "p2"]}))] + (t/is (= "p2" (get-in result [:params "page-id"]))) + (t/is (= "p2" (:page-id (href-params (:href result))))))) + +(t/deftest no-route-returns-the-base-url + (let [result (location/location {})] + (t/is (= {} (:params result))) + (t/is (= (:baseUrl result) (:href result))))) diff --git a/frontend/test/frontend_tests/plugins/register_test.cljs b/frontend/test/frontend_tests/plugins/register_test.cljs index afa0cfe304..b59b3141cc 100644 --- a/frontend/test/frontend_tests/plugins/register_test.cljs +++ b/frontend/test/frontend_tests/plugins/register_test.cljs @@ -363,11 +363,45 @@ (t/is (preg/global-allowed? {:plugin-id preg/mcp-plugin-id :host "https://design.penpot.app/plugins/mcp/"})) (doseq [host ["http://localhost:4400/" "http://127.0.0.1:4400/" "http://[::1]:4400/" - "http://LOCALHOST:4400/" "http://LocalHost/" "http://localhost.:4400/"]] + "http://LOCALHOST:4400/" "http://LocalHost/" "http://localhost.:4400/" + "https://localhost:4400/" "https://127.0.0.1/"]] (t/is (preg/global-allowed? {:plugin-id "local" :host host}) host)) (t/is (not (preg/global-allowed? {:plugin-id "remote" :host "https://plugins.example.com/"}))) (t/is (not (preg/global-allowed? {:plugin-id "remote" :host "https://localhost.example.com/"})))) +(t/deftest global-plugins-are-allowed-for-penpot-domains + (doseq [host ["https://api-test-suite.plugins.penpot.dev/" + "https://design.penpot.dev/plugins/x/" + "https://plugins.penpot.app/" + "https://Plugins.PENPOT.app./"]] + (t/is (preg/global-allowed? {:plugin-id "penpot" :host host}) host)) + (doseq [host ["http://api-test-suite.plugins.penpot.dev/" + "https://penpot.dev/" + "https://penpot.app/" + "https://evilpenpot.app/" + "https://penpot.app.example.com/" + "https://plugins.penpot.dev.example.com/"]] + (t/is (not (preg/global-allowed? {:plugin-id "remote" :host host})) host))) + +(t/deftest parse-manifest-keeps-localhost-management-permissions + (let [manifest (preg/parse-manifest + "http://localhost:4400/manifest.json" + #js {:name "Local management plugin" + :code "plugin.js" + :permissions #js ["content:read" "manage:projects" "manage:teams" "manage:delete"]})] + (t/is (= #{"content:read" "manage:projects" "manage:teams" "manage:delete"} + (:permissions manifest))))) + +(t/deftest parse-manifest-keeps-penpot-domain-global-scope + (let [manifest (preg/parse-manifest + "https://api-test-suite.plugins.penpot.dev/manifest.json" + #js {:name "Penpot global plugin" + :code "plugin.js" + :scope "global" + :permissions #js ["content:read" "manage:projects"]})] + (t/is (= "global" (:scope manifest))) + (t/is (contains? (:permissions manifest) "manage:projects")))) + (t/deftest parse-manifest-rejects-remote-global-scope (t/is (= ::preg/global-not-allowed (global-not-allowed-error @@ -413,5 +447,11 @@ (t/is (preg/has-permission? "reg-global-remote" "content:read")) (t/is (not (preg/has-permission? "reg-global-remote" "allow:global"))) (t/is (not (preg/has-permission? "reg-global-remote" "manage:projects"))) + (preg/install-plugin! {:plugin-id "reg-global-penpot" + :host "https://api-test-suite.plugins.penpot.dev/" + :scope "global" + :permissions permissions}) (t/is (preg/has-permission? "reg-global-local" "allow:global")) - (t/is (preg/has-permission? "reg-global-local" "manage:projects")))))) + (t/is (preg/has-permission? "reg-global-local" "manage:projects")) + (t/is (preg/has-permission? "reg-global-penpot" "allow:global")) + (t/is (preg/has-permission? "reg-global-penpot" "manage:projects")))))) diff --git a/frontend/test/frontend_tests/runner.cljs b/frontend/test/frontend_tests/runner.cljs index 96945e4679..5e3e187f96 100644 --- a/frontend/test/frontend_tests/runner.cljs +++ b/frontend/test/frontend_tests/runner.cljs @@ -42,6 +42,7 @@ [frontend-tests.data.workspace-context-menu-test] [frontend-tests.data.workspace-focus-test] [frontend-tests.data.workspace-interactions-test] + [frontend-tests.data.workspace-layout-other-page-test] [frontend-tests.data.workspace-libraries-load-test] [frontend-tests.data.workspace-libraries-sync-test] [frontend-tests.data.workspace-mcp-test] @@ -102,6 +103,7 @@ [frontend-tests.plugins.interactions-test] [frontend-tests.plugins.library-test] [frontend-tests.plugins.local-storage-test] + [frontend-tests.plugins.location-test] [frontend-tests.plugins.management-test] [frontend-tests.plugins.page-active-validation-test] [frontend-tests.plugins.page-test] @@ -270,6 +272,7 @@ 'frontend-tests.data.workspace-context-menu-test 'frontend-tests.data.workspace-focus-test 'frontend-tests.data.workspace-interactions-test + 'frontend-tests.data.workspace-layout-other-page-test 'frontend-tests.data.workspace-libraries-load-test 'frontend-tests.data.workspace-libraries-sync-test 'frontend-tests.data.workspace-mcp-test @@ -331,6 +334,7 @@ 'frontend-tests.plugins.interactions-test 'frontend-tests.plugins.library-test 'frontend-tests.plugins.local-storage-test + 'frontend-tests.plugins.location-test 'frontend-tests.plugins.page-active-validation-test 'frontend-tests.plugins.page-test 'frontend-tests.plugins.parser-test diff --git a/frontend/translations/en.po b/frontend/translations/en.po index 75000006d3..7828a52549 100644 --- a/frontend/translations/en.po +++ b/frontend/translations/en.po @@ -8579,7 +8579,7 @@ msgstr "No plugins installed yet" #: src/app/main/data/plugins.cljs, src/app/main/ui/dashboard.cljs, src/app/main/ui/workspace/plugins.cljs msgid "workspace.plugins.error.global-not-allowed" -msgstr "Plugins that work outside a file can only be installed from localhost for now." +msgstr "Plugins that work outside a file can only be installed from trusted sources for now." #: src/app/main/ui/workspace/plugins.cljs:237 msgid "workspace.plugins.error.manifest" diff --git a/frontend/translations/es.po b/frontend/translations/es.po index 86ae3007c3..5645657ffb 100644 --- a/frontend/translations/es.po +++ b/frontend/translations/es.po @@ -8664,7 +8664,7 @@ msgstr "No se encuentran extensiones" msgid "workspace.plugins.error.global-not-allowed" msgstr "" "Por ahora, las extensiones que funcionan fuera de un archivo solo se pueden " -"instalar desde localhost." +"instalar desde fuentes de confianza." #: src/app/main/ui/workspace/plugins.cljs:237 msgid "workspace.plugins.error.manifest" diff --git a/mcp/packages/server/data/initial_instructions.md b/mcp/packages/server/data/initial_instructions.md index dc49df83e7..1def2cf07c 100644 --- a/mcp/packages/server/data/initial_instructions.md +++ b/mcp/packages/server/data/initial_instructions.md @@ -206,6 +206,9 @@ A key object for navigating the currently active Penpot file is the `penpot` obj * `penpot.root` provides the root shape of the currently active page. * Generation of CSS content for elements via `penpot.generateStyle` * Generation of HTML/SVG content for elements via `penpot.generateMarkup` + * `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. 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). diff --git a/plugins/CHANGELOG.md b/plugins/CHANGELOG.md index db2c6f861a..3e51bb5ff8 100644 --- a/plugins/CHANGELOG.md +++ b/plugins/CHANGELOG.md @@ -5,6 +5,7 @@ - **plugin-types, plugins-runtime:** Added `penpot.waitForSave(timeout?)` to wait until pending file changes are saved (or there is nothing to save). Rejects on save failure, rollback during the wait, timeout (default 60000 ms), or an invalid timeout. The Error `code` property is `save-timeout`, `rolled-back`, `save-retrying` (an earlier failed save Penpot keeps retrying) or the save failure code. - **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 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 diff --git a/plugins/apps/plugin-api-test-suite/src/generated/api-surface.json b/plugins/apps/plugin-api-test-suite/src/generated/api-surface.json index d8886bec66..18e9d0b9c5 100644 --- a/plugins/apps/plugin-api-test-suite/src/generated/api-surface.json +++ b/plugins/apps/plugin-api-test-suite/src/generated/api-surface.json @@ -104,6 +104,7 @@ "history", "library", "localStorage", + "location", "openPage", "openViewer", "replaceColor", @@ -376,6 +377,7 @@ "Path": ["commands", "d", "fills", "type"], "PathCommand": ["command", "params"], "Penpot": ["closePlugin", "off", "on", "ui", "utils"], + "PenpotLocation": ["baseUrl", "href", "params"], "PenpotMgmt": [ "createTeam", "getFile", @@ -2253,6 +2255,12 @@ "type": "Theme", "array": false }, + "location": { + "decl": "Context", + "kind": "get", + "type": "PenpotLocation", + "array": false + }, "localStorage": { "decl": "Context", "kind": "get", @@ -6711,6 +6719,12 @@ "type": "Theme", "array": false }, + "location": { + "decl": "Context", + "kind": "get", + "type": "PenpotLocation", + "array": false + }, "localStorage": { "decl": "Context", "kind": "get", @@ -6892,6 +6906,26 @@ "array": false } }, + "PenpotLocation": { + "baseUrl": { + "decl": "PenpotLocation", + "kind": "get", + "type": null, + "array": false + }, + "href": { + "decl": "PenpotLocation", + "kind": "get", + "type": null, + "array": false + }, + "params": { + "decl": "PenpotLocation", + "kind": "get", + "type": null, + "array": false + } + }, "PenpotMgmt": { "workspace": { "decl": "PenpotMgmt", diff --git a/plugins/apps/plugin-api-test-suite/src/tests/platform.test.ts b/plugins/apps/plugin-api-test-suite/src/tests/platform.test.ts index f77e063304..b96a33d518 100644 --- a/plugins/apps/plugin-api-test-suite/src/tests/platform.test.ts +++ b/plugins/apps/plugin-api-test-suite/src/tests/platform.test.ts @@ -45,6 +45,54 @@ describe('Platform', () => { }); }); + describe('Location', () => { + // Parses a query string by hand: the plugin sandbox may not expose `URL`. + function queryParams(href: string): Record { + const query = href.split('?')[1] ?? ''; + const params: Record = {}; + for (const pair of query.split('&').filter(Boolean)) { + const [key, value = ''] = pair.split('='); + params[decodeURIComponent(key)] = decodeURIComponent( + value.replace(/\+/g, ' '), + ); + } + return params; + } + + test('baseUrl is an absolute instance URL ending in a slash', (ctx) => { + const { baseUrl } = ctx.penpot.location; + expect(/^https?:\/\/[^/?#]+(\/[^?#]*)?$/.test(baseUrl)).toBe(true); + expect(baseUrl.endsWith('/')).toBe(true); + }); + + test('href links to the open file and page', (ctx) => { + const { baseUrl, href } = ctx.penpot.location; + const file = ctx.penpot.currentFile; + const page = ctx.penpot.currentPage; + expect(file).not.toBeNull(); + expect(page).not.toBeNull(); + expect(href.startsWith(baseUrl + '?')).toBe(true); + + const params = queryParams(href); + expect(params['screen']).toBe('workspace'); + expect(params['file-id']).toBe(file!.id); + expect(params['page-id']).toBe(page!.id); + expect(params['team-id']).toBe(ctx.penpotMgmt.workspace.teamId); + }); + + test('params match the query of href', (ctx) => { + const { href, params } = ctx.penpot.location; + expect(params).toEqual(queryParams(href)); + }); + + test('each read returns a new snapshot', (ctx) => { + const first = ctx.penpot.location; + const second = ctx.penpot.location; + expect(first === second).toBe(false); + expect(first).toEqual(second); + }); + }); + describe('History', () => { test('undo block begin and finish wrap operations', (ctx) => { const block = ctx.penpot.history.undoBlockBegin(); diff --git a/plugins/libs/plugin-types/index.d.ts b/plugins/libs/plugin-types/index.d.ts index fade26e1f2..3ae76ca542 100644 --- a/plugins/libs/plugin-types/index.d.ts +++ b/plugins/libs/plugin-types/index.d.ts @@ -1165,6 +1165,19 @@ export interface Context { */ readonly theme: Theme; + /** + * 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 + * ```js + * const { baseUrl, href, params } = penpot.location; + * console.log(baseUrl); // "https://design.penpot.app/" + * console.log(params['file-id']); + * ``` + */ + readonly location: PenpotLocation; + /** * Access to the localStorage proxy */ @@ -3404,6 +3417,33 @@ export interface LibraryTypography extends LibraryElement { setFont(font: Font, variant?: FontVariant): void; } +/** + * 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`. + */ +export interface PenpotLocation { + /** + * The public URL of the Penpot instance, ending in `/`, + * e.g. `"https://design.penpot.app/"`. + */ + readonly baseUrl: 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. + */ + readonly href: 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. + */ + readonly params: Record; +} + /** * Proxy for the local storage. Only elements owned by the plugin * can be stored and accessed. diff --git a/plugins/libs/plugins-runtime/src/lib/api/index.ts b/plugins/libs/plugins-runtime/src/lib/api/index.ts index 5fa70a68c7..e99678670b 100644 --- a/plugins/libs/plugins-runtime/src/lib/api/index.ts +++ b/plugins/libs/plugins-runtime/src/lib/api/index.ts @@ -19,6 +19,7 @@ import type { Page, Path, Penpot, + PenpotLocation, PenpotMgmt, Rectangle, Shape, @@ -268,6 +269,11 @@ export function createApi( return plugin.context.theme; }, + get location(): PenpotLocation { + checkPermission('content:read', false); + return plugin.context.location; + }, + get localStorage(): LocalStorage { checkPermission('allow:localstorage'); return plugin.context.localStorage; diff --git a/plugins/libs/plugins-runtime/src/lib/api/plugin-api.spec.ts b/plugins/libs/plugins-runtime/src/lib/api/plugin-api.spec.ts index d177d02f9c..835ce567b7 100644 --- a/plugins/libs/plugins-runtime/src/lib/api/plugin-api.spec.ts +++ b/plugins/libs/plugins-runtime/src/lib/api/plugin-api.spec.ts @@ -276,4 +276,38 @@ describe('Plugin api', () => { expect(currentSelection).toEqual(selection); }); }); + + describe('location', () => { + const location = { + baseUrl: 'https://design.penpot.app/', + href: 'https://design.penpot.app/?screen=dashboard-recent&team-id=t', + params: { screen: 'dashboard-recent', 'team-id': 't' }, + }; + + it('returns the location while no workspace is ready', () => { + const { penpot } = createApi({ + ...pluginManager, + manifest: { ...pluginManager.manifest, scope: 'global' }, + context: { + ...pluginManager.context, + location, + management: { workspace: { status: 'none' } }, + }, + } as any); + + expect(penpot.location).toEqual(location); + }); + + it('requires content:read', () => { + const { penpot } = createApi({ + ...pluginManager, + manifest: { ...pluginManager.manifest, permissions: [] }, + context: { ...pluginManager.context, location }, + } as any); + + expect(() => penpot.location).toThrow( + 'Permission content:read is not granted', + ); + }); + }); }); diff --git a/render-wasm/src/shapes/modifiers.rs b/render-wasm/src/shapes/modifiers.rs index 1898ed7276..b79d811459 100644 --- a/render-wasm/src/shapes/modifiers.rs +++ b/render-wasm/src/shapes/modifiers.rs @@ -17,6 +17,7 @@ use crate::shapes::{ }; use crate::state::{ShapesPoolRef, State}; use crate::uuid::Uuid; +use crate::{get_render_state, has_render_state}; #[allow(clippy::too_many_arguments)] fn propagate_children( @@ -438,6 +439,22 @@ fn propagate_reflow( } } +fn propagate_nested_reflows( + ids: &[Uuid], + shapes: ShapesPoolRef, + reflown: &HashSet, + entries: &mut VecDeque, +) { + for shape in ids.iter().filter_map(|id| shapes.get(id)) { + for child_id in shape.all_children_iter(shapes, false, false) { + if !reflown.contains(&child_id) && shapes.get(&child_id).is_some_and(Shape::has_layout) + { + entries.push_back(Modifier::reflow(child_id, false)); + } + } + } +} + fn reflow_shape( id: &Uuid, state: &State, @@ -504,6 +521,16 @@ pub fn propagate_modifiers( // are transformed in the same pass. let mut pending_reflows = HashSet::::new(); + let requested_reflows: Vec = entries + .iter() + .filter_map(|modifier| match modifier { + Modifier::Reflow(id, _) => Some(*id), + Modifier::Transform(..) => None, + }) + .collect(); + let interactive = has_render_state() && get_render_state().options.is_interactive_transform(); + let mut nested_layouts_queued = interactive || requested_reflows.is_empty(); + // We first propagate the transforms to the children and then after // recalculate the layouts. The layout can create further transforms that // we need to re-propagate. @@ -564,6 +591,14 @@ pub fn propagate_modifiers( } reflow_shape(id, state, &mut reflown, &mut entries, &mut bounds_temp)?; } + + // A requested reflow also lays out the layouts below it that kept + // their size, so were skipped: a component sync can leave their + // children where the layout would not put them. + if entries.is_empty() && !nested_layouts_queued { + nested_layouts_queued = true; + propagate_nested_reflows(&requested_reflows, shapes, &reflown, &mut entries); + } } Ok(modifiers @@ -927,4 +962,81 @@ mod tests { assert_eq!(bounds.width(), 4.0); assert_eq!(bounds.height(), 4.0); } + + fn add_flex_row(shape: &mut Shape) { + shape.set_shape_type(Type::Frame(Frame::default())); + shape.set_flex_layout_data( + FlexDirection::Row, + 0.0, + 0.0, + AlignItems::Start, + AlignContent::Start, + JustifyItems::Start, + JustifyContent::Start, + WrapType::NoWrap, + 0.0, + 0.0, + 0.0, + 0.0, + ); + } + + fn add_fixed_layout_child(shape: &mut Shape, parent_id: Uuid) { + shape.set_parent(parent_id); + shape.set_flex_layout_child_data( + 0.0, + 0.0, + 0.0, + 0.0, + Sizing::Fix, + Sizing::Fix, + None, + None, + None, + None, + None, + false, + None, + ); + } + + #[test] + fn test_reflow_lays_out_nested_layout_that_keeps_its_size() { + let outer_id = Uuid::new_v4(); + let inner_id = Uuid::new_v4(); + let child_id = Uuid::new_v4(); + + let mut state = State::new(); + state.shapes.initialize(10); + { + let child = state.shapes.add_shape(child_id); + child.set_selrect(100.0, 0.0, 116.0, 16.0); + add_fixed_layout_child(child, inner_id); + + let inner = state.shapes.add_shape(inner_id); + add_flex_row(inner); + add_fixed_layout_child(inner, outer_id); + inner.add_child(child_id); + inner.set_selrect(0.0, 0.0, 300.0, 16.0); + + let outer = state.shapes.add_shape(outer_id); + add_flex_row(outer); + outer.add_child(inner_id); + outer.set_selrect(0.0, 0.0, 300.0, 16.0); + } + + let entry = TransformEntry::from_input(outer_id, Matrix::new_identity()); + let result = propagate_modifiers(&state, &[entry], PixelPrecision::Disabled).unwrap(); + + let transform = result + .iter() + .find(|entry| entry.id == child_id) + .map(|entry| entry.transform) + .expect("the child of the nested layout is laid out"); + + let child = state.shapes.get(&child_id).unwrap(); + let bounds = child.bounds().transform(&transform); + + assert!(is_close_to(bounds.min_x(), 0.0)); + } }