lecodes-sdk 2.2.11 → 2.2.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (79) hide show
  1. package/dist/global.d.ts +2 -0
  2. package/dist/host.d.ts +8 -2
  3. package/dist/types/core/Aspect.d.ts +5 -0
  4. package/dist/types/g2/Physics2D.d.ts +3 -2
  5. package/dist/types/g2/Scene2D.d.ts +6 -0
  6. package/dist/types/gl/Scene.d.ts +6 -0
  7. package/dist/types/gl/Texture.d.ts +2 -7
  8. package/dist/types/gl/animation/DynamicBone.d.ts +3 -0
  9. package/dist/types/gl/animation/Locomotion.d.ts +3 -0
  10. package/dist/types/gl/physics/Physics.d.ts +2 -1
  11. package/dist/types/gl/physics/Ragdoll.d.ts +4 -0
  12. package/dist/types/gl/vehicle/Vehicle.d.ts +4 -0
  13. package/dist/types/inject.d.ts +1 -1
  14. package/dist/types/runtime/app.d.ts +4 -2
  15. package/dist/types/runtime/fetch.d.ts +3 -0
  16. package/dist/types/runtime/storage.d.ts +6 -1
  17. package/dist/types/server/db/marci/query.d.ts +8 -2
  18. package/dist/types/ui/UIButton.d.ts +2 -2
  19. package/dist/types/ui/UIContainer.d.ts +4 -2
  20. package/dist/types/ui/UINode.d.ts +1 -1
  21. package/dist/types/ui/UIScreen.d.ts +2 -2
  22. package/dist/types/ui/UIVideo.d.ts +3 -2
  23. package/dist/types/ui/router.d.ts +1 -1
  24. package/dist/types/version.d.ts +1 -1
  25. package/dist/types.json +1 -1
  26. package/package.json +2 -5
  27. package/src/compile/assetIconMacro.ts +2 -1
  28. package/src/compile/assetMacro.ts +2 -1
  29. package/src/compile/compileProject.ts +28 -4
  30. package/src/compile/header.ts +17 -0
  31. package/src/compile/index.ts +2 -0
  32. package/src/core/Aspect.ts +2 -1
  33. package/src/g2/Physics2D.ts +6 -3
  34. package/src/g2/Scene2D.ts +9 -1
  35. package/src/gl/Scene.ts +9 -1
  36. package/src/gl/Texture.ts +2 -1
  37. package/src/gl/animation/DynamicBone.ts +6 -2
  38. package/src/gl/animation/Locomotion.ts +11 -1
  39. package/src/gl/physics/Physics.ts +3 -2
  40. package/src/gl/physics/Ragdoll.ts +8 -3
  41. package/src/gl/vehicle/Vehicle.ts +7 -2
  42. package/src/host.d.ts +8 -2
  43. package/src/inject.ts +1 -1
  44. package/src/runtime/app.ts +4 -2
  45. package/src/runtime/fetch.ts +6 -0
  46. package/src/runtime/storage.ts +14 -4
  47. package/src/server/db/marci/query.ts +8 -2
  48. package/src/ui/UIButton.ts +2 -2
  49. package/src/ui/UIContainer.ts +4 -2
  50. package/src/ui/UINode.ts +1 -1
  51. package/src/ui/UIScreen.ts +2 -2
  52. package/src/ui/UIVideo.ts +3 -2
  53. package/src/ui/router.ts +4 -3
  54. package/src/version.ts +1 -1
  55. package/prompts/2d.md +0 -391
  56. package/prompts/3d-scene-files.md +0 -113
  57. package/prompts/3d-scene.md +0 -122
  58. package/prompts/3d.md +0 -299
  59. package/prompts/README.md +0 -142
  60. package/prompts/ar.md +0 -142
  61. package/prompts/canvas.md +0 -28
  62. package/prompts/compose.ts +0 -46
  63. package/prompts/concept.md +0 -49
  64. package/prompts/core-design.md +0 -98
  65. package/prompts/core.md +0 -294
  66. package/prompts/design.md +0 -218
  67. package/prompts/dist/2d-game.md +0 -1567
  68. package/prompts/dist/3d-app.md +0 -1712
  69. package/prompts/dist/ar-app.md +0 -1585
  70. package/prompts/dist/concept.md +0 -49
  71. package/prompts/dist/design.md +0 -521
  72. package/prompts/dist/ui-app.md +0 -1175
  73. package/prompts/index.md +0 -39
  74. package/prompts/intake-prompt.md +0 -33
  75. package/prompts/namer-prompt.md +0 -12
  76. package/prompts/router-prompt.md +0 -50
  77. package/prompts/select.ts +0 -126
  78. package/prompts/ui-design.md +0 -203
  79. package/prompts/ui.md +0 -813
package/prompts/ui.md DELETED
@@ -1,813 +0,0 @@
1
- // ===== UI RULES =====
2
- // - Default screen background is BLACK — always set bgColor and text color explicitly
3
- // - Only use style properties listed below — never invent new ones, they may not exist in the engine
4
- // - Extract repeated styles into Style<T> objects and repeated UI into factory functions
5
- // - Keep layout minimal — no wrapper containers that exist only to align something (alignment is a container property)
6
-
7
- // ===== UI COMPONENTS =====
8
- // Every element is created by a global factory function (never `new`) that takes only the element's
9
- // CONTENT — children as plain arguments (or text/src/...). Everything else — styles, handlers — is
10
- // configured by chaining: every configuring method returns the element itself, so construction reads
11
- // as one chain.
12
- UIColumn(UIText("Title"), UIButton(UIText("Go")))
13
- // An ARRAY argument is flattened into the children — pass items.map(Row) directly, no spread:
14
- UIColumn(header, items.map(Row), footer)
15
-
16
- // UIRow, UIColumn — containers (UIColumn stacks vertically, UIRow horizontally)
17
- UIRow(...children) / UIColumn(...children)
18
- // Child management — imperative, no diffing; works before and after the element is on screen:
19
- // .append(...nodes), .insert(index, ...nodes), .remove(...nodes), .setContent(nodes), .children (readonly)
20
- // .setContent is the "re-render" primitive — build a fresh array (items.map(Row)) and swap it in.
21
- // For long or unbounded data use UIVirtualizedList instead of setContent over a big array.
22
-
23
- // UIScreen — root screen, always fills the device. Behaves as a UIColumn.
24
- UIScreen(...children)
25
- // .open() / .close() — show/close directly (single-screen apps; open() while a Router is active hides the router)
26
- // .onOpen(cb), .onClose(cb) — fire on EVERY activation, not just the first: Router.push away fires onClose,
27
- // popping back fires onOpen again. Anything started in onOpen (loops, intervals, sockets) MUST be stopped
28
- // in onClose (see TIMERS & FRAME LOOP above).
29
- // .onTouchStart(cb) — fires for touches anywhere on the screen; use for full-screen gestures (see TOUCH GESTURES above)
30
- // .onBack(cb) — Android hardware/gesture back; typically Router.pop()
31
- // Screens NEVER scroll — the canonical screen is fixed chrome (header, tab bar) + ONE UIScrollable body
32
- // with flexGrow: 1: UIScreen(Header(), UIScrollable(content).style({ flexGrow: 1 }))
33
- // Note: a screen always fills the device — sizing styles on it (width, height, flexGrow, flexShrink, position) are no-ops
34
-
35
- // UITabs — THE bottom-tab app shell: swipeable tabs (a UIPager) + a themed tab bar, as one UIScreen.
36
- // USE THIS for every tabbed app — never hand-build a tab bar. Keys are tab ids, in tab order:
37
- const tabs = UITabs({
38
- home: { label: "Home", icon: assetIcon("lucide:house"), screen: homeScreen },
39
- profile: { label: "Profile", icon: assetIcon("lucide:user"), screen: profileScreen },
40
- })
41
- Router.init(tabs) // UITabs IS a UIScreen — present it directly
42
- // .select(id), .tab (getter), .onSelect(cb(id, i)) — fires on a bar tap, swipe, or select()
43
- // .badge(id, value) — true = dot, number/string = count pill, false/null/0 clears
44
- // Ambient, from any screen, no reference threading: UITabs.current (the visible tabs, or null) and
45
- // UITabs.select("profile") — the twin of UIPager.current / UIPager.push
46
- // .pager — the UIPager underneath; UIPager.push(detail) from any screen keeps the bar
47
- // The bar is colored by the theme's roles (accent, textMuted, surface, border) — no keys of its
48
- // own; one bar's own colors: tabs.bar.theme({ accent, surface }). Custom layout: UIPager below.
49
-
50
- // UIPager — the navigation primitive under UITabs: sibling tabs that swipe natively, each tab its
51
- // OWN push/pop stack. Reach for it directly for a plain stack (one-screen pager) or a fully custom
52
- // tab bar. Renders no bar — build your own next to it; give the pager flexGrow: 1.
53
- UIPager(...tabs) // the tab root screens (arrays flatten); tabs are FIXED at construction
54
- // .select(i, animated?) (instant by default), .index, .onSelect(cb(i)) — fires for taps AND swipes: sync the
55
- // bar highlight here. Tabs keep their stack/scroll state when switched away and back.
56
- // .push(screen) — slides onto the CURRENT tab; edge back-swipe / Android back pops natively.
57
- // .pop(), .popToRoot(), .replace(screen), .depth (tab swiping is disabled while > 1), .onChange(cb(depth))
58
- // Ambient from any screen, no reference needed: UIPager.push(screen) / UIPager.pop() / UIPager.current
59
- // pager.push = detail INSIDE the tab (bar stays); Router.push = above the whole shell (bar covered).
60
- // Note: tab screens are built up front, but onOpen fires only when the tab becomes visible (maybe never) —
61
- // load initial data at build time, keep onOpen for re-entry.
62
- const pager = UIPager(homeTab, searchTab, profileTab).style({ flexGrow: 1 })
63
- Router.init(UIScreen(pager, tabBar)) // bar buttons: .onClick(() => pager.select(i))
64
-
65
- // UIWidget — floating overlay, independent of screens, always position: fixed in device coordinates
66
- // Persists across Router navigation — create ONCE at module scope, reuse; hidden by default.
67
- UIWidget(...children)
68
- // .show(), .hide(), .isShown (getter), .onTouchStart(cb), .onBack(cb)
69
- // extra style: overlayColor — full-screen scrim BEHIND the widget that blocks taps underneath, turning it into
70
- // a modal; null (default) = no layer, "transparent" = invisible but still blocks. A scrim tap fires
71
- // .onOverlayTap(cb) — usually () => widget.hide()
72
- // If a widget belongs to one screen only, pair it with that screen's lifecycle:
73
- // screen.onOpen(() => sheet.show()).onClose(() => sheet.hide())
74
- // Exit animation: .animateTo({ ..., commit: false }) then .hide() — see animateTo below.
75
-
76
- // UIModal — a UIWidget prewired as a dialog: USE THIS for confirm/alert dialogs
77
- // Scrim on by default (overlayColor "rgba(0,0,0,0.5)"), animated show/hide (200ms fade), scrim tap and
78
- // back button close it automatically. Create ONCE at module scope, like any widget.
79
- UIModal(...children)
80
- // .show(), .hide() (animated on a modal), .isOpen (getter), .onOpen(cb), .onClose(cb), .dismissible(false)
81
- // — plus the full UIWidget surface
82
- // .transition(hidden) — replace the show/hide animation: `hidden` is the off-screen pose (show animates FROM
83
- // it, hide TO it; its duration times both), e.g. .transition({ transform: "translateY(480px)", duration: 250 })
84
- // for a slide. Px only — no % in transform.
85
- // Position/size it like a widget (left/right/top/...); style the box (bgColor, borderRadius, p)
86
-
87
- // UIBottomSheet — a UIModal pinned to the bottom edge: USE THIS for every bottom sheet, never hand-build one
88
- // Content-sized by default (as tall as its children, capped at the screen) — one position, drag down to
89
- // dismiss: the action-sheet shape. Native hosts own the drag (snap, velocity, scroll handoff); web shows it static.
90
- UIBottomSheet(...children)
91
- // .detents([0.3, 0.6, 1]) — snap positions, ascending fractions of screen height (the map-app model). Call
92
- // BEFORE show(); sizes the sheet to the HIGHEST detent — lower detents show the top slice of the content.
93
- // .setDetent(i) (animated), .detent (getter), .onDetent(cb(i)) — every settle: finger snap or setDetent()
94
- // .show()/.hide() slide in/out — plus the full UIModal surface (scrim, onOpen/onClose, dismissible).
95
- // Dragging below the lowest detent closes it (fires onClose); .dismissible(false) collapses there instead —
96
- // the persistent map sheet (pair it with overlayColor: null so the page behind stays interactive).
97
- // An inner UIScrollable just works: it scrolls at the top detent; pulling down from its top drags the sheet.
98
-
99
- // UIPopover — a UIModal prewired as an ANCHORED menu: USE THIS for dropdowns, context menus, tooltips
100
- // Transparent intercepting scrim (outside tap dismisses; content under it can't scroll), 120ms fade,
101
- // automatic placement: below the anchor, flips above near the bottom edge, clamped into the viewport.
102
- // Attaches itself to Presentable.current (hides with the page it opened on).
103
- UIPopover(...children)
104
- // .show(anchor?) — anchor: any element, or { x: ev.clientX, y: ev.clientY } for long-press context menus
105
- // .hide() — plus the full UIModal surface (isOpen, onOpen/onClose, dismissible, transition)
106
- // Style the menu box yourself (width, bgColor, borderRadius); do NOT set left/top — show(anchor) owns them.
107
-
108
- // UIScrollable — THE scroll container: a screen's scrolling body, a list under a pinned header, a carousel
109
- UIScrollable(...children)
110
- // extra styles: scrollDirection ("horizontal" | "vertical", default vertical), showScrollbar: boolean,
111
- // overscrollMode ("none" | "absorb" | "default"), refreshControlColor — tints the pull-to-refresh spinner,
112
- // keyboardDismissMode ("interactive" | "scroll" | "none") — "scroll": any drag dismisses the keyboard at once (search lists)
113
- // snap ("none" | "start" | "center" | "end", default "none") — paging: a released drag settles on a
114
- // direct child's boundary; the value picks where the child rests in the viewport. Snap targets are
115
- // the children themselves, so item widths can differ. (Mobile hosts; web degrades to free scrolling.)
116
- // .onScroll(cb(pos)), .onScrollRelease(cb), .onOverscroll(cb(delta))
117
- // .onRefresh(async cb) — pull-to-refresh; spinner stays until the returned promise settles. Attach BEFORE the
118
- // element mounts; vertical only; native hosts (web preview: no-op). UIVirtualizedList has the same contract.
119
- // Note: NO programmatic scrolling (no scrollTo) — if you need scrollTo/scrollToEnd, use UIVirtualizedList
120
- // Note: defaults flexShrink: 1 (scrolls instead of overflowing); wrapping ancestors still need flexShrink: 1
121
- // themselves. flexGrow: 1 to fill the remaining space is still yours to set.
122
- // Carousel = scrollDirection: "horizontal" + FIXED-width cards + snap: "start" ("center" for a card-deck-with-peek)
123
-
124
- // UIVirtualizedList<T> — windowed list for LONG or unbounded data (feeds, chats, search results): only the
125
- // visible rows (plus a buffer) are mounted. Use it instead of UIScrollable + map() whenever the item count
126
- // is large, grows over time, or is unknown.
127
- UIVirtualizedList<T>({
128
- data?: () => T[], // the rows, read reactively: write the signal, the list follows (new array, keys matched)
129
- // absent = fed by hand: .setData(items) / .append(...items) / .prepend(...items) / .update(...items) / .removeByKey(...keys)
130
- // (one feed per list: a list with `data` has no append on its type)
131
- keyOf: (item: T) => string, // STABLE unique id per item (never the array index)
132
- render: (item: T) => UINodeChild, // builds one row; called lazily as rows enter the window
133
- estimatedHeight: number | ((item: T) => number), // px guess per row (real height measured after mount)
134
- overscan?: number, // extra px mounted above/below the viewport (default: one viewport)
135
- inverted?: boolean, // true = chat mode: starts scrolled to the end, append at bottom auto-scrolls
136
- })
137
- // Rows added at the end scroll a chat at its bottom; rows added before the first (history) move nothing; a row
138
- // whose item is a new object re-renders. Never re-create the list.
139
- // .itemCount (getter) / .getItem(key)
140
- // .scrollTo(offset, animated?) / .scrollToKey(key, animated?) / .scrollToEnd(animated?) / .onScroll(cb(pos))
141
- // .onEndReached(thresholdPx: number, cb) // threshold FIRST and required; fires near the BOTTOM — load next page
142
- // .onStartReached(thresholdPx: number, cb) // near the TOP (chat history)
143
- // .onRefresh(async cb) // pull-to-refresh, same contract as UIScrollable (attach before mount)
144
- // Edge callbacks are latched — fire once entering the threshold zone, re-arm when scrolled back out;
145
- // still keep your own busy/end flags for paging.
146
- // extra styles: refreshControlColor + element styles — no intrinsic height: give it flexGrow: 1 (or an explicit height) or it collapses to 0
147
- // Note: render() must be pure over the item — a row may be unmounted and re-rendered at ANY time, so its output
148
- // can't depend on outside mutable state. To change a mounted row, change the item and call .update(item).
149
- // estimatedHeight only needs to be close — accurate guesses just reduce scroll jitter.
150
-
151
- // UIText
152
- UIText(text)
153
- // .text (get/set) — mutating re-renders immediately
154
- // extra styles: fontSize (default 14), fontWeight (number | "normal" | "bold"), fontFamily, color,
155
- // textAlign ("start"|"center"|"end"|"left"|"right", default left), lineHeight, fontStyle ("normal"|"italic"),
156
- // textDecoration ("underline"|"line-through"|"none"), letterSpacing
157
-
158
- // UIImage
159
- UIImage(src) // src: string url | FetchResponse | File | SvgSource | Canvas (see CANVAS section —
160
- // charts/generated graphics; redraw + canvas.update() refreshes the shown image)
161
- // .src (get/set) — swaps the displayed image
162
- // extra styles: objectFit ("cover"|"contain"|"fill"), tintColor (SVG only), borderRadius (number px only on UIImage)
163
- // .setSourceRect(x, y, w, h) — crop to a sub-rect of the source (texture px); frame fills the box, objectFit
164
- // ignored. Chainable, safe to call before mount. For atlases/spritesheets — swap the rect to change frame.
165
- // Note: tintColor applies only to SVG sources — it replaces ALL fill and stroke colors (monochrome icons only)
166
- // Note: a project file by its path as a string — UIImage("images/photo.png") — is the bundled asset (the compile resolves it; a path that names no file fails the compile); plain https:// strings are remote URLs
167
-
168
- // UIVideo — the on-screen surface only; playback lives entirely on the VideoPlayer (see AUDIO / VIDEO above)
169
- UIVideo(player)
170
- // .player (readonly) — the VideoPlayer passed at construction
171
- // extra styles: objectFit ("cover"|"contain"|"fill")
172
- const player = new VideoPlayer(src)
173
- const video = UIVideo(player).style({ width: "100%", height: 220, objectFit: "cover" })
174
- player.play() // stop playback in the screen's onClose; .dispose() when gone for good
175
-
176
- // UIButton — the only TAPPABLE container: a UIRow with children centered on both axes by default.
177
- // To make anything clickable (a card, a list row, an icon) — wrap it in a UIButton.
178
- UIButton(...children)
179
- // .onClick(cb), .onTouchStart(cb), .isPressed (getter) // gestures: see TOUCH GESTURES above
180
- // .onMouseEnter(ev => ev.track({ onMove?, onEnd?, onCancel? })), .isHovered (getter) // mouse only; no leave event — onEnd is the leave
181
- // extra styles: $pressed: { bgColor, opacity, ..., duration? } — style while the finger is down (reserved class);
182
- // rippleColor ("default" or a Color, Android only)
183
- // Note: press feedback is OPT-IN — nothing happens visually unless you set it. rippleColor replaces the
184
- // $pressed visual on Android, so rippleColor + $pressed = ripple on Android, $pressed dim on iOS.
185
- // Note: buttons render no chrome of their own — style bgColor/borderRadius/padding yourself, and give a
186
- // button an explicit height (on its own it is only as tall as its text). flexDirection: "column" for cards.
187
-
188
- // UIInput / UITextArea — single-line / multi-line text field
189
- UIInput() / UITextArea()
190
- // .value (get/set), .onChange(cb(value)), .onFocus(cb), .onBlur(cb), .focus(), .blur()
191
- // .onSubmit(cb(value)) — keyboard return key (UIInput ONLY; in UITextArea Enter is a newline)
192
- // extra styles: placeholder, placeholderColor, plus text styles (fontSize, color, ...)
193
- // type: "text"|"password"|"search"|"phone"|"email"|"number"|"decimal"|"url"|"date"|"time"
194
- // enterKey: "done"|"go"|"next"|"search"|"send" (UIInput only) — return-key label
195
- // maxLength: number; autocapitalize: "none"|"words"|"sentences"|"characters"; autocorrect: boolean
196
- // autofocus: boolean — takes the focus as its screen opens (a composer, a chat, a search; once, one per screen)
197
- // keyboardShrink: boolean (default true) — false: keyboard OVERLAYS the UI, no relayout (chat composers)
198
- // keyboardDismiss: boolean (default true) — false: taps never dismiss the keyboard (chat composers)
199
- // $focused: { borderColor, ..., duration? } — style while focused (reserved class)
200
- // Note: type values are KEYBOARD HINTS, not validators — "number" doesn't block pasted letters. The
201
- // phone-pad value is "phone" (there is NO "tel").
202
- // Note: "date"/"time" open the native PICKER in the keyboard slot (typing disabled). .value and onChange stay
203
- // canonical ("YYYY-MM-DD" / "HH:MM" 24h) while the field displays localized — set/compare canonical only.
204
- // Note: on submit the keyboard dismisses UNLESS enterKey is "next" — then call next.focus() in onSubmit:
205
- // name.style({ enterKey: "next" }).onSubmit(() => email.focus())
206
- // Note: keyboard dismissal is automatic (tap on a NON-INTERACTIVE area; return key; iOS Done bar on number
207
- // pads). Taps on buttons/other inputs NEVER dismiss (the control acts, focus stays), and scrolling doesn't
208
- // either unless the scrollable opts in via keyboardDismissMode — so dropdowns/autocomplete under a focused
209
- // input just work. The host scrolls the focused field into view — write NO keyboard code beyond the
210
- // enterKey: "next" chain (and .blur(); keyboardDismiss: false on a chat composer).
211
- // Note: an input collapses to its placeholder's width and its text's height — see SIZING below.
212
-
213
- // app.keyboardHeight (logical px, 0 hidden) + app.addEventListener("keyboard", cb(height, durationMs)) —
214
- // the keyboard's RAW overlap with the viewport. Pair with keyboardShrink: false for a chat composer:
215
- // app.addEventListener("keyboard", h => { composer.style.pb = Math.max(24, h) })
216
-
217
- // UISpacer — flexible empty space (defaults flexGrow: 1), eats free space along the main axis.
218
- // Only when plain alignment can't express it (one item pushed to the far end while the rest stay put):
219
- UIRow(title, UISpacer(), closeButton)
220
- // If ALL children move together, justifyContent ("space-between", "flex-end", ...) does it with no extra element.
221
-
222
- // @deprecated UIBox — legacy centered container: defaults justifyContent AND alignItems to "center"
223
- // (column direction). Kept for old projects — write new code with UIRow/UIColumn + explicit alignment.
224
-
225
- // ===== STYLING =====
226
- // Every UI element has a .style() method. It MERGES the given styles (does not replace) and RETURNS the
227
- // element, so calls chain and later calls only override the keys they mention:
228
- UIText("Hi").style({ color: "white" }).style({ fontSize: 20 }).onClick(...)
229
-
230
- // Ways to set styles — pick the right one:
231
- // 1. .style({...}) → declarative merge, the default. Use this 99% of the time.
232
- // 2. el.style.foo = bar → direct single-property mutation after creation (hot paths),
233
- // e.g. el.style.transform = `translateY(${y}px)`; el.style.foo reads it back.
234
- // 3. .animateTo({..., duration, delay?, commit?, loop?}) → tween current → given values (duration in MS).
235
- // Targets are COMMITTED into the style immediately; pass commit: false to play without persisting —
236
- // the exit-animation pattern (fade an overlay, then .hide(); next show() starts from the intact style).
237
- // loop: true | n repeats the tween — loopMode: "ping-pong" (default: there and back) or "restart"
238
- // (snap back + replay — full-turn spinners via transform: "rotate(360deg)", shimmers). A looping
239
- // animation is an effect, not a state change: it never commits, delay applies once, and it stops on
240
- // the element's next animateTo/animateFrom or when it leaves the screen. (web/iOS/desktop; Android plays once until its next runtime.)
241
- // 4. .animateFrom({..., duration, delay?}) → snap to given values, animate back to current (fade-in).
242
- // Never modifies the stored style.
243
- // For free-value tweens use animate() — see ANIMATION above.
244
- // Older code may pass a style object as the FIRST factory argument — legacy; write new styles with .style().
245
-
246
- // Mutable CONTENT properties are NOT styles — they live on the element:
247
- // UIText: .text UIInput/UITextArea: .value UIImage: .src UIButton: .isPressed (read-only)
248
- myText.text = "Updated" // re-renders immediately
249
-
250
- // Style<T> is a global helper type for reusable style objects, no import needed:
251
- const btn: Style<UIButton> = { bgColor: "#333", borderRadius: 12 }
252
-
253
- // --- Style vocabulary ---
254
- // Layout is Flexbox-only (Yoga engine). No CSS grid, no block layout.
255
- // Every element is a flex container, position: relative, flexDirection: column by default (UIRow AND UIButton flip to row).
256
- // Container layout: flexDirection, justifyContent ("flex-start"|"center"|"flex-end"|"space-between"|"space-evenly"),
257
- // alignItems ("flex-start"|"center"|"flex-end"|"stretch", default "stretch"), gap, flexWrap
258
- // Flex child: flex (flex: 1 ≡ grow 1 + shrink 1 + basis 0 — see SIZING), flexGrow (default 0),
259
- // flexShrink (default 0), flexBase (NOT flexBasis), alignSelf, aspectRatio
260
- // Size: width, height, minWidth, maxWidth, minHeight, maxHeight
261
- // Position: position ("relative"|"absolute"|"static"), top, left, right, bottom
262
- // Padding: p, px, py, pt, pb, pl, pr (≡ padding, paddingHorizontal, paddingVertical, paddingTop, ...)
263
- // Margin: m, mx, my, mt, mb, ml, mr — margins also accept "auto" (mx: "auto" centers a fixed-width element)
264
- // Background (containers/screen/button/input/video; UIText/UIImage/UISpacer have bgColor only):
265
- // bgColor, bgImage (string | FetchResponse | File | SvgSource), bgSize ("cover"|"contain"|"fill"|"tile"), bgGradient
266
- // bgGradient: a CSS linear-gradient() or radial-gradient() string, e.g. "linear-gradient(to top, rgba(0,0,0,0.7), transparent)"
267
- // or "radial-gradient(circle at 50% 40%, #7B2FF7, #0a0a1a)". Comma-separate several gradients to stack them (first = on top).
268
- // Layers paint bottom-to-top: bgColor → bgImage → bgGradient (gradient over image = text scrim).
269
- // bgImage is decoration BEHIND children — an image that IS the content belongs in UIImage.
270
- // Border: border ("1px solid #333" or bare width), borderWidth, borderColor,
271
- // borderRadius (UIValue, or per-corner string "0 0 20 20"), per-side shorthands (borderTop, ...) and
272
- // longhands (borderTopWidth, borderTopColor, borderTopLeftRadius, ...)
273
- // Other: display ("none" | "flex"), opacity (0..1), transform (CSS string, e.g. `translateY(12px)` — great for
274
- // gestures), overflow ("hidden" | "visible"), boxSizing ("border-box" | "content-box"),
275
- // pointerEvents ("all" | "none" — "none" lets taps pass through)
276
-
277
- // --- Values & units (UIValue) ---
278
- // number (px) | "50%" | "50vw" | "50vh" | "50vmin" | "50vmax" | "1.5em" | "calc(...)" | "min(...)" | "max(...)" | "clamp(min, val, max)" | "var(--name)" / "var(--name, fallback)"
279
- // Note: number value → logical px; string value → same semantics as on the web
280
- // Note: "em" resolves against the element's OWN fontSize (default 14) — there is NO style inheritance
281
- // Note: calc()/min()/max()/clamp() combine px, viewport units, em, safe-area keywords, and nest freely —
282
- // but do NOT support % ("calc(100% - 20px)" is invalid; use "calc(100vw - 20px)")
283
-
284
- // --- Colors in UI styles ---
285
- // any CSS color (hex, rgb()/hsl(), the CSS names — green = #008000, transparent/clear), 0xRRGGBB, [r,g,b(,a)],
286
- // or "var(--x)" — the same colors as every engine API (see COLORS above); a non-color throws
287
-
288
- // --- Safe areas & comfort ---
289
- // Env keywords resolving to the device insets (notch, home indicator):
290
- // "safe-top" | "safe-bottom" | "safe-left" | "safe-right"; "safe-all" — p / m shorthands only
291
- // Comfort tokens — where content comfortably starts, never collapse to 0: max(safe-edge, knob) on clearance
292
- // insets (iOS notch/home indicator); past exact-height system BARS (Android status/nav bar) the
293
- // knob ADDS instead. Knob defaults: 12 top, 8 bottom, 16 horizontal (the page gutter):
294
- // "comfort-top" | "comfort-bottom" | "comfort-left" | "comfort-right"
295
- // "comfort-x" — px/mx | "comfort-y" — py/my | "comfort-all" — p / m
296
- // Accepted on per-side padding & margin, position offsets (top/left/bottom/right), and inside calc()/min()/max():
297
- .style({ pb: "comfort-bottom" }) // bottom bar: 34 over a home indicator, 56 above Android's button bar, 8 on inset-less devices
298
- .style({ px: "comfort-x" }) // page gutter that also clears the notch in landscape
299
- .style({ pb: "calc(comfort-bottom + 56px)" }) // scroll content clearing a 56px floating bar
300
-
301
- // --- Theme variables ---
302
- // theme({...}) merges app vars into one table; styles read them with "var(--name)" (numbers are px
303
- // lengths, null removes a key). Re-calling re-styles the LIVE UI — dark mode is a second call.
304
- // ONE call per app. Returned accessors ARE the var() strings:
305
- const T = theme({ accent: "#0A84FF", "comfort-left": 20 })
306
- label.style({ color: T.accent, pl: "var(--comfort-left)" })
307
- // ROLES — keys the SDK reads itself; use them as your palette and add your own keys beside them:
308
- // bg (every screen's background) · surface (cards, bars; the tab bar) · border (hairlines)
309
- // text (text with no color of its own) · textMuted (secondary; inactive tabs) · accent (active tab)
310
- // fontFamily (text with no font of its own). Light theme = set text once, not a color per label.
311
- // SCOPE: el.theme({...}) — the same keys for ONE subtree (a card, tabs.bar, a whole screen); its
312
- // descendants read them first. A pushed screen / a widget is its own root: give it its own.
313
- // Bare comfort-* tokens apply the safe-area formula; "var(--comfort-top)" reads the raw knob.
314
- // "var(--name, fallback)" applies the fallback while the key is unset. Env names (safe-*, vw/vh) are not theme keys.
315
-
316
- // --- Style classes ($name) — the ONLY state mechanism; they CASCADE ---
317
- // A $-prefixed key in .style() declares a style state (yours: selected, checked, expanded);
318
- // duration/delay/easing inside the block animate the swap. Drive yours via el.class:
319
- const item = UIButton(UIText("Wi-Fi")).style({ bgColor: "#151515", $selected: { bgColor: "#1d2b45", duration: 150 } })
320
- item.onClick(ev => ev.target.class.selected = !ev.target.class.selected)
321
- // el.class.selected reads/writes a boolean; el.class({ a: true, b: false }) is the chainable batch
322
- // form; names work with or without the $. Class state persists across screen close/reopen.
323
- // CASCADE: a class set on an element also activates same-name $ blocks on ALL its descendants —
324
- // one toggle restyles a whole composite control, each part declaring its own reaction:
325
- UIButton(
326
- UIImage(icon).style({ tintColor: "#888", $selected: { tintColor: "#5b8cff" } }),
327
- UIText("Label").style({ color: "#888", $selected: { color: "#5b8cff" } }),
328
- ) // .class.selected = true → icon AND label restyle (the cascade stops at hosted screens/widgets)
329
- // RESERVED — the system toggles them, el.class.pressed = … throws:
330
- // $hovered / $pressed / $focused (mouse over / finger down / input focused) cascade to children but STOP at
331
- // a nested UIButton — a button inside a pressed card is not pressed;
332
- // $landscape / $portrait — GLOBAL, from the display size (the swap on rotation is instant).
333
- UIButton(UIText("Buy").style({ $pressed: { color: "#999" } })).style({ $hovered: { opacity: 0.9 }, $pressed: { transform: "scale(0.97)" } })
334
- screen.style({ flexDirection: "column", p: 16, $landscape: { flexDirection: "row", p: 32 } })
335
- // Precedence on the same prop: base < $landscape/$portrait < $classes < $hovered < $pressed < $focused.
336
-
337
- // --- Defaults that surprise ---
338
- // flexShrink: 0 — elements don't shrink to fit (exception: UIScrollable, UIVirtualizedList and UIPager
339
- // default flexShrink: 1 so they shrink/scroll instead of overflowing; wrapping ancestors still default to 0).
340
- // flexGrow: 0 — nothing grows along the main axis without asking; no implicit min-sizes either.
341
- // alignItems: "stretch" — children FILL the cross axis by default; set a size or alignSelf to opt out.
342
- // overflow: "hidden" — children are clipped to the parent's box; set overflow: "visible" to let them escape.
343
- // boxSizing: "border-box" — width/height include padding & border.
344
- // Screen bg is black, default text is WHITE at fontSize 14 (retarget once via theme({ bg, text, fontFamily })).
345
- // On any light surface — white cards, sheets, inputs — white text renders invisible: use dark text there
346
- // ("#111"/black), checking every UIText against the surface it actually sits on, not the screen.
347
-
348
- // --- Screen size ---
349
- // Units are logical px (iOS pt / Android dp), NOT physical pixels — fontSize: 16 looks the same on every device.
350
- // Design for a phone canvas: width ~360–430 (use 390 as default), height ~670–930.
351
- // Vertical space is scarce — SE-class screens run ~670, so long content goes in a UIScrollable body (screens never scroll).
352
-
353
- // ===== REUSABLE COMPONENTS =====
354
- // Extract repeated UI into factory functions — they return elements you can chain methods on:
355
-
356
- const ClickableCard = (title: string, subtitle: string) => UIButton(
357
- UIText(title).style({ fontWeight: 700, color: "white" }),
358
- UIText(subtitle).style({ color: "#888", fontSize: 13 })
359
- ).style({ px: 16, py: 12, gap: 4, flexDirection: "column", alignItems: "flex-start" })
360
-
361
- // Use like any other element — chain after the call:
362
- ClickableCard("Title", "Subtitle").style({ bgColor: "#111" }).onClick(() => ...)
363
-
364
- // For shared styles use Style<T>:
365
- const headingStyle: Style<UIText> = { color: "#ffffff", fontSize: 24, fontWeight: 700 }
366
-
367
- // ===== CAPTURING ELEMENT REFERENCES =====
368
- // Use an assignment expression right in the children — standard TypeScript:
369
-
370
- let label: UIText
371
- let input: UIInput
372
-
373
- UIColumn(
374
- label = UIText("Hello"), // = both assigns the variable AND adds the element to the column
375
- input = UIInput(),
376
- )
377
-
378
- // Later:
379
- label.text = "Updated"
380
- input.value // read current value
381
-
382
- // Prefer captured refs over .children[] — refs are typed; children entries need a cast
383
- // ((button.children[0] as UIText).text vs buttonText.text).
384
-
385
- // ===== CONDITIONAL CHILDREN =====
386
- // A null / undefined / false child is skipped — no element, no layout slot.
387
- UIColumn(header, isLoading ? spinner : null, showFooter && footer)
388
- // Works for whole blocks too — a falsy argument is skipped, an array argument is flattened:
389
- UIColumn(header, showList && items.map(Row))
390
-
391
- // ===== SIZING: the two axes behave differently =====
392
- // MAIN axis (row → width, column → height): elements stay as small as their content — nothing grows
393
- // without flexGrow: 1 (no implicit min-sizes).
394
- // CROSS axis: children fill the parent by default (alignItems defaults to "stretch"); set an explicit size
395
- // or alignSelf to opt out.
396
- // So UIRow(UIInput()) leaves the input at placeholder width — give it flexGrow: 1 to fill the row.
397
- // EQUAL-width children (tab bars, button pairs): flex: 1 on each — it grows from a ZERO basis, so they end up
398
- // equal. flexGrow: 1 alone splits only the LEFTOVER space on top of content-sized bases — the child with the
399
- // longer label stays wider.
400
- // Prefer giving UIInput and UIButton an explicit height — on their own they're only as tall as their text.
401
-
402
- // ===== ELEMENT DIMENSIONS =====
403
- // Sizes exist only after layout — no synchronous el.width getter.
404
- // .onLayout(cb) — react to the element's measured box. Fires on first layout and whenever the
405
- // box changes (resize, content change).
406
- // layout: { width, height, top, left } // logical px; top/left RELATIVE TO THE PARENT
407
- UIButton().onLayout(({ width }) => { buttonWidth = width })
408
- // .getBoundingClientRect() — ABSOLUTE device-space rect on demand, like the web API: the same
409
- // space UIWidget top/left position in, scroll offsets included. null before mount.
410
- // { x, y, left, top, right, bottom, width, height }
411
- // For dropdown/context menus DON'T hand-roll with this — UIPopover.show(anchor) does the whole
412
- // anchoring (placement, flip, clamp, attach). Reach for the raw rect only for custom positioning.
413
- // Position once at an interaction — never poll per frame.
414
-
415
- // ===== ROUTER (multi-page apps) =====
416
- // Tabs are UITabs' job, in-tab stacks UIPager's (see UI COMPONENTS) — the Router owns what sits ABOVE the shell.
417
- Router.init(homeScreen, opts?: { showDefaultBackButton?: boolean }) // call once in the entry file (default false)
418
- Router.push(screen, opts?: { transition, popTransition }) // push onto the stack, screen becomes active (default "push")
419
- Router.pop(to?: number, opts?: { transition })
420
- // default -1 = one back; negative = relative (-2 = back two), 0/positive = absolute
421
- // stack index (0 = home). Popped screens' native trees are destroyed; the UIScreen
422
- // object stays reusable (push remounts it). Plays the way back the screen remembers.
423
- Router.replace(screen, opts?: { transition, popTransition }) // swap the top screen (default "none"; theme({ replaceTransition }))
424
- Router.current // the active UIScreen (getter)
425
- Router.hide(opts?) / Router.restore(opts?) // hide/restore the whole router — stack stays alive; fires the top screen's onClose/onOpen
426
- // TRANSITIONS — every call above, and open() / close() of any destination, takes { transition }:
427
- // a name: "push" | "pop" | "slide-from-left" | "slide-from-right" | "slide-from-top" | "slide-from-bottom" |
428
- // "zoom" | "zoom-in" | "zoom-out" | "fade" | "none"
429
- // or your own: { enter?: pose, exit?: pose, onTop?: "enter" | "exit" } — the incoming screen comes FROM `enter`,
430
- // the outgoing one goes TO `exit`. pose = { transform?, opacity?, dim?, duration? (ms, 300), delay?, easing? };
431
- // arrays are keyframes; in a pose a % in translate is a percent of the screen ("translateY(100%)").
432
- // e.g. Router.push(page, { transition: { enter: { transform: "translateY(100%)", duration: 400 }, exit: { dim: 0.3 } } })
433
- // popTransition = the way BACK the screen remembers (Router.pop(), the back gesture, the system's back play it).
434
- // Default: the transition it came with, the other way round (a slide from the bottom leaves downwards;
435
- // a zoom / a fade go back with a fade). A replace without one keeps the way back of the screen it replaces.
436
- // A screen's own transform / opacity are not seen while a transition moves it — style a child instead.
437
- Router.addEventListener("change", (screen: UIScreen) => ...) / .removeEventListener("change", cb) // after every navigation
438
- // Screens BELOW the top stay mounted — element trees and state survive, they're just not rendered.
439
- // push fires the outgoing screen's onClose + the incoming one's onOpen; pop fires them in reverse and
440
- // re-fires onOpen on the screen you land on.
441
-
442
- // ===== FONTS =====
443
- // System fonts need no setup — use as fontFamily directly: "serif", "sans-serif", "monospaced".
444
- // Custom fonts: the font() compile macro installs a font AND returns its family name. No loading
445
- // code, no promises, no gating — just build the UI; the host has the faces ready at first paint.
446
- theme({ fontFamily: font("manrope") }) // app-wide default text font
447
- UIText("Big").style({ fontFamily: font("unbounded"), fontSize: 32 }) // or per node
448
- font("ibm-plex-sans", { weights: [400, 600], italic: true }) // narrow/extend the installed faces
449
- // Default weights are ~400/500/700 — install the weights you use (fontWeight: 600 wants a 600 face).
450
- // The argument must be a string literal. Registry ids (all OFL, cyrillic-capable unless noted):
451
- // sans: inter manrope golos-text onest rubik nunito montserrat ibm-plex-sans pt-sans jost exo-2
452
- // display: unbounded russo-one oswald comfortaa space-grotesk(latin only)
453
- // serif: playfair-display lora pt-serif cormorant literata
454
- // mono: jetbrains-mono fira-code ibm-plex-mono handwriting: caveat pacifico
455
- // A project's own file: font("./fonts/Brand.ttf") → real family name read from the file itself
456
- // (weight/italic too — no options); two weight files of one family return the same name.
457
- // registerFont(family, url, {weight, style}) survives ONLY for runtime-computed URLs — rare.
458
- // The app's font: theme({ fontFamily }). A second family is set per UIText (extract a shared Style<UIText>).
459
-
460
- // ===== SVG IMAGES =====
461
- // SvgSource wraps raw SVG XML for use as an image source: UIImage(SvgSource(`<svg ...>`)).
462
- // Rendered by native nanosvg, not a browser — only basic geometry works (path, rect, circle, line, polygon,
463
- // solid fill/stroke, opacity, transform, gradients). No text, filters or CSS — they vanish on device.
464
- // Prefer a separate .svg file over inline XML — importing one yields a ready SvgSource (and gives the user a preview):
465
- import heart from './assets/heart.svg' // or inline: asset('./assets/heart.svg')
466
- UIImage(heart).style({ width: 24, height: 24, tintColor: "#666" }) // tintColor recolors the icon
467
- // Keep inline SvgSource(`...`) only for SVG generated dynamically from data.
468
-
469
- // ===== ICONS (assetIcon) =====
470
- // Use real icons instead of emoji. assetIcon("pack:name") resolves the icon at COMPILE time and
471
- // inlines it as an image source (same shape as SvgSource) — no imports, no project files, offline.
472
- // It returns an SvgSource — the same type an imported .svg and SvgSource(xml) give — so a component
473
- // that takes an icon is typed (icon: SvgSource), never (icon: string).
474
- UIImage(assetIcon("lucide:bell")).style({ width: 24, height: 24, tintColor: "#8a8f98" })
475
- // The id must be a string literal; an unknown id is a compile error (with name suggestions).
476
- // Recolor via the tintColor style or the { color } option (hex literal bakes in; expression tints).
477
- // Packs: lucide, tabler, heroicons, feather, bi, carbon, mdi, ri, solar.
478
-
479
- // ===== COMMON MISTAKES — DO NOT DO THESE =====
480
-
481
- // ❌ CSS that doesn't exist here
482
- display: "grid" // WRONG — Flexbox only (Yoga)
483
- calc(100% - 20px) // WRONG — calc() can't mix with %
484
- lineHeight: 1.5 // WRONG — number is px (=1.5px); for a multiplier use "1.5em"
485
-
486
- // ❌ touch handler on a non-touch element
487
- UIColumn(...).onTouchStart(cb) // WRONG — only UIButton/UIScreen/UIWidget; wrap in UIButton
488
-
489
- // ❌ let/const among the children — `let` is a statement, not an expression
490
- UIRow(let input = UIInput()) // WRONG
491
- // ✅ declare outside, assign inside (assignment both sets the var AND appends)
492
- let input: UIInput
493
- UIRow(input = UIInput())
494
-
495
- // ❌ setting a UIImage's content through bgImage
496
- const img = UIImage("") // WRONG — empty source as a placeholder
497
- img.style.bgImage = url // WRONG — bgImage is a container background, not image content
498
- // ✅ pass the source to the constructor, or swap it via .src
499
- const img = UIImage(url)
500
- img.src = newUrl // updates the displayed image
501
-
502
- // ❌ expecting an input to fill width like in CSS
503
- UIRow(UIInput()) // WRONG — collapses to placeholder width
504
- // ✅ stretch it explicitly
505
- UIColumn(UIInput().style({ width: "100%" })) // cross axis
506
- UIRow(input = UIInput().style({ flexGrow: 1 }), sendBtn) // main axis
507
-
508
- // ❌ a button that should match the input's height but shrinks to its text
509
- UIRow(input.style({ height: 40 }), UIButton()) // button ends up shorter
510
- // ✅ give controls the same explicit height
511
- UIRow(input.style({ height: 40 }), UIButton().style({ height: 40 }))
512
-
513
- // ❌ flexGrow: 1 for equal-width children — it splits only the LEFTOVER space, bases stay content-sized
514
- UIRow(yes.style({ flexGrow: 1 }), no.style({ flexGrow: 1 })) // longer label = wider button
515
- // ✅ flex: 1 — grows from a zero basis, children end up equal
516
- UIRow(yes.style({ flex: 1 }), no.style({ flex: 1 }))
517
-
518
- // ❌ empty containers as spacers to align children (web habit)
519
- UIRow(UIColumn().style({ flexGrow: 1 }), label) // WRONG
520
- // ✅ alignment is a CONTAINER property, not an extra element
521
- UIRow(label).style({ justifyContent: "flex-end" })
522
-
523
- // ❌ empty element as a placeholder for a conditional child
524
- UIRow(isGroup ? button : UIColumn()) // WRONG
525
- // ✅ null is skipped in children — no phantom element
526
- UIRow(isGroup ? button : null)
527
-
528
- // ❌ callback-first edge callbacks on UIVirtualizedList
529
- list.onEndReached(loadNextPage) // WRONG — threshold is the first argument, and required
530
- // ✅ threshold (px from the edge) first
531
- list.onEndReached(600, loadNextPage)
532
-
533
- // ❌ re-creating a UIWidget or UIVirtualizedList to "re-render"
534
- const openSheet = () => UIWidget(...).show() // WRONG — leaks a new widget every call
535
- // ✅ create once at module scope; show()/hide() the widget, setData/append/update the list
536
-
537
- // ===== EXAMPLES =====
538
-
539
- // === EXAMPLE 1: Single-file app ===
540
- <file name="main.ts">
541
- let text: UIText
542
- const screen = UIScreen(
543
- text = UIText("Hello, world!").style({ mb: 16, fontWeight: 700, fontSize: 24, textAlign: "center" }),
544
- UIText("Your name:").style({ textAlign: "center" }),
545
- UIInput()
546
- .style({ bgColor: "white", height: 40, px: 8, borderRadius: 8, color: "black" })
547
- .onChange(str => {
548
- text.text = `Hello, ${str}!`
549
- })
550
- ).style({ justifyContent: "center", p: 20, gap: 8 })
551
-
552
- screen.open()
553
- </file>
554
-
555
- // === EXAMPLE 2: Theme tokens + fetched list with loading / error states ===
556
- // A tokens module every screen imports, light-themed. ONE theme() call: the roles (bg, surface,
557
- // border, text, textMuted, accent) color the screens, the default text and the tab bar — no
558
- // color: "#111" on every label — and the app's own keys sit beside them.
559
- <file name="tokens.ts">
560
- // Accessors ARE "var(--x)" strings — re-calling theme() with new values restyles the live app.
561
- export const colors = theme({
562
- bg: "#F4F6F5", surface: "#FFFFFF", border: "#E4E8E6",
563
- text: "#131A17", textMuted: "#606B65", accent: "#15A34A",
564
- accentSoft: "#E7F6ED", onAccent: "#FFFFFF",
565
- })
566
- export const font = { // type scale — spread into styles: .style({ ...font.h2 })
567
- h2: { fontSize: 22, fontWeight: 700 }, bodyStrong: { fontSize: 16, fontWeight: 600 },
568
- small: { fontSize: 14 }, tiny: { fontSize: 12, fontWeight: 500 },
569
- }
570
- </file>
571
- <file name="main.ts">
572
- import { colors, font } from './tokens'
573
-
574
- type User = { id: number; name: string; email: string }
575
-
576
- const Row = (u: User) => UIRow(
577
- UIColumn(UIText(u.name[0]).style({ ...font.bodyStrong, color: colors.accent }))
578
- .style({ width: 44, height: 44, borderRadius: 22, bgColor: colors.accentSoft,
579
- justifyContent: "center", alignItems: "center" }),
580
- UIColumn(
581
- UIText(u.name).style({ ...font.bodyStrong }),
582
- UIText(u.email).style({ ...font.small, color: colors.textMuted }),
583
- ).style({ flexGrow: 1, flexShrink: 1, gap: 2, alignItems: "flex-start" }),
584
- ).style({ alignItems: "center", gap: 12, bgColor: colors.surface, borderRadius: 16,
585
- border: `1px solid ${colors.border}`, p: 14 })
586
-
587
- const Centered = (...children: UINodeChild[]) =>
588
- UIColumn(children).style({ flexGrow: 1, justifyContent: "center", alignItems: "center", gap: 12 })
589
-
590
- let body: UIColumn
591
-
592
- const loadData = async () => {
593
- body.setContent([Centered(UIText("Loading…").style({ color: colors.textMuted }))])
594
- const res = await fetch("https://jsonplaceholder.typicode.com/users")
595
- if (res.status !== 200) {
596
- body.setContent([Centered(
597
- UIText("Couldn't load users"),
598
- UIButton(UIText("Retry").style({ color: colors.onAccent, fontWeight: 600 }))
599
- .style({ height: 44, px: 24, borderRadius: 12, bgColor: colors.accent })
600
- .onClick(() => loadData()),
601
- )])
602
- return
603
- }
604
- body.setContent(res.json<User[]>().map(Row)) // res.json is sync — no await
605
- }
606
-
607
- const screen = UIScreen(
608
- UIText("Users").style({ ...font.h2, pb: 8, px: 16 }),
609
- UIScrollable(
610
- body = UIColumn().style({ flexGrow: 1, gap: 8 })
611
- ).style({ flexGrow: 1, p: 16, pt: 0 }) // the ONE scrolling body — the screen itself never scrolls
612
- .onRefresh(() => loadData()), // pull-to-refresh; attached before screen.open()
613
- ).style({ bgColor: colors.bg, pt: "comfort-top" })
614
- .onOpen(() => loadData())
615
-
616
- screen.open()
617
- </file>
618
-
619
- // === EXAMPLE 3: Tabbed app — UITabs, font(), in-tab detail ===
620
- <file name="home.ts">
621
- const detailScreen = (name: string) => UIScreen(
622
- UIButton(
623
- UIImage(assetIcon("lucide:chevron-left")).style({ width: 20, height: 20, tintColor: "white" }),
624
- UIText("Back")
625
- ).style({ alignSelf: "flex-start", height: 32, gap: 4 }).onClick(() => UIPager.pop()),
626
- UIText(name).style({ fontSize: 24, fontWeight: 700 }),
627
- UIButton(
628
- UIImage(assetIcon("lucide:heart")).style({ width: 18, height: 18, tintColor: "#8a919e", $fav: { tintColor: "#ff453a" } }),
629
- UIText("Favorite").style({ color: "#8a919e", $fav: { color: "#ff453a" } })
630
- ).style({ name: "fav", alignSelf: "flex-start", height: 36, px: 12, gap: 6, borderRadius: 18, bgColor: "#17181c", $fav: { bgColor: "#2a181a", duration: 150 } })
631
- .onClick(ev => ev.target.class.fav = !ev.target.class.fav) // one toggle — the $fav blocks on icon + label light up too (cascade)
632
- ).style({ p: 16, pt: "comfort-top", gap: 16, bgColor: "black" })
633
-
634
- const Item = (name: string) => UIButton(UIText(name).style({ color: "white" }))
635
- .style({ height: 52, px: 16, justifyContent: "flex-start", borderRadius: 12, bgColor: "#151515", $pressed: { opacity: 0.7 } })
636
- .onClick(() => UIPager.push(detailScreen(name))) // in-tab push: tab bar stays, back-swipe pops
637
-
638
- export const homeScreen = UIScreen(
639
- UIText("Home").style({ fontSize: 28, fontWeight: 700, fontFamily: font("unbounded") }), // display face
640
- UIScrollable(["Alpha", "Beta", "Gamma"].map(Item)).style({ flexGrow: 1, gap: 8 })
641
- ).style({ p: 16, pt: "comfort-top", gap: 16, bgColor: "black" })
642
- </file>
643
- <file name="profile.ts">
644
- export const profileScreen = UIScreen(
645
- UIText("Profile").style({ fontSize: 28, fontWeight: 700, fontFamily: font("unbounded") })
646
- ).style({ p: 16, pt: "comfort-top", bgColor: "black" })
647
- </file>
648
- <file name="main.ts">
649
- import { homeScreen } from './home'
650
- import { profileScreen } from './profile'
651
-
652
- theme({ fontFamily: font("manrope") }) // app-wide default text font — one line, no loading code
653
-
654
- const tabs = UITabs({
655
- home: { label: "Home", icon: assetIcon("lucide:house"), screen: homeScreen },
656
- profile: { label: "Profile", icon: assetIcon("lucide:user"), screen: profileScreen },
657
- })
658
- tabs.badge("profile", true) // notification dot on the tab
659
- Router.init(tabs)
660
- </file>
661
-
662
- // === EXAMPLE 4: Form — field factory, return-key chain, validation, busy submit ===
663
- // The keyboard needs NO code beyond the enterKey chain: the host scrolls the focused field into
664
- // view and handles dismissal itself.
665
- <file name="main.ts">
666
- // Field anatomy: label above, styled input, a RESERVED message line below (minHeight — an
667
- // appearing error never jumps the form). Typing in an errored field clears it.
668
- const Field = (label: string, style: Style<UIInput> = {}) => {
669
- const input = UIInput().style({ height: 50, px: 14, borderRadius: 12, bgColor: "#161A22",
670
- border: "1px solid #262C3A", color: "white", placeholderColor: "#5A6272",
671
- $focused: { borderColor: "#4C8DFF" }, ...style })
672
- const message = UIText("").style({ fontSize: 13, minHeight: 18, color: "#FF6B6B" })
673
- input.onChange(() => message.text = "")
674
- return {
675
- node: UIColumn(
676
- UIText(label).style({ fontSize: 13, fontWeight: 600, color: "#8A93A6" }),
677
- input, message,
678
- ).style({ gap: 6 }),
679
- input,
680
- error: (text: string) => { message.text = text },
681
- }
682
- }
683
-
684
- const name = Field("Name", { placeholder: "Jane Appleseed", autocapitalize: "words" })
685
- const email = Field("Email", { type: "email", placeholder: "you@example.com" })
686
- const password = Field("Password", { type: "password" })
687
-
688
- // The return key walks the form; the last field submits. This is ALL the keyboard code.
689
- name.input.style({ enterKey: "next" }).onSubmit(() => email.input.focus())
690
- email.input.style({ enterKey: "next" }).onSubmit(() => password.input.focus())
691
- password.input.style({ enterKey: "go" }).onSubmit(() => submit())
692
-
693
- let btnLabel: UIText
694
- let busy = false
695
-
696
- // The submit button is never disabled — a tap on a bad form PAINTS the errors and focuses the
697
- // first offender, which beats a dead button that explains nothing. `busy` swallows double-taps.
698
- const submit = async () => {
699
- if (busy) return
700
- let bad: ReturnType<typeof Field> | null = null // checked bottom-up, so `bad` ends at the FIRST invalid field
701
- if (password.input.value.length < 8) { password.error("At least 8 characters"); bad = password }
702
- if (!email.input.value.includes("@")) { email.error("Enter a valid email"); bad = email }
703
- if (name.input.value.trim() === "") { name.error("Name is required"); bad = name }
704
- if (bad) { bad.input.focus(); return }
705
- busy = true
706
- btnLabel.text = "Creating…"
707
- const res = await fetch("https://api.example.com/register", {
708
- method: "POST", headers: { "Content-Type": "application/json" },
709
- body: JSON.stringify({ name: name.input.value.trim(), email: email.input.value, password: password.input.value }),
710
- })
711
- busy = false
712
- btnLabel.text = "Create account"
713
- if (res.status !== 200) { email.error("Registration failed — try again"); return }
714
- toast("Welcome!")
715
- }
716
-
717
- const screen = UIScreen(
718
- UIScrollable( // no fixed chrome — the keyboard leaves ~460px of screen and a form wants all of them
719
- UIText("Create account").style({ fontSize: 28, fontWeight: 700, mb: 12 }),
720
- name.node, email.node, password.node,
721
- UIButton(btnLabel = UIText("Create account").style({ fontSize: 16, fontWeight: 700 }))
722
- .style({ name: "submit", height: 52, borderRadius: 14, bgColor: "#4C8DFF", mt: 8, $pressed: { opacity: 0.85 } })
723
- .onClick(() => submit())
724
- ).style({ flexGrow: 1, px: 20, pt: "comfort-top", pb: 28, gap: 8 })
725
- ).style({ bgColor: "#0C0F14" })
726
-
727
- screen.open()
728
- </file>
729
-
730
- // === EXAMPLE 5: UIBottomSheet — persistent map-style sheet with detents ===
731
- <file name="main.ts">
732
- type Place = { id: number; name: string; distance: string }
733
- const places: Place[] = [
734
- { id: 1, name: "Blue Bottle Coffee", distance: "120 m" },
735
- { id: 2, name: "City Library", distance: "400 m" },
736
- { id: 3, name: "Riverside Park", distance: "1.2 km" },
737
- ]
738
-
739
- const Row = (p: Place) => UIRow(
740
- UIText(p.name).style({ color: "#111", fontSize: 16 }),
741
- UIText(p.distance).style({ color: "#888", fontSize: 14 })
742
- ).style({ px: 16, height: 52, alignItems: "center", justifyContent: "space-between" })
743
-
744
- const sheet = UIBottomSheet(
745
- UIColumn().style({ width: 50, height: 6, borderRadius: 3, bgColor: "#D9D9D9", mx: "auto", my: 12 }),
746
- UIText("Nearby").style({ px: 16, fontWeight: 700, fontSize: 20, mb: 8, color: "black" }),
747
- UIScrollable(places.map(Row)).style({ flexGrow: 1 }) // scrolls at the top detent, drags the sheet below it
748
- )
749
- .style({ bgColor: "white", borderRadius: 20, overlayColor: null }) // no scrim — the map stays interactive
750
- .detents([0.25, 0.6, 1]) // collapsed / half / full
751
- .dismissible(false) // drag below the lowest detent collapses, never closes
752
- .onDetent(i => console.log("detent", i))
753
-
754
- const mapScreen = UIScreen(
755
- // the map / page content behind the sheet
756
- ).onOpen(() => sheet.show()).onClose(() => sheet.hide())
757
-
758
- mapScreen.open()
759
-
760
- // An action sheet is even less: content-sized, no detents() — UIBottomSheet(rows).show(),
761
- // scrim and drag-down-to-dismiss included.
762
- </file>
763
-
764
- // === EXAMPLE 6: UIVirtualizedList — chat (inverted, imperative append) ===
765
- <file name="main.ts">
766
- type Msg = { id: string; text: string; mine: boolean }
767
-
768
- let nextId = 0
769
- const idOf = () => String(++nextId)
770
-
771
- // The list owns the rows imperatively — never re-create it, never map() over data into it.
772
- const list = UIVirtualizedList<Msg>({
773
- keyOf: m => m.id,
774
- estimatedHeight: m => 44 + Math.ceil(m.text.length / 34) * 20,
775
- inverted: true, // newest at the bottom
776
- render: m => UIRow(
777
- UIRow(
778
- UIText(m.text).style({ color: m.mine ? "white" : "#111" })
779
- ).style({
780
- bgColor: m.mine ? "#FF4032" : "#EEE",
781
- px: 12, py: 8, borderRadius: 16, maxWidth: "75%"
782
- })
783
- ).style({ px: 12, py: 4, justifyContent: m.mine ? "flex-end" : "flex-start" })
784
- }).style({ flexGrow: 1 })
785
-
786
- let input: UITextArea
787
- let sendBtn: UIButton
788
-
789
- const send = () => {
790
- const text = input.value.trim()
791
- if (!text) return
792
- list.append({ id: idOf(), text, mine: true }) // O(1); inverted list auto-scrolls to it
793
- input.value = ""
794
- sendBtn.style.opacity = 0.4
795
- }
796
-
797
- const screen = UIScreen(
798
- list,
799
- UIRow(
800
- input = UITextArea().style({ placeholder: "Message...", placeholderColor: "#999",
801
- color: "#111", flexGrow: 1, flexShrink: 1, px: 16, py: 10, bgColor: "#F0F0F0", borderRadius: 20, maxHeight: 110,
802
- keyboardDismiss: false
803
- }),
804
- sendBtn = UIButton(UIImage(assetIcon("lucide:arrow-up")).style({ width: 20, height: 20, tintColor: "white" }))
805
- .style({ width: 40, height: 40, borderRadius: 20, bgColor: "#FF4032", opacity: 0.4 })
806
- .onClick(send)
807
- ).style({ p: 8, pb: "comfort-bottom", gap: 8, alignItems: "flex-end" })
808
- ).style({ bgColor: "white" })
809
-
810
- input.onChange(v => { sendBtn.style.opacity = v.trim() ? 1 : 0.4 }) // direct style write — the hot-path form
811
-
812
- screen.open()
813
- </file>