Framework

Spatial components and committed layout

Import components from bedform/Spatial/Components and geometry operations from bedform/Spatial/Layout. They are also exposed as Spatial.Components and Spatial.Layout. They use the single bedform/Spatial/React client; imports start no runtime, timers, native actors or display. Automatic JSX uses jsxImportSource: "bedform/Spatial/React".

import { View, TitledPanel, Row, Button, Text } from "bedform/Spatial/Components";

const application = <View Dimension="minecraft:overworld" Width={160}
    Transform={{ position: { x: 0, y: 64, z: 0 }, rotation: { x: 0, y: 0, z: 0, w: 1 } }}>
    <TitledPanel Title={<Text>Controls</Text>} Width={160}>
        <Row Gap={4} Align="center">
            <Button><Text>Open</Text></Button>
            <Text>Ready <Text Color="#55FF55">now</Text></Text>
        </Row>
    </TitledPanel>
</View>;
root.Render(application);

The runtime requires an injected surface backend. The components provide typed descriptors and layout for controls, images, inventory slots, mobs, callouts, bars and framed panels. The surface consumes committed geometry and descriptors to draw textures and actors. Layout retains OnActivate, the other interaction callbacks and controlled values for the interaction router.

Component catalog

All names below are available as named imports from bedform/Spatial/Components.

ComponentsCommitted contract
View, Panel, Row, Column, InputScopeWorld-space views, flow containers and inherited input policies.
Text, ImageMeasured text lines and a leaf for generated Canvas descriptors or runtime raster images. Font selection and native presentation limits are described in Spatial text.
Slot, ItemStackAn empty slot or one resolved stack. A stack is a leaf with an item ID and optional quantity. Quantities above one generate a bottom-right text count.
ScrollViewControlled offsets, rectangular viewport clips and track geometry. See scrollbar behavior below.
Button, Toggle, SliderButton accepts reactive appearance="pause" (default) or appearance="raised". Pause is 28 layout pixels high with container or content width. Raised follows the disconnect screen's 128 × 26 template. Explicit dimensions take precedence. Set hoverColor="light-blue" on an opaque gray pause button for a blue face and white label on hover. Set variant="purple" for the Realms palette and a white label. Toggle and slider values are controlled. Use Text for labels.
Input, TextAreaControlled text fields. A field is a 1-pixel border around a surface with one line of text (Input, default 120 × 20) or Rows wrapped lines (TextArea, default 4 rows and 160 wide). Overflow is cut at the end. A live draft keeps its end in view instead. Placeholder shows while Value is empty. Color tints the text, BackgroundColor the surface and Padding insets the text. Formatting codes and NUL are removed from the drawn text. Fields take no children. Using a field opens a modal editor; see text fields.
FieldPlaces Label and optional Subtitle above one child control. Status defaults to idle. warn, error and success show a written status with the theme's warning, caution and tip accents. Optional Message appears below the control.
MobA leaf with a mob type ID and presentation bounds. The component exposes no imperative ref. An injected backend that spawns world entities must account for their world visibility. Renderer audience leases alone cannot make a native actor private.
Callout, DividerKind accepts Note, Tip, Important, Warning or Caution. The callout draws a frame in the kind's accent color, 1 layout pixel thick with a 3-pixel left edge. Inside is a readable body surface with a 7 × 7 accent-tinted Canvas icon, the heading and then the children. The standard heading is the kind's name. A custom Heading must be a Text element. Both default to the accent color, and body Text defaults to the theme's callout foreground. Color overrides the accent and BackgroundColor the surface. Padding, Gap, Align and Justify lay out the body. Kind, theme and color changes keep the mounted nodes. A divider is a noninteractive leaf with Orientation="horizontal" (default) or Orientation="vertical". Length runs along the orientation (default 16) and Thickness across it (default 1). Explicit Width/Height win. Color, else BackgroundColor, sets the line color, which defaults to the theme's Divider token. A divider rejects interaction callbacks, so it never owns an input proxy.
BarControlled vanilla HUD meter. See HUD bars.
ThemeProviderReactive light/dark palette and layout defaults, with nested token overrides. Tokens.Callout merges with the inherited callout tokens: surface, foreground, the five accents and the frame, padding and gap metrics. Tokens.Field merges in the same way. It holds the text field surface, border, active border, foreground, placeholder, pending (concealed edit) and disabled colors, border width and text padding. The defaults reuse BedformCanvas's GitHub-derived light/dark accents on a white or #1E1E1E surface, so every heading has at least 4.5:1 contrast.
FramedPanel, TitledPanel, Tabs, TabButtonTop-level frame descriptors, a centered Text title and an optional above-frame strip of recipe and subtle tabs.

The categorized legacy-computing and Mojangles bedform/Spatial/Glyph components are pending in ty2k.28. The canonical Terminal component and Nerd Fonts families are deferred integrations (ty2k.27 and ty2k.29).

HUD bars

Bar defaults to Kind="health". Health, hunger, armor and air measure 81 × 9 layout pixels before overrides. Experience and boss health measure 182 × 5. Health, hunger and armor round up to the next half icon. Air uses whole bubbles. Hunger and air fill from the right, the other meters from the left. Both continuous tracks clip their full artwork to the exact fraction.

Value and Maximum must be finite and Maximum must be nonnegative. The display clamps values to the interval from zero through the maximum. A zero maximum shows the empty artwork. Changing any of these props keeps the same mounted bar. Any overlay label is an explicit Text child. All values control the display only.

Surfaces can render the committed item with BarArt.Paint from bedform/Spatial and apply its committed clip and layer spacing. The painter uses BedformCanvas's HUD artwork captured from Minecraft for Windows 1.26.6501.0. Its resolved Color comes from the explicit color or the theme's BarTint (white) and BossBarTint (purple).

Coordinates and flow

Each View defines a dimension and rigid quaternion transform. Local X points right and Y points down. PixelsPerBlock defaults to 36 and LayerDepth to 0.03 world blocks. Finite nonzero quaternions are normalized; no yaw-only restriction applies. Project and Unproject use the committed pose. Callers must use an item's resolved Depth as its projection depth. The shared Canvas depth policy orders boxes by Layer then tree paint order and separates overlapping boxes by at least LayerDepth along local positive Z. Disjoint boxes retain their layer plane; hidden and clipped-away boxes do not push visible boxes forward. LayerDepth must be positive and finite. Unproject preserves the same local hit coordinates after the normal offset, and HitTest keeps the same paint order.

Width/Height accept nonnegative pixels or "auto" (also the omitted default). Content sizes include padding; minima constrain both explicit and natural sizes. Padding is a number or { Top, Right, Bottom, Left }, with omitted sides zero. Row flows horizontally; Column, View and Panel flow vertically unless Panel.Direction selects a row. Gap separates flow children. Align selects start/center/end/stretch on the cross axis; stretch applies to automatic sizes. Justify selects start/center/end/space-between on the main axis. Grow divides positive remaining space proportionally, without implicit shrinking. Content can overflow an explicitly small box.

Relative X/Y offsets preserve the child's original flow space. Absolute children use the padded content origin and contribute no natural flow size. Layer adds to inherited depth and controls hit order. Visible={false} and React's hidden host state hide descendants. No arbitrary ancestor clipping is introduced. ScrollView provides clamped nonnegative offsets, content viewport rectangles and their intersected clips for both presentation and hit testing. For overflowing content, scrollbarVisibility="always" (default) supplies a track, "hidden" omits it, and "hover" lets the pointer tracker report visibility on hover or while a gesture holds the bar. An invisible hover track remains targetable. Item.Track describes the pointer strip. Item.Scrollbar supplies the rail, thumb, optional arrow boxes and scrollbar paint depth. Horizontal orientation flows children in a row by default. Direction can override the flow. Item.ScrollRange caps controlled ScrollX and ScrollY independently.

Set Arrows to reserve a square at each end of the strip. The squares match the thumb's cross-axis thickness. Arrows are omitted when the viewport cannot fit both squares and a positive rail. The rail is two pixels narrower than the thumb (at least one pixel) and centered beneath it. The thumb uses the viewport-to-content ratio and a minimum of eight layout pixels, capped at the rail length. A rail with no thumb travel still maps an aimed position directly to the scrollable range. A viewport with no overflow on its selected axis has no track.

Pass Item.Clip to Canvas.Surface.Flatten to crop particle fills, images and glyph sprites, including their UVs. Native text lines and their private-use glyphs are omitted when a clip edge cuts through the line. ScrollView rejects ItemStack and Mob descendants because those native actors cannot be cropped to the viewport.

See pointer targeting and interaction routing.

InputScope contributes no visual box or flow gap. Its item requirements and access policies accumulate with those on ancestors; pointer settings inherit with nearer overrides. Access control applies the policies. Pointer.Visible={false} hides the pointer line without hiding targets. Pointer.MaxDistance and the reactive Pointer.Color callback are described in pointer targeting.

Spatial forms

Field takes one child element, such as an Input or Toggle. It can display status supplied by the caller or obtained through useField. Import the hooks from bedform/Spatial/Form or use Spatial.Form.

import { Button, Column, Field, Input, Text, Toggle } from "bedform/Spatial/Components";
import { useField, useForm, useSubmit } from "bedform/Spatial/Form";

type Settings = { Name: string; Announce: boolean };

function SettingsForm({ Save }: { Save: (settings: Readonly<Settings>) => Promise<void> }) {
    const form = useForm<Settings>({
        InitialValues: { Name: "", Announce: false },
        Validate: ({ Name }) => Name.trim()
            ? {}
            : { Name: { Status: "error", Message: "Enter a display name" } },
        OnSubmit: Save
    });
    const name = useField(form, "Name");
    const announce = useField(form, "Announce");
    const submit = useSubmit(form);

    return <Column Gap={4}>
        <Field Label="Display name" Subtitle="Shown to other players"
            Status={name.Status} Message={name.Message}>
            <Input Value={name.Value} OnChange={name.OnChange} />
        </Field>
        <Field Label="Announce changes">
            <Toggle Checked={announce.Value} OnChange={announce.OnChange} />
        </Field>
        <Button {...submit}><Text>Save</Text></Button>
        {form.SubmitStatus === "error" && <Text>Save failed. Try again.</Text>}
    </Column>;
}

Use Value with Input, TextArea and Slider, or pass it as Checked to Toggle. Text fields update form values when the player confirms the modal editor. SetValue updates any field programmatically, and Reset restores the mount-time values and clears feedback. The form and each binding expose Dirty and Touched; an edit marks a field touched even if the value stays the same.

Validation runs on submit. An error issue blocks the save. Warnings and success messages are advisory. Changing a value clears validation feedback. useSubmit provides the Button's OnActivate and Disabled props and the save callback receives the activation as its second argument. For programmatic submission, call await form.Submit(). The promise resolves to success, invalid, error or busy, and SubmitError exposes a thrown validation or save error. Edits or resets during a pending save leave its submitted snapshot intact. Its result still resolves to the caller, while the edited form returns to idle. Each mounted form owns its state, so a shared spatial root shares that form's values.

Text and child contracts

Display text uses Text, including the labels rendered internally by Field. Text accepts scalar content and nested Text; nested runs can change Color and repeat equal Font, Fallback and FallbackScope settings. Other nested layout or text-setting changes are errors, including alignment, visibility and access/pointer policy overrides: an inline run has no independent box or target. Layout retains inline color ranges and code-point-safe line boundaries (range indices use UTF-16), measured with the shared Minecraft font tables. Measure can override line widths. The text surface encodes color runs, enforces native byte limits and places each line from this layout. Font fallback/substitution and physical client calibration remain separate qualification work.

Containers exclude strings and numbers from their child types, including arrays. Slot admits no child or one ItemStack. ItemStack, Image, Mob, Divider and future glyph props are leaves. Title and custom callout Heading are explicit Text element slots, rather than string labels. Tabs admit TabButtons. These restrictions are checked again after composite/fragment reconciliation, including descendant-only state updates. Invalid frames are withheld and the nearest component guard throws through an ordinary React error boundary.

Inventory slots

Compose Inventory.CreateSurface from bedform/Spatial/Inventory with the spatial Text.CreateSurface in the same renderer. Include the current BedformCanvas behavior and resource packs. The surface draws the captured 18 × 18 recessed frame with a one-pixel inset around the default 16 × 16 stack box. The measured count uses the theme foreground and the Text surface's font and byte limits.

<Row Gap={4}>
    <Slot />
    <Slot><ItemStack Item="minecraft:stick" Presentation="flat" /></Slot>
    <Slot><ItemStack Item="minecraft:stone" Presentation="block" Quantity={32} /></Slot>
</Row>

Item is an item type ID. Presentation selects the flat-palm icon or ordinary full cube transform. When omitted, an ID registered as a block selects the cube transform. Plain custom icons can use flat. Per-item hand poses and custom GUI transforms (including tools, attachables and non-cubic blocks), damage values, glint, arbitrary entities, and mutated native stacks are outside this contract. Quantity is a positive safe integer within the native item's stack maximum. Each holder equips a single unit. A false or null conditional child gives an empty slot. ScrollView supports empty slots and rejects native stack descendants because it cannot clip their geometry.

Both private and shared roots use one holder lease per admitted viewer. The holder starts visually hidden and the renderer enables its scale for that viewer through a client-synced property override. Equipment is replicated world state. As for the rest of spatial layout, inherited access policies govern input on ancestor controls. Holders are transient. Retail-client inventory comparison and two-client visual isolation are tracked in Bedform-ty2k.18.

JSX erases an element's precise component/prop identity. Types cannot reliably reject a Panel passed where a Text/ItemStack element is expected, a composite that resolves to the wrong host, or forbidden ancestry through providers. Runtime checks are authoritative. React drops empty strings, booleans and null output; the host cannot inspect scalar output it never receives. Direct container children and fragments are additionally checked before that normalization.

Modals

Declare a Modal in the widget tree and call Open() or Close() on its ref. It starts closed. Its frame is centered on the enclosing top-level framed panel or the View, with a default width of 128 layout pixels and a height sized to its contents. The optional Title accepts inline text, and the optional children can contain read-only components such as Text, Image, and ScrollView. Close shares the footer row with the optional action, which can run a callback or navigate through its enclosing session. The callback controls whether the modal closes. A modal declared inside a page participates only while that page is presented. Declare it in the session's shell to keep it available across route changes.

import { Button, FramedPanel, Modal, Text, View } from "bedform/Spatial/Components";
import type { ModalHandle } from "bedform/Spatial/Components";
import { useRef } from "bedform/Spatial/React";

export function Settings({ save }: { save: () => void }) {
    const modal = useRef<ModalHandle>(null);
    return <View Dimension="minecraft:overworld">
        <FramedPanel Width={200} Height={140}>
            <Button OnActivate={() => modal.current?.Open()}><Text>Save changes</Text></Button>
            <Modal ref={modal} Title="Save changes?"
                Action={{ Label: "Save", OnActivate: () => { save(); modal.current?.Close(); } }}>
                <Text>Your changes will take effect immediately.</Text>
            </Modal>
        </FramedPanel>
    </View>;
}

The modal owns input within its View while open. Its black backdrop uses exponential ease-in-out over eight renderer ticks to reach 60% opacity, and reverses from its current opacity when closed. Surface backends receive the frame as a normal FramedPanel item. Draw the ModalBackdrop panel with alpha blending at its committed depth, using its BackgroundColor alpha. The Canvas renderer can apply DepthWrite: false to that sprite while retaining depth writes for the foreground modal.

Frames, tabs and themes

FramedPanel and TitledPanel must be top-level visual children of View. Fragments, providers, function components and nonvisual InputScopes may intervene; they never erase a visual ancestor. Initial renders and reactive ancestry changes are checked. Sibling panels follow the View's ordinary layout and can use absolute positioning like other direct children.

VariantNative referenceNine-slice minimumDefault padding (left, top, right, bottom)
"crafting" (default), "furnace"Shared opaque dialog frame, filled with #C6C6C68 × 88, 8, 8, 8
"loading"World-loading and connecting dialog, with a gray title band and a translucent #090909CC well16 × 3112, 27, 12, 12

Dimensions are in View pixels. The theme defaults both layout minima to 32. MinWidth and MinHeight can override the theme and are clamped to the native slice minimum. The default content padding adds the theme's gap inside each variant's border. An explicit Padding takes precedence. BackgroundColor replaces the center fill.

TitledPanel measures its title and padded body together. The title takes the width inside the frame padding and centers each wrapped line. A line too wide to fit, for example one containing a glyph wider than the slot, is omitted from native paint. The panel raises its height as needed for the title, TitleGap and padded body. Align, Direction, Gap and Justify arrange children inside the body. ContentPadding sets its inner inset. Body Text defaults to white and can specify its own color. JSX rejects a string in the Title slot. After JSX erases the component type, the renderer checks that the slot resolves to exactly one Text and enforces the placement rule for both panel components.

The loading titled panel defaults to 8 pixels of padding at the sides and bottom, with the title starting 9 pixels below the top. Its dark well uses the captured loading tint #090909CC and paints as one surface at a separate depth from the rounded frame and text. BackgroundColor overrides the well tint. The crafting and furnace variants layer the translucent body over the opaque frame.

import { FramedPanel, Text, ThemeProvider, View } from "bedform/Spatial/Components";

export function StatusPanel() {
    return <View Dimension="minecraft:overworld">
        <ThemeProvider theme="dark">
            <FramedPanel Variant="loading" Width={120} Height={64}>
                <Text Color="#FFFFFF">Connecting</Text>
            </FramedPanel>
        </ThemeProvider>
    </View>;
}

Particle backends use FrameSprites from bedform/Canvas/Frame with the item's committed bounds and variant. Pass BackgroundColor as the Interior option for a FramedPanel. For a loading TitledPanel, pass Interior: false and paint the separate content item for the well. Paint the slices on the frame's plane and use the layout's depth ordering for children and tabs. The Canvas resource pack supplies the frame textures. WidgetDemo uses this path.

Tabs attaches above its frame's upper-right edge, like the crafting screen's recipe, documentation and close tabs. A frame accepts at most one strip, as its direct visual child (InputScopes may wrap it). Inset moves the strip left from the frame's right edge and Overlap moves it down over the frame's top edge, up to the strip's own height. The frame owns placement, so Position, X, Y and Grow are rejected on Tabs. Buttons default to bottom alignment, so shorter tabs also stand on the frame edge, and the strip paints one layer above the frame, so its overlap targets the tabs. Gaps between tabs pass through to whatever is behind them. WidgetDemo tucks the shared toolbar backing two pixels behind the frame's top edge to cover its rounded corner. The backing has one pixel of top padding, eight on the left and six on the right.

The strip follows its frame's position and size and the View's transform. It does not enlarge normal flow, but it does extend the View's visible extent. A strip wider than the frame's width less Inset is hidden, including every hit target and interaction proxy, rather than overflowing or shrinking to a negative size. The frame's RequiredItem, Access and Pointer settings, theme and lifecycle apply to its tabs: unmounting or hiding the frame releases them.

TabButton belongs in Tabs; anywhere else it is rejected. Its reactive appearance is exactly "recipe" (the default) or "subtle" (TabButtonAppearance). Both follow the crafting screen as captured in BedformCanvas's WidgetStyle.TabButton:

AppearanceNative referenceDefault layoutArt by state
"recipe"Recipe-book tab selector25 × 27, theme control padding, content centered for the 17-pixel tab iconIndividual beveled face with hover feedback. The depressed face stays visible while Selected.
"subtle"Toolbar documentation (common.help_button) and close (common.light_close_button)15 × 15, no padding, content centeredTransparent at rest; flat fill on hover and press; the icon ink changes color per state

TabButtonSize holds these default sizes. Explicit Width, Height, Padding, Align, Justify and BackgroundColor override them, and switching appearance recomputes the remaining defaults without remounting the tab or its content. The native tab overlaps its panel by 4 pixels, which <Tabs Overlap={4}> reproduces.

Content is ordinary children: Text for labels (Legacy by default, as in Button) or an Image. TabIcon.RecipeBook supplies a 17 × 17 book mask for the recipe button. TabIcon.Documentation and TabIcon.Close are the native ? and × ink as 15 × 15 white masks at their source position, so either one fills a default subtle square exactly. A renderer tints untinted icon masks and Text inside a subtle tab with the state's ink color; an explicit Color wins. Label is an optional nonempty accessible name for icon-only content, matching the client's "How to Play" and "Close" narration. It never draws or changes layout, and renderers may show it as a tooltip.

Selected and Disabled are caller-controlled and independent of appearance. Activation only invokes the caller's callbacks: it never changes Selected (of that tab or its siblings), opens documentation or disposes a root, so an action-only tab need never become selected. To make the recipe tabs mutually exclusive, store a single active tab key and pass each button Selected based on that key. A disabled tab is denied and never activates. Tabs inherit their View's transform, theme, audience, RequiredItem, Access and Pointer policies through their frame, and unmounting releases them. Give each TabButton a stable key when the set changes, so the remaining tabs keep their identity.

import { useState } from "bedform/Spatial/React";
import { Image, Tabs, TabButton, TabIcon, Text, ThemeProvider, TitledPanel, View }
    from "bedform/Spatial/Components";

function RecipePanel({ showHelp, close }: { showHelp: () => void; close: () => void }) {
    const [recipesOpen, setRecipesOpen] = useState(false);
    return <View Dimension="minecraft:overworld" Width={200}>
        <ThemeProvider theme="light">
            <TitledPanel Width={200} Title={<Text>Crafting</Text>}>
                <Tabs Overlap={4}>
                    {/* A recipe toggle: the caller owns Selected. */}
                    <TabButton Label="Recipe book" Selected={recipesOpen}
                        OnActivate={() => setRecipesOpen(open => !open)}>
                        <Image Source={TabIcon.RecipeBook} />
                    </TabButton>
                    {/* Documentation and close actions never become selected. */}
                    <TabButton appearance="subtle" Label="How to Play" OnActivate={showHelp}>
                        <Image Source={TabIcon.Documentation} />
                    </TabButton>
                    <TabButton appearance="subtle" Label="Close" OnActivate={close}>
                        <Image Source={TabIcon.Close} />
                    </TabButton>
                </Tabs>
                <Text>{recipesOpen ? "Recipes" : "Inventory"}</Text>
            </TitledPanel>
        </ThemeProvider>
    </View>;
}

WidgetDemo's frame specimen runs this example in the world, painting both appearances from the generated BedformCanvas art.

ThemeProvider supplies reactive light/dark Minecraft-style palette and layout tokens, with nested partial overrides. An omitted theme inherits its parent; explicit component colors and dimensions override defaults. Theme.Dark and Theme.Light are frozen defaults. These logical tokens do not certify a match to native Minecraft screen assets.

Surface and verification

The text surface consumes the same encoded per-line layout, including nested colors, native byte wrapping and measured alignment. Partially clipped Text lines are omitted from both text drawing and text hit-testing.

Root.Layout and SurfaceFrame.Layout reference the same frozen result for each valid commit: View poses/extents, item bounds/content, layers, text lines/runs, policies and scroll clips. HitTest returns visible rectangles front-to-back using layer then paint order and half-open edges. It retains access-denied or disabled-policy surfaces so the later pointer layer can preserve occlusion. It does not perform world raycasting or permission decisions. Nested opaque consumer prop objects follow the runtime's shallow snapshot contract.

npm run test:spatial-layout --workspace bedform

Tests cover flow properties, arbitrary orientation, clipping, reactive metadata, themes, titles/tabs, resolved child/ancestry failures and error boundaries. The independently installed archive compiles positive/negative consumers and executes both automatic JSX modes in a restricted host without native/Node/browser imports. These are source/host/package checks. Native BDS rendering, texture fidelity, physical-client input, visibility and Switch acceptance remain unverified.

On this page