gpuix-svelte v0.5.0
llms.txt

Guide

Forms

There is no bind: here. Inputs report through events, and the event carries the value:

<input value={text} onchange={(e) => (text = e.value)} onsubmit={(e) => send(e.value)} />
<textarea value={notes} onchange={(e) => (notes = e.value)}></textarea>

onchange fires on every edit; there is no oninput.

To get hold of an element, use {@attach (node) => …} (or use:). To measure it, get_native().getElementBounds(node.nativeId) returns its border box (padding and border included) as { x, y, width, height } in window coordinates, and getScrollOffset(node.nativeId) the scroll position of a scroll container. On Windows and Linux each getElementBounds call makes GPUI draw a frame before it answers, so don't call it on a timer. onlayout and onscrollchange (see below) tell you when something changed and cost nothing while nothing does. Under Wayland a window the compositor isn't drawing, such as a minimized one, has no next frame, so the call blocks for 2 seconds and then throws. read_native turns the throw into null, but not the wait.

In a <textarea>, Enter inserts a newline unless the element has onsubmit. With onsubmit, Enter submits and Shift+Enter inserts the newline. In an <input>, Enter always submits.

div and text take a highlight prop, which GPUI paints behind matching text, and they report the match count through onhighlight. TextSearch keeps that state for a find bar:

<script lang="ts">
  import { TextSearch } from 'gpuix-svelte';
  const search = new TextSearch({ color: '#f5a52455', active_color: '#f5a524' });
</script>

<input value={search.query} onchange={(e) => (search.query = e.value)} onsubmit={search.next} />
<text>{search.total ? search.active + 1 : 0}/{search.total}</text>
<div highlight={search.spec} onhighlight={search.on_highlight}>{body}</div>

You can set query, case_sensitive and whole_word at any time. total is the match count, and active is the current match. next() and prev() wrap around, and go_to(i) ignores an index outside the matches. An empty query makes spec null, which clears the highlight. Besides the colours, the constructor takes a radius for the highlight's corners. The count covers the elements that carry the highlight, so rows a virtual list has not rendered are not in it.

find_ranges(text, query, { case_sensitive, whole_word }) does the same matching in JS and returns the [start, end) pairs that highlight={{ ranges }} takes. Use it for text that is not on screen.

For a virtual list, count the matches yourself with find_ranges and set matches (or pass it to the constructor): total is every match, and index_offset how many come before the first row the list has rendered, counted in matches rather than rows. total and active then follow it, next() and prev() wrap at it, and the active match is painted on the right row. Setting it to null hands the count back to native. find_ranges takes the search itself as its options, which keeps the flags in step:

<script lang="ts">
  import { TextSearch, find_ranges } from 'gpuix-svelte';
  const search = new TextSearch();
  const per_row = $derived(rows.map((row) => find_ranges(row.text, search.query, search).length));

  $effect(() => {
    search.matches = {
      total: per_row.reduce((n, count) => n + count, 0),
      index_offset: per_row.slice(0, first_visible_row).reduce((n, count) => n + count, 0)
    };
  });
</script>

Moving the list to the active match is up to you, for example with scrollToItem.

Keyboard shortcuts and focus

keydown on an element needs that element focused (tabindex="0" or autofocus). A key reaches the focused element and every focusable ancestor that listens. For app shortcuts, listen on the window:

<script>
  import { on_window_key, blur, focus_element } from 'gpuix-svelte';
  let search;

  $effect(() =>
    on_window_key('keydown', (e) => {
      if (e.modifiers.cmd && e.key === 'k') return focus_element(search);
      if (e.key === 'escape') return e.editing ? blur() : close();
    })
  );
</script>

<input {@attach (node) => (search = node)} />

on_window_key hears a key whatever has focus and returns an unsubscribe function, so returning it from an $effect cleans up for you. render() takes onKeyDown and onKeyUp options that do the same and survive remounts. A text field still receives the keys typed into it, and e.editing tells your handler that a field has focus, so it can step aside. A field's own bindings (Enter, arrows, Backspace, cmd/ctrl with a, c, v, x or z) can consume a key before the window handler sees it. e.modifiers.cmd is the platform key: Cmd on macOS, the Windows key on Windows and Linux.

blur() hands focus back from a field to the window, and focus_element(node) focuses an element. focused_element() returns the focused element. focus_next_within(node) and focus_previous_within(node) cycle through the tab stops inside one element, wrapping there.

Tab and Shift+Tab move focus through the window's tab stops, in document order and wrapping at the ends, as in a browser. Tab never types a tab character into an <input> or <textarea>, and Ctrl, Alt and Cmd combinations are left alone. The move happens after every key handler for that keystroke has run, so any of them can keep it:

<div
  tabindex="0"
  onkeydown={(e) => {
    if (e.key !== 'tab') return;
    e.preventDefault(); // keep this Tab, say to indent
    indent();
  }}
></div>

A key goes to the focused element, then to each focusable ancestor that listens, then to the window's on_window_key handlers. e.stopPropagation() skips the ones after it, and e.defaultPrevented tells a later handler that an earlier one called preventDefault(). e.keystrokeId is the same on the element's keydown and the window's for one keystroke. render(App, { tabNavigation: false }) turns the default off; then focus_next() and focus_previous() are yours to call. They walk the same order as the Tab moves.

The order is the tab stops of the last painted frame, so a stop that an {#if} has just rendered joins it once it has painted. To focus a particular new element, give it autofocus or call focus_element(node).

An overlay that Escape closes, such as a menu, a popover or a modal, goes on the window's layer stack with dismiss_layer, which returns the function that takes it off again:

<script>
  import { dismiss_layer, dismiss_scope } from 'gpuix-svelte';
  let { open, onclose } = $props();
  const scope = dismiss_scope();

  $effect(() => {
    if (!open) return;
    return dismiss_layer({ onEscape: () => onclose(), scope });
  });
</script>

Escape reaches only the layer on top, the one that opened last, so a tooltip inside a popover closes before the popover does. dismiss_scope() keeps that true when both open at once: it ties the overlay to the ones mounted inside it, so call it while the component initialises, not in the effect. Like the Tab move, Escape runs after every key handler for that keystroke, so e.preventDefault() in any of them keeps the layer open, and so does e.stopPropagation() on the focused element or one of its ancestors, which says that handler used the key (one in an on_window_key handler does not, as other window listeners still hear it). A held key's repeats and Escape with Ctrl, Alt or Cmd are left alone. Tooltip and Popover both use it.

:focus-visible rules and the focus-visible="..." attribute style an element while it has keyboard focus (not after a click), and outline-width, outline-color and outline-offset draw the ring outside its border. GPUI can also dim every other focusable element to 40% opacity while one has keyboard focus, which shows where Tab can go (a focused text field dims nothing). gpuix-svelte leaves that off: render(App, { keyboardFocusDim: true }) turns it on (and mount_headless takes the same option), set_keyboard_focus_dim(enabled) switches it at runtime (a hot reload keeps the switch), and keyboard-focus-dim: false in an element's style exempts it. That style is not inherited, so it goes on the focusable element itself.

Window size and insets

window_size and window_insets are reactive wherever a template, $derived or $effect reads them:

<script>
  import { window_size, window_insets } from 'gpuix-svelte';
  const columns = $derived(window_size.width < 600 ? 1 : 2);
</script>

<div style:padding-top="{window_insets.safeArea.top}px">
  {columns} column(s) at {window_size.width}×{window_size.height}
</div>

They ask the window every 100 ms, but only while something reactive is reading them. A read anywhere else (a click handler, module code) gets the last polled value while a poll is running, and asks the window directly otherwise. Keep any $derived over them inside a component: one in a .svelte.ts module that is first read outside an effect keeps polling for the life of the process.

window_insets carries safeArea, ime and effective (each { top, right, bottom, left }) plus keyboardTop, keyboardVisible and visibleHeight. The names are camelCase, like every other value GPUI reports. Only macOS reports real insets; Windows, Linux and headless tests see zeros. Headless tests see their real viewport size. Before any window exists, the size reads as 800×600.

Media queries

A layout that changes with the window's width can be written as CSS. @media in a <style> block takes queries over width, height and orientation (min-/max- or the range syntax, in px, rem or em), the rules inside apply while the query holds, and the elements they style are restyled when the window's size changes:

<div class="cards">…</div>

<style>
  .cards { display: flex; flex-direction: row; gap: 16px; }
  @media (max-width: 700px) {
    .cards { flex-direction: column; gap: 8px; }
  }
</style>

media_query(query) is the same test for JavaScript, matchMedia-shaped: current is reactive wherever a template, $derived or $effect reads it, so a component can branch its markup rather than its CSS.

<script>
  import { media_query } from 'gpuix-svelte';
  const narrow = media_query('(max-width: 700px)');
</script>

{#if narrow.current}<Menu />{:else}<Sidebar />{/if}

Both read the window through the one poll window_size uses, so a resize shows within 100 ms, the three never disagree, and the poll runs only while something depends on it. A query a window cannot answer (prefers-color-scheme, hover, a vw length) never matches, as a browser's not all, while the other alternatives of a comma list still count; an @media block or a media_query with no answerable alternative is warned about, once per query. Styling has the details.

Title bar on GNOME

On GNOME under Wayland a gpuix window has no title bar: GNOME leaves drawing it to the app, and GPUI draws none. So render() draws a simple one above your app there, with the window title (it follows set_window_title) and minimise, maximise and close buttons, and leaves every other platform alone. That is its titlebar option's default, 'auto': titlebar: false turns the bar off and titlebar: true draws it everywhere. Your app then mounts in the box below the bar, and rootStyle styles that box, so a <Portal> still covers the whole window. The bar can't be dragged to move the window, since @gpuix/native has no window move yet; Super+drag still moves it. A double-click maximises, and close unmounts the app and ends the process. Its colours are --titlebar-bg, --titlebar-fg, --titlebar-hover and --titlebar-close, declared in a :root rule. Running the app under X11 instead (WAYLAND_DISPLAY unset) gets GNOME's own title bar.

Window and desktop helpers

All of these come from gpuix-svelte, and wherever they take an element they take the node an {@attach} gives you. Where the platform has no such call, they quietly do nothing: the window controls and blur do nothing headlessly, and the browser build has no file system. In a browser DOM build each one becomes its DOM counterpart or a no-op; Rendering Svelte components in both gpuix-svelte and normal DOM lists them. The repository's desktop-apis example puts most of them to work in one component (in a clone, npm run demo:desktop), and native-0.11 shows what @gpuix/native 0.11 added (npm run demo:native-0.11).

  • set_window_title(title), activate_window(), minimize_window(), zoom_window() and toggle_fullscreen().
  • prompt_for_paths({ files, directories, multiple, prompt }) opens the system picker and resolves to absolute paths, or to null on cancel and headlessly. It rejects in a browser, and on Linux when no XDG desktop portal is reachable. It has no file-type filter. See While a file picker is open.
  • on_selection_change(handler) hears every change to the window's text selection, a clear included. e.value is the selected text, and undefined after a clear. It returns its unsubscribe, and render() takes an onSelectionChange option for the same thing.
  • selected_text() is the selected text, or null, and is reactive where a template, $derived or $effect reads it, through the same event rather than a poll. clear_selection() drops the selection; selected_text() follows once the next frame reports the change.
  • is_terminal() is true when @gpuix/native's terminal mode (GPUIX_TERMINAL=1) draws the app inside the terminal, where there is no title bar to leave room for. It is false until render() has opened the window, so read it while rendering, not at module scope.
  • scroll_into_view(node) scrolls the nearest scroll container or <virtual-list> until node shows.
  • set_image(node, bytes) puts encoded image bytes (PNG, JPEG, WebP, GIF, SVG, …) on an <img>. set_image_pixels(node, width, height, pixels, format) takes packed straight-alpha pixels and scales them into the element's box, so upload at 2× for a sharp image on retina screens. format is 'rgba' (the default) or 'bgra', GPUI's own order, which skips a per-pixel swizzle and is what ffmpeg's -pix_fmt bgra produces. The image is dropped when the element is destroyed or its src changes. Called from {@attach}, both wait for the element to exist.
  • register_font(bytes) adds a TrueType or OpenType file (or collection), so font-family can name the families it declares. Register it before the text that uses the family is first laid out. It throws on a file GPUI can't use, and does nothing in a browser.
  • elements_at(x, y) returns the elements painted under a window point, topmost first, like the DOM's elementsFromPoint. It skips anything clipped away or pointer-events: none, and returns nothing in a browser.

Elements also take onfiledrop, for files dropped from the system's file manager. e.paths are absolute, and e.x / e.y is the drop point. <virtual-list> doesn't get it, so wrap a list in a div to take drops. onmotioncomplete fires when a motion track reaches its target.

onlayout (on div and text) reports an element's border box after its first paint and again whenever its size changes: e.width and e.height, with e.x / e.y in window coordinates. onscrollchange reports a scroll container's offset as e.scrollX / e.scrollY (0 at the start, negative as the content moves) after every scroll, including scroll_into_view() and scrollTo, where onscroll hears only wheel input. It does not fire on <virtual-list>. Neither one takes the pointer, so neither costs a hitbox="self" ancestor its clicks.

role and aria-* attributes reach VoiceOver and other screen readers through GPUI. Accessibility lists which ones, and what to use for those GPUI doesn't have yet.

While a file picker is open

On Windows the picker runs on GPUI's UI thread, so until it closes, a native call that waits for that thread stalls JavaScript for 2 seconds and then throws. Your timers keep running, and an exception from a timer ends the process. The helpers here account for it while a prompt_for_paths() is open on Windows. On macOS and Linux the UI thread keeps running behind the picker, the app stays usable, and they work as usual.

  • focused_element() returns null, elements_at() nothing and debug_overlay() / debug_overlay_stats() undefined, without asking native.
  • window_size holds the size from when the picker opened.
  • set_image and set_image_pixels wait until it closes, then upload the newest image per element.
  • Scroller and Popover need nothing from you.

A read made through get_native() directly gets no such protection, and the same throw can hit a call that is in flight as the last window closes. If a read can run on a timer or in an effect, wrap it in read_native, which returns null while a picker is open on Windows or if the UI thread can't answer, and lets any other error through:

const top = read_native((native) => native.getListScrollTop(node.nativeId));
if (top) place_marker(top);

register_font, set_debug_overlay and cycle_debug_overlay aren't covered, so they can throw a timeout during a picker.

The draw-time overlay

GPUI can show an overlay in the top-right corner with the current, 1%-worst, 10%-worst and maximum draw times in ms, plus a frame count; minimal shows only the last draw. These are draw times, so compare them with the frame budget: 8.3 ms per frame is 120 Hz.

Turn it on with render(App, { debugFrameOverlay: 'full' }), or for any app with GPUIX_FPS=1 (or =minimal), which takes precedence over the option. At runtime, set_debug_overlay(mode), cycle_debug_overlay() (hidden → minimal → full, handy for a key binding) and debug_overlay() control it. debug_overlay_stats() reads the same numbers for a script or a headless bench, and reset_debug_overlay_stats() clears the draw samples (the frame count keeps going). They keep recording while the overlay is hidden. A hot reload keeps whatever mode is showing.

State that survives hot reload

render_hot remounts the root every time you save a .svelte file, so component state resets. A .svelte.ts module loads once and is not reloaded, which makes it the place for state that should outlive a reload: the current route, the theme, an app object.

// state.svelte.ts
export const app = $state({ route: '/', theme: 'system' });

The flip side: editing a .svelte.ts file, or any other .ts or .js module, needs a restart. render_hot prints a reminder the first time one changes under the watched directory.