From 57b508f12854616470112e63d5352ca6db0b8c6a Mon Sep 17 00:00:00 2001 From: Evan Hu Date: Fri, 20 Nov 2026 20:53:44 +0900 Subject: [PATCH] fix(tsx): dispose entry mounts for view exports --- CHANGELOG.md | 1 + docs/public/en/tsx.md | 2 +- docs/public/zh/tsx.md | 2 +- tsx/dom.go | 6 ++++-- tsx/sandbox.go | 4 ++++ tsx/tsx.go | 2 ++ tsx/view.go | 2 +- tsx/view_test.go | 31 +++++++++++++++++++++++++++++++ 8 files changed, 45 insertions(+), 5 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 7965b613b..315448a91 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,7 @@ - Add the `macos_universal` build target, which joins the arm64 and x64 apps, libraries and widgets into one direct-channel disk image and Sparkle feed (#265 by @houko). - Stop resolving and emitting the whole tree when the platform reports only a new window frame, maximized state, lifecycle or title bar, as on every step of a window drag; what reads them through `Env` still updates (#178 by @houko). - Convert macOS `nsgotest` captures and screenshots to sRGB, so their pixels no longer depend on whether the Mac's display is Display P3 (#311 by @houko). +- Stop a `tsx.View` that renders an `Export` from also running what the package's entry module mounts, with its effects, handlers, timers and animation frames (#923 by @houko). - Add `TabStyle` and `IndicatorStyle` to `ui.Tabs` to restyle its tabs, the selected tab and the indicator (#958 by @houko). - Reload a TSX `` in place with the new script when `injectedJavaScriptBeforeContentLoaded` changes, as `core.WebView.InjectedJavaScriptBeforeContentFunc` does, rather than replacing the web view (#895 by @houko). - Keep partial borders above Apple backdrop, material and glass layers while leaving app children above the border (#935 by @houko). diff --git a/docs/public/en/tsx.md b/docs/public/en/tsx.md index 39bbfbb9c..6ec404f46 100644 --- a/docs/public/en/tsx.md +++ b/docs/public/en/tsx.md @@ -91,7 +91,7 @@ core.Catch{Try: view.Render, Fallback: failed} trust.Accept(p) // once it ran, older builds are refused ``` -`Sandbox.Grant` gives it less than it declares, `Sandbox.Limits` other time budgets and quotas, and `Sandbox.Modules` Go functions and components beyond NSGo's own. Its keyboard shortcuts, back handlers and navigation stacks take effect only while the keyboard focus is in its view, and it moves the focus itself (`focus()`, `autoFocus`, `Keyboard.dismiss`, `setAccessibilityFocus`) only while the focus is already there or in answer to the user's press in it. It shows in a view of its own that fills the room its parent gives it, no more, and clips it, menus, popovers and toasts included; in a scroll view, put it in a view to let it take its content's height. A dialog, an alert, a context menu or an announcement of its shows only in the same way, and back closes a dialog of its even if it does not remove it. `View.Export` names a component the package's entry module exports, shown in place of the root the entry mounts and given `View.Props`, a JSON-encodable map copied for each view, so one package provides several views, each with state of its own, under the same capabilities and limits; a missing export panics with `tsx.ErrNoViewExport` and one that is not a function with `tsx.ErrViewExportNotComponent`. A package whose entry exports functions is a plugin of functions: `tsx.Load(cx, p, tsx.Sandbox{})` runs it unseen and synchronously on the caller's goroutine, under a `cx` that belongs to a view tree (without one it returns `tsx.ErrNoTree`), or returns what its entry module threw as it loaded, and `Plugin.Call` calls them. `go tool nsgo dev -limits` runs an app as such a view would, and `go tool nsgo revoke` signs a list of revoked release keys and packages for `Trust.UpdateRevocations`. `examples/plugins` asks the user to grant a package's capabilities, installs it and runs it. `Limits.Memory`, 64 MiB by default and `memory=` in `-limits` (`memory=0` turns it off), caps what the built-ins that allocate by a size hold for a package on native targets: `ArrayBuffer` and the typed arrays, `repeat`, `padStart`, `padEnd`, `Array.from`, `join`, `fill`, array copies such as `toSorted`, the argument lists of `apply`, and `JSON.stringify`. Each checks before it allocates, so an allocation past it stops the package with `ERR_NSH_QUOTA_EXCEEDED` instead of ending the app, and what it made counts until it is collected; the Go collector runs before a package is stopped, so garbage alone does not stop it. Objects, concatenated strings, arrays grown element by element, copies such as `concat`, `flat` and spreads, and what `replace` makes are not counted, nor anything on the web, so it stops runaway allocations, not a package written to exhaust memory. An app that signs packages itself with `pkg.Build`, or `go tool nsgo publish -extra ` with that file's bytes, can put metadata of its own in `pkg.Contents.Extra`, such as what a plugin adds to its menus: it is signed with the package, and `Verify` returns it unchanged as `p.Extra` for the app to parse, so the app reads it without running the package's code. +`Sandbox.Grant` gives it less than it declares, `Sandbox.Limits` other time budgets and quotas, and `Sandbox.Modules` Go functions and components beyond NSGo's own. Its keyboard shortcuts, back handlers and navigation stacks take effect only while the keyboard focus is in its view, and it moves the focus itself (`focus()`, `autoFocus`, `Keyboard.dismiss`, `setAccessibilityFocus`) only while the focus is already there or in answer to the user's press in it. It shows in a view of its own that fills the room its parent gives it, no more, and clips it, menus, popovers and toasts included; in a scroll view, put it in a view to let it take its content's height. A dialog, an alert, a context menu or an announcement of its shows only in the same way, and back closes a dialog of its even if it does not remove it. `View.Export` names a component the package's entry module exports, shown in place of the root the entry mounts, whose `mount` then neither renders nor runs its component, and given `View.Props`, a JSON-encodable map copied for each view, so one package provides several views, each with state of its own, under the same capabilities and limits; a missing export panics with `tsx.ErrNoViewExport` and one that is not a function with `tsx.ErrViewExportNotComponent`. A package whose entry exports functions is a plugin of functions: `tsx.Load(cx, p, tsx.Sandbox{})` runs it unseen and synchronously on the caller's goroutine, under a `cx` that belongs to a view tree (without one it returns `tsx.ErrNoTree`), or returns what its entry module threw as it loaded, and `Plugin.Call` calls them. `go tool nsgo dev -limits` runs an app as such a view would, and `go tool nsgo revoke` signs a list of revoked release keys and packages for `Trust.UpdateRevocations`. `examples/plugins` asks the user to grant a package's capabilities, installs it and runs it. `Limits.Memory`, 64 MiB by default and `memory=` in `-limits` (`memory=0` turns it off), caps what the built-ins that allocate by a size hold for a package on native targets: `ArrayBuffer` and the typed arrays, `repeat`, `padStart`, `padEnd`, `Array.from`, `join`, `fill`, array copies such as `toSorted`, the argument lists of `apply`, and `JSON.stringify`. Each checks before it allocates, so an allocation past it stops the package with `ERR_NSH_QUOTA_EXCEEDED` instead of ending the app, and what it made counts until it is collected; the Go collector runs before a package is stopped, so garbage alone does not stop it. Objects, concatenated strings, arrays grown element by element, copies such as `concat`, `flat` and spreads, and what `replace` makes are not counted, nor anything on the web, so it stops runaway allocations, not a package written to exhaust memory. An app that signs packages itself with `pkg.Build`, or `go tool nsgo publish -extra ` with that file's bytes, can put metadata of its own in `pkg.Contents.Extra`, such as what a plugin adds to its menus: it is signed with the package, and `Verify` returns it unchanged as `p.Extra` for the app to parse, so the app reads it without running the package's code. An app can sign its own JSON documents, such as a catalog of its plugins, with `pkg.SignDocument` and verify them with `Signed.Open`, with the keys `nsgo keygen` prints. Give each kind of document an `app:` context of its own with a version, as `app:catalog-v1`: a document never passes for another kind, nor for a package, certificate or revocation list. `Open` trusts exactly the public keys it is given, with no certificate or revocation list, and refuses body fields the type it decodes into lacks. The envelope holds no time or sequence, so an older document verifies as well as a newer one: put a version or expiry in the body and check it. In a native sandbox, `JSON.stringify`, `JSON.parse` with a reviver, `Array.prototype.join`, `toString`, `toLocaleString` and `flat`, and so `String()` of an array, throw a catchable `RangeError` once they go more than 1,000 levels deep, counting one inside another, as an array's `toString` and the `join` it calls each count; deeper data would hang the call or end the app. The web uses the browser's built-ins. diff --git a/docs/public/zh/tsx.md b/docs/public/zh/tsx.md index ef5e345c1..66374369c 100644 --- a/docs/public/zh/tsx.md +++ b/docs/public/zh/tsx.md @@ -91,7 +91,7 @@ core.Catch{Try: view.Render, Fallback: failed} trust.Accept(p) // 运行之后,更旧的构建会被拒绝 ``` -`Sandbox.Grant` 让它得到比声明更少的权限,`Sandbox.Limits` 设置其他时间预算和配额,`Sandbox.Modules` 给它 NSGo 自带之外的 Go 函数和组件。它的快捷键、返回处理器和导航栈只在键盘焦点位于它的视图内时生效;它自己移动焦点(`focus()`、`autoFocus`、`Keyboard.dismiss`、`setAccessibilityFocus`)也只在焦点已在其中、或响应用户在其中的按压时才生效。它显示在自己的视图中,这个视图占满且不超出父视图给它的空间,并裁剪它的内容,菜单、弹出框和提示也在其中;放在滚动视图中时,用一个视图包住它,它才会按内容的高度显示。它的对话框、警告框、上下文菜单和读屏播报也只按同样的规则显示;即使它不移除自己的对话框,返回也会关闭它。`View.Export` 指定包的入口模块导出的一个组件,显示它而不是入口挂载的根,并把 `View.Props` 作为它的 props;`View.Props` 是可以 JSON 编码的 map,每个视图各得一份副本。这样一个包能提供多个视图,各有自己的状态,权限和限额都相同;导出不存在时以 `tsx.ErrNoViewExport` panic,导出的不是函数时以 `tsx.ErrViewExportNotComponent` panic。入口导出函数的包是函数型插件:`tsx.Load(cx, p, tsx.Sandbox{})` 在调用方的 goroutine 上同步运行它而不显示,要求 `cx` 属于一个视图树,否则返回 `tsx.ErrNoTree`;入口模块加载时抛出错误则返回这个错误,`Plugin.Call` 调用这些函数。`go tool nsgo dev -limits` 像这样的视图一样运行应用,`go tool nsgo revoke` 签署吊销发布密钥和包的列表,供 `Trust.UpdateRevocations` 使用。`examples/plugins` 会请用户授予包声明的权限,再安装并运行它。`Limits.Memory` 默认为 64 MiB,在 `-limits` 中写作 `memory=`(`memory=0` 关闭它),它在原生目标上限制按大小分配的内置函数为包占用的内存:`ArrayBuffer` 和各种类型化数组、`repeat`、`padStart`、`padEnd`、`Array.from`、`join`、`fill`、`toSorted` 等数组副本、`apply` 的参数列表,以及 `JSON.stringify`。它们在分配前检查,超出时包以 `ERR_NSH_QUOTA_EXCEEDED` 停止,而不会让应用退出;分配出的内存一直计入,直到被回收;停止包之前会先运行 Go 的垃圾回收,所以仅仅是垃圾不会让它停止。对象、拼接出的字符串、逐个元素增长的数组、`concat`、`flat` 和展开语法产生的副本,以及 `replace` 生成的字符串都不计入,Web 上也不限制,所以它防的是失控的分配,而不是有意耗尽内存的包。自己用 `pkg.Build` 签名包的应用,或用 `go tool nsgo publish -extra <文件>` 放入该文件内容的应用,可以把自己的元数据放进 `pkg.Contents.Extra`,例如插件要加到菜单里的项:它和包一起签名,`Verify` 原样以 `p.Extra` 返回,由应用自己解析,因此应用无需运行包的代码就能读到它。 +`Sandbox.Grant` 让它得到比声明更少的权限,`Sandbox.Limits` 设置其他时间预算和配额,`Sandbox.Modules` 给它 NSGo 自带之外的 Go 函数和组件。它的快捷键、返回处理器和导航栈只在键盘焦点位于它的视图内时生效;它自己移动焦点(`focus()`、`autoFocus`、`Keyboard.dismiss`、`setAccessibilityFocus`)也只在焦点已在其中、或响应用户在其中的按压时才生效。它显示在自己的视图中,这个视图占满且不超出父视图给它的空间,并裁剪它的内容,菜单、弹出框和提示也在其中;放在滚动视图中时,用一个视图包住它,它才会按内容的高度显示。它的对话框、警告框、上下文菜单和读屏播报也只按同样的规则显示;即使它不移除自己的对话框,返回也会关闭它。`View.Export` 指定包的入口模块导出的一个组件,显示它而不是入口挂载的根,此时入口的 `mount` 既不渲染也不运行它的组件,并把 `View.Props` 作为它的 props;`View.Props` 是可以 JSON 编码的 map,每个视图各得一份副本。这样一个包能提供多个视图,各有自己的状态,权限和限额都相同;导出不存在时以 `tsx.ErrNoViewExport` panic,导出的不是函数时以 `tsx.ErrViewExportNotComponent` panic。入口导出函数的包是函数型插件:`tsx.Load(cx, p, tsx.Sandbox{})` 在调用方的 goroutine 上同步运行它而不显示,要求 `cx` 属于一个视图树,否则返回 `tsx.ErrNoTree`;入口模块加载时抛出错误则返回这个错误,`Plugin.Call` 调用这些函数。`go tool nsgo dev -limits` 像这样的视图一样运行应用,`go tool nsgo revoke` 签署吊销发布密钥和包的列表,供 `Trust.UpdateRevocations` 使用。`examples/plugins` 会请用户授予包声明的权限,再安装并运行它。`Limits.Memory` 默认为 64 MiB,在 `-limits` 中写作 `memory=`(`memory=0` 关闭它),它在原生目标上限制按大小分配的内置函数为包占用的内存:`ArrayBuffer` 和各种类型化数组、`repeat`、`padStart`、`padEnd`、`Array.from`、`join`、`fill`、`toSorted` 等数组副本、`apply` 的参数列表,以及 `JSON.stringify`。它们在分配前检查,超出时包以 `ERR_NSH_QUOTA_EXCEEDED` 停止,而不会让应用退出;分配出的内存一直计入,直到被回收;停止包之前会先运行 Go 的垃圾回收,所以仅仅是垃圾不会让它停止。对象、拼接出的字符串、逐个元素增长的数组、`concat`、`flat` 和展开语法产生的副本,以及 `replace` 生成的字符串都不计入,Web 上也不限制,所以它防的是失控的分配,而不是有意耗尽内存的包。自己用 `pkg.Build` 签名包的应用,或用 `go tool nsgo publish -extra <文件>` 放入该文件内容的应用,可以把自己的元数据放进 `pkg.Contents.Extra`,例如插件要加到菜单里的项:它和包一起签名,`Verify` 原样以 `p.Extra` 返回,由应用自己解析,因此应用无需运行包的代码就能读到它。 应用可以用 `pkg.SignDocument` 为自己的 JSON 文档(例如插件目录)签名,再用 `Signed.Open` 验证,密钥使用 `nsgo keygen` 生成的即可。每种文档使用一个带版本的独立 `app:` 上下文,例如 `app:catalog-v1`:一种文档不会被当作另一种文档,也不会被当作包、证书或吊销列表。`Open` 只信任传给它的公钥,不使用证书和吊销列表,并拒绝解码目标类型中没有的字段。信封中没有时间和序号,旧文档与新文档同样能通过验证:请在正文中放入版本或过期时间并加以检查。 在原生沙箱中,`JSON.stringify`、带 reviver 的 `JSON.parse`、`Array.prototype.join`、`toString`、`toLocaleString` 和 `flat`,以及数组的 `String()`,深入超过 1,000 层时会抛出可捕获的 `RangeError`;一个在另一个内部调用时层数累计,数组的 `toString` 和它调用的 `join` 各算一层。更深的数据会让调用卡住或让应用退出。Web 使用浏览器的内置函数。 diff --git a/tsx/dom.go b/tsx/dom.go index 6e7864651..b90660c53 100644 --- a/tsx/dom.go +++ b/tsx/dom.go @@ -717,9 +717,11 @@ func keyOf(v js.Value) any { } } -// mount is `mount(App, props)`: App rendered into the surface; it returns -// a function that removes it. +// mount is `mount(App, props)`: App rendered into the surface; it returns a function that removes it. In a view of an export it neither renders nor runs App, whose effects, handlers, timers and frames would otherwise run hidden beside the export, and returns a function that does nothing. func (r *runtime) mount(call js.FunctionCall) js.Value { + if r.exportView { + return r.function(func(js.FunctionCall) js.Value { return js.Undefined() }) + } app, props := arg(call, 0), arg(call, 1) if _, ok := props.(*js.Object); !ok { props = r.vm.NewObject() diff --git a/tsx/sandbox.go b/tsx/sandbox.go index 86d713b49..ac2f103b2 100644 --- a/tsx/sandbox.go +++ b/tsx/sandbox.go @@ -137,6 +137,8 @@ func ParseLimits(spec string) (Limits, error) { type Sandbox struct { // plugin says Load runs it, whose calls Limits.CallTotal holds. plugin bool + // exportView says a view renders one of its exports in place of what its entry module mounts. + exportView bool // Limits are what it may use, DefaultLimits when nil. Limits *Limits // Capabilities are what its code may reach (a package's own); nil @@ -180,6 +182,7 @@ func Sandboxed(name, src string, s Sandbox, options ...ViewOptions) func(cx *cor if len(options) > 0 { view = options[0] } + s.exportView = view.Export != "" return func(cx *core.Scope) core.Node { inner := cx.Child() var root core.Node @@ -256,6 +259,7 @@ func (s Sandbox) start(cx *core.Scope, name, src string) *runtime { r.regexTimeout = limits.Load } r.sandbox = &sandboxed{caps: s.Capabilities != nil || s.Grant != nil, modules: s.Modules} + r.exportView = s.exportView if limits.Stack > 0 { r.vm.SetMaxCallStackSize(limits.Stack) } diff --git a/tsx/tsx.go b/tsx/tsx.go index 25e3c14bd..23da52092 100644 --- a/tsx/tsx.go +++ b/tsx/tsx.go @@ -135,6 +135,8 @@ type runtime struct { // committing is set while a commit is asked for after the page's // engine called Go (engine_browser.go). committing bool + // exportView says a view renders one of the entry module's exports, so mount attaches nothing and runs nothing of what it is given. + exportView bool } // maxCallStack is how deep JS calls nest in any app. diff --git a/tsx/view.go b/tsx/view.go index 3d9904b81..1e39e45bf 100644 --- a/tsx/view.go +++ b/tsx/view.go @@ -18,7 +18,7 @@ import ( // core.Catch{Try: tsx.View{Package: p}.Render, Fallback: failed} type View struct { Package *pkg.Package - // Export names a component the package's entry module exports, which the view renders in place of the root the entry mounts; empty keeps that root. + // Export names a component the package's entry module exports, which the view renders in place of the root the entry mounts, whose mount then neither renders nor runs its component; empty keeps that root. Export string // Props are Export's props object, as JSON encodes them. Props map[string]any diff --git a/tsx/view_test.go b/tsx/view_test.go index 27ea22127..4cb600a11 100644 --- a/tsx/view_test.go +++ b/tsx/view_test.go @@ -109,6 +109,37 @@ export function Second() { const n = signal(0); return { setInterval(() => ticks.set(ticks() + 1), 10); }); + const loop = () => { frames.set(frames() + 1); requestAnimationFrame(loop); }; + requestAnimationFrame(loop); + queueMicrotask(() => setInterval(() => late.set(late() + 1), 10)); + return mounted; +} +mount(Mounted); +export function Panel() { return {() => "export " + ticks() + " " + frames() + " " + late()}; }`, 1) + p, err := trust.Verify(data) + if err != nil { + t.Fatal(err) + } + app := nsgotest.Start(t, func(cx *core.Scope) core.Node { + return tsx.View{Package: p, Export: "Panel", Sandbox: tsx.Sandbox{WebUnisolated: true}} + }) + if app.Exists("id:mounted") || app.Find("id:export").Text != "export 0 0 0" { + t.Fatalf("entry mount was left in the root\n%s", app.Dump()) + } + app.FastForward(100 * time.Millisecond) + if got := app.Find("id:export").Text; got != "export 0 0 0" { + t.Fatalf("entry mount kept running: %q", got) + } +} + func TestViewNamedExportErrors(t *testing.T) { data, trust := signedPackage(t, `export const NotAComponent = 1;`, 1) p, err := trust.Verify(data)