gpuix-svelte README

README проекта с github.com/khromov/gpuix-svelte. Одним файлом markdown: README.md.

gpuix-svelte

Docs · Playground · npm

Write desktop apps in Svelte and render them into a native, GPU-accelerated window. gpuix-svelte is a Svelte custom renderer for GPUI, the UI framework behind the Zed editor. It talks to GPUI through @gpuix/native.

Four gpuix-svelte demos running as native macOS windows

Quick start

npm create gpuix-svelte@latest my-app
cd my-app
npm install
npm start

A counter opens in its own window. Edit App.svelte, save, and the window hot-reloads.

The starter app's window: a dark card with the count 2, a minus button, a plus button and the hint

You need Node.js 24 or later or Bun 1.4 or later, on macOS (Apple Silicon), Windows (x64 or arm64) or Linux (x64). The GPUI binary comes prebuilt from npm, so npm install is all the setup there is. On Bun, run bun create gpuix-svelte my-app, then cd my-app, bun install and bun run start. Building the app for distribution (npm run build: a .app on macOS, an .exe on Windows, a binary on Linux) needs Bun even if you develop on Node; see Shipping.

On Linux the binary loads libxcb, libxkbcommon and libxkbcommon-x11. Desktop installs have them, a minimal container does not (apt install libxcb1 libxkbcommon0 libxkbcommon-x11-0), and a machine without a GPU also needs a software Vulkan driver such as mesa-vulkan-drivers. Wayland and X11 both work. GNOME under Wayland gives the window no title bar, so there render() draws a simple one of its own (details).

Writing Svelte with gpuix-svelte

<!-- App.svelte -->
<script lang="ts">
  let count = $state(0);
</script>

<div class="app">
  <text class="count">{count}</text>
  <div class="btn" onclick={() => count++}>Add one</div>
</div>

<style>
  .app {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 16px;
    padding: 32px;
    width: 100%;
    height: 100%;
    background-color: #000000;
  }
  .count {
    font-size: 48px;
    color: #ededed;
  }
  .btn {
    padding: 12px 24px;
    border-radius: 8px;
    border-width: 1px;
    border-style: solid;
    border-color: #242424;
    background-color: #111111;
    color: #ededed;
  }
  .btn:hover {
    border-color: #404040;
    background-color: #1c1c1c;
  }
</style>
// app.ts
import { render_hot } from "gpuix-svelte";

render_hot(new URL("./App.svelte", import.meta.url), {
  title: "My app",
  width: 640,
  height: 480,
});
npx gpuix-svelte app.ts          # Node
npx gpuix-svelte --bun app.ts    # Bun

Runes, snippets, {#each}, {#if}, {#await}, <svelte:boundary> and .svelte.ts state modules all work. Scoped <style> blocks work for class rules (the styling page has the details). GPUI paints the window on the GPU. Your app runs in Node or Bun, so it can read files, spawn processes, open SQLite databases and load native addons directly.

Coming from Svelte on the web

Documentation

Styling Every CSS property and value GPUI understands, what is dropped, theming with variables
Components Scroller (incl. virtualised lists), Portal, Tooltip, Popover, the native <anchored> they build on, and RtlText for right-to-left paragraphs
Guide Forms, text search, keyboard and focus, reactive window size, the GNOME title bar, window and desktop helpers, fonts and right-to-left text, state that survives hot reload
Accessibility What reaches a screen reader, what GPUI lacks and what to use instead, keyboard patterns for menus, dialogs and lists
Testing Headless tests that click through GPUI's real hit testing, screenshots, and driving a running window
Shipping Standalone binaries, signed macOS apps, and running in a browser via WebGPU
DOM Rendering Svelte components in both gpuix-svelte and normal DOM, with Vite or SvelteKit: IS_GPUIX, what each helper and component does there, writing for both renderers
UI toolkit gpuix-svelte-ui: buttons, fields, choices, menus, dialogs, toasts, layout and feedback components for both renderers, a router, the theme behind them, responsive layouts
Updating In-app updates from a static manifest, hash and signature checked, with a GitHub release workflow
Migrating What to change when upgrading between releases, with instructions to paste to a coding agent

For real code, the examples are the best reference (see Examples). To try a component without installing anything, the playground compiles one in the browser and runs it on GPUI's WebAssembly build or in the DOM, with the element tree, the mutations and the compiled JavaScript beside it.

Adding it to an existing project

npm install gpuix-svelte svelte

svelte is a peer dependency, 5.59.1 or later (see About the Svelte version). Run your entry through the package's bin, usually from package.json:

{
  "type": "module",
  "scripts": {
    "start": "gpuix-svelte app.ts",
    "test": "gpuix-svelte test.ts"
  }
}

The bin starts Node, or Bun when you pass --bun or launch it with bun run. Before your entry loads, it sets the svelte-custom-renderer condition, which picks Svelte's client runtime and this package's GPUI build, and teaches the runtime to import .svelte files. Your .ts files need nothing extra: Node and Bun run TypeScript themselves.

Runtime flags go before the entry, and a flag that takes a value needs the = form (gpuix-svelte --experimental-ffi app.ts, gpuix-svelte --import=tsx app.ts). Arguments after the entry go to your script. Spelled out, the bin runs:

node --conditions svelte-custom-renderer --conditions development --import gpuix-svelte/register app.ts
bun  --conditions svelte-custom-renderer --conditions development --preload gpuix-svelte/plugin app.ts

The two --conditions flags matter: without them svelte resolves to its server build and mount() does not exist. A bunfig.toml preload on its own is not enough for a plain bun file.ts run, so go through the bin.

TypeScript

The package ships type declarations. For the editor and svelte-check to type your markup as GPUI elements, your tsconfig.json needs the gpuixHTML namespace:

{
  "compilerOptions": {
    "module": "nodenext",
    "strict": true,
    "noEmit": true,
    "allowImportingTsExtensions": true,
    "erasableSyntaxOnly": true,
    "verbatimModuleSyntax": true,
    "customConditions": ["svelte-custom-renderer", "development"],
    "types": ["node", "gpuix-svelte/html"],
    "skipLibCheck": true,
  },
  "svelteOptions": { "namespace": "gpuixHTML" },
}

That config needs typescript, @types/node and svelte-check as dev dependencies. You'll also want a *.svelte module declaration and a svelte.config.js that turns off Svelte's DOM accessibility advice. starter/ has all of it, ready to copy.

Node runs TypeScript by stripping the types, which rules out enums, namespaces, parameter properties, a type imported without import type, and a relative import without a file extension. Bun transpiles and accepts all of those, but the config above makes tsc flag them so the app runs on both. If your app needs that syntax on Node anyway, install tsx and load it through the bin: gpuix-svelte --import=tsx app.ts.

Event handlers take a GpuixEvent and {@attach} gets a ShadowNode. Both are exported as types:

<script lang="ts">
  import type { GpuixEvent, ShadowNode } from 'gpuix-svelte';
</script>

Examples

Every example under examples/ is an ordinary app: its .svelte components and a main.ts that calls render_hot, so any of them drops into a project made with npm create gpuix-svelte (liquid-glass-ffi also needs the liquid-glass component beside it). The scripts below run them in a clone of the repository (bun install, then the command):

npm run demo:counter The counter, hot-reloading on save
npm run demo:tictactoe Tic-tac-toe with score tracking
npm run demo:hn Hacker News reader: live network data in a scrolling list
npm run demo:glass A translucent control center over macOS vibrancy (demo:glass-ffi: NSGlassEffectView via FFI, macOS 26 and Node 26.1 or later)
npm run demo:styling Which CSS reaches GPUI and which is dropped, side by side
npm run demo:desktop Window controls, file picker and drops, live image pixels, selection, focus, accessibility
npm run demo:native-0.11 What @gpuix/native 0.11 added: keyboard focus styles and dimming, Tab, layout and scroll events, new styles, fonts
npm run demo:web Tic-tac-toe in a browser on GPUI's WebAssembly build (Bun)
npm run demo:cross One component on both renderers: a GPUI window here, a browser DOM through Vite with npm run demo:dom
npm run demo:ui The UI toolkit's showcase, every gpuix-svelte-ui component in a GPUI window; the same page in a browser with npm run demo:ui-dom
npm run demo:ui-app Orbit, a small deployment dashboard built from the UI toolkit: a sidebar, three screens behind its router, forms, a dialog and toasts
npm run tutorial A 12-step interactive guide to the renderer, itself a gpuix-svelte app

Each of these, apart from demo:web (which always runs on Bun) and demo:dom / demo:ui-dom (Vite), has a Bun twin under a bun: prefix, such as npm run bun:demo:counter.

Outside this repository, gpuix-svelte-sveltekit-shared-components-demo is a small component library rendered by a SvelteKit site and by a GPUI window at the same time, with npm run dev opening both.

About the Svelte version

[!NOTE] This section describes 0.7.0, which isn't released yet. Until it is on npm, 0.6 bundles its own Svelte build; the migration guide covers the move.

Custom renderers arrived in Svelte 5.59 as an experimental feature, and gpuix-svelte needs 5.59.1 or later. Svelte is a peer dependency, so your app, svelte-check and the renderer all run on the one copy your app installs.

In practice:

Good to know

How it works

Svelte's custom renderer API hands the renderer DOM-shaped operations: create an element, insert it before an anchor, set an attribute, add a comment node. GPUI's tree is flat, keyed by numeric id, and holds elements and text. gpuix-svelte keeps a lightweight shadow tree in JavaScript and projects it onto GPUI. Only elements and non-blank text get native nodes, and they're created lazily, once they're attached to the window. Every change in a frame is queued and shipped as one batch before the next paint.

Around that sit a .svelte loader for Node and one for Bun, which compile components with the renderer baked in and turn <style> blocks into class rules, a translator from CSS to GPUI styles that expands shorthands and drops what GPUI would reject, a ~125 fps frame loop, and in-process hot reload. The full design notes are in CLAUDE.md.

Contributing

See docs/contributing.md for running the demos and tests, and how releases are cut.

License

MIT

gpuix-svelte (khromov/gpuix-svelte)

Ищем в базе…

Что это?gpuix-svelte — это кастомный рендерер, который позволяет обычным Svelte-компонентам отрисовывать нативные окна рабочего стола через GPUI (GPU-ускоренный UI-фреймворк из Zed), без какого-либо webview.
Это десктопный фреймворк или просто бэкенд отрисовки для Svelte?Это пакет-библиотека рендерера, который вы устанавливаете в Svelte-проект; он подменяет ещё не выпущенный target кастомного рендерера Svelte на GPUI вместо DOM, так что ваши компоненты становятся нативными окнами.
Как добавить его в свой проект?Скопируйте папку starter/ (самый маленький полный проект), выполните npm install, затем запускайте свой входной файл через собственный bin пакета, например gpuix-svelte app.ts.
Нужен ли установленный Rust или другие нативные тулчейны?Нет. Нативный аддон @gpuix/native поставляется прекомпилированным из npm, поэтому нужен только Node.js 24+ или Bun 1.4.0+ — Rust и настройка компилятора не требуются.
Это достаточно стабильно, чтобы строить на нём настоящее приложение?Нет — это откровенно экспериментальная незавершённая работа поверх ещё не выпущенного API кастомных рендереров Svelte, так что по мере изменения этого API поломки ожидаемы.
На каких платформах это реально работает?Десктопные сборки тестируются на macOS и Windows и совместимы также с Linux; те же компоненты вдобавок могут работать в браузере, поскольку GPUI компилируется в WebAssembly и рисует через WebGPU.
Можно ли собрать отдельный исполняемый файл, не требующий Node или Bun?Да, Bun может скомпилировать пример в один самодостаточный бинарник, которому на этапе выполнения не нужны ни Node, ни Bun, ни node_modules. Результат — около 80 МБ: рантайм Bun, рантайм Svelte и 17-МБ аддон GPUI; собирать нужно нативно на каждой целевой платформе, кросс-компиляции нет.
Как устроена стилизация, если нет ни DOM, ни CSS?CSS-движка нет: атрибут style на компоненте разбирается в простой объект и отправляется прямо в GPUI, который раскладывает всё флексбоксом в логических пикселях, а значения темы меняются вызовом setcssvars() со ссылками вида var(--name).
Какие UI-строительные блоки пакет даёт из коробки?В комплекте два готовых Svelte-компонента: Scroller — колонка с прокруткой и нарисованным ползунком, потому что GPUI не рисует нативный скроллбар, — и виртуальный список, который рендерит только строки рядом с видимой областью, чтобы длинные списки оставались быстрыми.
Нужно ли подписывать приложение, прежде чем передавать его другим людям?Для распространения на macOS — да: собранные бинарники по умолчанию не подписаны, и macOS блокирует запуск скачанной неподписанной копии, пока её явно не разрешат в Системных настройках, поэтому в проект входит процесс подписания и нотаризации через Developer ID и notarytool.
Какие есть похожие проекты?gpuix, Avalonia, nanoui, mygo, flutter, compose-multiplatform, electrobun, ondine
В каких он темах?ui-framework, svelte, bun, rendering, wasm, desktop, framework, gui, gpu, frontend, npm, desktop-app
Автор
khromov
Размер
25.1 MB
Звёзды
474
Возраст
3 мес
Коммиты · 90 дней