Expand description
day-core — the Piece model, realized tree, mounter, layout engine, and event routing (DESIGN.md §5, §7). Build-once: pieces are constructed exactly once; all dynamism flows through reactive bindings (day-reactive) writing to the thread-local tree.
Re-exports§
pub use frame::FrameConsumer;pub use frame::add_frame_consumer;pub use frame::frame_consumer_count;pub use frame::install_frame_requester;pub use frame::remove_frame_consumer;pub use lifecycle::dispatch_lifecycle;pub use lifecycle::lifecycle_supported;pub use lifecycle::on_lifecycle;pub use list::BuiltRow;pub use list::ListDriver;pub use list::ListReorderDriver;pub use list::install_list;pub use list::list_reload;pub use list::list_scroll_to_end;pub use list::list_scroll_to_row;pub use list::list_set_selected;pub use list::list_try_reorder;pub use toolbar::dispatch_toolbar_value;pub use toolbar::patch_toolbar;pub use toolbar::patch_window_toolbar;pub use toolbar::register_toolbar_value;pub use toolbar::set_toolbar;pub use toolbar::set_window_toolbar;pub use windows::WindowHandle;pub use windows::finish_window_open;pub use windows::focused_window;pub use windows::open_new_window;pub use windows::open_preferences;pub use windows::open_window;pub use windows::register_new_window;pub use windows::register_preferences;pub use windows::register_preferences_with;pub use windows::window_by_key;
Modules§
- frame
- Frame clock / continuous-animation driver (§8.4, docs/animation.md).
- lifecycle
- App-lifecycle callbacks (docs/lifecycle.md). An app registers closures for
day_spec::Lifecyclephases withon_lifecycle; each backend, at the matching moment in its native app/activity delegate, emitsEvent::Lifecycle(phase)(or day-core dispatches the launch phases uniformly), and the event pump routes it here to run the closures inside a reactive batch — the same rails asEvent::MenuAction, so a lifecycle handler that writes signals updates the UI like any callback. - list
- Recycling-list driver (docs/list.md, §10). The native list host owns scrolling + cell reuse;
Day owns row content. day-core injects a
day_spec::ListSourceinto the backend; when the native data-source pulls a cell,bind_rowbuilds it once (per physical cell) and thereafter rebinds it — one slot-write — as the cell recycles. - menu
- Menu action dispatch (§ menus). The MODEL (
day_spec::MenuItem) is toolkit-neutral and carries only ids for its actions; the real closures live here, keyed by id. A backend firesEvent::MenuAction(id)when a native item is chosen; the event pump routes it todispatch_menu_action, which runs the app’s closure. Ids are process-unique and monotonic. - shield
- The system-gesture / interactive-dismiss shield (docs/cover.md): the registries behind the
defers_system_gesturesandinteractive_dismiss_disabledmodifiers. Each mounted modifier pushes an entry while its subtree is alive; the union of entries is the app’s current request. - toolbar
- Window toolbars (docs/toolbars.md). The MODEL (
day_spec::ToolbarItem) is toolkit-neutral and carries only ids for its commands; the real closures live here, keyed by id — the same shape ascrate::menu, and deliberately the same id space, so one closure can back both a toolbar button and its menu-bar twin. - windows
- Secondary windows (docs/windows.md): the app-facing
open_windowAPI, the per-window registry, and the fallback that presents window content as a fullscreen cover where the toolkit cannot open windows (Cap::MultiWindow=Unsupported).
Structs§
- AnyPiece
- Type-erased piece for heterogeneous branches and dynamic construction.
- Asset
Name - The bundled-data name that
resourceresolves by (the full file name, extension included). - BuildCx
- Cover
Layout - Fullscreen cover (docs/cover.md): the COVER node occupies no space where it sits in the
tree (its native surface is presented over the window, outside the parent’s bounds), and
its content is laid out at the size the backend reported via
Event::FrameChanged— the same native-owned-frame contract asNavLayoutpages. - Engine
Cx - Fill
Through - Paint/clip wrapper (
.background,.corner_radius, the animatable layers): likePassThroughfor measurement, but the GRANTED rect flows to the child verbatim at place time — these containers exist to paint or clip the area the parent granted, so a grow stretch above them must reach the painted surface (the grid-cell card case) instead of being re-hugged at every wrapper. Under a parent that places at measured size — every stack, grid rigid cell, and overlay — bounds equal the measure and nothing changes. - Flex
- Read-only layout facts a parent may consult about a child (§7.2 ChildRef).
- Font
Family - The family name of a bundled custom font, feeding
Font::custom. Holds a&'static str(soFontstaysCopy); generatedres::fonts::…constants supply it. The untypedFont::Custom(&'static str, f64)variant remains the escape hatch for a family known another way. - Frame
Layout - Grid
Facts - Per-node grid facts (docs/grid.md), carried on
Flex— the shipped form of the §7.2 ChildRef facts surface. Set at build time bygrid_rowand the.grid_span/.grid_alignmodifiers; onlyGridLayoutreads them. - Grid
Layout - SwiftUI-style grid negotiation (docs/grid.md): columns are inferred from
grid_rowchildren, a column’s width is the max ideal width of its span-1 cells, agrow_wcell makes its column flexible (leftover width split evenly — theStackLayoutshare rule), and a non-row child is a full-width cell spanning every column.spacer()is an inert empty cell. The contract: exactly two measure proposals per cell per layout — unconstrained (pass A) and at the final column width (pass B) — andplacere-runs the same proposals, so it measures from cache. - Grow
Layout - The
grow/grow_w/grow_hdecorators (§5.2): a single-child wrapper carrying growFlexso the parent stack OFFERS it the space, and a greedy measure/place so the child actually FILLS it. Non-grown axes hug the child (likeframe(maxWidth: .infinity)on one axis). - Image
Name - The bundled-image name that
imagecallers resolve by (the file stem). - Leaf
Layout - Native leaf: measurement delegates to the toolkit.
- MaxWidth
Layout - The
.max_width(w)decorator (docs/layout.md): proposes at mostwto the child, so text wraps instead of overflowing, while narrower content still hugs. The vertical axis passes through untouched. - NavController
- A mounted host’s control surface. Closures run user code (route builders), so the registry
NEVER holds a borrow across a call (§3.3 discipline: clone the
Rcout, then call). - NavLayout
- Navigation host (docs/navigation.md): page FRAMES are native-owned (splitter panes,
nav-controller views), so
set_frameon pages is a toolkit no-op; Day lays each page’s CONTENT within the size the toolkit last reported viaEvent::FrameChanged, falling back to a sidebar/detail split (or the full host) of the host bounds. - NavToken
- Opaque handle from
register_nav; a nested host callsunregister_navon dispose. - Node
Data - Node
Probe - Cached last-applied props for the dayscript element index (§14.2).
- Overlay
Layout - Z-layering (§overlay): children share the container bounds, stacked back-to-front in child
order (first child = bottom of the z-order), each positioned by a single
Alignment.size_to_firstreports only the FIRST child’s natural size — the badge/annotation sizing ofoverlay(the annotation does not grow the frame); otherwise the layout reports the UNION (max) of all children’s natural sizes — the ZStack sizing ofzstack. No native work: the container is the same panel ascolumn/row, so backends stack children by attach order. - Padding
Layout - Pass
Through - Single-child pass-through (root, wrappers, group fallback): top-leading.
- Piece
Vec - Runtime-heterogeneous children (
column_vec-style call sites). - Present
Future - RNode
- Realized-node key.
NodeId(the spec-boundary id) is its FFI encoding. - Resource
- A handle to a bundled resource’s bytes with efficient random read-only access.
- Scroll
Layout - Scroll viewport (§7.6): greedy on the proposal; content measured unconstrained on the
scroll axis and reported via
set_scroll_content. Children are placed in the scroll’s content coordinate space (the scroll node is their native ancestor). - Sleep
- Future returned by
sleep. - Stack
Layout - Column/row negotiation (§7.2): rigid children first, remaining main-axis space divided
among flexible children;
spacer()is maximally flexible; group anchors expand inline. - Task
Handle - A handle to a spawned
task.Copyand!Send(the executor is thread-local). - Tree
- Vector
Name - The bundled-vector name that
vectorcallers resolve by (docs/vectors.md): the stem of aresource/vectors/SVG (or.symbolsetbundle). Vectors and images share one per-backend resolution namespace — staging guarantees every vector name resolves as whatever form that backend loads natively (a VectorDrawable, a catalog entry, a rasterized PNG).
Enums§
- Alignment
- Two-axis placement of a child within a container’s bounds (SwiftUI’s
Alignment). Used by the z-layering primitives (OverlayLayout):zstack,overlay/overlay_aligned. - Axis
- Boundary
- Measure-invalidation boundary (§7.4):
Yesstops upward needs-measure propagation (scroll viewports, nav pages). Named enum instead of a bare bool at call sites (docs/api-style.md). - Cross
Align - Scroll
Target - A programmatic scroll destination (§7.6, docs/scroll.md). Edges are axis extremes
(
Top/Bottomvertical,Leading/Trailinghorizontal — start/end in layout direction);Offsetpins the viewport origin to a content-space point (clamped by the platform);Idreveals the element with that dayscript id inside its nearest enclosing scroll. - Window
Root Reply TreeOps::open_window_root’s answer — the tree-level face ofday_spec::WindowOpenReply, carrying the adopted (or parked) root node.
Constants§
Traits§
- Layout
- Open layout protocol (§7.2).
childrenare the node’s direct children; group nodes (when/eachanchors) are layout-transparent — stacks expand them inline. - Layout
Ops - The engine surface visible to
Layoutimplementations. - NavStore
- A key/value sink a nav surface’s
.restorepersists its state through, so navigation survives a relaunch or an Android process death (docs/navigation.md). The framework never installs one — an app opts in by installing a store (e.g.day_part_prefs::install_nav_store) and marking the surfaces it wants remembered with.restore(key). With no store installed,.restoreis a silent no-op, so a surface’s.restorecall never fails to build. - Piece
- A UI description consumed once (§5.2). Returns the root realized node it created.
- Piece
Seq - Children of a container: a tuple of pieces (the floem
ViewTuplepattern — implemented ONLY for tuples,(), andPieceVec, never via a blanket, to stay coherent). - TreeOps
Functions§
- app_
temp_ dir - An app-writable scratch directory (docs/files.md) — re-exported from
day_spec::presentsoday_core::app_temp_dir()keeps working for the pieces layer’s file-save staging. An app-writable scratch directory: the backend-supplied one, elsestd::env::temp_dir(). Used by the file-save flow (docs/files.md) to stage bytes before the native save picker. - backend_
name - The compile-time target key of the running backend (
"macos-appkit","ios-uikit", …, thePlatform::TARGETstring), recorded bylaunch_with.Nonebefore launch. - capability
- Query the active toolkit’s support for a capability (docs). Lets app/piece code adapt its own
content to the backend — e.g. a page can skip a title the native nav already shows in a header
(
Cap::NavHeader), or pick a presentation fromCap::NavSplit. - clear_
controllers - Drop every controller — a fresh mount / test boot (called from tree install/uninstall).
- current_
anim - The ambient animation set by the innermost enclosing
with_animation, if any. - current_
route - The FULL current route: every mounted surface’s contribution, outermost to innermost,
/-joined (docs/navigation.md).None= no surface mounted;Some("")= everything at its root. Round-trips throughnavigate, so persisting navigation state issave(current_route())on the way out andnavigate(&saved)on the way back in. - dark_
mode - Whether the platform is rendering in dark appearance (see
Toolkit::dark_mode): the branch apps take when painting custom OPAQUE surfaces so fills track the theme that the default text colors already follow. - debug_
title_ tag - The development tag every window title carries in a DEBUG build:
(<version>/<toolkit>[/<script>])—(1.1.0/appkit), or(1.1.0/gtk/walkthrough.yaml)while a dayscript is driving. With several apps, toolkits and scripted runs open at once, the title bar is the only place that says which window is which. - direction_
of_ locale - The writing direction a locale implies (language subtag match).
- encode_
route - Assemble a route string from segments and params — the inverse of
parse_route. Reserved characters (/,?,&,=,%) in segments and params are percent-encoded. - enqueue_
event - The enqueue-only event sink installed into every backend (§8.3). May be invoked re-entrantly from inside any Toolkit method; dispatch happens at the next safe point.
- enqueue_
events - Enqueue several events into ONE drain before dispatching. Backends that observe a focus
move at a single point (Qt’s
focusChanged(old, new), an AppKit first-responder change) deliver the loss+gain pair through this so the pump can dispatch the gain first and a shared group signal never passes throughNone(docs/focus.md). - has_
launch_ deeplink - Whether a launch deep link is pending (
DAY_DEEPLINKor a platform hint). A nav surface’s.restorereads this so a deep link wins over restored state (docs/navigation.md). - has_
tree - id_of
- Resolve a dispatched
NodeIdback to the app-authored.id()string that named its node (find_by_id’s inverse, §5.5), orNonefor an id-less node or one no longer in the tree. The recorder (day::record, §14.6) calls this from inside its event observer to label a tap/input with the id an app would target in a dayscript step. Borrow-safe: returnsNonerather than panicking if the tree is momentarily borrowed by a re-entrant backend call. - id_
to_ rnode - install_
tree - invalidate_
size - Tell layout that a node’s intrinsic size may have changed. For tweaks (docs/tweaks.md): after a native call that alters a widget’s preferred size (fonts, tick marks, bezel styles), the measure cache along the node’s path must be invalidated — Day can’t see native mutations it didn’t make. Relayout runs at the next turn boundary as usual. No-op on a disposed node.
- is_rtl
- Whether the app is being rendered right-to-left (docs/localization) — a convenience over
layout_direction. The layout engine already mirrors widget placement under an RTL locale, but acanvasdraws in its own coordinate space, so a custom drawing that has a reading direction (a battery that drains one way, an arrow, a progress sweep) can call this to mirror itself. Fixed for the life of the process, likelayout_direction. - label_
of - A human-readable label for a node, for annotating a recorded script (§14.6): the accessibility
label if one is set (
.a11y(label = …), the localized string the screen reader speaks), otherwise the control’s own visible text.Nonewhen the node carries neither. - launch_
with - Launch a Day app on the given platform backend: sets up the reactive scheduler and the cross-thread poster, mounts the root piece into the window’s content container, runs the initial layout, and installs the turn-end layout callback (§3.3). The backend then owns the native main loop.
- layout_
direction - The app-wide layout direction (docs/localization): mirrors every horizontal placement in
the place pass when [
day_geometry::LayoutDirection::Rtl]. Resolved lazily from theDAY_LOCALElaunch environment (so toolkits can read it before any UI exists);set_layout_direction(called byinstall_localesfor the resolved locale) overrides. Fixed for the life of the process — switching locale at runtime does not re-mirror. - nav_
back - Pop one level, day-initiated (the toolkit presents the pop). Native-initiated pops arrive as
Event::NavBackand go through the owning host’spopdirectly. - nav_
store_ load - Read a
.restorekey through the installedNavStore(Noneif none is installed or the key was never saved). - nav_
store_ save - Write a
.restorekey through the installedNavStore(a no-op if none is installed). - navigate
- Navigate to a route (docs/navigation.md).
- note_
appearance_ changed - Re-read the toolkit’s appearance into the reactive
dark_modesignal. Backends call this when the SYSTEM appearance changes under a running app (macOS theme switch, GTK style-manager change), andset_appearancecalls it after applying an override — so closures readingdark_mode()recolor live instead of going stale until a rebuild. - note_
navigation - Announce a navigation to
routefrom its SOURCE — a nav host (the sidebar selector) calls this the instant it changes the bound selection, so the observer sees it synchronously instead of waiting for the route to settle intoNAV_STACKa frame later (whichmaybe_notify_route_changereads). Deduped like the pump-boundary path.routeis the host’s local key, which replays as a relativenavigate(innermost-first) — correct for both a top-level sidebar and a nested one. - open_
url - Open
urlin the platform’s default handler (system browser forhttp(s), mail client formailto:, …). The seam behind thelinkpiece; call it directly from a tap handler for a custom affordance. Fire and forget — no result, unopenable URLs are ignored by the backend. - parse_
route - Split a route string into its path segments and query params. Segments and param
names/values are percent-decoded (
%2F→/, …); everything else is taken literally. - pending_
presentation - The most recently opened still-pending presentation, for dayscript inspection/response.
- piece_
fn - A piece from a closure.
- present
- Present a native modal and await its answer (docs/dialogs.md). The pieces layer wraps
this in
Alert/confirm/prompt; call it directly for a customPresentSpec. - pump_
events - Dispatch queued native events (see [
pump_events_inner]), CONTAINING any panic. Native event callbacks reach Day throughextern "C"signal trampolines (GTK’svalue_changed_trampoline, Qt’s event filters, …) that ABORT the process on unwind (panic_cannot_unwind). A panic in a Day event handler or its reactive drain — e.g. the reactive-cycle assertion firing during a slider drag — would thereforeSIGABRTthe whole app instead of surfacing. Catch it at this single backend-agnostic boundary, log it (the message carries the offending effect’s source location), and reset the runtime so the app keeps running (degraded) rather than crashing. - pump_
generation - The current pump generation (see
PUMP_GEN). Read by the recorder’s nav coalescing. - rc_
layout - Helper for constructing shared layout Rcs.
- register_
nav - Install a controller (innermost = last). Returns its token. The root
nav()registers once and never unregisters; nested hosts (tabs()in a route) unregister when their scope disposes. - request_
route - Ask the app to navigate, from anywhere, at any time.
- resolve_
presentation - Deliver a native answer (the modal already dismissed itself). Called from
pump_eventsonEvent::PresentResult. - resource
- Open a bundled resource by name for efficient random read-only access.
- respond_
presentation - Answer a still-open modal programmatically (dayscript). Resolves with the given result FIRST (removing the pending request), then dismisses the native control — so the native dismissal’s own completion event finds nothing pending and is a no-op. False = no such pending request.
- rnode_
to_ id - route_
param - The value of one query param of the most recent
navigate(None= not present). - route_
params - The query params carried by the most recent
navigatecall (?name=value&…). Read them inside a destination builder:route_param("id"). They describe the navigation in flight — a push you perform by writing a path signal directly carries its data in your own state instead (docs/navigation.md). - safe_
area - The window’s safe-area insets, in points. Zero on every backend that clamps Day’s root to
the safe area natively (the default everywhere); nonzero only where a backend runs the root
edge-to-edge — today day-android’s opt-in immersive mode (docs/layout.md, the android
platform page). Compose it yourself where a background should run under the system bars:
paint the background unpadded, pad the content by these insets. The read is tracked, but
layout attributes like
.paddingcapture the value at build time — a mid-run inset change (rotation) does not re-pad already-built pages. - scroll_
to - Imperatively scroll a
scrollpiece (docs/scroll.md):nodeis the SCROLL node for edge and offset targets (ScrollTarget::Idignores it and reveals the named element in its own nearest scroll). Animated on-screen; dayscript uses the unanimated variant for determinism. Call with no tree borrow held. - set_
appearance - Override the app’s appearance:
Some(true)dark,Some(false)light,Nonefollow the system again. On backends reportingCap::Appearancethe native widgets restyle in place anddark_modeanswers the override; app-painted surfaces pick it up on their next rebuild. Other backends ignore the call — probe before offering a theme picker. - set_
contained_ panic_ observer - Register the contained-panic observer. First registration wins; later calls are no-ops (there is one crash reporter per process).
- set_
event_ observer - Install (or clear, with
None) an observer that sees every event day-core dispatches, in queue order, at the one point EVERY backend funnels native events through (enqueue_events, §8.3) — BEFORE the event reaches the app, so it observes exactly what the app receives. This is the recording/telemetry seam behindday::record(§14.6): a higher layer captures user actions into a replayable dayscript without touching any of the backends. Main-thread only; aNoneobserver adds no cost to the event path. The boxed closure is adopted into anRcinternally soenqueue_eventscan call it with no borrow held. - set_
launch_ deeplink - Record the host’s launch deep link before
launch_withruns (docs/navigation.md). Platform glue only — apps navigate withnavigate.DAY_DEEPLINK, where a process environment exists, takes precedence. - set_
layout_ direction - Override the layout direction (normally from
install_locales). Must be called before the first layout pass to take effect everywhere. - set_
nav_ observer - Install (or clear, with
None) the navigation observer. Resets the dedup baseline so the next change fires regardless of where recording started. - set_
nav_ store - Install the app’s navigation persistence store (docs/navigation.md). Call once at startup,
before the UI mounts, so a
.restoresurface reads it on first build. A later call replaces the store. - set_
resource_ opener - Register the active backend’s resource opener (Android
AAssetManager, GTKGResource, QtQResource, ArkUI rawfile, …). Called once during backend init. A second call is ignored, so a backend that shares the default file opener need not call this at all. - set_
safe_ area - Backend-facing: report the window’s safe-area insets (points). Call from the native inset
pass whenever the value changes; apps observe it through
safe_area. - sleep
- Resolve after (at least)
msmilliseconds, on the UI thread — the portable delay forday::taskflows (docs/async.md). RidesPlatform::post_delayed, so it works on single-threaded hosts (web) wherestd::thread::sleep+Settercannot. - synthesize_
text - Deliver synthetic TYPING to a text control (the dayscript
inputstep and the autodrive string commands both route here): paint the widget via the ordinary app-write patch, then enqueue theTextChangedevent. Both halves are needed — when a real user types, the text is already in the native field by the time its change event fires, so the two-way binding’s echo guard deliberately suppresses the write-back (§4.4); a synthesized event alone would drive the app’s signal while the widget kept showing its old text. - task
- Spawn an async flow onto Day’s main-loop executor. This is the opt-in seam for actions
that open modals or pickers:
button.action(|| day::task(async move { … .await … })). The future is polled once before this returns; the returned handle canTaskHandle::abortit and is freely discardable. - toolkit_
key - The toolkit key of the running backend (
"appkit","gtk", … — thePlatform::TOOLKITstring), recorded bylaunch_with.Nonebefore launch. - try_
with_ tree - Like
with_tree, but returnsNoneinstead of panicking when the tree can’t be entered: already borrowed, or not installed yet. A snapshot (TreeOps::snapshot) holds the borrow while the backend draws the window synchronously, and that draw can re-enter Day through a native callback — e.g. a lazy list’sviewForRow/connect_bind/cellForRowfiring duringcacheDisplayInRect. And platform style callbacks can fire beforeinstall_tree— e.g. GTK’s StyleManager emits adarknotify whilestartupapplies a forcedDAY_THEMEscheme, beforeactivatemounts the tree; a panic there unwinds into a C signal trampoline and aborts the process. Such callbacks use this and simply skip their work; the next real layout (or the signal’s first post-mount read) catches up. - uninstall_
tree - Reset the thread-local tree + queues (tests).
- unregister_
nav - Remove a controller whose host was disposed. No-op if already gone.
- with_
animation - Explicitly animate every state change made in
f— Day’s equivalent of SwiftUI’swithAnimation. The mutation runs inside aday_reactive::batch; that batch’s synchronous fixpoint drain (bindings →patch, plus the turn-end layout →set_frame) executes whilespecis ambient, so the resulting native updates carry the animation intent and the toolkit animates them on its own compositor. Nesting overrides; the previous ambient restores after. - with_
tree - Access the installed tree. Tree methods never run user code, so nesting cannot occur while a borrow is held; if events were queued during the call, they are pumped after the borrow is released (the “safe point” of §3.3).
Type Aliases§
- Event
Handler - An event handler registered on a realized node.
- Event
Observer - The recording/telemetry observer installed via
set_event_observer(§14.6): called with every dispatched(NodeId, Event), in queue order, before the app receives it. - NavObserver
- A navigation observer (§14.6): called with the new FULL route each time it changes, from any
source — imperative
navigate/nav_back, a nav_link or sidebar row (which navigate from an event handler, bypassing the event observer), a stack push, or a native back gesture.""is the root. Installed by the recorder in day-script; day-core only fires it. - Resource
Opener - A backend’s resource opener: maps a declared name (e.g.
"stations.json") to its bytes, orNoneif there is no such resource.