# Loom > Render a roblox-ts UI tree as a live web DOM preview, driven by Vite. - Docs: https://docs.astra-void.xyz/loom/ - Source: https://github.com/astra-void/loom # Loom > Render a roblox-ts UI tree as a live web DOM preview, driven by Vite. Source: https://docs.astra-void.xyz/loom/ Loom renders the `@rbxts/react` or `vide` UI you ship to Roblox in a browser. Layout follows Roblox's rules, not CSS's: `UIListLayout`, `UIPadding`, `AutomaticSize`, `UISizeConstraint` and text measurement run in a Rust layout engine compiled to WASM. Clicks, typing and hover reach your code through `UserInputService` and instance signals, so a preview is interactive. Run it on a roblox-ts project with no setup: ```bash pnpm exec loom preview . ``` Or add one plugin to your own Vite config: ```ts title="vite.config.ts" import { loomPreview } from "@loom-dev/preview/vite"; import { defineConfig } from "vite"; export default defineConfig({ plugins: [loomPreview()] }); ``` The plugin generates the page, installs the Roblox globals (`UDim2`, `Color3`, `Enum`, `game`) and the Luau standard library, and points `@rbxts/*` imports at browser versions. There is no `rbxtsc` step: esbuild transpiles your TSX, and HMR works. Start with [Installation](https://docs.astra-void.xyz/loom/getting-started/installation.md). --- # Installation > Install the loom CLI or the Vite plugin, and confirm a preview renders. Source: https://docs.astra-void.xyz/loom/getting-started/installation/ Loom ships as two packages. Most projects need only one. | How you want to run it | Install | | --- | --- | | The `loom preview` / `loom build` CLI, no Vite config of your own | `loom-dev` | | `loomPreview()` in your own `vite.config.ts` | `@loom-dev/preview`, `react@18`, `vite` | | Both | All of the above | ## Install the CLI Start here if you're unsure. It is one dependency and needs no config file: ```bash pnpm add -D loom-dev ``` `loom-dev` brings its own `@loom-dev/preview`, React and Vite. ## Install the plugin To add the plugin to a Vite project you already have, install it with its peers: ```bash pnpm add -D @loom-dev/preview react@^18.3.1 vite ``` The peers are `react ^18.3.1` and `vite ^6.0.0 || ^7.0.0`. Then follow [Vite integration](https://docs.astra-void.xyz/loom/guides/vite-integration.md). > **React 18 only** > > Loom's React adapter reads React 18 internals, so React 19 fails as soon as the preview loads. Pin > `react@^18.3.1` and `@types/react@^18.3.12`. ## Verify Run this in a roblox-ts project that has a client entry: ```bash title="Smoke test" pnpm exec loom preview . ``` Open the printed URL, by default on port 5173. A dark page with your UI on it means everything is working. A blank page usually means the entry doesn't mount itself; see [Your first preview](https://docs.astra-void.xyz/loom/getting-started/first-preview.md#the-entry-must-mount-itself). ## What you don't install - No roblox-ts build step. esbuild transpiles your TSX directly. - No Rust toolchain. The layout engine ships prebuilt as a `.wasm` file inside `@loom-dev/layout`. Both packages are ESM-only and MIT-licensed. Keep every `@loom-dev/*` package on the same version: they release together, and mixed versions are not supported. ## Next step Point loom at a project and get a preview on screen: [Your first preview](https://docs.astra-void.xyz/loom/getting-started/first-preview.md). --- # Your first preview > Preview a roblox-ts project with the loom CLI and no config, or start one from scratch. Source: https://docs.astra-void.xyz/loom/getting-started/first-preview/ Run the CLI and hand it a project directory: ```bash title="Preview a project" pnpm exec loom preview ~/code/my-game ``` You don't add anything to the project: no `vite.config.ts`, no `index.html`, no entry changes. The directory doesn't need its own `node_modules` either. To get the same thing from your own Vite config, see [Vite integration](https://docs.astra-void.xyz/loom/guides/vite-integration.md). ## A complete project from scratch No roblox-ts project yet? These three files are enough to render: ```text title="Project layout" my-preview/ ├── package.json ├── vite.config.ts └── src/ └── main.client.tsx ``` ```json title="package.json" { "name": "my-preview", "private": true, "type": "module", "scripts": { "dev": "vite", "build": "vite build" }, "devDependencies": { "@loom-dev/preview": "^0.13.2", "react": "^18.3.1", "vite": "^6.0.0" } } ``` ```ts title="vite.config.ts" import { loomPreview } from "@loom-dev/preview/vite"; import { defineConfig } from "vite"; export default defineConfig({ plugins: [loomPreview()] }); ``` ```tsx title="src/main.client.tsx" import { useState } from "@rbxts/react"; import { createRoot } from "@rbxts/react-roblox"; function App() { const [count, setCount] = useState(0); return ( setCount((n) => n + 1) }} > ); } createRoot().render(); ``` ```bash title="Run it" pnpm install && pnpm vite ``` Open the printed URL. You get a rounded card with a label and a blue button, and the count goes up when you click. Edits to `main.client.tsx` hot-reload. You never import `UDim2`, `Color3`, `Enum` or `Vector2`. The plugin installs them as globals before your entry runs. > **Your editor will show type errors** > > The project renders, but your editor redlines `@rbxts/react`, `UDim2` and the lowercase elements. > [TypeScript setup](https://docs.astra-void.xyz/loom/guides/typescript-setup.md) fixes that. ## What the plugin looks for With no `index.html`, the plugin generates a page and loads the first entry it finds from this list: ```text title="Entry candidates, in priority order" src/main.client.tsx src/main.client.ts src/client/main.client.tsx src/client/main.client.ts src/main.tsx src/main.ts src/index.tsx src/client.tsx ``` A normal roblox-ts project already matches one. If yours doesn't, name it with the plugin's `entry` option. If the project has its own `index.html`, loom uses it, and its ` ``` This is the same page the plugin generates. Write your own when you want something extra in it, such as a font link, a wrapper element or a different background. If `#loom-root` is missing, `createRoot()` adds one to ``, but it is unstyled and won't fill the viewport. The entry is an ordinary roblox-ts client entry. See [Your first preview](https://docs.astra-void.xyz/loom/getting-started/first-preview.md). Run `vite` and you have an interactive preview: state updates, `Activated` handlers and text input all work. ## 5. `vite build` produces a static preview ```bash pnpm vite build # → dist/ ``` The build is a self-contained, client-only site: your entry, the renderer and the layout engine, hostable anywhere. The plugin loads the Roblox globals (`UDim2` and friends) before your entry, in the generated page and in your own `index.html`. You don't need to import them yourself. If a built page still throws `UDim2 is not defined`, see [Troubleshooting](https://docs.astra-void.xyz/loom/guides/troubleshooting.md). ## 6. Gallery mode from the plugin Pass `targets` to get the CLI's `*.loom.tsx` gallery under `vite`. `vite build` then builds it as a static site you can deep-link into: ```ts title="vite.config.ts" export default defineConfig({ plugins: [loomPreview({ targets: "src/scenes" })], }); ``` Each target becomes its own chunk. The built page follows the same [URL contract](https://docs.astra-void.xyz/loom/guides/static-builds-and-embedding.md#the-url-contract) as `loom build`, since it is the same build. See [Gallery targets](https://docs.astra-void.xyz/loom/guides/gallery-targets.md) for how to write a target. ## Next steps Two things often break a working setup in a real workspace: importing the plugin by file path, and sharing a Vite config with an app that has its own React. Both are covered in [Advanced Vite setup](https://docs.astra-void.xyz/loom/guides/advanced-vite-setup.md). For error messages and what they mean, see [Troubleshooting](https://docs.astra-void.xyz/loom/guides/troubleshooting.md). --- # Advanced Vite setup > Import the plugin by its bare specifier, and keep it out of a Vite config that serves another React app. Source: https://docs.astra-void.xyz/loom/guides/advanced-vite-setup/ [Vite integration](https://docs.astra-void.xyz/loom/guides/vite-integration.md) covers the setup that works. This page covers two ways it breaks once it moves into a real workspace. ## Always import the plugin by its bare specifier Import `@loom-dev/preview/vite` and nothing else: ```ts // correct import { loomPreview } from "@loom-dev/preview/vite"; // broken — do not do this import { loomPreview } from "../loom/packages/preview/src/vite.ts"; ``` The plugin finds the modules it aliases relative to its own file. A path import lets Vite bundle the plugin into a temporary file inside your project, which moves that anchor. The config still loads, and the build fails later with an error that looks unrelated: ```text [commonjs--resolver] Failed to resolve entry for package "@loom-dev/layout". The package may have incorrect main/module/exports specified in its package.json. ``` ## Don't merge this into an app that also uses React `loomPreview()` changes the whole Vite config it lives in, not just your Roblox files: - It aliases bare `react`, `react/jsx-runtime` and `react/jsx-dev-runtime` to loom's own React 18. - It sets `esbuild.jsx: "automatic"` for every module. Add it to an existing React web app's config and that app gets loom's React 18. A React 19 app breaks, and alongside `@vitejs/plugin-react` you get two JSX transforms fighting. Keep the preview in its own Vite instance. Any of these works: - **A dedicated preview app** in your workspace, with its own `vite.config.ts` and dependencies. A config holding only `loomPreview()` is enough. - **No Vite project at all.** `loom preview` and `loom build` ignore your project's Vite config, so they can't collide with it. - **Mounted inside your app's dev server** with [`loom-dev/embed`](https://docs.astra-void.xyz/loom/reference/cli.md#loom-devembed--the-programmatic-api). The gallery still runs in its own Vite instance, so the two module graphs never meet. > **These docs use the third option** > > An Astro integration mounts the gallery in dev and emits the static bundle at build. Putting > `loomPreview()` in `astro.config.mjs` would replace the site's own React 19. ## When something breaks Every error string, including the runtime ones, is in [Troubleshooting](https://docs.astra-void.xyz/loom/guides/troubleshooting.md). --- # Gallery targets > Browse many scenes at once — the `preview` export contract, discovery globs and error containment. Source: https://docs.astra-void.xyz/loom/guides/gallery-targets/ Gallery mode shows a sidebar of every scene in your project and mounts one at a time. Use it while building a component library. It is also the only mode `loom build` supports. ```bash title="Enable gallery mode" pnpm exec loom preview ~/code/my-ui --targets ``` With `--targets`, loom doesn't look for a client entry, and it serves its own page even if your project has an `index.html`. In a project with its own Vite config, pass the same option to the plugin: ```ts title="vite.config.ts" export default defineConfig({ plugins: [loomPreview({ targets: "src/scenes" })], }); ``` `vite` then serves the gallery, and `vite build` builds it as a static site. ## The target contract A target is any file matching the discovery glob that exports a `preview` object: ```tsx title="src/scenes/Counter.loom.tsx" import { useState } from "@rbxts/react"; function CounterScene() { const [count, setCount] = useState(0); return ( setCount((c) => c + 1) }} /* ... */ /> ); } export const preview = { render: () => , title: "Counter (Activated)", } as const; ``` | Field | Required | Behavior | | --- | --- | --- | | `render` | yes | A function returning a React element. It is rendered as a function component, so hooks inside it work. | | `title` | no | Replaces the file path in the sidebar. Titles load in the background, so the sidebar shows paths first. | Anything else, such as a default export, a bare component export, or a `preview` with no `render` function, shows an error panel: ```text invalid preview export in src/scenes/Counter.loom.tsx target must export `const preview = { render: () => <.../>, title: "..." } as const` ``` > **`render` is called as a component, not invoked once** > > `render` re-runs whenever React re-renders. Keep state in hooks inside the scene component, not in > module variables the `render` function closes over. ## Discovery `--targets` and the plugin's `targets` option take three shapes: | Invocation | Resulting glob | | --- | --- | | `--targets` (no value), or `targets: true` | `**/*.loom.tsx` | | `--targets src/scenes` (no `*`) | `src/scenes/**/*.loom.tsx` | | `--targets "apps/*/src/**/*.scene.tsx"` | used verbatim | The plugin option also takes an array. The CLI flag doesn't. Globs support only `**/` (any depth, including none), `**` and `*` (anything but `/`). There are no braces, `?` or negation. `node_modules` and folders starting with `.` are skipped. The sidebar is sorted by path. See [Glob semantics](https://docs.astra-void.xyz/loom/reference/cli.md#glob-semantics) for the full rules. Adding or deleting a `*.loom.tsx` file reloads the page and keeps the selected target. Editing a target hot-reloads it. ## `loom.config.ts` To stop typing flags, add a config file to the project root: ```ts title="loom.config.ts" export default { targets: "src/scenes", port: 5204, }; ``` `loom preview` reads three fields: `targets` (a string or non-empty array of strings), `port` (a number) and [`shims`](https://docs.astra-void.xyz/loom/guides/package-compatibility.md#shims). CLI flags win over the file. Node loads it with its built-in TypeScript support. A file that fails to import only prints a warning. `loom build` doesn't read this file. > **A config without `targets` or `shims` is skipped whole** > > A config with neither field is ignored entirely, `port` included, and you get the hint below. The > preview continues in single-entry mode. ```text loom: loom.config.ts found, but its default export has no `targets` or `shims` field — skipping it (legacy config?). Use `--targets [glob]` or export `{ targets?: string | string[], port?: number, shims?: Record }`. ``` ## Error containment A target that throws can't break the page. The error shows in a red panel with its stack, and the sidebar keeps working. There are three kinds: - Import failure: `failed to import ` (a syntax error, a missing module). - Bad contract: `invalid preview export in `. - Render throw: `render error in `. Switching targets clears the panel. A target that throws on purpose makes a good regression check for this. ## Inspecting a target The sidebar's `debug` button, Ctrl+Alt+D, or `?debug=1` opens a panel over the stage. It shows timings, the viewport the scene laid out against, the live instance tree, which fonts loaded, and a hover inspector. It runs nothing while closed. See [The debug panel](https://docs.astra-void.xyz/loom/guides/debug-panel.md). ## Routing With the sidebar, selecting a target sets `#/`, and the hash survives reloads. On first load, `?target=` picks the target when there is no hash. Docs-site iframes use this to deep link. See [Static builds and embedding](https://docs.astra-void.xyz/loom/guides/static-builds-and-embedding.md#the-url-contract). --- # Animation > Three ways to move a preview — bindings, TweenService and springs — at zero React renders. Source: https://docs.astra-void.xyz/loom/guides/animation/ Animation in a preview runs on loom's own frame loop, through the same `RunService` signals your Roblox code uses. The renderer uses no CSS transitions, so what you see is what your code computes. Pick the layer that fits: | Layer | Use it for | | --- | --- | | [Bindings](#bindings) | A value you drive yourself, per frame, without re-rendering. | | [`TweenService`](#tweenservice) | The engine's tween API, with the same easing enums. | | [`@rbxts/ripple`](#rbxtsripple) | Springs, tweens and motion as React hooks. | ## Bindings `createBinding`, `useBinding` and `joinBindings` come from `@rbxts/react`. Any host prop accepts a plain value or a binding: ```tsx import { useBinding } from "@rbxts/react"; function Follower() { const [position, setPosition] = useBinding(UDim2.fromOffset(0, 0)); return ( setPosition(UDim2.fromOffset(input.Position.X, input.Position.Y)), }} /> ); } ``` The renderer writes a bound prop straight onto the live instance, skipping React. A 60fps animation is 60 property writes and zero renders. Bindings from `useBinding` and from ripple's `useSpring` are the same kind of object, so you can mix them freely. ## `TweenService` Import it the way you already do: ```tsx import { useEffect, useRef } from "@rbxts/react"; import { TweenService } from "@rbxts/services"; function SlideIn() { const ref = useRef(); useEffect(() => { const frame = ref.current; if (!frame) return; const info = new TweenInfo(0.3, Enum.EasingStyle.Quad, Enum.EasingDirection.Out); const tween = TweenService.Create(frame, info, { Position: UDim2.fromScale(0.5, 0.5), }); tween.Play(); return () => tween.Cancel(); }, []); return ; } ``` `TweenInfo` takes the engine's arguments in the engine's order: `(Time, EasingStyle, EasingDirection, RepeatCount, Reverses, DelayTime)`. | Surface | Supported | | --- | --- | | `TweenService` | `Create`, `GetValue`. | | `GuiObject` | `TweenPosition`, `TweenSize`, `TweenSizeAndPosition`. | | `Tween` | `Play`, `Pause`, `Cancel`, `Completed`, `PlaybackState`. | | `TweenInfo` | `DelayTime`, `RepeatCount`, `Reverses`, and every `EasingStyle` / `EasingDirection`. | | Interpolated types | `number`, `Color3`, `UDim`, `UDim2`, `Vector2`. | Tweens advance on the scheduler's frame signal. Pausing the scheduler pauses the tween. ## `@rbxts/ripple` `@rbxts/ripple` and `@rbxts/react-ripple` work with no configuration. Loom swaps in a browser port of the published implementation. See [Package compatibility](https://docs.astra-void.xyz/loom/guides/package-compatibility.md#rbxtsripple-and-rbxtsreact-ripple) for details. ```tsx import { config, useSpring } from "@rbxts/react-ripple"; function AnimatedButton() { const [offset, spring] = useSpring(0, config.stiff); return ( UDim2.fromOffset(200 + value, 50 + value))} Event={{ MouseEnter: () => spring.setGoal(10), MouseLeave: () => spring.setGoal(0), }} /> ); } ``` The spring math, easing curves, Oklab color interpolation and rest thresholds follow the Luau source, so a component animates the way it does in Roblox. ### Exports `createSpring`, `createTween`, `createMotion`, `config`, `easing`, `springScheduler`, `tweenScheduler`, `motionScheduler`, and the `useSpring` / `useTween` / `useMotion` hooks. The hooks package also re-exports the core, as the real one does. Every published `config` preset and `easing` curve is implemented. ### Controller methods These match the published `.d.ts`: | Controller | Methods | | --- | --- | | All three | `getPosition` `getGoal` `setPosition` `setGoal` `onChange` `onComplete` `step` `idle` `configure` `start` `stop` `destroy` | | `Spring` / `Motion` | `getVelocity` `setVelocity` | | `Spring` | `impulse` `halt` | | `Tween` | `getFrom` `setFrom` | | `Motion` | `spring` `tween` | Every documented option works: | Controller | Options | | --- | --- | | Spring | `start`, `tension`, `friction`, `mass`, `dampingRatio`, `frequency`, `precision`, `restVelocity`, `position`, `velocity`, `impulse` | | Tween | `start`, `easing`, `duration`, `repeats`, `reverses`, `position` | | Motion | `start`, `spring`, `tween` | ### Values You can animate `number`, `Vector2`, `Vector3`, `Color3`, `UDim`, `UDim2`, `Rect`, and records of numbers. A record accepts a partial goal, so keys you leave out stay put. `Color3` interpolates through Oklab, and `UDim` / `UDim2` offsets round to integers, as in Roblox. `CFrame` throws instead of animating, because loom's `CFrame` holds position only: ```text [loom] Ripple compatibility does not yet support animating CFrame ``` Any other unsupported value, such as a string or a record of non-numbers, also throws by name. Subpaths like `@rbxts/ripple/foo` are not covered. ### Differences from upstream - `destroy()` also drops the controller's `onChange` and `onComplete` callbacks, so a destroyed controller can't call into an unmounted component. Upstream only stops it. - As upstream, the hooks ignore a changed `initialOptions` after mount. Call `controller.configure(...)` to retune a controller in place. ## One frame loop Every spring, tween and motion controller shares one `RunService.Heartbeat` connection, released when the last one settles. Values go into a binding, so React never re-renders. > **Animations freeze in a background tab** > > Browsers don't fire `requestAnimationFrame` for a hidden tab, so loom stops stepping. The animation > resumes where it left off when the tab comes back. --- # Fonts and text metrics > Which Roblox font families ship, how to register the others, and how loom sizes and wraps text. Source: https://docs.astra-void.xyz/loom/guides/fonts/ The preview loads Roblox's open typefaces for you. There is nothing to install or import, and React and Vide previews get the same faces. This matters for layout, not just looks. `AutomaticSize` and `TextWrapped` work by [measuring text](https://docs.astra-void.xyz/loom/reference/supported-properties.md#automaticsize-on-text). Without the right face, the browser falls back to a different system font on each OS, and the same scene lays out differently on each machine. ## The families that ship a face These are bundled as Fontsource `woff2` files. No CDN, nothing installed on the machine. | Roblox family | Typeface | | --- | --- | | `SourceSans*` | Source Sans 3 | | `Roboto*` | Roboto | | `RobotoMono*` | Roboto Mono | | `RobotoCondensed` | Roboto Condensed | | `Inconsolata` / `Code` | Inconsolata | | `Arimo` | Arimo | | `Jura` `Merriweather` `Nunito` `Oswald` `Ubuntu` `TitilliumWeb` | their own | | `JosefinSans` `GrenzeGotisch` `Sarpanch` `Michroma` | their own | | `AmaticSC` `Bangers` `Creepster` `DenkOne` `Fondamento` | their own | | `IndieFlower` `Kalam` `LuckiestGuy` `PatrickHand` `PermanentMarker` `SpecialElite` | their own | | `FredokaOne` | Fredoka. Google folded "Fredoka One" into Fredoka's heavier weights, so this one is an approximation. | That is 28 families, all OFL-1.1 except Ubuntu. `Arial` and `Legacy` need nothing. Every machine has Arial, and the bundled Arimo has the same metrics. A page only downloads the families and scripts its scenes actually paint with. See [What comes out](https://docs.astra-void.xyz/loom/guides/static-builds-and-embedding.md#what-comes-out) for the size of a static build. ### Named, but not loaded Loom can't ship the proprietary `Gotham` and `BuilderSans`, or `Bodoni`, `Garamond`, `Cartoon`, `SciFi`, `Arcade`, `Fantasy`, `Antique` and `Highway`. Each resolves to a font stack led by the right typeface, so a machine that has the real font uses it. Otherwise loom falls back and [warns](#the-warning). `Enum.Font` has all 53 of the engine's items, in the engine's order, so a scene that names any of them runs. ## Registering a face yourself Use `registerFont` to install a typeface for a Roblox family. If you have the Gotham files: ```ts import { registerFont } from "@loom-dev/renderer"; import gotham from "./fonts/Gotham-VF.woff2"; registerFont("Gotham", { family: "Gotham", faces: [{ src: gotham, weight: "100 900" }], }); ``` `@loom-dev/renderer` is a transitive dependency. Declare it to import it directly: ```bash pnpm add -D @loom-dev/renderer ``` If the page already provides the font (a CDN ``, your own `@font-face`, or a font installed on the machine), leave out `faces` and just name it: ```ts registerFont("SourceSans", { family: "Source Sans 3 Variable" }); ``` A registration replaces whatever loom shipped for that family, so this is also how you swap one out. ### The registration shape | Field | Type | Notes | | --- | --- | --- | | `family` | `string` | Required. The CSS family to paint and measure with. With `faces`, also the name they are declared under. | | `faces` | `{ src, weight?, style?, display? }[]` | `@font-face` rules to declare. `src` is a URL the page can load, usually a bundler import. `weight` defaults to `400` and takes a range (`"200 900"`) for a variable font. `style` defaults to `normal`, `display` to `swap`. | | `fallback` | `string` | Appended after `family`. Defaults to that family's default stack. | ### One key per family Register the family once and every spelling of it is covered. Roblox writes a family several ways: `GothamBold` from a legacy `Enum.Font` item, or `GothamSSm` from a `FontFace` asset. Loom matches by prefix, longest first, so `RobotoMono` is never read as `Roboto` and weight suffixes come free. The aliases worth knowing: | Spelling | Registers as | | --- | --- | | `GothamSSm` | `Gotham` | | `SourceSansPro` | `SourceSans` | | `Code` | `Inconsolata` | | `Fredoka` | `FredokaOne` | | `LegacyArial` | `Legacy` | | `HighwayGothic` | `Highway` | A name outside the family table uses the generic sans stack and can't be registered. ## A late face re-lays-out You can register a font at any time. When a registration lands or a `@font-face` finishes downloading, every `AutomaticSize` bound measured with the old font is dropped and re-measured. The first layout waits up to 1.5 seconds for each font it measured that hasn't loaded yet. That keeps a component that sizes itself from `AbsoluteSize` from locking in widths measured with the fallback. A registered face loads when text first paints in it, not when you register it. Loom re-measures on every `loadingdone` event from `document.fonts`. To hook in yourself: ```ts import { onFontsChanged } from "@loom-dev/renderer"; const stop = onFontsChanged(() => { // every text measurement taken before this is stale }); ``` `clearRegisteredFonts()` removes every registration and the `@font-face` rules loom added. It is mostly useful in tests. ## `TextSize` is not a font size Roblox fits the whole face, ascender to descender, into `TextSize`. A one-line label is exactly `TextSize` tall. CSS `font-size` sets the em square instead, which is smaller. Painting `font-size: TextSize` would draw every glyph too big, by 17% for Roboto and 47% for Oswald. So loom divides `TextSize` by the face's height. Text then sizes the way the engine sizes it: - `LineHeight` is set in pixels from `TextSize`, as in the engine. - A `` run in `RichText` converts using the face that run is painted in. - Every [shipped family](#the-families-that-ship-a-face) uses the engine's own ratio, calibrated against `TextService:GetTextBoundsAsync`. - Any other family, including one you registered and `Gotham`, uses the height the browser reports. The calibrated ratio applies only once the browser really has the face. Until then, loom measures the fallback it is actually painting, and re-measures when the face arrives. `familyIsAvailable` is exported if you register your own faces and need the same check. Painted text is also kept inside the engine's box. If the browser shapes a line wider than the engine would, the paint is tightened to fit. ## Where a line breaks Loom measures strings the way the engine does, not the way a browser does: - Each grapheme advances on a half-pixel boundary. Browser canvas measurement is a few percent narrower and wraps long paragraphs at different words. - Runs are kerned: `AV` is 19.5 units wide, where `A` and `V` alone are 10.5 and 10. - One function decides every wrap, for both measuring and painting. `RichText` runs go through the same wrap, each measured in its own ``. React and Vide measure the same way, so a live preview and a compiled scene agree. Newlines and runs of spaces in `Text` are kept, wrapped or not and `RichText` or not, as in Roblox. ## The warning When text asks for a family with no face loaded, loom warns once: ```text loom: no face is loaded for the Roblox font family "Gotham" — its text is painted and measured in the system fallback instead, which is a different typeface per OS and does not match the engine's layout. Register one with registerFont("Gotham", { family, faces }), or import "@loom-dev/renderer/fonts" for the families Roblox licenses openly. ``` To fix it, [register a face](#registering-a-face-yourself). - It waits for font loading to finish, so a face that is still downloading doesn't trigger it. - It also fires for a registered face whose file never arrived. - `Arial` and `Legacy` never warn. Both land on a font every machine has. Loom checks availability by measuring a probe string against two very different generic fonts. A real family changes at least one width. It doesn't use `document.fonts.check()`, which returns `true` even for a family nobody has. `familyIsAvailable` runs the same probe. ## What is still approximate The face, size, advances and wraps match the engine. Shaping, hinting and sub-pixel rounding are still the browser's. In practice measurement runs about 1% wide, so text wraps slightly early rather than overflowing its box. --- # The debug panel > Timings, the logical viewport, the live instance tree, loaded typefaces, and a stage inspector. Source: https://docs.astra-void.xyz/loom/guides/debug-panel/ Every gallery has a debug panel that describes the scene in Roblox terms: instances, sizes and fonts, not the `div`s a browser inspector shows. ## Opening it Use any of these: - the `debug` button in the sidebar header, - Ctrl+Alt+D, - `?debug=1` on any gallery URL. The panel is off by default. While it's closed it does no work at all, and it never touches the render path, so a scene behaves the same with it open or closed. A bare `?debug` turns it on. `0`, `false`, `off`, `no` and `none` turn it off. Any other value turns it on. The gallery remembers the toggle across HMR reloads for the tab. An embed (`chrome=none`) doesn't, so a panel only appears on an embedded preview when its URL asks for one. ## What it reports Each section folds away and still shows its headline number while folded. | Section | Shows | | --- | --- | | target | The target's path and title, how long its `import()` took, and time from mount to first frame. `↻` re-mounts the target to take those timings again. | | viewport | The stage in real pixels, the logical viewport the scene laid out against, `Workspace.CurrentCamera.ViewportSize`, the scale factor, device pixel ratio and theme. | | scene | Live instances, how many are GuiObjects and how many of those are invisible, tree depth, DOM node count, a count per class, and each layer with its `DisplayOrder` and size. | | fonts | Every typeface the scene's text resolved to, the weights requested, and whether the browser actually loaded each one. | | frame | Frame rate, DOM patches since the panel opened, and a count of loom's log messages. | | inspect | The object under the pointer. See [Inspecting the stage](#inspecting-the-stage). | Where to look first: - A scene looks empty: check the invisible count in scene. - A scene looks too small: in viewport, the four sizes agree unless the page uses `?base=`. They tell a scene that laid out small from one that was drawn small. See [Previews on a phone](https://docs.astra-void.xyz/loom/guides/mobile-previews.md). - Layout differs on another machine: check fonts. A family that never loaded still paints, at the wrong metrics. See [Fonts and text metrics](https://docs.astra-void.xyz/loom/guides/fonts.md). - Something is off and you don't know what: the warnings counted under frame often explain it. ## Inspecting the stage Hover the stage. The panel names the `GuiObject` under the pointer, outlines it, and lists its ancestry, absolute geometry, `UI*` modifiers, resolved typeface and properties. - Alt+click pins the selection. Escape releases it. - Click the ancestry trail or the under rows to walk the tree. The under rows list everything else beneath the pointer. - Hit testing uses the scene's own `PlayerGui:GetGuiObjectsAtPosition`, not the browser's. You can inspect a click-through frame that a browser inspector can't reach. ## Taking a snapshot out `copy` puts the readout on the clipboard as text. `json` downloads every section as data, plus the full instance tree with each object's absolute position and size. Attach that to a bug report instead of a screenshot. While the panel is open, the same object is available from the console: ```js title="In the devtools console, panel open" copy(loomDebug.snapshot()); ``` ## See also - [Gallery targets](https://docs.astra-void.xyz/loom/guides/gallery-targets.md): what the target section reports on. - [Previews on a phone](https://docs.astra-void.xyz/loom/guides/mobile-previews.md): the logical viewport and `?base=`. - [Troubleshooting](https://docs.astra-void.xyz/loom/guides/troubleshooting.md): symptom-first fixes. --- # Static builds and embedding > Bundle a gallery into a hostable SPA, then deep-link one scene per iframe. Source: https://docs.astra-void.xyz/loom/guides/static-builds-and-embedding/ `loom build` turns a gallery into a static, client-only site you can host anywhere. Use it to embed a live, interactive scene in a docs page instead of a screenshot. ```bash title="Build a gallery" pnpm exec loom build ~/code/my-ui --targets src/scenes --out dist-preview --base ./ ``` If your `vite.config.ts` already passes `targets` to `loomPreview()`, `pnpm vite build` produces the same bundle. See [Vite integration](https://docs.astra-void.xyz/loom/guides/vite-integration.md#6-gallery-mode-from-the-plugin). ## Flags ```text loom build [dir] --targets [glob] [--out ] [--base ] [--no-assets] ``` | Flag | Default | Notes | | --- | --- | --- | | `--targets` | required | Same as for `preview`. Without it: ``loom: `build` requires --targets [glob] (the static gallery is target-driven)``. | | `--out` | `dist-preview` | Resolved against the current directory, not the project dir. | | `--base` | `./` | Public path. The relative default lets the output be hosted anywhere. | | `--no-assets` | off | Skips the [`rbxassetid://` download](#rbxassetid-in-a-static-build). | `build` doesn't read `loom.config.ts`, so pass `--targets` every time. > **`--out` is emptied before writing** > > Point `--out` at a directory only loom uses. Aiming it at your site's whole `public/` deletes > everything else in it. ## What comes out ```text title="dist-preview/" index.html assets/index-.js # shell + runtime + adapter assets/index-.css # gallery chrome assets/loom_layout_wasm_bg-.wasm assets/CardScene.loom-.js # one async chunk per target assets/CounterScene.loom-.js assets/roboto-latin-400-normal-.woff2 # …and ~110 more ``` - Each target is its own lazy chunk, so a page loads only the scene it shows. - The `.wasm` layout engine is about 205 kB (78 kB gzipped), fetched once and cached. - The [engine's typefaces](https://docs.astra-void.xyz/loom/guides/fonts.md) add ~2.8 MB across ~110 files. A browser fetches only the families and scripts a scene paints with. The Roblox globals load before any scene code, so a built gallery never throws `UDim2 is not defined`. ## `rbxassetid://` in a static build A static host has no server to resolve asset ids, so the build does it ahead of time. It downloads each image into the output and writes a manifest the page reads: ```text title="dist-preview/" __loom/assets.json # { "6031075938": "__loom/asset/6031075938.png" } __loom/asset/6031075938.png # the downloaded image ``` `Image="rbxassetid://6031075938"` then loads from your own origin, with no request to Roblox. The build finds ids two ways. It scans the output for `rbxassetid://`. It also mounts every target in node and reads the images in its tree, which catches ids built at runtime like `` `rbxassetid://${iconId}` ``. - **Only the first render is baked.** An image that appears later, behind a hover or after a fetch, stays unresolved. Give it a real URL, or install your own `setImageResolver`. - Mounting targets only happens in gallery builds. A build with a single client `entry` only scans. - An image never fails the build. An id that won't resolve, or a target that won't render, is warned about and left out. To keep a build off the network, turn the download off: `loomPreview({ assets: false })`, `loom build --no-assets`, or `assets: false` on `buildGallery` and `withLoomGallery`. ## The URL contract The built page reads six query parameters. This is the whole embedding API. | Parameter | Values | Effect | | --- | --- | --- | | `target` | a target's relative path, URL-encoded | Mounts that target on load. | | `chrome` | `none` | Hides the sidebar and shows one target full-bleed. Any other value keeps the sidebar. | | `theme` | `light` \| `dark` | Sets the stage background and seeds `PlayerGui.LoomTheme`. Anything but `light` means `dark`. | | `background` | a CSS color | Paints the stage backdrop, overriding the theme's. See [below](#background-for-a-backdrop-that-is-not-either-theme). | | `base` | px (bare `?base` is 960), or `none` / `off` / `0` | Lays the scene out at this width and scales it to fit, instead of reflowing. Off by default. See [Previews on a phone](https://docs.astra-void.xyz/loom/guides/mobile-previews.md#base-keeps-a-wide-composition). | | `debug` | present, or `0`/`false`/`off`/`no`/`none` for off | Opens the [debug panel](https://docs.astra-void.xyz/loom/guides/debug-panel.md) on load. A bare `?debug` means on. | ```text title="Deep-link one scene, chromeless, light" /loom-preview/index.html?target=src%2Fscenes%2FCounter.loom.tsx&chrome=none&theme=light ``` With `chrome=none`, the page always shows the `?target=` scene. With the sidebar, the page routes by `#/` and `?target=` only picks the first scene. `?debug=1` is the only way to open the debug panel in a `chrome=none` embed. An embed doesn't remember the panel between reloads. ### `?background=` for a backdrop that is not either theme `theme` sets the whole palette. `background` changes only the backdrop. For a white stage under the light palette, use `?theme=light&background=white`. Use `transparent` to show the host page through. > **Hex, without the `#`** > > `?background=#ffffff` never reaches the gallery, because `#` starts the URL fragment. Write > `%23ffffff` or just `ffffff`. Only colors are accepted: hex, a color name, and functional forms like `rgb(...)`. A gradient or `url(...)` is ignored and the theme's backdrop stays. The backdrop is set before first paint, so an embed never flashes the dark default. ## Live theme switching A host page can change a loaded frame's theme without reloading it: ```js title="From the embedding page" // GALLERY_ORIGIN is where the built gallery is served from — same-origin // embeds can use window.location.origin. frame.contentWindow.postMessage( { type: "loom-theme", theme: "dark" }, GALLERY_ORIGIN, ); ``` The backdrop works the same way: ```js title="Re-point the backdrop live" frame.contentWindow.postMessage( { type: "loom-background", background: "#0b0d10" }, GALLERY_ORIGIN, ); // With no colour, the backdrop goes back to whatever the theme paints. frame.contentWindow.postMessage({ type: "loom-background" }, GALLERY_ORIGIN); ``` The gallery listens for these two messages and ignores everything else. > **Name the target origin, not a wildcard** > > Pass the gallery's origin, not `"*"`. The gallery doesn't check `event.origin`, so if you fork the > shell and add messages that do more than repaint, add an origin check. A theme change also writes `LoomTheme` onto `Players.LocalPlayer.PlayerGui`. A scene can follow the host page's theme with plain Roblox APIs: ```tsx title="A scene that follows the host page's theme" const playerGui = Players.LocalPlayer.WaitForChild("PlayerGui"); const [theme, setTheme] = useState(playerGui.LoomTheme ?? "dark"); useEffect(() => { const conn = playerGui .GetPropertyChangedSignal("LoomTheme") .Connect(() => setTheme(playerGui.LoomTheme)); return () => conn.Disconnect(); }, []); ``` ## A working embed pipeline Running `loom build` before each site build works, but the output goes stale whenever a scene changes, and you get no hot reload. If your site uses Vite, mount the gallery instead with [`loom-dev/embed`](https://docs.astra-void.xyz/loom/reference/cli.md#loom-devembed--the-programmatic-api). For a Next.js site, use [Next.js integration](https://docs.astra-void.xyz/loom/guides/nextjs-integration.md). This Astro integration serves the gallery in dev and builds it next to the site: ```ts title="src/integrations/loom-preview.ts (abridged)" import { buildGallery, createGalleryServer, findGalleryTargets } from "loom-dev/embed"; export default function loomPreview(): AstroIntegration { let gallery; return { name: "loom-preview", hooks: { // Dev: Loom's own Vite server, mounted under the site's base. "astro:server:setup": async ({ server }) => { gallery = await createGalleryServer({ root: latticeApp, targets: "src/preview-targets", base: "/loom-preview/", }); server.middlewares.use(gallery.middleware); }, "astro:server:done": async () => await gallery?.close(), // Build: the same gallery, emitted next to the site's own output. "astro:build:done": async ({ dir }) => { await buildGallery({ root: latticeApp, targets: "src/preview-targets", outDir: fileURLToPath(new URL("loom-preview/", dir)), }); }, }, }; } ``` Editing a scene hot-reloads the frame in the docs page, and no generated bundle lives in the repo. Some tips: - Mount under your site's own base path rather than a hard-coded `/loom-preview/`, so previews still work if the site moves to a subpath. - Skip previews when the component project is missing, instead of failing. Fresh clones and CI still build. `findGalleryTargets()` tells you whether there is anything to serve without starting a server. Use an env var to make it strict for deploys. - Set iframe `src` lazily, for example with an `IntersectionObserver`, and append `&theme=` from the site's current theme. Push later theme changes with `postMessage`. For a host that isn't a Vite app, such as a Hugo or Jekyll site, use `loom build`. Its output is identical to `buildGallery()`. ## Error containment survives the build Each target keeps its own error boundary in a built gallery. A target that throws shows an inline error panel with its stack, and the rest of the page keeps working. --- # Previews on a phone > What a preview does on a 390px screen, and the `?base=` opt-out for a wide composition. Source: https://docs.astra-void.xyz/loom/guides/mobile-previews/ Open a preview on a phone and the scene lays out against the phone's screen, as the engine would on that device. Nothing needs configuring. ## The stage is the viewport The size of the preview's mount is the Roblox viewport. Loom feeds it to the layout engine and to `Workspace.CurrentCamera.ViewportSize`. On a narrow screen: - text re-wraps, - a `UIListLayout` with `Wraps` re-flows, - `AutomaticSize` re-measures, - a scene that branches on `ViewportSize` takes its narrow path. A layout of fixed offsets wider than the screen runs off the edge and is clipped, as it would on a real device. The generated pages size with `dvh`, so the stage doesn't hide under a mobile browser's toolbars. > **Loom does not make your UI responsive** > > Neither does Roblox. Make the scene adapt with a `UIScale`, a breakpoint on `ViewportSize`, or an > `AbsoluteSize` binding. ## `?base=` keeps a wide composition If you embed a preview at a narrow width and want the desktop layout shrunk to fit, add `?base=`: ```text title="A 1280-wide logical viewport, whatever the frame is" /loom-preview/index.html?target=src%2Fscenes%2FCounter.loom.tsx&chrome=none&base=1280 ``` | Value | Effect | | --- | --- | | *absent* | The default. The scene lays out against the real viewport. | | `?base=` | Lay out at this width. Below it, the stage scales down to fit; at or above it, nothing changes. | | `?base` (bare) | Same as `?base=960`. An unreadable value also means 960. | | `?base=none` (or `off`, or `0`) | The default, spelled out, for a host page that always templates the param. | A wider base keeps more of the desktop layout but draws everything smaller. At 960 a phone renders at about 40%; at 1280, about 30%, where body text stops being readable. > **A scaled preview hides narrow-screen bugs** > > With a base, you see the wide layout drawn smaller, not the layout a phone would get. Text keeps its > wide line breaks and wrapped rows keep their wide count. The [debug panel](https://docs.astra-void.xyz/loom/guides/debug-panel.md) shows both the real and the logical size, and the scale between them. `?base=` is part of the [URL contract](https://docs.astra-void.xyz/loom/guides/static-builds-and-embedding.md#the-url-contract). When the stage is scaled, loom converts pointer positions back to layout pixels, so clicks land where the scene appears. That covers `MouseEnter`, `Activated` and `InputChanged` positions, `GetMouseLocation`, and wheel deltas. ## Touch - A drag inside a `ScrollingFrame` scrolls it, with the same clamping as the mouse wheel. Past a small threshold the drag stops counting as a tap, so dragging across a button doesn't activate it. - Only `ScrollingFrame`s capture touch panning. Everywhere else the page scrolls normally, so an embedded preview never traps the reader's scroll. - Taps register immediately, without the browser's ~300ms double-tap delay. ## The gallery on a phone In the full gallery, the 248px sidebar becomes a top bar with a `targets` button. Picking a target closes it. With `?chrome=none` there is no sidebar, so an embedded preview only gets the touch handling. --- # Next.js integration > Serve the gallery from a Next.js app with `withLoomGallery()` — proxied in dev, static at build. Source: https://docs.astra-void.xyz/loom/guides/nextjs-integration/ `withLoomGallery()` from `loom-dev/next` serves a loom gallery inside a Next.js app. You start `next dev` as usual and the gallery comes up at `/loom-preview/`. `next build` builds it as a static site in `public/`. It works with the pages router and the App Router, webpack and Turbopack, and React 18 or 19 in your app. It has been tested on Next 15.5 and 16.2. ## 1. Dependencies ```bash npm i -D loom-dev ``` That is all. Your app keeps its own React and Next, and no `@loom-dev/*` packages enter its dependency tree. > **If you prune devDependencies in production** > > `next start` also loads `next.config`, so `loom-dev` must be installed wherever it runs. If your > deploy prunes devDependencies, list it under `dependencies`. ## 2. The config ```ts title="next.config.ts" import { withLoomGallery } from "loom-dev/next"; export default withLoomGallery( { reactStrictMode: true }, // your Next config { root: "../my-ui", // the roblox-ts project, relative to the app dir targets: "src/scenes", // same semantics as loom preview --targets }, ); ``` That is the whole setup. No prebuild script, no manual `loom build`, no second terminal. > **Compose it outermost** > > `withLoomGallery` returns Next's function config form, which other wrappers can't wrap. Put it > outside: `withLoomGallery(withMDX(config), options)`. Add the build output to `.gitignore`: ```text title=".gitignore" public/loom-preview/ ``` ## 3. What each command does | Command | Where the gallery comes from | | --- | --- | | `next dev` | A loom Vite server on a free loopback port, started on first use. Next proxies `/loom-preview/*` to it. | | `next build` | Built into `public/loom-preview` before the app compiles. | | `next start` | The static build in `public/loom-preview`. | The gallery runs in its own Vite instance with its own React. Your app's React and bundler config are untouched. ### `next dev` - Target discovery, per-scene hot reload and the error panel work as under `loom preview`. - The proxy runs ahead of `public/`, so an old static gallery there can't shadow the live one. - If the gallery fails to start, `next dev` keeps running. The error is logged and `/loom-preview` returns 404. It retries on the next config reload. ```text browser ──► next dev (:3000) ── beforeFiles rewrite ──► loom Vite server (127.0.0.1:) │ │ └────────────── HMR WebSocket (direct, bypasses Next) ◄──┘ ``` ### `next build` The wrapper builds the same bundle as [`loom build`](https://docs.astra-void.xyz/loom/guides/static-builds-and-embedding.md) into `public/loom-preview`, once, then the app build continues. - Zero targets warns and skips, so adding the wrapper before your first `*.loom.tsx` doesn't break `next build`. - **A real gallery build error fails the app build**, so a broken gallery doesn't ship silently. If your CI runs `loom build` itself, pass `staticBuild: false`. ### `next start` Nothing starts and nothing is built. The app serves the gallery from `public/`, and the wrapper maps the bare `/loom-preview` to its `index.html`. Deep links and iframes work the same as in dev. ## 4. Options | Option | Type | Default | Notes | | --- | --- | --- | --- | | `root` | `string` | required | Project dir whose targets are served, relative to the app dir. | | `targets` | `string \| string[] \| true` | `true` | A glob, a directory, a list of either, or `true` for `**/*.loom.tsx`. Same as `loom preview --targets`. | | `base` | `string` | `/loom-preview/` | Where the gallery is mounted in the app. Also sets the build output dir (`public/`). Next's `basePath` is added for you, so don't repeat it here. | | `port` | `number` | free port | Pin the dev gallery's port. | | `hmrPort` | `number \| false` | free port | Vite's HMR WebSocket port. `false` turns off hot reload. | | `staticBuild` | `boolean` | `true` | `false` skips the gallery build during `next build`. | | `shims` | `Record` | `{}` | Replacements for roblox-ts packages loom can't run. Paths are relative to `root`, not the Next app. See [Package compatibility](https://docs.astra-void.xyz/loom/guides/package-compatibility.md#shims). | | `assets` | `boolean` | `true` | `false` stops the `next build` gallery downloading its `rbxassetid://` images. The dev gallery is unaffected. | ## 5. Embedding scenes in pages The [URL contract](https://docs.astra-void.xyz/loom/guides/static-builds-and-embedding.md#the-url-contract) is the same in dev and in the static build, so an iframe written once works in both: ```tsx