Skip to content

armgit / BUI

Public Imported from GitHub
0

Blender's GPU Accelerated UI, Decoupled from it's original codebase. Supports Rust, Python, JS, React, C & C++. Twice as good as GPUI

svelte styles

Preetham Pemmasani94090d87fad9
diff --git a/bindings/svelte/compile.js b/bindings/svelte/compile.js
index 4491ae1..4abbfe0 100644
--- a/bindings/svelte/compile.js
+++ b/bindings/svelte/compile.js
@@ -3,45 +3,95 @@
// parser), and Svelte's browser build (the `browser` export condition). One
// place for both, used by the Node.js hooks and the Bun plugin.
//
+// Compiled files are cached (node_modules/.cache/@blender-ui/svelte, by
+// content, Svelte version and mode): an app starts without loading Svelte's
+// compiler unless a component changed.
+//
// SPDX-License-Identifier: GPL-2.0-or-later
-import { compile, compileModule } from 'svelte/compiler'
+import crypto from 'node:crypto'
import fs from 'node:fs'
+import { createRequire } from 'node:module'
import path from 'node:path'
+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
+const CACHE = path.join(process.cwd(), 'node_modules', '.cache', '@blender-ui', 'svelte')
+let compiler = null // svelte/compiler (its CommonJS build: one file), on the first cache miss
/** Components (`.svelte`) and rune modules (`.svelte.js`). */
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')
const CONDITIONS = ['browser', 'import', 'default']
-let warnedCss = false
/** The client JavaScript of a `.svelte` / `.svelte.js` file. */
export function compileSvelte (source, filename, dev = process.env.NODE_ENV === 'development') {
- if (!filename.endsWith('.svelte')) return compileModule(source, { filename, generate: 'client', dev }).js.code
- const r = compile(source, { filename, generate: 'client', fragments: 'tree', css: 'external', dev })
- if (r.css && !warnedCss) {
- warnedCss = true
- console.warn(`@blender-ui/svelte: ${path.basename(filename)}: <style> blocks aren't applied; style with class (Tailwind) and style`)
+ const key = crypto.createHash('sha1').update(`${VERSION}\0${dev}\0${filename}\0${source}`).digest('hex')
+ const cached = path.join(CACHE, `${key}.js`)
+ try {
+ return fs.readFileSync(cached, 'utf8')
+ } catch {
+ const code = compileNow(source, filename, dev)
+ try {
+ fs.mkdirSync(CACHE, { recursive: true })
+ fs.writeFileSync(cached, code)
+ } catch {} // a read-only place: no cache
+ return code
}
- return r.js.code
+}
+
+function compileNow (source, filename, dev) {
+ compiler ??= require('svelte/compiler')
+ if (!filename.endsWith('.svelte')) return 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
+ // 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` +
+ `__buiAddStyle(${JSON.stringify(key)}, ${JSON.stringify(r.css.code)})\n`
}
/** The file `specifier` (`svelte`, `svelte/store` ...) names in its package's
* browser build, resolved from `fromDir`. */
export function resolveBrowser (specifier, fromDir) {
+ const key = `${fromDir}\0${specifier}`
+ let file = resolved.get(key)
+ if (file === undefined) resolved.set(key, (file = findBrowser(specifier, fromDir)))
+ return file
+}
+
+const resolved = new Map() // fromDir + specifier -> file
+const exportsByRoot = new Map() // package root -> its package.json's exports
+
+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
+}
+
+function findBrowser (specifier, fromDir) {
const slash = specifier.indexOf('/')
const name = slash < 0 ? specifier : specifier.slice(0, slash)
const sub = slash < 0 ? '.' : '.' + specifier.slice(slash)
for (let dir = fromDir; ; dir = path.dirname(dir)) {
const root = path.join(dir, 'node_modules', name)
if (fs.existsSync(path.join(root, 'package.json'))) {
- const target = pick(JSON.parse(fs.readFileSync(path.join(root, 'package.json'), 'utf8')).exports?.[sub])
+ const target = pick(packageExports(root)[sub])
if (target === null) throw new Error(`@blender-ui/svelte: ${specifier}: no browser export`)
return path.join(root, target)
}
- if (path.dirname(dir) === dir) throw new Error(`@blender-ui/svelte: cannot find ${name} from ${fromDir}`)
+ if (path.dirname(dir) === dir) {
+ if (fromDir !== HERE) return findBrowser(specifier, HERE) // not installed there: as this package sees it
+ throw new Error(`@blender-ui/svelte: cannot find ${name}`)
+ }
}
}
@@ -57,8 +107,7 @@ export function browserRedirect (file) {
let map = redirects.get(m[1])
if (map === undefined) {
map = new Map()
- const exports = JSON.parse(fs.readFileSync(path.join(m[1], 'package.json'), 'utf8')).exports ?? {}
- for (const entry of Object.values(exports)) {
+ for (const entry of Object.values(packageExports(m[1]))) {
const browser = pick(entry)
const fallback = typeof entry === 'object' && entry !== null ? pickFrom(entry, ['default']) : null
if (browser && fallback && browser !== fallback) map.set(path.join(m[1], fallback), path.join(m[1], browser))
diff --git a/bindings/svelte/index.js b/bindings/svelte/index.js
index b0fcd2f..0ecc171 100644
--- a/bindings/svelte/index.js
+++ b/bindings/svelte/index.js
@@ -22,10 +22,15 @@ import Widget from './Widget.svelte'
* the window closes). */
export function createRoot (window) {
let component = null
+ if (!styled.has(window)) {
+ styled.set(window, new Set())
+ window.on('close', () => styled.delete(window))
+ }
const root = {
/** Mount `Component` (replacing what this root showed); returns its exports. */
render (Component, options = {}) {
root.unmount()
+ addStyles(window)
component = mount(Component, { target: window.body, props: options.props, context: options.context })
return component
},
@@ -39,6 +44,29 @@ export function createRoot (window) {
return root
}
+// Components' scoped stylesheets (their <style> blocks): each one is added to
+// a window once, as a <style> element, however many instances it shows.
+const styles = new Map() // key (the component's file) -> CSS
+const styled = new Map() // window with a root -> the keys added to it
+
+/** Called by compiled components that have a <style> block (compile.js). */
+export function addStyle (key, css) {
+ if (styles.has(key)) return
+ styles.set(key, css)
+ for (const window of styled.keys()) addStyles(window)
+}
+
+function addStyles (window) {
+ const added = styled.get(window)
+ for (const [key, css] of styles) {
+ if (added.has(key)) continue
+ added.add(key)
+ const el = window.createElement('style')
+ el.textContent = css
+ window.body.insertBefore(el, window.body.firstChild)
+ }
+}
+
/** Open a window (and an App, unless `options.app` is given) and mount `Component` in it. */
export function render (Component, options = {}) {
const { app, window } = host.open(options)
diff --git a/bindings/svelte/plugin.js b/bindings/svelte/plugin.js
index c6071cd..3cffd2a 100644
--- a/bindings/svelte/plugin.js
+++ b/bindings/svelte/plugin.js
@@ -5,11 +5,12 @@
// SPDX-License-Identifier: GPL-2.0-or-later
import fs from 'node:fs'
import path from 'node:path'
-import { SVELTE_FILE, BROWSER_PACKAGE, BROWSER_PACKAGE_FILE, compileSvelte, resolveBrowser, browserRedirect } from './compile.js'
+import { SVELTE_FILE, BROWSER_PACKAGE, BROWSER_PACKAGE_FILE, SELF, SELF_FILE, compileSvelte, resolveBrowser, browserRedirect } 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
diff --git a/bindings/svelte/register.js b/bindings/svelte/register.js
index 9916118..75ea8d4 100644
--- a/bindings/svelte/register.js
+++ b/bindings/svelte/register.js
@@ -6,7 +6,7 @@
import fs from 'node:fs'
import path from 'node:path'
import { fileURLToPath, pathToFileURL } from 'node:url'
-import { SVELTE_FILE, BROWSER_PACKAGE, compileSvelte, resolveBrowser } from './compile.js'
+import { SVELTE_FILE, BROWSER_PACKAGE, SELF, SELF_FILE, compileSvelte, resolveBrowser } from './compile.js'
import plugin from './plugin.js'
if (typeof Bun !== 'undefined') {
@@ -16,6 +16,7 @@ if (typeof Bun !== 'undefined') {
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 (!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 }
diff --git a/bindings/svelte/test/fixtures/Blocks.svelte b/bindings/svelte/test/fixtures/Blocks.svelte
new file mode 100644
index 0000000..d2ec824
--- /dev/null
+++ b/bindings/svelte/test/fixtures/Blocks.svelte
@@ -0,0 +1,20 @@
+<!-- {#await}, {#key}, class objects, bind:group and a scoped <style>. -->
+<script>
+ let { promise, expose } = $props()
+ let version = $state(1)
+ let active = $state(false)
+ let flavor = $state('a')
+ expose({ bump: () => version++, toggle: () => (active = !active) })
+</script>
+
+<div id="await">{#await promise}loading{:then value}got {value}{/await}</div>
+{#key version}<span id="key">v{version}</span>{/key}
+<span id="cls" class={{ on: active, base: true }}>x</span>
+<input id="fa" type="radio" value="a" bind:group={flavor} />
+<input id="fb" type="radio" value="b" bind:group={flavor} />
+<p id="flavor">{flavor}</p>
+<div class="red"></div>
+
+<style>
+ .red { width: 40px; height: 20px; background: #ff0000; }
+</style>
diff --git a/bindings/svelte/test/svelte.test.js b/bindings/svelte/test/svelte.test.js
index 1d31b38..62bb3cf 100644
--- a/bindings/svelte/test/svelte.test.js
+++ b/bindings/svelte/test/svelte.test.js
@@ -9,6 +9,7 @@ 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'
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)] }
@@ -138,6 +139,39 @@ test('Svelte: bindings, Blender widgets, snippets, context and lifecycle', async
assert.deepStrictEqual(log, ['mount', 'destroy'], 'closing the window unmounts')
})
+test('Svelte: {#await}, {#key}, class objects, bind:group and a scoped <style>', async (t) => {
+ let resolve
+ let set
+ const promise = new Promise((r) => { resolve = r })
+ const { app, window } = render(Blocks, { props: { promise, expose: (s) => { set = s } }, headless: true, width: 100, height: 100 })
+ t.after(() => app.quit())
+ window.body.style = 'margin: 0; background: #000'
+ const find = finder(window)
+ await tick()
+ assert.strictEqual(find('await').textContent, 'loading')
+ resolve(42)
+ await tick()
+ assert.strictEqual(find('await').textContent, 'got 42')
+ const first = find('key')
+ act(() => set.bump())
+ await tick()
+ assert.notStrictEqual(find('key'), first, '{#key} re-created its content')
+ assert.strictEqual(find('key').textContent, 'v2')
+ assert.strictEqual(find('cls').className, 'base')
+ act(() => set.toggle())
+ assert.deepStrictEqual(find('cls').className.split(' ').sort(), ['base', 'on'])
+ find('fb')._dispatch({ kind: 'change', checked: true })
+ await tick()
+ assert.strictEqual(find('flavor').textContent, 'b', 'bind:group')
+ // (no id attribute: BUI measures elements without one)
+ const red = [...window._nodes.values()].find((n) => n.getAttribute?.('class')?.startsWith('red'))
+ 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')
+ 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)', () => {
assert.strictEqual(typeof HANDLERS, 'symbol')
})