Blender's GPU Accelerated UI, Decoupled from it's original codebase. Supports Rust, Python, JS, React, C & C++. Twice as good as GPUI
svelte fastpath
Preetham Pemmasani81abd23db918
diff --git a/bindings/svelte/compile.js b/bindings/svelte/compile.jsindex fdd80a0..9c489c5 100644--- a/bindings/svelte/compile.js+++ b/bindings/svelte/compile.js@@ -8,7 +8,6 @@// compiler unless a component changed.//// SPDX-License-Identifier: GPL-2.0-or-later-import crypto from 'node:crypto'import fs from 'node:fs'import { createRequire } from 'node:module'import path from 'node:path'@@ -16,11 +15,16 @@ import { fileURLToPath } from 'node:url'const require = createRequire(import.meta.url)const HERE = path.dirname(fileURLToPath(import.meta.url))-const VERSION = require('svelte/package.json').version-// in the project's node_modules (none: no cache)-const CACHE = fs.existsSync(path.join(process.cwd(), 'node_modules'))- ? path.join(process.cwd(), 'node_modules', '.cache', '@blender-ui', 'svelte')- : null+export const VERSION = require('svelte/package.json').version++/** The cache (compiled components, runtime.js's bundle) in the project's+ * node_modules: the nearest one from the working directory up; none, no cache. */+export const CACHE = (() => {+ for (let dir = process.cwd(); ; dir = path.dirname(dir)) {+ if (fs.existsSync(path.join(dir, 'node_modules'))) return path.join(dir, 'node_modules', '.cache', '@blender-ui', 'svelte')+ if (path.dirname(dir) === dir) return null+ }+})()let compiler = null // svelte/compiler (its CommonJS build: one file), on the first cache miss/** Components (`.svelte`) and rune modules (`.svelte.js`). */@@ -28,17 +32,20 @@ export const SVELTE_FILE = /\.svelte(\.js)?$//** Packages whose browser build a BUI app needs (Svelte's runtime, and the* `esm-env` flags it reads). */export const BROWSER_PACKAGE = /^(svelte|esm-env)(\/.*)?$/-/** This package, as compiled components import it: always this copy (one- * event patch, one stylesheet registry), installed next to them or not. */-export const SELF = /^@blender-ui\/svelte$/-export const SELF_FILE = path.join(HERE, 'index.js')+/** This package, as compiled components import it (`@blender-ui/svelte`, and+ * `/internal` for Svelte's runtime): always this copy (one event patch, one+ * stylesheet registry), installed next to them or not. */+export const SELF = /^@blender-ui\/svelte(\/internal)?$/+export const selfFile = (specifier) => path.join(HERE, specifier.endsWith('/internal') ? 'internal.js' : 'index.js')+// compiled output's format: part of the cache key (bump when the rewrite changes)+const FORMAT = 2const CONDITIONS = ['browser', 'import', 'default']/** The client JavaScript of a `.svelte` / `.svelte.js` file. */export function compileSvelte (source, filename, dev = process.env.NODE_ENV === 'development') {if (CACHE === null) return compileNow(source, filename, dev)- const key = crypto.createHash('sha1').update(`${VERSION}\0${dev}\0${filename}\0${source}`).digest('hex')+ const key = `${hash(`${FORMAT}\0${VERSION}\0${dev}\0${filename}\0${source}`)}-${source.length}`const cached = path.join(CACHE, `${key}.js`)try {return fs.readFileSync(cached, 'utf8')@@ -54,15 +61,35 @@ export function compileSvelte (source, filename, dev = process.env.NODE_ENV ===function compileNow (source, filename, dev) {compiler ??= require('svelte/compiler')- if (!filename.endsWith('.svelte')) return compiler.compileModule(source, { filename, generate: 'client', dev }).js.code+ if (!filename.endsWith('.svelte')) return toBui(compiler.compileModule(source, { filename, generate: 'client', dev }).js.code)const r = compiler.compile(source, { filename, generate: 'client', fragments: 'tree', css: 'external', dev })- if (r.css === null) return r.js.code+ if (r.css === null) return toBui(r.js.code)// the scoped stylesheet: added to each window once (index.js), not per instance- const key = crypto.createHash('sha1').update(filename).digest('hex').slice(0, 12)- return `${r.js.code}\nimport { addStyle as __buiAddStyle } from '@blender-ui/svelte'\n` ++ const key = hash(filename)+ return `${toBui(r.js.code)}\nimport { addStyle as __buiAddStyle } from '@blender-ui/svelte'\n` +`__buiAddStyle(${JSON.stringify(key)}, ${JSON.stringify(r.css.code)})\n`}+/** A 53-bit hash of `s` (cyrb53), in hex: cache file names, without loading+ * node:crypto at startup. */+export function hash (s) {+ let h1 = 0xdeadbeef+ let h2 = 0x41c6ce57+ for (let i = 0; i < s.length; i++) {+ const c = s.charCodeAt(i)+ h1 = Math.imul(h1 ^ c, 2654435761)+ h2 = Math.imul(h2 ^ c, 1597334677)+ }+ h1 = Math.imul(h1 ^ (h1 >>> 16), 2246822507) ^ Math.imul(h2 ^ (h2 >>> 13), 3266489909)+ h2 = Math.imul(h2 ^ (h2 >>> 16), 2246822507) ^ Math.imul(h1 ^ (h1 >>> 13), 3266489909)+ return (4294967296 * (2097151 & h2) + (h1 >>> 0)).toString(16)+}++/** Svelte's runtime as this package serves it to compiled code (internal.js). */+function toBui (code) {+ return code.replace("from 'svelte/internal/client'", "from '@blender-ui/svelte/internal'")+}+/** The file `specifier` (`svelte`, `svelte/store` ...) names in its package's* browser build, resolved from `fromDir`. */export function resolveBrowser (specifier, fromDir) {@@ -75,7 +102,7 @@ export function resolveBrowser (specifier, fromDir) {const resolved = new Map() // fromDir + specifier -> fileconst exportsByRoot = new Map() // package root -> its package.json's exports-function packageExports (root) {+export function packageExports (root) {let e = exportsByRoot.get(root)if (e === undefined) exportsByRoot.set(root, (e = JSON.parse(fs.readFileSync(path.join(root, 'package.json'), 'utf8')).exports ?? {}))return e@@ -103,9 +130,9 @@ function findBrowser (specifier, fromDir) {export const BROWSER_PACKAGE_FILE = /[\\/]node_modules[\\/](svelte|esm-env)[\\/]/const redirects = new Map() // package root -> Map(default file -> browser file)-/** Module source re-exporting the browser build of `file` when `file` is a- * package's non-browser entry (`svelte/src/index-server.js` ...), or null. */-export function browserRedirect (file) {+/** The browser counterpart of `file` when it is a package's non-browser entry+ * (`svelte/src/index-server.js` -> `index-client.js`), else `file`. */+export function browserTarget (file) {const m = /^(.*[\\/]node_modules[\\/](?:svelte|esm-env))[\\/]/.exec(file)if (m === null) return nulllet map = redirects.get(m[1])@@ -118,13 +145,18 @@ export function browserRedirect (file) {}redirects.set(m[1], map)}- const target = map.get(path.normalize(file))- if (target === undefined) return null- const to = JSON.stringify(target)- return `export * from ${to}\n${/\bexport default\b/.test(fs.readFileSync(target, 'utf8')) ? `export { default } from ${to}\n` : ''}`+ return map.get(path.normalize(file)) ?? file+}++/** Module source re-exporting `file` (and its default export, if it has one). */+export function reexport (file) {+ const to = JSON.stringify(file)+ const hasDefault = /\bexport default\b|\bas default\b/.test(fs.readFileSync(file, 'utf8'))+ return `export * from ${to}\n${hasDefault ? `export { default } from ${to}\n` : ''}`}-function pick (entry) { return pickFrom(entry, CONDITIONS) }+/** The browser build of an export entry (`./store`'s ...), or null. */+export function pick (entry) { return pickFrom(entry, CONDITIONS) }function pickFrom (entry, conditions) {if (typeof entry === 'string' || entry == null) return entry ?? nulldiff --git a/bindings/svelte/internal.js b/bindings/svelte/internal.jsnew file mode 100644index 0000000..f4a4090--- /dev/null+++ b/bindings/svelte/internal.js@@ -0,0 +1,76 @@+// What compiled components import instead of `svelte/internal/client`+// (compile.js rewrites the import): Svelte's runtime, with the functions its+// templates call on every update writing straight into BUI's nodes.+//+// - A plain value: Svelte's own versions go through the DOM API+// (`text.nodeValue = s`, `el.style.cssText = s`, `el.className = s`) and+// keep a cache property per node; here an update is one call on the node,+// which compares with what it holds and queues the native op.+// - A BUI signal (`<div style={styleSignal}>{labelSignal}</div>`, no `$`):+// the node is bound to it, so a write updates that node straight from the+// signal and Svelte doesn't run at all (as with React's signal props).+//+// A redirected function is used only when Svelte's has the shape this file+// was written against (test/svelte.test.js checks each one against Svelte's,+// on the same inputs); otherwise Svelte's own runs, through the DOM.+//+// SPDX-License-Identifier: GPL-2.0-or-later+import * as svelte from 'svelte/internal/client'+import native from '@blender-ui/native'++export * from 'svelte/internal/client'++const { isSignal, memo } = native++/** The functions redirected, and the parameter count of Svelte's versions. */+export const REDIRECTS = { set_text: 2, set_attribute: 4, set_style: 4, set_class: 6, clsx: 1 }++/** Those whose Svelte version still has that shape (the rest stay Svelte's). */+export const redirected = Object.keys(REDIRECTS).filter((k) => svelte[k]?.length === REDIRECTS[k])++const use = (name, fast) => (redirected.includes(name) ? fast : svelte[name])+// a node bound to a signal: the public setters, which unbind it first+const bound = (node) => node._bindings !== null++/** `{expression}` text. */+export const set_text = use('set_text', (text, value) => {+ if (isSignal(value) || bound(text)) text.data = isSignal(value) ? value : value == null ? '' : `${value}`+ else text._setText(value == null ? '' : `${value}`)+})++/** An attribute; strings (and signals) go straight through, other values+ * Svelte's way (some of them set DOM properties). */+export const set_attribute = use('set_attribute', (element, attribute, value, skipWarning) => {+ if (isSignal(value) || (typeof value === 'string' && bound(element))) element.setAttribute(attribute, value)+ else if (typeof value === 'string') element._setAttr(attribute, value)+ else svelte.set_attribute(element, attribute, value, skipWarning)+})++/** `style="..."`; with `style:` directives, Svelte's way. */+export const set_style = use('set_style', (dom, value, prevStyles, nextStyles) => {+ if (nextStyles !== undefined || (value != null && typeof value !== 'string' && !isSignal(value))) {+ return svelte.set_style(dom, value, prevStyles, nextStyles)+ }+ if (value == null || value === '') dom.removeAttribute('style')+ else if (isSignal(value) || bound(dom)) dom.setAttribute('style', value)+ else dom._setAttr('style', value)+})++/** `class="..."` (with the component's scoping hash); with `class:`+ * directives, Svelte's way. */+export const set_class = use('set_class', (dom, isHtml, value, hash, prevClasses, nextClasses) => {+ if (nextClasses !== undefined) return svelte.set_class(dom, isHtml, value, hash, prevClasses, nextClasses)+ if (isSignal(value)) return dom.setAttribute('class', hash ? memo(() => withHash(value.value, hash)) : value)+ const name = withHash(value, hash)+ if (name === '') dom.removeAttribute('class') // as Svelte: no class at all+ else if (bound(dom)) dom.setAttribute('class', name)+ else dom._setAttr('class', name)+})++/** `class={value}` is `clsx(value)` first: a signal passes through, to be bound. */+export const clsx = use('clsx', (value) => (isSignal(value) ? value : svelte.clsx(value)))++function withHash (value, hash) {+ const name = value == null ? '' : '' + value+ return hash ? (name ? name + ' ' + hash : hash) : name+}diff --git a/bindings/svelte/package.json b/bindings/svelte/package.jsonindex 746e1bc..fb2b396 100644--- a/bindings/svelte/package.json+++ b/bindings/svelte/package.json@@ -11,6 +11,7 @@"types": "./index.d.ts","default": "./index.js"},+ "./internal": "./internal.js","./register": "./register.js","./plugin": "./plugin.js","./compile": "./compile.js",@@ -23,6 +24,7 @@"index.js","index.d.ts","events.js",+ "internal.js","Widget.svelte","compile.js","plugin.js",diff --git a/bindings/svelte/plugin.js b/bindings/svelte/plugin.jsindex 3cffd2a..db14a54 100644--- a/bindings/svelte/plugin.js+++ b/bindings/svelte/plugin.js@@ -1,24 +1,32 @@-// The Bun plugin: `.svelte` files and Svelte's browser build. Bun's runtime-// loads it through `register.js`; `bui build` finds it through this-// package's `"bui": { "bunPlugin" }` field and bundles with it.+// The Bun plugin: `.svelte` files and Svelte's browser build. `bui build`+// finds the default export through this package's `"bui": { "bunPlugin" }`+// field and bundles with it; Bun's runtime loads `runtimePlugin(bundle)`+// through register.js, which also serves runtime.js's bundle.//// SPDX-License-Identifier: GPL-2.0-or-laterimport fs from 'node:fs'import path from 'node:path'-import { SVELTE_FILE, BROWSER_PACKAGE, BROWSER_PACKAGE_FILE, SELF, SELF_FILE, compileSvelte, resolveBrowser, browserRedirect } from './compile.js'+import { SVELTE_FILE, BROWSER_PACKAGE, BROWSER_PACKAGE_FILE, SELF, selfFile, compileSvelte, resolveBrowser, browserTarget, reexport } from './compile.js'-export default {- name: '@blender-ui/svelte',- setup (build) {- build.onResolve({ filter: SELF }, () => ({ path: SELF_FILE }))- build.onResolve({ filter: BROWSER_PACKAGE }, (args) =>- ({ path: resolveBrowser(args.path, args.importer ? path.dirname(args.importer) : process.cwd()) }))- // Bun's runtime resolves bare imports without plugins: its server build- // of Svelte loads the browser one instead- build.onLoad({ filter: BROWSER_PACKAGE_FILE }, (args) => {- return { contents: browserRedirect(args.path) ?? fs.readFileSync(args.path, 'utf8'), loader: 'js' }- })- build.onLoad({ filter: SVELTE_FILE }, (args) =>- ({ contents: compileSvelte(fs.readFileSync(args.path, 'utf8'), args.path), loader: 'js' }))- },+/** The plugin; `bundle` (runtime.js's map) serves Svelte's modules bundled. */+export function runtimePlugin (bundle = null) {+ return {+ name: '@blender-ui/svelte',+ setup (build) {+ build.onResolve({ filter: SELF }, (args) => ({ path: selfFile(args.path) }))+ build.onResolve({ filter: BROWSER_PACKAGE }, (args) =>+ ({ path: resolveBrowser(args.path, args.importer ? path.dirname(args.importer) : process.cwd()) }))+ // Bun's runtime resolves bare imports without plugins: a Svelte module+ // it loads re-exports the one it should be (the browser build, bundled)+ build.onLoad({ filter: BROWSER_PACKAGE_FILE }, (args) => {+ const target = browserTarget(args.path)+ const served = bundle?.get(target) ?? target+ return { contents: served === args.path ? fs.readFileSync(args.path, 'utf8') : reexport(served), loader: 'js' }+ })+ build.onLoad({ filter: SVELTE_FILE }, (args) =>+ ({ contents: compileSvelte(fs.readFileSync(args.path, 'utf8'), args.path), loader: 'js' }))+ },+ }}++export default runtimePlugin()diff --git a/bindings/svelte/register.js b/bindings/svelte/register.jsindex 75ea8d4..17c281f 100644--- a/bindings/svelte/register.js+++ b/bindings/svelte/register.js@@ -1,25 +1,30 @@// `import '@blender-ui/svelte/register'` (or `node --import` / `bun --preload`// it): `.svelte` files import as components, and `svelte` resolves to its-// browser build. Node.js through module hooks, Bun through its plugin.+// browser build, bundled once (runtime.js). Node.js through module hooks,+// Bun through its plugin.//// SPDX-License-Identifier: GPL-2.0-or-laterimport fs from 'node:fs'import path from 'node:path'import { fileURLToPath, pathToFileURL } from 'node:url'-import { SVELTE_FILE, BROWSER_PACKAGE, SELF, SELF_FILE, compileSvelte, resolveBrowser } from './compile.js'-import plugin from './plugin.js'+import { SVELTE_FILE, BROWSER_PACKAGE, SELF, selfFile, compileSvelte, resolveBrowser } from './compile.js'+import { runtimePlugin } from './plugin.js'+import { runtimeBundle } from './runtime.js'++const bundle = runtimeBundle() // Svelte's runtime as a few modules (null: its source files)if (typeof Bun !== 'undefined') {- Bun.plugin(plugin)+ Bun.plugin(runtimePlugin(bundle))} else {const { registerHooks } = await import('node:module')if (typeof registerHooks !== 'function') throw new Error('@blender-ui/svelte: needs Node.js 22.15 or newer (module.registerHooks), or Bun')registerHooks({resolve (specifier, context, next) {- if (SELF.test(specifier)) return { url: pathToFileURL(SELF_FILE).href, format: 'module', shortCircuit: true }+ if (SELF.test(specifier)) return { url: pathToFileURL(selfFile(specifier)).href, format: 'module', shortCircuit: true }if (!BROWSER_PACKAGE.test(specifier)) return next(specifier, context)const from = context.parentURL?.startsWith('file:') ? path.dirname(fileURLToPath(context.parentURL)) : process.cwd()- return { url: pathToFileURL(resolveBrowser(specifier, from)).href, format: 'module', shortCircuit: true }+ const file = resolveBrowser(specifier, from)+ return { url: pathToFileURL(bundle?.get(file) ?? file).href, format: 'module', shortCircuit: true }},load (url, context, next) {if (!url.startsWith('file:') || !SVELTE_FILE.test(url)) return next(url, context)diff --git a/bindings/svelte/runtime.js b/bindings/svelte/runtime.jsnew file mode 100644index 0000000..261262e--- /dev/null+++ b/bindings/svelte/runtime.js@@ -0,0 +1,62 @@+// Svelte's client runtime for Node.js and Bun, bundled once. Svelte ships it+// as about 90 source modules; loading them one by one is most of a Svelte+// app's start on Node.js. On the first run this bundles them with Bun (one+// module per export of the package, sharing chunks, so state stays shared)+// into the cache, keyed by Svelte's version, and register.js serves those+// files from then on. Without Bun or a cache, the source modules load as+// before. (`bui build` bundles the whole app itself.)+//+// SPDX-License-Identifier: GPL-2.0-or-later+import fs from 'node:fs'+import path from 'node:path'+import { CACHE, VERSION, hash, packageExports, pick, resolveBrowser } from './compile.js'++/** Map(browser file of Svelte's -> its bundled module), or null. */+export function runtimeBundle () {+ if (CACHE === null || process.env.BUI_SVELTE_BUNDLE === '0') return null+ const entry = resolveBrowser('svelte', process.cwd())+ const root = entry.slice(0, entry.lastIndexOf(`${path.sep}src${path.sep}`))+ const id = hash(root)+ const dir = path.join(CACHE, `runtime-${VERSION}-${id}`)+ try {+ return new Map(JSON.parse(fs.readFileSync(path.join(dir, 'manifest.json'), 'utf8')))+ } catch {}+ const entries = []+ for (const [sub, exp] of Object.entries(packageExports(root))) {+ const file = pick(exp)+ // the client's modules: not the compiler, the server renderer or types+ if (file === null || !file.endsWith('.js') || sub === './compiler' || sub.includes('server')) continue+ entries.push(path.join(root, file))+ }+ const tmp = `${dir}.${process.pid}`+ if (!bundle(entries, root, tmp)) {+ fs.rmSync(tmp, { recursive: true, force: true })+ return null+ }+ const map = entries.map((f) => [f, path.join(dir, path.relative(root, f))])+ fs.writeFileSync(path.join(tmp, 'manifest.json'), JSON.stringify(map))+ try {+ fs.renameSync(tmp, dir)+ } catch {+ fs.rmSync(tmp, { recursive: true, force: true }) // another process made it first+ }+ return new Map(map)+}++const BUILD = `const o = JSON.parse(process.env.BUI_SVELTE_BUNDLE_OPTIONS)+const r = await Bun.build({ entrypoints: o.entries, root: o.root, outdir: o.out, splitting: true, format: 'esm',+ target: 'browser', minify: true, naming: { entry: '[dir]/[name].[ext]', chunk: '_chunks/[name]-[hash].[ext]' } })+if (!r.success) { for (const l of r.logs) console.error(l); process.exit(1) }`++function bundle (entries, root, out) {+ const { spawnSync } = process.getBuiltinModule('node:child_process') // only on the first run+ const bun = typeof Bun !== 'undefined'+ ? process.execPath+ : spawnSync('bun -e "process.stdout.write(process.execPath)"', { encoding: 'utf8', shell: true }).stdout?.trim()+ if (!bun) return false+ const r = spawnSync(bun, ['-e', BUILD], {+ stdio: 'pipe',+ env: { ...process.env, BUI_SVELTE_BUNDLE_OPTIONS: JSON.stringify({ entries, root, out }) },+ })+ return r.status === 0 && entries.every((f) => fs.existsSync(path.join(out, path.relative(root, f))))+}diff --git a/bindings/svelte/test/fixtures/Bound.svelte b/bindings/svelte/test/fixtures/Bound.sveltenew file mode 100644index 0000000..8800470--- /dev/null+++ b/bindings/svelte/test/fixtures/Bound.svelte@@ -0,0 +1,12 @@+<!-- BUI signals passed as values (no `$`): their nodes are bound to them. -->+<script>+ let { style, label, cls, onrender } = $props()+ onrender()+</script>++<div id="bound" style={style} class={cls} title={label}>{label}</div>+<p class="scoped">x</p>++<style>+ .scoped { color: red; }+</style>diff --git a/bindings/svelte/test/svelte.test.js b/bindings/svelte/test/svelte.test.jsindex 62bb3cf..73bc6d5 100644--- a/bindings/svelte/test/svelte.test.js+++ b/bindings/svelte/test/svelte.test.js@@ -4,12 +4,20 @@ import test from 'node:test'import assert from 'node:assert'import { render, act, signal, Button } from '../index.js'import { HANDLERS } from '../events.js'+import * as internal from '../internal.js'+import * as svelteInternal from 'svelte/internal/client'+import { compileSvelte } from '../compile.js'+import native from '@blender-ui/native'++const { REDIRECTS, redirected } = internal+const { document } = nativeimport Counter from './fixtures/Counter.svelte'import Panel from './fixtures/Panel.svelte'import Modes from './fixtures/Modes.svelte'import Show from './fixtures/Show.svelte'import Form from './fixtures/Form.svelte'import Blocks from './fixtures/Blocks.svelte'+import Bound from './fixtures/Bound.svelte'const tick = (ms = 30) => new Promise(r => setTimeout(r, ms))const at = (s, x, y) => { const i = (y * s.width + x) * 4; return [...s.data.subarray(i, i + 3)] }@@ -62,6 +70,31 @@ test('Svelte: BUI signals are stores; writes update their nodes without re-runniassert.strictEqual(renders, 1, 'Panel ran once: signal writes went straight to the nodes')})+test('Svelte: a BUI signal passed as a value binds its node; writes skip Svelte', async (t) => {+ const style = signal('width: 80px; height: 30px; background-color: #0000ff')+ const label = signal('one')+ const cls = signal('a')+ let renders = 0+ const { app, window } = render(Bound, { props: { style, label, cls, onrender: () => renders++ }, headless: true, width: 200, height: 120 })+ t.after(() => app.quit())+ window.body.style = 'margin: 0; background: #000'+ await tick()+ const el = finder(window)('bound')+ assert.strictEqual(el.textContent, 'one')+ assert.strictEqual(el.getAttribute('title'), 'one')+ assert.match(el.className, /^a svelte-/, 'the scoping hash follows the signal')+ assert.deepStrictEqual(at(await window.screenshot(), 70, 20), [0, 0, 255])+ label.value = 'two'+ style.value = 'width: 80px; height: 30px; background-color: #00ff00'+ cls.value = 'b'+ // synchronously: the bindings wrote the nodes, no Svelte flush in between+ assert.strictEqual(el.textContent, 'two')+ assert.strictEqual(el.getAttribute('title'), 'two')+ assert.match(el.className, /^b svelte-/)+ assert.deepStrictEqual(at(await window.screenshot(), 70, 20), [0, 255, 0])+ assert.strictEqual(renders, 1)+})+test('Svelte: text and elements take turns; keyed lists reorder; dropped nodes are freed', async (t) => {let setconst { app, window } = render(Modes, { props: { expose: (s) => { set = s } }, headless: true, width: 100, height: 100 })@@ -168,10 +201,40 @@ test('Svelte: {#await}, {#key}, class objects, bind:group and a scoped <style>',assert.match(red.className, /svelte-/, 'scoped class')const box = await red.getBoundingClientRect()assert.deepStrictEqual([box.width, box.height], [40, 20], 'the component stylesheet applies')- const styles = window.body.childNodes.filter((n) => n.localName === 'style')+ const styles = window.body.childNodes.filter((n) => n.localName === 'style' && n.textContent.includes('.red'))assert.strictEqual(styles.length, 1, 'one stylesheet per component, per window')})-test('Svelte: the event-delegation symbol is found (fails when a Svelte release changes it)', () => {+test('Svelte internals: the event-delegation symbol is found (fails when a Svelte release changes it)', () => {assert.strictEqual(typeof HANDLERS, 'symbol')})++test('Svelte internals: every redirected update function matches Svelte\'s (fails when a release changes one)', () => {+ // Svelte still has each one, with the shape internal.js was written for+ // (otherwise internal.js falls back to Svelte's own, and this fails loudly)+ assert.deepStrictEqual(redirected, Object.keys(REDIRECTS), 'a redirected function changed shape in this Svelte release')+ // compiled templates still call them+ const code = compileSvelte('<script>let { a, b } = $props()</script><p class={a} style={b} title={a}>{a}</p>', 'Probe.svelte')+ assert.match(code, /from '@blender-ui\/svelte\/internal'/)+ for (const name of Object.keys(REDIRECTS)) assert.match(code, new RegExp(`\\$\\.${name}\\(`), `compiled code no longer calls ${name}`)+ // and each does what Svelte's does, on the same inputs+ const make = () => {+ const el = document.createElement('div')+ el.append(document.createTextNode(' '))+ return el+ }+ const state = (el) => [el.getAttributeNames().sort().map((n) => [n, el.getAttribute(n)]), el.firstChild.data]+ const cases = [+ ['set_text', (el) => [el.firstChild, 42]], ['set_text', (el) => [el.firstChild, null]],+ ['set_attribute', (el) => [el, 'title', 'hi']], ['set_attribute', (el) => [el, 'title', null]],+ ['set_style', (el) => [el, 'color: red']], ['set_style', (el) => [el, '']], ['set_style', (el) => [el, null]],+ ['set_class', (el) => [el, 1, 'a b', 'svelte-x']], ['set_class', (el) => [el, 1, null, undefined]],+ ]+ for (const v of ['a', { b: true, c: false }, ['d', { e: 1 }], null]) assert.deepStrictEqual(internal.clsx(v), svelteInternal.clsx(v), 'clsx')+ for (const [name, args] of cases) {+ const ours = make(), theirs = make()+ internal[name](...args(ours))+ svelteInternal[name](...args(theirs))+ assert.deepStrictEqual(state(ours), state(theirs), `${name}${JSON.stringify(args(make()).slice(1))}`)+ }+})