From a4d5862470ea2afa9d2627b31b3683055b47ed8e Mon Sep 17 00:00:00 2001 From: Yao Jingxi <23722032@bjtu.edu.cn> Date: Thu, 19 Nov 2026 13:12:46 +0800 Subject: [PATCH] =?UTF-8?q?feat(plugins):=20=E8=A7=86=E5=9B=BE=E4=BA=8B?= =?UTF-8?q?=E4=BB=B6=E5=B8=A6=20width=EF=BC=8C=E7=94=BB=E5=B8=83=E5=8F=AF?= =?UTF-8?q?=E4=BB=A5=E5=86=99=20resize=20=E8=B7=9F=E9=9A=8F=E7=AA=97?= =?UTF-8?q?=E5=8F=A3=E9=87=8D=E6=96=B0=E6=8E=92=E7=89=88?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 会报告宽度的宿主在每个视图事件里带 width(排版视图节点用的宽度,也是顶层画布的宽度),量到宽度之后才发 open;画布的 on 可以写 resize,宽度停止变化 400 ms 后宿主发 resize 和新的 width。契约 README 同时写明缩放为 1 时怎样放 viewBox:不写 pan 时显示整个 viewBox、从左上角开始,写了 pan 时宽度占满视图。 Core 画布校验接受 on: ["viewport", "resize"],schema 同步;Rust、Java、Node 三个 SDK 支持 width 和 resize 并补 README;settings.md 中英说明区域画布按 width 排版和旧宿主下的固定宽度;更新记录登记本次补充,并把 #105 的条目移到时间线。取代 #107。 --- rust/crates/plugin-ui/src/canvas.rs | 2 +- rust/crates/plugin-ui/src/lib.rs | 10 +++++- shared/plugins/contract/v1/README.md | 34 ++++++++++++++++--- .../plugins/contract/v1/plugin-ui.schema.json | 4 +-- shared/plugins/reference/domains/settings.md | 2 ++ .../plugins/reference/protocol-changelog.md | 8 ++++- shared/plugins/sdk/java/README.md | 6 +++- .../litheidea/plugin/sdk/ViewEvent.java | 16 +++++++++ .../github/litheidea/plugin/sdk/ViewTest.java | 13 +++++-- shared/plugins/sdk/node/README.md | 6 +++- shared/plugins/sdk/node/src/index.d.ts | 10 ++++-- shared/plugins/sdk/node/src/view.mjs | 5 +-- shared/plugins/sdk/node/test/backend.test.mjs | 7 ++-- shared/plugins/sdk/node/test/types/view.mts | 5 +++ shared/plugins/sdk/rust/README.md | 6 +++- .../plugins/sdk/rust/plugin-sdk/src/view.rs | 27 +++++++++++++-- 16 files changed, 137 insertions(+), 24 deletions(-) diff --git a/rust/crates/plugin-ui/src/canvas.rs b/rust/crates/plugin-ui/src/canvas.rs index b95e446c..7973265b 100644 --- a/rust/crates/plugin-ui/src/canvas.rs +++ b/rust/crates/plugin-ui/src/canvas.rs @@ -98,7 +98,7 @@ pub(crate) fn check(walk: &mut Walk<'_>, value: &Value, path: &str) -> Checked<( )); } } - events(map, path, &["viewport"])?; + events(map, path, &["viewport", "resize"])?; let nodes = map .get("nodes") .ok_or_else(|| fail(at(path, "nodes"), "Required."))?; diff --git a/rust/crates/plugin-ui/src/lib.rs b/rust/crates/plugin-ui/src/lib.rs index e2e42f9d..9bd526d0 100644 --- a/rust/crates/plugin-ui/src/lib.rs +++ b/rust/crates/plugin-ui/src/lib.rs @@ -204,7 +204,7 @@ mod tests { ]} ]}, {"type":"canvas","id":"graph","label":"Module graph","height":200,"viewBox":[0,0,400,200], - "pan":true,"zoom":[0.5,4],"on":["viewport"],"nodes":[ + "pan":true,"zoom":[0.5,4],"on":["viewport","resize"],"nodes":[ {"type":"rect","x":0,"y":0,"w":400,"h":200,"radius":8,"fill":{"linear":[[0,"#1E1F22"],[1,"$surface"]],"angle":90}}, {"type":"path","d":"M 10 10 L 390 190","stroke":{"light":"#3574F0","dark":"#548AF7"},"width":2,"dash":[4,2],"cap":"round"}, {"type":"group","id":"node.core","x":40,"y":40,"w":120,"h":48,"radius":6,"on":["click"], @@ -424,6 +424,14 @@ mod tests { } let bad_box = json!([{"type":"canvas","id":"c","label":"C","height":10,"viewBox":[0,0,0,10],"nodes":[]}]); assert_eq!(field(&context, bad_box), "view[0].viewBox"); + let on = |events: serde_json::Value| { + json!([{"type":"canvas","id":"c","label":"C","height":10,"viewBox":[0,0,10,10],"on":events,"nodes":[]}]) + }; + assert_eq!(field(&context, on(json!(["click"]))), "view[0].on[0]"); + assert_eq!( + field(&context, on(json!(["resize", "resize"]))), + "view[0].on[1]" + ); } #[test] diff --git a/shared/plugins/contract/v1/README.md b/shared/plugins/contract/v1/README.md index f4a29e9c..0e42e1ac 100644 --- a/shared/plugins/contract/v1/README.md +++ b/shared/plugins/contract/v1/README.md @@ -5129,7 +5129,7 @@ event, with these params: | Field | Meaning | | --- | --- | -| `event` | `open`, `close`, `click`, `change`, `select`, `activate`, `viewport`, or `settings` (below) | +| `event` | `open`, `close`, `click`, `change`, `select`, `activate`, `viewport`, `resize`, or `settings` (below) | | `instance` | Host-chosen string naming this showing of the view. A new `open` gets a new instance; the same tool window open in two workspaces has two. | | `surface` | `{toolWindowID}` or `{settingRegionID}`: the declaration being drawn | | `language` | Interface language tag, such as `en` or `zh-Hans`. View text is plugin content; the backend returns it in this language. | @@ -5140,6 +5140,7 @@ event, with these params: | `setting` | `change` of a control bound to a setting: the setting ID | | `item` | `select`, `activate`: the tree item ID; `node` is the tree's ID | | `viewport` | `viewport`: `{x, y, width, height}`, the visible part of the canvas in view-box coordinates | +| `width` | Every event, from a host that reports it: the width in points the host lays the view's nodes out in, which is also the width of a canvas at the top level, a whole number of at least 1. A host that reports it sends `open` only once it knows the width. | | Event | Sent when | Result | | --- | --- | --- | @@ -5149,13 +5150,14 @@ event, with these params: | `change` | A `textField` commits on Enter, focus loss, or submit; a `select`, `segmented`, or `toggle` changes | Any | | `select`, `activate` | A tree item is selected; double-clicked or activated with Return | Any | | `viewport` | 400 ms after a pan or zoom stops, only for a canvas whose `on` lists `viewport` | Any | +| `resize` | 400 ms after the view's `width` stops changing, only while the drawn view has a canvas whose `on` lists `resize` | Any | | `settings` | `effective` or `draft` changes: the user edits a declared row or a bound control, applies, cancels, or a value changes elsewhere | Any | Hovering, pressing, keyboard focus and focus rings, tooltips, tree expansion, scrolling, panning, zooming, and typing never reach the plugin. A text field does not call the backend per keystroke. The host sends one event at a time -per instance, in order, and may merge waiting `viewport` or `settings` events -into the latest one. A view changes only in answer to an event; this version +per instance, in order, and may merge waiting `viewport`, `resize`, or +`settings` events into the latest one. A view changes only in answer to an event; this version has no way for a plugin to push a view on its own. #### Results and patches @@ -5241,11 +5243,35 @@ follows [source-backed settings](#source-backed-settings-editors). ``` A canvas draws its `nodes` in order, in `viewBox` coordinates -(`[x, y, width, height]`) scaled to the width of the view and `height` points +(`[x, y, width, height]`), in an area as wide as the view and `height` points tall (1–2000). `label` is the scene's accessible name. `pan` lets the user drag the empty area, and `zoom` is the `[minimum, maximum]` range around 1 (0.05–20); the host draws the zoom buttons. The scroll wheel scrolls the page; ⌘ or Ctrl with the wheel zooms, and so does a pinch on a host that reports one. +`on` lists the events the canvas sends: `viewport` and `resize` (see +[Events](#events)). + +At zoom 1 the host scales the `viewBox` in one of two ways: + +- **Without `pan`**, the whole `viewBox` shows: it is scaled to the width of + the view, but no taller than `height`, and starts at the area's top-left + corner. A scene whose `viewBox` is as wide as the view and `height` tall + draws at one point a unit. In a wider view it keeps that size, whole, with + the area's trailing part left empty; in a narrower one it shrinks to the + width and leaves the area's bottom empty. +- **With `pan`**, the `viewBox`'s width fills the view and its top edge is at + the area's top; the user pans to the parts below the area. Zoomed out until + the `viewBox` is narrower than the area, it is centered across it. + +A scene that follows the window lays itself out for the event's `width`: it +gives its `viewBox` that width, picks `height` for what it draws there, and +lists `resize` in `on`, so the host sends `resize` with the new `width` once +the window stops being resized and the plugin returns the scene laid out +again. Until the answer arrives the host scales the scene it has, as above. A +host that does not report `width` sends no `resize` and may refuse a canvas +that lists it, so a plugin lists `resize` only in answer to an event that +carried `width`, and otherwise lays the scene out for a width of its own +choosing. | `type` | Fields | | --- | --- | diff --git a/shared/plugins/contract/v1/plugin-ui.schema.json b/shared/plugins/contract/v1/plugin-ui.schema.json index ce1bd7e6..5017c158 100644 --- a/shared/plugins/contract/v1/plugin-ui.schema.json +++ b/shared/plugins/contract/v1/plugin-ui.schema.json @@ -341,7 +341,7 @@ } }, "canvas": { - "description": "A vector scene the host draws natively in view-box coordinates, scaled to the view width. Pan, zoom, hover states and tooltips stay in the host; viewport sends viewport events after the user pans or zooms. Canvas text is not searchable; a settings region names its words in keywords.", + "description": "A vector scene the host draws natively in view-box coordinates, in an area as wide as the view and height points tall. Without pan, the whole view box shows at zoom 1, scaled to the view width but no taller than height, from the top-left corner; with pan, its width fills the view. Pan, zoom, hover states and tooltips stay in the host; viewport sends viewport events after the user pans or zooms, and resize sends resize events with the new view width after the window is resized. Canvas text is not searchable; a settings region names its words in keywords.", "type": "object", "additionalProperties": false, "required": ["type", "id", "label", "height", "viewBox", "nodes"], @@ -365,7 +365,7 @@ "maxItems": 2, "items": { "type": "number", "minimum": 0.05, "maximum": 20 } }, - "on": { "type": "array", "maxItems": 1, "uniqueItems": true, "items": { "const": "viewport" } }, + "on": { "type": "array", "maxItems": 2, "uniqueItems": true, "items": { "enum": ["viewport", "resize"] } }, "nodes": { "$ref": "#/$defs/shapes" } } }, diff --git a/shared/plugins/reference/domains/settings.md b/shared/plugins/reference/domains/settings.md index 3b802b7a..93b566fc 100644 --- a/shared/plugins/reference/domains/settings.md +++ b/shared/plugins/reference/domains/settings.md @@ -86,6 +86,7 @@ - `keywords`:1–32 个,忽略大小写互不相同,每个 1–64 个字符、不换行、首尾没有空白。设置搜索除了页面标题和声明的行,也按这些词找到页面,并打开到这个插件的部分。 - `view`:`{function}`,插件后端的视图函数,画在页面标题和插件声明的行之间。视图可以放宿主控件、画布,也可以用绑定控件编辑本插件的设置(和声明的行改的是同一份草稿)、放本插件按钮和显示本插件工具解析结果的工具行,但不能放树。需要 `backend`、`ui` 0 和 `ui.contribute` 权限;页面打开时宿主启动后端。 - 只写关键词的区域不需要后端。区域本身不保存任何值。声明区域也算使用了 `settings`。 +- 区域里的画布要跟随窗口宽度时,按事件里的 `width` 排版:`viewBox` 的宽度就设成 `width`,`height` 取在这个宽度下画出来需要的高度,并在画布的 `on` 里写 `resize`。用户调整窗口大小、停下 400 ms 后,宿主发 `resize` 和新的 `width`,插件按新宽度返回重新排版的场景,场景始终一个单位一个点。不写 `pan` 时,宿主在答复到达前按[画布](../../contract/v1/README.md#canvas)的规则显示整个 `viewBox`,不会放大到裁掉下半部分。事件里没有 `width` 的旧宿主不发 `resize`,也可能拒绝写了它的画布,所以这时不写 `resize`,按固定宽度排版:桌面端窗口最小时,语言页的区域约 610 点宽,构建系统页和编译器页右侧详情里的区域约 340 点宽。 ### 两层保存与生效顺序 @@ -238,6 +239,7 @@ Content that declared rows cannot draw goes in `settingRegions` (at most 16, uni - `keywords`: 1–32, distinct ignoring case, each 1–64 characters without line breaks or surrounding spaces. Settings search finds the page by them in addition to the page title and the declared rows, and opens the page at this plugin's part. - `view`: `{function}`, a view function of the plugin's backend, drawn between the page header and the plugin's declared rows. The view may hold host controls and canvases, edit the plugin's own settings through bound controls (the same draft the declared rows edit), show the plugin's buttons and tool rows with how its tools resolve, but no tree. It needs `backend`, `ui` 0, and the `ui.contribute` permission; the host starts the backend when the page opens. - A region with keywords only needs no backend. A region stores no values. Declaring regions counts as using `settings`. +- A canvas in a region that follows the window lays itself out for the event's `width`: its `viewBox` is `width` wide, its `height` is what the scene needs at that width, and its `on` lists `resize`. Once the user stops resizing the window for 400 ms, the host sends `resize` with the new `width`, and the plugin answers the scene laid out again, so it always draws at one point a unit. Without `pan`, the host shows the whole `viewBox` until the answer arrives (see [canvas](../../contract/v1/README.md#canvas)), never scaled up so far that its bottom is cut off. An older host sends no `width` and no `resize` and may refuse a canvas that lists it, so without `width` a plugin leaves `resize` out and lays the scene out for a fixed width: in Lithe desktop's smallest window a region is about 610 points wide on a language page and about 340 in the detail pane of a build system or compiler page. ### Two layers and their order diff --git a/shared/plugins/reference/protocol-changelog.md b/shared/plugins/reference/protocol-changelog.md index a26d52c9..f0b956b8 100644 --- a/shared/plugins/reference/protocol-changelog.md +++ b/shared/plugins/reference/protocol-changelog.md @@ -14,7 +14,7 @@ ## 待合入 -- `ui` 0、`settings` 0 内的说明补充(API-13、API-19):契约 README 写明画布 `image` 节点怎样读取:路径留在插件包内、经过真实目录、指向普通 PNG 文件,单个文件最多 256 KiB、每边最多 1024 像素(预算表新增一行);宿主在场景第一次画到它时于窗口线程外读取,保留到视图关闭,读到之前或读取失败时场景不画它,失败只记一次日志。`image` 节点的字段表补上 `opacity`。文字是一行,基线在 `y`,`align` 把行首(默认)、中点或行尾放在 `x`;渐变 `angle` 与 CSS `linear-gradient` 一致(0 向上、90 向右、默认 180 向下),渐变线穿过形状中心;分组的 `x`、`y` 放置原点,`scale` 缩放内部,`children`、`w`、`h`、`radius` 都在分组自己的坐标里;捏合缩放只在宿主能上报捏合时可用。fixture `fixtures/ui/view-results.json` 的文字基线移到卡片中间。[能力与协议版本对照](capabilities-and-versions.md)删掉“插件视图尚未在桌面端绘制”的脚注,`domains/ui.md`、`domains/settings.md` 的桌面端一行改为已呈现插件视图、设置区域和包内翻译 `l10n/`([1lck/Lithe-IDEA#2181](https://github.com/1lck/Lithe-IDEA/issues/2181))。没有新增版本号、宿主方法、通知或 SDK 版本。实现见 [#105](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/105)。 +- `ui` 0 内的补充(API-13):视图事件新增 `width` 和 `resize`,画布可以跟随窗口宽度重新排版。会报告宽度的宿主在每个视图事件里带 `width`(排版视图节点用的宽度,单位为点,至少为 1 的整数,也是顶层画布的宽度),并且量到宽度之后才发 `open`;画布的 `on` 除 `viewport` 外可以写 `resize`,视图里有这样的画布时,宽度停止变化 400 ms 后宿主发 `resize` 和新的 `width`,等待中的 `resize` 可以合并成最新的一个。插件只有在收到带 `width` 的事件后才写 `resize`:不报告宽度的宿主不发 `resize`,它的 Core 也会拒绝写了 `resize` 的画布。契约 README 同时写明画布在缩放 1 时怎样放 `viewBox`:不写 `pan` 时显示整个 `viewBox`,按视图宽度缩放但不超过 `height`,从区域左上角开始;写了 `pan` 时宽度占满视图、上边对齐区域顶部,缩小到比区域窄时水平居中。以前的说明只有“按视图宽度缩放、`height` 点高”,在更宽的窗口里会裁掉场景下半部分。Core 的画布校验接受 `on: ["viewport", "resize"]`,`plugin-ui.schema.json` 的 canvas 说明和 `on` 同步;Rust SDK 新增 `ViewEventKind::Resize` 和 `ViewEvent::width`,Java SDK 新增 `Kind.RESIZE` 和 `width()`,Node SDK 的 `ViewEventKind` 加上 `resize`、`ViewEvent` 加上 `width`、画布 `on` 的类型放宽,三个 SDK 的 README 补充用法;`domains/settings.md` 中英两段说明区域画布怎样按 `width` 排版,以及旧宿主下的固定宽度(语言页约 610 点、构建系统页和编译器页右侧详情约 340 点)([1lck/Lithe-IDEA#2181](https://github.com/1lck/Lithe-IDEA/issues/2181))。没有新增能力版本、宿主方法、通知或 SDK 版本,取代 [#107](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/107)。 ## 按协议查首次出现 @@ -144,6 +144,12 @@ ## 时间线(新的在上) +### 2026-11-19 + +| PR | 修改人 | API 编号 | 协议 / 能力 | 改了什么 | +| --- | --- | --- | --- | --- | +| [#105](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/105) | [@xiaoyumuxi](https://github.com/xiaoyumuxi) | API-13、API-19 | `ui` 0、`settings` 0 内的说明补充(API-13、API-19) | 契约 README 写明画布 `image` 节点怎样读取:路径留在插件包内、经过真实目录、指向普通 PNG 文件,单个文件最多 256 KiB、每边最多 1024 像素(预算表新增一行);宿主在场景第一次画到它时于窗口线程外读取,保留到视图关闭,读到之前或读取失败时场景不画它,失败只记一次日志。`image` 节点的字段表补上 `opacity`。文字是一行,基线在 `y`,`align` 把行首(默认)、中点或行尾放在 `x`;渐变 `angle` 与 CSS `linear-gradient` 一致(0 向上、90 向右、默认 180 向下),渐变线穿过形状中心;分组的 `x`、`y` 放置原点,`scale` 缩放内部,`children`、`w`、`h`、`radius` 都在分组自己的坐标里;捏合缩放只在宿主能上报捏合时可用。fixture `fixtures/ui/view-results.json` 的文字基线移到卡片中间。[能力与协议版本对照](capabilities-and-versions.md)删掉“插件视图尚未在桌面端绘制”的脚注,`domains/ui.md`、`domains/settings.md` 的桌面端一行改为已呈现插件视图、设置区域和包内翻译 `l10n/`([1lck/Lithe-IDEA#2181](https://github.com/1lck/Lithe-IDEA/issues/2181))。没有新增版本号、宿主方法、通知或 SDK 版本。 | + ### 2026-11-18 | PR | 修改人 | API 编号 | 协议 / 能力 | 改了什么 | diff --git a/shared/plugins/sdk/java/README.md b/shared/plugins/sdk/java/README.md index 94762d0b..1efa0dc7 100644 --- a/shared/plugins/sdk/java/README.md +++ b/shared/plugins/sdk/java/README.md @@ -104,7 +104,11 @@ handler answers a `ViewResult`: Nodes are plain JSON maps shaped as [`plugin-ui.schema.json`](../../contract/v1/plugin-ui.schema.json) describes. Core checks every answer, and the host draws nothing that Core refused. Return -view text in `event.language()`. +view text in `event.language()`. A host that reports the view's width sends +it as `event.width()` on every event; a canvas that follows the window lays +itself out at that width, lists `resize` in its `on`, and answers +`Kind.RESIZE` with the scene laid out again +([Canvas](../../contract/v1/README.md#canvas)). ```java backend.view("explorer.draw", (event, context) -> { diff --git a/shared/plugins/sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/ViewEvent.java b/shared/plugins/sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/ViewEvent.java index 23f5bd4c..a2f95e9e 100644 --- a/shared/plugins/sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/ViewEvent.java +++ b/shared/plugins/sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/ViewEvent.java @@ -28,6 +28,11 @@ public enum Kind { SELECT("select"), ACTIVATE("activate"), VIEWPORT("viewport"), + /** + * The view's width stopped changing, for a view with a canvas whose + * {@code on} lists {@code resize}; {@link ViewEvent#width()} is the new width. + */ + RESIZE("resize"), /** The effective or draft setting values changed. */ SETTINGS("settings"); @@ -96,6 +101,7 @@ public double height() { private final String setting; private final String item; private final Viewport viewport; + private final Double width; private ViewEvent(Map params) { kind = Kind.parse(required(params, "event")); @@ -128,6 +134,7 @@ private ViewEvent(Map params) { Map area = object(box); viewport = new Viewport(number(area, "x"), number(area, "y"), number(area, "width"), number(area, "height")); } + width = params.get("width") == null ? null : number(params, "width"); } /** @@ -213,6 +220,15 @@ public Viewport viewport() { return viewport; } + /** + * The width in points the host lays the view out in, on every event from a + * host that reports it; or null. List {@code resize} in a canvas's + * {@code on} only when it is present: a host without it may refuse the canvas. + */ + public Double width() { + return width; + } + private static PluginSdkError invalid() { return new PluginSdkError(INVALID_EVENT, "Invalid view event."); } diff --git a/shared/plugins/sdk/java/plugin-sdk/src/test/java/io/github/litheidea/plugin/sdk/ViewTest.java b/shared/plugins/sdk/java/plugin-sdk/src/test/java/io/github/litheidea/plugin/sdk/ViewTest.java index c58d932a..32ad7c27 100644 --- a/shared/plugins/sdk/java/plugin-sdk/src/test/java/io/github/litheidea/plugin/sdk/ViewTest.java +++ b/shared/plugins/sdk/java/plugin-sdk/src/test/java/io/github/litheidea/plugin/sdk/ViewTest.java @@ -32,7 +32,8 @@ private static Map event(Object... extra) { void readsEveryFieldTheHostSends() { ViewEvent parsed = ViewEvent.parse(event( "node", "otp", "setting", "otpRelease", "value", "27", - "viewport", map("x", 0L, "y", 10.5, "width", 1200L, "height", 640L))); + "viewport", map("x", 0L, "y", 10.5, "width", 1200L, "height", 640L), + "width", 612L)); assertEquals(ViewEvent.Kind.CHANGE, parsed.kind()); assertEquals("otp", parsed.settingRegionId()); assertNull(parsed.toolWindowId()); @@ -43,13 +44,18 @@ void readsEveryFieldTheHostSends() { assertEquals("27", parsed.value()); assertEquals(10.5, parsed.viewport().y()); assertEquals(1200.0, parsed.viewport().width()); + assertEquals(612.0, parsed.width()); assertNull(parsed.item()); assertThrows(UnsupportedOperationException.class, () -> parsed.draft().put("otpRelease", "28")); // An optional field sent as null counts as absent. - ViewEvent absent = ViewEvent.parse(event("node", null, "value", null, "viewport", null)); + ViewEvent absent = ViewEvent.parse(event("node", null, "value", null, "viewport", null, "width", null)); assertNull(absent.node()); assertNull(absent.value()); assertNull(absent.viewport()); + assertNull(absent.width()); + ViewEvent resize = ViewEvent.parse(event("event", "resize", "width", 340L)); + assertEquals(ViewEvent.Kind.RESIZE, resize.kind()); + assertEquals(340.0, resize.width()); } @Test @@ -65,7 +71,8 @@ void refusesEventsWithoutTheirRequiredShape() { noDraft, event("node", 3L), event("value", Arrays.asList("a")), - event("viewport", map("x", 0L))); + event("viewport", map("x", 0L)), + event("width", "wide")); for (Map params : cases) { PluginSdkError error = assertThrows(PluginSdkError.class, () -> ViewEvent.parse(params), String.valueOf(params)); assertEquals("sdk.view.invalidEvent", error.code()); diff --git a/shared/plugins/sdk/node/README.md b/shared/plugins/sdk/node/README.md index cfeaee83..9a5d65aa 100644 --- a/shared/plugins/sdk/node/README.md +++ b/shared/plugins/sdk/node/README.md @@ -146,7 +146,11 @@ Nodes are plain objects shaped as [`plugin-ui.schema.json`](../../contract/v1/plugin-ui.schema.json) describes; `index.d.ts` types them as `ViewNode`, `CanvasNode` and `ViewPatch`. Core checks every answer, and the host draws nothing that Core refused. Return view -text in `event.language`. +text in `event.language`. A host that reports the view's width sends it as +`event.width` on every event; a canvas that follows the window lays itself +out at that width, lists `resize` in its `on`, and answers the `resize` event +with the scene laid out again +([Canvas](../../contract/v1/README.md#canvas)). ```js backend.view('explorer.draw', (event) => { diff --git a/shared/plugins/sdk/node/src/index.d.ts b/shared/plugins/sdk/node/src/index.d.ts index 9c44edec..614deebd 100644 --- a/shared/plugins/sdk/node/src/index.d.ts +++ b/shared/plugins/sdk/node/src/index.d.ts @@ -542,7 +542,7 @@ export interface VcsTraits { // the result it returns. contract/v1/plugin-ui.schema.json is the authority; // Core's plugins.ui.applyResult enforces the rules a type cannot express. -export type ViewEventKind = 'open' | 'close' | 'click' | 'change' | 'select' | 'activate' | 'viewport' | 'settings'; +export type ViewEventKind = 'open' | 'close' | 'click' | 'change' | 'select' | 'activate' | 'viewport' | 'resize' | 'settings'; /** Params of one call to a view function. */ export interface ViewEvent { @@ -567,6 +567,12 @@ export interface ViewEvent { item?: string; /** `viewport`: the visible part of the canvas, in view-box coordinates. */ viewport?: { x: number; y: number; width: number; height: number }; + /** + * The width in points the host lays the view out in, on every event from a + * host that reports it; `resize` sends the new width. List `resize` in a + * canvas's `on` only when it is present: a host without it may refuse the canvas. + */ + width?: number; } /** A whole view, a batch of patches, or `{}` when nothing changed. The first result after `open` is a view. */ @@ -645,7 +651,7 @@ export interface ViewCanvas { viewBox: [x: number, y: number, width: number, height: number]; pan?: boolean; zoom?: [minimum: number, maximum: number]; - on?: ['viewport']; + on?: Array<'viewport' | 'resize'>; nodes: CanvasNode[]; } diff --git a/shared/plugins/sdk/node/src/view.mjs b/shared/plugins/sdk/node/src/view.mjs index 5c957edc..a82d756a 100644 --- a/shared/plugins/sdk/node/src/view.mjs +++ b/shared/plugins/sdk/node/src/view.mjs @@ -4,7 +4,7 @@ import { PluginSdkError } from './errors.mjs'; -const KINDS = new Set(['open', 'close', 'click', 'change', 'select', 'activate', 'viewport', 'settings']); +const KINDS = new Set(['open', 'close', 'click', 'change', 'select', 'activate', 'viewport', 'resize', 'settings']); const OPTIONAL_TEXT = ['node', 'canvas', 'setting', 'item']; const isObject = (value) => typeof value === 'object' && value !== null && !Array.isArray(value); @@ -20,7 +20,7 @@ export function checkViewEvent(params) { const invalid = () => new PluginSdkError('sdk.view.invalidEvent', 'Invalid view event.'); if (!isObject(params) || !KINDS.has(params.event)) throw invalid(); if (typeof params.instance !== 'string' || typeof params.language !== 'string') throw invalid(); - const { surface, settings, value, viewport } = params; + const { surface, settings, value, viewport, width } = params; if (!isObject(surface) || !isOptionalText(surface.toolWindowID) || !isOptionalText(surface.settingRegionID) || isAbsent(surface.toolWindowID) === isAbsent(surface.settingRegionID)) { throw invalid(); @@ -32,5 +32,6 @@ export function checkViewEvent(params) { && ['x', 'y', 'width', 'height'].every((key) => typeof viewport[key] === 'number'))) { throw invalid(); } + if (!isAbsent(width) && typeof width !== 'number') throw invalid(); return params; } diff --git a/shared/plugins/sdk/node/test/backend.test.mjs b/shared/plugins/sdk/node/test/backend.test.mjs index 5e03d16a..04d53a0b 100644 --- a/shared/plugins/sdk/node/test/backend.test.mjs +++ b/shared/plugins/sdk/node/test/backend.test.mjs @@ -127,7 +127,7 @@ test('a view function gets the view event and answers {} when it returns nothing // An optional field sent as null counts as absent. const absent = await host.request('lithe/function/invoke', { functionID: 'explorer.draw', operationID: 'op-3', - params: { event: 'change', node: null, value: null, viewport: null, ...base }, + params: { event: 'change', node: null, value: null, viewport: null, width: null, ...base }, }); assert.deepEqual(absent.result, {}); // Params that are not a view event never reach the handler. @@ -150,8 +150,10 @@ test('a view event without its required shape is refused', () => { settings: { effective: { otpRelease: '26' }, draft: { otpRelease: '27' } }, ...extra, }); - const parsed = event({ setting: 'otpRelease', value: 27, viewport: { x: 0, y: 10.5, width: 1200, height: 640 } }); + const parsed = event({ setting: 'otpRelease', value: 27, viewport: { x: 0, y: 10.5, width: 1200, height: 640 }, width: 612 }); assert.equal(checkViewEvent(parsed), parsed); + const resize = event({ event: 'resize', width: 340 }); + assert.equal(checkViewEvent(resize), resize); for (const params of [ null, [], @@ -164,6 +166,7 @@ test('a view event without its required shape is refused', () => { event({ node: 3 }), event({ value: ['a'] }), event({ viewport: { x: 0 } }), + event({ width: 'wide' }), ]) { assert.throws(() => checkViewEvent(params), (error) => error.code === 'sdk.view.invalidEvent', JSON.stringify(params)); } diff --git a/shared/plugins/sdk/node/test/types/view.mts b/shared/plugins/sdk/node/test/types/view.mts index 14ec34c4..ea98d57e 100644 --- a/shared/plugins/sdk/node/test/types/view.mts +++ b/shared/plugins/sdk/node/test/types/view.mts @@ -9,6 +9,11 @@ backend.view('explorer.draw', (event, context) => { void draft; void context.operationID; if ('settingRegionID' in event.surface) return {}; + // A scene that follows the window lays itself out at the reported width. + const width: number = event.width ?? 610; + if (event.event === 'resize') { + return { view: [{ type: 'canvas', id: 'fit', label: 'Fit', height: 120, viewBox: [0, 0, width, 120], on: ['resize'], nodes: [] }] }; + } if (event.event === 'open') { const graph: CanvasNode[] = [ { type: 'path', id: 'edge', d: 'M190 20C234 20 216 80 260 80', stroke: '$line', width: 1.5 }, diff --git a/shared/plugins/sdk/rust/README.md b/shared/plugins/sdk/rust/README.md index 3ddbc1d3..582f083e 100644 --- a/shared/plugins/sdk/rust/README.md +++ b/shared/plugins/sdk/rust/README.md @@ -118,7 +118,11 @@ field that is `null` counts as absent. The handler answers a Nodes stay `serde_json` values shaped as [`plugin-ui.schema.json`](../../contract/v1/plugin-ui.schema.json) describes. Core checks every answer, and the host draws nothing that Core refused. Return -view text in `event.language`. +view text in `event.language`. A host that reports the view's width sends +it as `event.width` on every event; a canvas that follows the window lays +itself out at that width, lists `resize` in its `on`, and answers +`ViewEventKind::Resize` with the scene laid out again +([Canvas](../../contract/v1/README.md#canvas)). ```rust use lithe_plugin_sdk::view::{Patch, ViewEventKind, ViewResult}; diff --git a/shared/plugins/sdk/rust/plugin-sdk/src/view.rs b/shared/plugins/sdk/rust/plugin-sdk/src/view.rs index ed6537d7..9d86f224 100644 --- a/shared/plugins/sdk/rust/plugin-sdk/src/view.rs +++ b/shared/plugins/sdk/rust/plugin-sdk/src/view.rs @@ -26,6 +26,9 @@ pub enum ViewEventKind { Select, Activate, Viewport, + /// The view's width stopped changing, for a view with a canvas whose + /// `on` lists `resize`; [`ViewEvent::width`] is the new width. + Resize, /// The effective or draft setting values changed. Settings, } @@ -40,6 +43,7 @@ impl ViewEventKind { "select" => Self::Select, "activate" => Self::Activate, "viewport" => Self::Viewport, + "resize" => Self::Resize, "settings" => Self::Settings, _ => return None, }) @@ -87,6 +91,10 @@ pub struct ViewEvent { /// A select or activate event: the tree item ID. pub item: Option, pub viewport: Option, + /// The width in points the host lays the view out in, on every event + /// from a host that reports it. List `resize` in a canvas's `on` only + /// when it is present: a host without it may refuse the canvas. + pub width: Option, } impl ViewEvent { @@ -146,6 +154,10 @@ impl ViewEvent { }) } }; + let width = match object.get("width") { + None | Some(Value::Null) => None, + Some(width) => Some(width.as_f64().ok_or_else(invalid)?), + }; let value = match object.get("value") { None | Some(Value::Null) => None, Some(value @ (Value::String(_) | Value::Bool(_) | Value::Number(_))) => { @@ -166,6 +178,7 @@ impl ViewEvent { setting: optional("setting")?, item: optional("item")?, viewport, + width, }) } } @@ -290,6 +303,7 @@ mod tests { let parsed = ViewEvent::parse(&event(json!({ "node": "otp", "setting": "otpRelease", "value": "27", "viewport": { "x": 0, "y": 10.5, "width": 1200, "height": 640 }, + "width": 612, }))) .unwrap(); assert_eq!(parsed.kind, ViewEventKind::Change); @@ -299,15 +313,21 @@ mod tests { assert_eq!(parsed.setting.as_deref(), Some("otpRelease")); assert_eq!(parsed.value, Some(json!("27"))); assert_eq!(parsed.viewport.unwrap().y, 10.5); + assert_eq!(parsed.width, Some(612.0)); assert_eq!(parsed.item, None); // An optional field sent as null counts as absent. let absent = ViewEvent::parse(&event( - json!({ "node": null, "value": null, "viewport": null }), + json!({ "node": null, "value": null, "viewport": null, "width": null }), )) .unwrap(); assert_eq!( - (absent.node, absent.value, absent.viewport), - (None, None, None) + (absent.node, absent.value, absent.viewport, absent.width), + (None, None, None, None) + ); + let resize = ViewEvent::parse(&event(json!({ "event": "resize", "width": 340 }))).unwrap(); + assert_eq!( + (resize.kind, resize.width), + (ViewEventKind::Resize, Some(340.0)) ); } @@ -323,6 +343,7 @@ mod tests { event(json!({ "node": 3 })), event(json!({ "value": ["a"] })), event(json!({ "viewport": { "x": 0 } })), + event(json!({ "width": "wide" })), ] { let error = ViewEvent::parse(¶ms).unwrap_err(); assert_eq!(error.code(), INVALID_EVENT, "{params}");