lecodes-sdk 0.20.0 → 0.20.2
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.
- package/dist/global.d.ts +31 -0
- package/dist/inject.js +361 -260
- package/dist/types/audio/Bus.d.ts +45 -0
- package/dist/types/audio/Sound.d.ts +28 -0
- package/dist/types/audio/Voice.d.ts +27 -0
- package/dist/types/audio/audio.d.ts +83 -0
- package/dist/types/audio/support.d.ts +1 -0
- package/dist/types/gl/AudioSource.d.ts +60 -0
- package/dist/types/gl/AudioZone.d.ts +32 -0
- package/dist/types/gl/DecalSet.d.ts +103 -0
- package/dist/types/gl/Geometry.d.ts +5 -0
- package/dist/types/gl/Light.d.ts +7 -0
- package/dist/types/gl/Material.d.ts +86 -2
- package/dist/types/gl/Mesh.d.ts +11 -0
- package/dist/types/gl/Scene.d.ts +23 -0
- package/dist/types/gl/SceneAudio.d.ts +11 -0
- package/dist/types/gl/Texture.d.ts +29 -1
- package/dist/types/gl/animation/AnimationClip.d.ts +25 -12
- package/dist/types/gl/animation/core.d.ts +15 -10
- package/dist/types/gl/state.d.ts +0 -1
- package/dist/types/inject.d.ts +10 -0
- package/dist/types/runtime/input.d.ts +11 -0
- package/dist/types/ui/UIImage.d.ts +15 -5
- package/dist/types.json +1 -1
- package/package.json +1 -1
- package/prompts/dist/2d-game.md +408 -197
- package/prompts/dist/3d-app.md +491 -166
- package/prompts/dist/ar-app.md +373 -163
- package/prompts/dist/design.md +83 -87
- package/prompts/dist/ui-app.md +325 -136
- package/src/audio/Bus.ts +102 -0
- package/src/audio/Sound.ts +96 -0
- package/src/audio/Voice.ts +102 -0
- package/src/audio/audio.ts +161 -0
- package/src/audio/support.ts +6 -0
- package/src/bridges.d.ts +1481 -1352
- package/src/compile/compileProject.ts +30 -15
- package/src/compile/index.ts +3 -0
- package/src/core/Aspect.ts +33 -8
- package/src/g2/Scene2D.ts +7 -0
- package/src/gl/AudioSource.ts +113 -0
- package/src/gl/AudioZone.ts +75 -0
- package/src/gl/CameraPlace.ts +52 -52
- package/src/gl/DecalSet.ts +233 -0
- package/src/gl/Geometry.ts +5 -0
- package/src/gl/Light.ts +16 -0
- package/src/gl/Lightmap.ts +3 -2
- package/src/gl/Material.ts +152 -4
- package/src/gl/Mesh.ts +20 -1
- package/src/gl/Ragdoll.ts +270 -270
- package/src/gl/Scene.ts +41 -7
- package/src/gl/SceneAudio.ts +26 -0
- package/src/gl/Texture.ts +43 -3
- package/src/gl/Trigger.ts +45 -45
- package/src/gl/Vehicle.ts +5 -5
- package/src/gl/animation/AnimationClip.ts +43 -20
- package/src/gl/animation/Animator.ts +4 -3
- package/src/gl/animation/core.ts +20 -15
- package/src/gl/scenarios.ts +291 -291
- package/src/gl/state.ts +1 -1
- package/src/inject.ts +12 -0
- package/src/runtime/input.ts +6 -1
- package/src/scene/gizmos.ts +148 -148
- package/src/ui/UIImage.ts +21 -7
package/prompts/dist/3d-app.md
CHANGED
|
@@ -102,6 +102,16 @@ After every edit you make, the platform automatically verifies it — syntax, a
|
|
|
102
102
|
|
|
103
103
|
A `[Selected element]` section describes a UI element the user picked in the running app's preview — its type, text, current style, and "created at" (the code that creates it). Apply the request to exactly that element, starting from the created-at location.
|
|
104
104
|
|
|
105
|
+
## Building from a design
|
|
106
|
+
|
|
107
|
+
A `design/` folder is the app's finished design, made on the design board: `screens/<id>.ts` — one static mockup per screen, its states a function of a state-string union; `shared/tokens.ts` — the brand as a `theme()` table; `shared/ui.ts` — the component kit; `shared/tabs.ts` — the tab bar (`defineTabs`); `meta.json` — screen descriptions, roles, groups, and the navigation edges between screens; `spec.md` — the data model, actors, and rules. When asked to build or implement the app (or a screen) from it, the design is the authority:
|
|
108
|
+
|
|
109
|
+
- Implement every designed screen, including each state in its union. Navigation follows `meta.json` edges (an `id@state` edge switches that screen's state, not a push) and the tab bar in `shared/tabs.ts` — its `defineTabs({...})` entries carry over 1:1 into `UITabs({...})` (same keys, labels, and icons; add each tab's root `screen`), which renders the identical bar.
|
|
110
|
+
- IMPORT the kit, don't restyle: app code imports `design/shared/tokens.ts` (its `theme()` call makes design and app one live theme) and the presentational components of `design/shared/ui.ts`. Rebuild only the mock-only pieces (static field mocks, fake keyboards) as real interactive equivalents with the exact same look.
|
|
111
|
+
- The mock data at the top of each screen is the schema draft: replace it with real state, storage, and logic per `spec.md`, keeping the field shapes.
|
|
112
|
+
- App screens are your own files (`main.ts` + the usual project layout) — never import `design/screens/*` into the app, and never write into `design/**`: the design stays the reference. If the design itself needs changing, say so and suggest `<mode>design</mode>`.
|
|
113
|
+
- Match the mockups; don't re-design. Where a mockup leaves behavior undefined, `spec.md` decides; where it's silent, pick the simplest behavior consistent with the design.
|
|
114
|
+
|
|
105
115
|
## Tools
|
|
106
116
|
|
|
107
117
|
You may be given tools (they appear in the API request, each with its own description). Default to
|
|
@@ -209,16 +219,22 @@ const sfx = new AudioPlayer(src) // src: asset('./x.mp3') or URL; same API: ne
|
|
|
209
219
|
// .dispose() — frees the native player; ANY use after dispose throws
|
|
210
220
|
// No pitch control, no auto-pooling: for overlapping SFX create several players up front and rotate.
|
|
211
221
|
|
|
212
|
-
// ===== INPUT (keyboard) =====
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
//
|
|
216
|
-
|
|
217
|
-
|
|
222
|
+
// ===== INPUT (keyboard / mouse / gamepad) =====
|
|
223
|
+
// A mouse button IS a key; so is a gamepad button. One code vocabulary: KeyboardEvent.code ('KeyW',
|
|
224
|
+
// 'Space', 'ArrowLeft'), 'MouseLeft|Right|Middle', 'GamepadSouth|East|West|North|L1|R1|L2|R2|Start|…'.
|
|
225
|
+
Input.key(code): boolean // held NOW — poll in setLoop for continuous movement (multiply by dt)
|
|
226
|
+
Input.on('keydown', e => …) // one-shot actions: e.code, e.repeat (auto-repeat), e.gamepad (pad index)
|
|
227
|
+
Input.on('keyup', e => …) // release (charged shots); Input.off(name, fn) to remove
|
|
228
|
+
Input.mouse.delta // { x, y } motion during the previous frame — FPS look; works while locked
|
|
229
|
+
Input.mouse.position / .wheel // cursor in logical px / wheel notches this frame
|
|
230
|
+
Input.mouse.lock() / unlock() / locked // hide + confine the cursor (call lock() from a keydown — web needs a gesture)
|
|
231
|
+
Input.gamepad(0).axis('leftX' | 'leftY' | 'rightX' | 'rightY' | 'leftTrigger' | 'rightTrigger') // −1..1 / 0..1
|
|
218
232
|
setLoop(dt => {
|
|
219
|
-
|
|
220
|
-
|
|
233
|
+
yaw -= Input.mouse.delta.x * 0.003 + Input.gamepad(0).axis('rightX') * 2 * dt
|
|
234
|
+
const x = (Input.key('KeyD') ? 1 : 0) - (Input.key('KeyA') ? 1 : 0) + Input.gamepad(0).axis('leftX')
|
|
221
235
|
})
|
|
236
|
+
Input.on('keydown', e => { if (e.code === 'Space' || e.code === 'GamepadSouth') jump() })
|
|
237
|
+
// No one-frame "pressed" polls (keyDown/actionDown) — discrete = event, continuous = poll.
|
|
222
238
|
|
|
223
239
|
// ===== TOUCH GESTURES =====
|
|
224
240
|
// 'click' fires on pointer-up over a target; 'touchstart' on pointer-down. ev: { clientX, clientY,
|
|
@@ -266,17 +282,23 @@ implement what you can with the loaded ones.
|
|
|
266
282
|
// Canvas: Canvas (retained 2D drawing baked to a texture — sprites/UI images), Bitmap
|
|
267
283
|
// Aspects: Aspect base — attachable node capabilities: node.aspect(Class, opts), custom aspects
|
|
268
284
|
// with per-frame update(dt)
|
|
269
|
-
// UI: UIScreen, Router,
|
|
285
|
+
// UI: UIScreen, Router, UITabs (bottom-tab shell), UIPager (tabs + per-tab stacks), UIRow,
|
|
286
|
+
// UIColumn, UIScrollable, UISpacer, UIText, UIImage, UIVideo,
|
|
270
287
|
// UIButton, UIInput, UITextArea, UIWidget/UIModal/UIPopover/UIBottomSheet (floating
|
|
271
288
|
// overlays: HUD / dialog / anchored menu / draggable sheet), UIVirtualizedList,
|
|
272
289
|
// registerFont; UIBox (deprecated)
|
|
273
290
|
// 2D engine: Scene2D, Node2D, Camera2D, Sprite, SpriteAnimation, Tilemap, Texture2D,
|
|
274
291
|
// Shape2D + Physics2D + Trigger2D + CharacterController2D (Box2D physics, sensors,
|
|
275
|
-
// raycast/overlap queries, picking)
|
|
292
|
+
// raycast/overlap queries, picking),
|
|
293
|
+
// defineScene2d (declarative *.scene2d.ts files) + cells + CameraFollow
|
|
276
294
|
// 3D engine: Scene, Node, Camera, Mesh (box/sphere/cylinder/plane), Model (.glb) + ModelAnimation,
|
|
277
295
|
// Geometry, Material (lit/unlit/custom shaders), Texture, Light.sun(),
|
|
278
296
|
// Shape + Physics + Trigger + CharacterController (Jolt physics, raycast),
|
|
279
297
|
// Particles + dynamic/dynamicColor, Ray, Plane, Noise
|
|
298
|
+
// 3D scene files: defineScene (declarative *.scene.ts read/written by the visual scene editor;
|
|
299
|
+
// default export is a SceneHandle: load()/open()) + use/ref/make in the def,
|
|
300
|
+
// scenario aspects MoveTo/FollowPath/Spin/LookAt/PlayAnimation;
|
|
301
|
+
// *.editor.ts + EDITOR/InspectorUI are editor-plugin files — never edit or import them
|
|
280
302
|
// AR: ARScene (camera passthrough, anchors, placement gestures via addControls)
|
|
281
303
|
|
|
282
304
|
// ===== CANVAS — retained drawing baked to a texture (engine-independent) =====
|
|
@@ -355,15 +377,13 @@ node.lookAt(point: Vec3Like, mode = '-z', up = [0, 1, 0]): this // aim a local
|
|
|
355
377
|
// 'click' pointer-up over the node — REQUIRES a Shape aspect (pick body)
|
|
356
378
|
// 'touchstart' pointer-down over the node (ev.track() drags) — requires Shape
|
|
357
379
|
// 'enter' / 'exit' (other: Node) physics contact / trigger overlap began/ended — Shape + Physics/Trigger
|
|
358
|
-
// 'completed' (clip: number) non-looping GLB clip finished — Model only
|
|
359
|
-
// 'loopReached' (clip: number) looping GLB clip wrapped — Model only
|
|
360
380
|
// Without a Shape a node is INVISIBLE to taps — only scene listeners fire (ev.target === null).
|
|
361
381
|
|
|
362
382
|
// ===== ASPECTS =====
|
|
363
383
|
// Capabilities attach to nodes as aspects and chain; each adds a named accessor:
|
|
364
384
|
node.aspect(Class, opts?) // attach + configure; returns the node (typed with the accessor)
|
|
365
385
|
node.get(Class) / node.has(Class) / node.removeAspect(Class)
|
|
366
|
-
// Named accessors: node.physics, node.trigger, node.controller, node.shape,
|
|
386
|
+
// Named accessors: node.physics, node.trigger, node.controller, node.shape, node.anim
|
|
367
387
|
// Custom game logic = your own aspect with per-frame update(dt seconds):
|
|
368
388
|
class Spin extends Aspect<'spin', Node> { // <accessor name, node kind>
|
|
369
389
|
speed = 90 // class fields = configurable defaults (opts override)
|
|
@@ -431,24 +451,34 @@ const hero = await Model.load(asset('./hero.glb')) // asset path | https URL |
|
|
|
431
451
|
scene.add(hero) // a Model IS a Node — transform/events/aspects all apply
|
|
432
452
|
hero.traverse(n => { if (n.name === 'Sword') n.visible = false }) // GLB internals are plain child Nodes
|
|
433
453
|
|
|
434
|
-
// Animation — every Model has
|
|
435
|
-
|
|
436
|
-
hero.anim.
|
|
437
|
-
hero.anim.
|
|
438
|
-
hero.anim.
|
|
439
|
-
|
|
440
|
-
hero.anim.
|
|
441
|
-
//
|
|
442
|
-
|
|
443
|
-
hero.
|
|
444
|
-
|
|
445
|
-
//
|
|
446
|
-
|
|
447
|
-
//
|
|
448
|
-
//
|
|
449
|
-
const
|
|
450
|
-
|
|
451
|
-
|
|
454
|
+
// Animation — every Model has an Animator pre-attached at model.anim (clip list = the glb's clips). A layer
|
|
455
|
+
// has a LOOP (what it rests on) and ONE-SHOTS played over it; any call overrides what's there over its own fade:
|
|
456
|
+
hero.anim.clips / hero.anim.clip('Run') / hero.anim.clip(0) // AnimationClip[] (file order) / by name / by index; unnamed clips = 'animation_0', …
|
|
457
|
+
hero.anim.playLoop('Idle', { fade: 0.2 }) // rest on a looping clip (crossfades from whatever plays); hero.anim.loop reads it
|
|
458
|
+
const loco = hero.anim.playLoop({ Idle: 0, Walking: 2, 'Fast Run': 6 }) // a BLEND as the loop (1D; [x, y] positions = 2D)
|
|
459
|
+
loco.value = speed // position on the axis — members stay in phase (no foot sliding)
|
|
460
|
+
const ok = await hero.anim.play('slash', { fadeIn: 0.1, fadeOut: 0.3 }) // one-shot over the loop, returns to it
|
|
461
|
+
// fades default to 0 (cut): fade = both ends, fadeIn / fadeOut = one end. Unknown name warns, plays nothing.
|
|
462
|
+
// The await resolves at the HAND-OVER (end − fadeOut) with true (false = cut short) — what you start right after is what
|
|
463
|
+
// the clip fades into: chains crossfade: if (ok) await hero.anim.play('slash2', { fadeIn: 0.3, fadeOut: 0.3 })
|
|
464
|
+
// then hero.anim.playLoop('Crouch', { fade: 0.3 }) — or nothing = back to the current loop.
|
|
465
|
+
if (!hero.anim.busy) hero.anim.play('kick') // busy = a one-shot hasn't handed over; play() always takes over otherwise
|
|
466
|
+
hero.anim.stop({ fade: 0.2 }) // everything off → rest; hero.anim.busy; hero.anim.speed = 0.3 (0 = pause)
|
|
467
|
+
// p = play(): p.done (return THIS from async fns) / p.playing / p.progress / p.weight / p.stop({ fade }) / p.seek(t)
|
|
468
|
+
// Clips from other files (Mixamo: one GLB per animation), procedural, sliced — add by name:
|
|
469
|
+
const [idle, slash] = await Promise.all([AnimationClip.load(asset('./idle.glb')), AnimationClip.load(asset('./attacks.glb'), 'Slash')])
|
|
470
|
+
hero.anim.addClip('slash', slash).addClip('kick', hero.anim.clip('Kick').slice(0.2, 1.1)) // slice = a sub-range, re-timed
|
|
471
|
+
AnimationClip.from({ tracks: { Hips: { position: [[0, [0,0,0]], [1, [0,0.05,0]]] } } }) // curves in code, binds by node NAME
|
|
472
|
+
// Clip events live on the CLIP, in SECONDS: slash.addEvent(0.4, 'hit') → hero.anim.on('hit', (clip, layer) => dealDamage())
|
|
473
|
+
// Layers (legs walk, arms aim): const upper = hero.anim.addLayer({ mask: 'Spine1' }); upper.playLoop('Aim', { fade: 0.3 }); upper.stop()
|
|
474
|
+
// { additive: true } = each clip's DELTA vs its first frame on top (recoil, breathe); upper.weight = 0.5
|
|
475
|
+
// Root motion (clips whose hips travel — Mixamo without 'In Place', rolls): hero.anim.rootMotion = true → the node moves
|
|
476
|
+
// (or its CharacterController, as a velocity — it collides); the bone stays put
|
|
477
|
+
hero.bone('RightHand')?.add(sword) // bones are Nodes — sockets
|
|
478
|
+
// FBX assets (Mixamo exports FBX): `lecodes assets convert hero.fbx --clips Idle.fbx Run.fbx -o hero.glb` → one GLB, clips merged by bone name
|
|
479
|
+
// IK — late-phase aspects ON BONES (over the Animator's pose): TwoBone on the END bone, LookAt on the bone itself
|
|
480
|
+
hero.bone('LeftFoot').aspect(IK.TwoBone, { target: footPoint, pole: kneeHint }).ik.weight = grounded ? 1 : 0
|
|
481
|
+
hero.bone('Head').aspect(IK.LookAt, { target: camera, limit: 70 }) // axis = bone-local forward, default [0,0,-1]
|
|
452
482
|
|
|
453
483
|
// ===== PHYSICS (Jolt) =====
|
|
454
484
|
|
|
@@ -464,9 +494,18 @@ node.aspect(Shape, {
|
|
|
464
494
|
sphere?: number, // radius
|
|
465
495
|
cylinder?: { halfHeight: number, radius: number }, // Y-aligned
|
|
466
496
|
capsule?: { halfHeight: number, radius: number }, // halfHeight = cylinder section only
|
|
497
|
+
mesh?: true | 'convex', // the node's OWN triangles (Mesh geometry or Model GLB, × world scale)
|
|
498
|
+
origin?: Vec3Like, // collider centre, offset from the node's pivot (world units, node rotation, NOT scaled)
|
|
467
499
|
raycast?: boolean, // default true; false = invisible to taps & raycasts
|
|
468
500
|
})
|
|
501
|
+
// mesh: true = exact triangle mesh → level geometry / terrain / ramps: static or kinematic Physics, Trigger,
|
|
502
|
+
// pick bodies, character ground. NEVER dynamic (Physics throws). mesh: 'convex' = convex hull → dynamic props.
|
|
503
|
+
// A Model collider is its bind pose (skinned parts skipped) — animated characters keep a capsule.
|
|
469
504
|
node.aspect(Shape, {}) // auto: box from the mesh AABB × world scale — right for most meshes
|
|
505
|
+
// origin: art modelled ABOVE its pivot (a character on its feet, a barrel on its base) needs the
|
|
506
|
+
// collider lifted: { capsule: {…}, origin: [0, 0.9, 0] }. An auto shape already centres on its mesh.
|
|
507
|
+
node.shape.fit(kind?) // measure dimensions + origin from what the node RENDERS (subtree,
|
|
508
|
+
// so a Model root works where {} can't) and rebuild the live collider. Fit AFTER Model.load resolves.
|
|
470
509
|
// A bare Shape (no Physics) creates a STATIC pick-only body → the node gets 'click'/'touchstart'.
|
|
471
510
|
// It snapshots the transform at attach time — a MOVING pickable object needs a Physics body too.
|
|
472
511
|
|
|
@@ -476,11 +515,14 @@ node.aspect(Shape, {}).aspect(Physics, {
|
|
|
476
515
|
mass?: number, // kg, dynamic only; default 1
|
|
477
516
|
})
|
|
478
517
|
node.physics.velocity // Vec3 world units/s — get (fresh copy) / set
|
|
518
|
+
node.physics.angularVelocity // Vec3 DEGREES/s about each world axis — get / set
|
|
479
519
|
node.physics.applyImpulse(v): this // instant impulse, wakes the body
|
|
480
|
-
node.
|
|
481
|
-
|
|
482
|
-
//
|
|
483
|
-
//
|
|
520
|
+
node.position = [x, y, z] // place / teleport — moves the node AND its body (no moveTo())
|
|
521
|
+
node.eulerAngles = [0, 90, 0] // orientation is routed to the body too (NOT for a CharacterController)
|
|
522
|
+
// A teleport keeps BOTH velocities: putting an object down is velocity = 0, angularVelocity = 0, position = p
|
|
523
|
+
// PHYSICS OWNS a dynamic body's transform: a position write teleports, but the sim takes over again —
|
|
524
|
+
// drive motion with velocity / applyImpulse. READING node.position/worldPosition is always correct.
|
|
525
|
+
// static = never moves (floors, walls); kinematic = write position each frame, pushes but isn't pushed.
|
|
484
526
|
|
|
485
527
|
// Contact events — on BOTH nodes of a contact/overlap, arg = the other node:
|
|
486
528
|
crate.addEventListener('enter', (other: Node) => {})
|
|
@@ -524,7 +566,8 @@ sparks.destroy() // from Node — removes the system
|
|
|
524
566
|
|
|
525
567
|
scene.camera // a Node — never constructed; every scene owns one.
|
|
526
568
|
// (Who MOVES it is mode-specific — see the Scene/AR section.)
|
|
527
|
-
camera.fov
|
|
569
|
+
camera.fov / .near / .far // lens: vertical FOV degrees (60), clip 0.01 / 1000 — SETTABLE.
|
|
570
|
+
camera.setProjection({ fov, near, far }) // any subset; .horizontalFov, .displaySize stay read-only
|
|
528
571
|
camera.getViewDirection(screenX, screenY): Vec3 // world dir through a screen point (logical px = ev.clientX/Y)
|
|
529
572
|
camera.getRay(screenX, screenY): Ray // origin = camera.worldPosition + that direction
|
|
530
573
|
|
|
@@ -699,14 +742,129 @@ setLoop(() => {
|
|
|
699
742
|
if (Input.key('Space')) hero.controller.jump()
|
|
700
743
|
})
|
|
701
744
|
|
|
702
|
-
//
|
|
745
|
+
// HUD over the 3D view: a UIWidget ATTACHED to the scene. (A UIScreen would REPLACE the scene —
|
|
746
|
+
// exactly one Presentable is visible at a time.)
|
|
703
747
|
let scoreLabel: UIText
|
|
704
|
-
const hud =
|
|
748
|
+
const hud = UIWidget(
|
|
705
749
|
scoreLabel = UIText('Score: 0').style({ color: 'white', fontSize: 24, fontWeight: 700 }),
|
|
706
|
-
|
|
750
|
+
).style({ top: 'max(safe-top, 16px)', right: 16 })
|
|
707
751
|
|
|
708
752
|
scene.open()
|
|
709
|
-
hud.
|
|
753
|
+
hud.attachTo(scene).show()
|
|
754
|
+
</file>
|
|
755
|
+
|
|
756
|
+
## Scene files (.scene.ts)
|
|
757
|
+
|
|
758
|
+
Projects may contain `*.scene.ts` files: declarative scenes that the platform's VISUAL scene
|
|
759
|
+
editor reads and writes. The user may have built them by dragging models around — treat the file
|
|
760
|
+
as their artwork. You may edit values and add nodes/aspects, but keep the `defineScene({...})`
|
|
761
|
+
literal-object shape; an imperative rewrite (`new Scene()` + `scene.add(...)`) destroys their
|
|
762
|
+
ability to keep editing it visually. `defineScene`, `use`, `ref` and `make` are globals.
|
|
763
|
+
|
|
764
|
+
// ===== DEFINE SCENE =====
|
|
765
|
+
|
|
766
|
+
// Default-export exactly one defineScene call per .scene.ts file.
|
|
767
|
+
export default defineScene({
|
|
768
|
+
env?: SceneOptions, // same options object as `new Scene(...)` above (skybox, ibl, bloom…)
|
|
769
|
+
nodes?: {
|
|
770
|
+
name: { // names are sibling-unique, no '/' or ':' in them
|
|
771
|
+
// -- source: AT MOST ONE of these per node; none = empty group node --
|
|
772
|
+
mesh?: { kind: 'box', size?: n | [x,y,z] } | { kind: 'sphere' | 'cylinder' | 'plane', ... },
|
|
773
|
+
model?: string, // GLB via the asset macro: asset('./hero.glb')
|
|
774
|
+
light?: { kind: 'sun', direction?, intensity?, shadowsQuality? }, // 'sun' is the ONLY kind
|
|
775
|
+
camera?: { fov?, near?, far? }, // this node IS the scene camera (defaults 60 / 0.01 / 1000)
|
|
776
|
+
make?: make(factoryFn, { ...literalArgs }), // code-built subtree from a user function
|
|
777
|
+
prefab?: SceneHandle, // another .scene.ts's default export (import it)
|
|
778
|
+
// -- for a mesh source --
|
|
779
|
+
material?: { lit: { color?, metallic?, roughness? } } | { unlit: { color? } },
|
|
780
|
+
// -- transform / render --
|
|
781
|
+
position?: [x,y,z], eulerAngles?: [x,y,z], scale?: [x,y,z] | n,
|
|
782
|
+
visible?, castShadows?, receiveShadows?,
|
|
783
|
+
locked?: boolean, // editor-only flag, zero runtime effect — leave it alone
|
|
784
|
+
// -- behavior / hierarchy --
|
|
785
|
+
aspects?: [ use(AspectClass, { ...props }) ], // props may use ref('otherNode') for node refs
|
|
786
|
+
children?: { name: { ...same shape } },
|
|
787
|
+
// pose parts INSIDE a model/prefab, and attach a child node to such a part:
|
|
788
|
+
overrides?: { 'Bone/Path': { position?, eulerAngles?, scale?, visible? } },
|
|
789
|
+
mount?: 'Bone/Path', // parents this node to that part of the PARENT node's asset
|
|
790
|
+
},
|
|
791
|
+
},
|
|
792
|
+
})
|
|
793
|
+
|
|
794
|
+
// ===== USING A SCENE FROM APP CODE =====
|
|
795
|
+
|
|
796
|
+
import city from './city.scene' // extension-less specifier; default export: SceneHandle
|
|
797
|
+
|
|
798
|
+
const { scene, nodes, get } = await city.open() // load (fetches GLBs) + become the active view
|
|
799
|
+
// city.load() — instantiate without showing; both are idempotent (same instance every call)
|
|
800
|
+
nodes.crate // typed by source: model → Model, mesh → Mesh, light → Light
|
|
801
|
+
nodes['props/lamp'] // keys are absolute '/'-joined paths; get(path) for dynamic
|
|
802
|
+
nodes.crate.position = [1, 0.5, 2] // plain SDK nodes — assign vectors, or scalar axes: node.y = 2
|
|
803
|
+
nodes.hero.anim.play('walk') // a model node is a Model: animations, parts — all there
|
|
804
|
+
scene.close() // closing goes through the scene (there is NO handle.close())
|
|
805
|
+
|
|
806
|
+
// ===== BEHAVIOR & INPUT =====
|
|
807
|
+
|
|
808
|
+
// Put per-frame behavior in ASPECTS attached in the file — not in code that mutates the doc:
|
|
809
|
+
// aspects: [use(Spin, { speed: 40 })]
|
|
810
|
+
// Built-in no-code aspects: MoveTo, FollowPath ({ path: ref('waypoints'), duration }), Spin,
|
|
811
|
+
// LookAt, PlayAnimation. Custom ones are ~5 lines (see Aspects; update(dt) — dt in SECONDS):
|
|
812
|
+
export class Spinner extends Aspect<'spinner'> {
|
|
813
|
+
speed = 30 // class fields = props settable from use(...)
|
|
814
|
+
update(dt: number) { this.node.eulerAngles = [0, this.node.eulerAngles.y + this.speed * dt, 0] }
|
|
815
|
+
}
|
|
816
|
+
// Clicks/taps: a node is pickable only with a Shape aspect — aspects: [use(Shape, {})] — then
|
|
817
|
+
// nodes.crate.addEventListener('click', ev => ...). Catch-all with target (null on miss):
|
|
818
|
+
// scene.addEventListener('click', ev => ev.target). Shape alone = static pick body; moving
|
|
819
|
+
// clickables also need Physics.
|
|
820
|
+
|
|
821
|
+
// ===== UI OVER AN OPEN SCENE =====
|
|
822
|
+
|
|
823
|
+
// Exactly one Presentable is visible at a time: UIScreen(...).open() REPLACES the scene. A HUD is
|
|
824
|
+
// a UIWidget attached to the scene — it shows/hides and transitions together with it:
|
|
825
|
+
const hud = UIWidget(UIText('Score: 0').style({ color: 'white', fontSize: 24 }))
|
|
826
|
+
.style({ top: 'max(safe-top, 16px)', left: 16 })
|
|
827
|
+
hud.attachTo(scene).show()
|
|
828
|
+
|
|
829
|
+
// ===== SCENE FILE MISTAKES — DO NOT DO THESE =====
|
|
830
|
+
|
|
831
|
+
// - Rebuilding a .scene.ts imperatively, or moving its content into main.ts. Edit the def in
|
|
832
|
+
// place; logic goes into aspect classes or app code around handle.open().
|
|
833
|
+
// - scene.ref(...), handle.close(), onTap — none exist. It's nodes[path] / get(path),
|
|
834
|
+
// loaded.scene.close(), addEventListener('click').
|
|
835
|
+
// - Two source keys on one node (e.g. mesh + model) — throws at load.
|
|
836
|
+
// - Expecting clicks without use(Shape, {}) on the node.
|
|
837
|
+
// - node.position.x = 3 — silent NO-OP (position returns a copy). Assign node.x = 3 or the vector.
|
|
838
|
+
// - env HDRI paths or light kinds other than 'sun' — not supported; ibl is just a boolean.
|
|
839
|
+
|
|
840
|
+
## Scene file wiring example
|
|
841
|
+
|
|
842
|
+
// A scene built in the visual editor, wired up with a click counter and a HUD.
|
|
843
|
+
|
|
844
|
+
<file name="main.scene.ts">
|
|
845
|
+
export default defineScene({
|
|
846
|
+
env: { skybox: '#a9b6c8' },
|
|
847
|
+
nodes: {
|
|
848
|
+
camera: { camera: {}, position: [0, 4, 9], eulerAngles: [-22, 0, 0] },
|
|
849
|
+
sun: { light: { kind: 'sun', shadowsQuality: 1 } },
|
|
850
|
+
ground: { mesh: { kind: 'box', size: [12, 0.4, 12] }, material: { lit: { color: '#3d4351' } },
|
|
851
|
+
position: [0, -0.2, 0], locked: true },
|
|
852
|
+
crate: { mesh: { kind: 'box' }, material: { lit: { color: '#8a8f98' } }, position: [0, 0.5, 0],
|
|
853
|
+
aspects: [use(Shape, {}), use(Spin, { speed: 25 })] },
|
|
854
|
+
},
|
|
855
|
+
})
|
|
856
|
+
</file>
|
|
857
|
+
|
|
858
|
+
<file name="main.ts">
|
|
859
|
+
import mainScene from './main.scene'
|
|
860
|
+
|
|
861
|
+
const { scene, nodes } = await mainScene.open()
|
|
862
|
+
|
|
863
|
+
let taps = 0
|
|
864
|
+
const label = UIText('Tap the crate').style({ color: 'white', fontSize: 20, fontWeight: 700 })
|
|
865
|
+
UIWidget(label).style({ top: 'max(safe-top, 16px)', left: 16 }).attachTo(scene).show()
|
|
866
|
+
|
|
867
|
+
nodes.crate.addEventListener('click', () => { label.text = `Taps: ${++taps}` })
|
|
710
868
|
</file>
|
|
711
869
|
|
|
712
870
|
// ===== UI RULES =====
|
|
@@ -717,18 +875,22 @@ hud.open()
|
|
|
717
875
|
|
|
718
876
|
// ===== UI COMPONENTS =====
|
|
719
877
|
// Every element is created by a global factory function (never `new`) that takes only the element's
|
|
720
|
-
// CONTENT
|
|
721
|
-
// every configuring method returns the element itself, so construction reads
|
|
878
|
+
// CONTENT — children as plain arguments (or text/src/...). Everything else — styles, handlers — is
|
|
879
|
+
// configured by chaining: every configuring method returns the element itself, so construction reads
|
|
880
|
+
// as one chain.
|
|
881
|
+
UIColumn(UIText("Title"), UIButton(UIText("Go")))
|
|
882
|
+
// An ARRAY argument is flattened into the children — pass items.map(Row) directly, no spread:
|
|
883
|
+
UIColumn(header, items.map(Row), footer)
|
|
722
884
|
|
|
723
885
|
// UIRow, UIColumn — containers (UIColumn stacks vertically, UIRow horizontally)
|
|
724
|
-
UIRow(children) / UIColumn(children)
|
|
886
|
+
UIRow(...children) / UIColumn(...children)
|
|
725
887
|
// Child management — imperative, no diffing; works before and after the element is on screen:
|
|
726
888
|
// .append(...nodes), .insert(index, ...nodes), .remove(...nodes), .setContent(nodes), .children (readonly)
|
|
727
889
|
// .setContent is the "re-render" primitive — build a fresh array (items.map(Row)) and swap it in.
|
|
728
890
|
// For long or unbounded data use UIVirtualizedList instead of setContent over a big array.
|
|
729
891
|
|
|
730
892
|
// UIScreen — root screen, always fills the device. Behaves as a UIColumn.
|
|
731
|
-
UIScreen(children)
|
|
893
|
+
UIScreen(...children)
|
|
732
894
|
// .open() / .close() — show/close directly (single-screen apps; open() while a Router is active hides the router)
|
|
733
895
|
// .onOpen(cb), .onClose(cb) — fire on EVERY activation, not just the first: Router.push away fires onClose,
|
|
734
896
|
// popping back fires onOpen again. Anything started in onOpen (loops, intervals, sockets) MUST be stopped
|
|
@@ -736,12 +898,40 @@ UIScreen(children)
|
|
|
736
898
|
// .onTouchStart(cb) — fires for touches anywhere on the screen; use for full-screen gestures (see TOUCH GESTURES above)
|
|
737
899
|
// .onBackPressed(cb) — Android hardware/gesture back; typically Router.pop()
|
|
738
900
|
// Screens NEVER scroll — the canonical screen is fixed chrome (header, tab bar) + ONE UIScrollable body
|
|
739
|
-
// with flexGrow: 1: UIScreen(
|
|
901
|
+
// with flexGrow: 1: UIScreen(Header(), UIScrollable(content).style({ flexGrow: 1 }))
|
|
740
902
|
// Note: a screen always fills the device — sizing styles on it (width, height, flexGrow, flexShrink, position) are no-ops
|
|
741
903
|
|
|
904
|
+
// UITabs — THE bottom-tab app shell: swipeable tabs (a UIPager) + a themed tab bar, as one UIScreen.
|
|
905
|
+
// USE THIS for every tabbed app — never hand-build a tab bar. Keys are tab ids, in tab order:
|
|
906
|
+
const tabs = UITabs({
|
|
907
|
+
home: { label: "Home", icon: assetIcon("lucide:house"), screen: homeScreen },
|
|
908
|
+
profile: { label: "Profile", icon: assetIcon("lucide:user"), screen: profileScreen },
|
|
909
|
+
})
|
|
910
|
+
Router.init(tabs) // UITabs IS a UIScreen — present it directly
|
|
911
|
+
// .select(id), .tab (getter), .onSelect(cb(id, i)) — fires on a bar tap, swipe, or select()
|
|
912
|
+
// .badge(id, value) — true = dot, number/string = count pill, false/null/0 clears
|
|
913
|
+
// .pager — the UIPager underneath; UIPager.push(detail) from any screen keeps the bar
|
|
914
|
+
// Styling is THEME-driven: theme({ primaryColor, mutedColor, tabbarBg, tabbarBorder, badgeColor })
|
|
915
|
+
// restyles the bar app-wide (dark fallbacks built in). For a custom bar layout use UIPager below.
|
|
916
|
+
|
|
917
|
+
// UIPager — the navigation primitive under UITabs: sibling tabs that swipe natively, each tab its
|
|
918
|
+
// OWN push/pop stack. Reach for it directly for a plain stack (one-screen pager) or a fully custom
|
|
919
|
+
// tab bar. Renders no bar — build your own next to it; give the pager flexGrow: 1.
|
|
920
|
+
UIPager(...tabs) // the tab root screens (arrays flatten); tabs are FIXED at construction
|
|
921
|
+
// .select(i, animated?) (instant by default), .index, .onSelect(cb(i)) — fires for taps AND swipes: sync the
|
|
922
|
+
// bar highlight here. Tabs keep their stack/scroll state when switched away and back.
|
|
923
|
+
// .push(screen) — slides onto the CURRENT tab; edge back-swipe / Android back pops natively.
|
|
924
|
+
// .pop(), .popToRoot(), .replace(screen), .depth (tab swiping is disabled while > 1), .onChange(cb(depth))
|
|
925
|
+
// Ambient from any screen, no reference needed: UIPager.push(screen) / UIPager.pop() / UIPager.current
|
|
926
|
+
// pager.push = detail INSIDE the tab (bar stays); Router.push = above the whole shell (bar covered).
|
|
927
|
+
// Note: tab screens are built up front, but onOpen fires only when the tab becomes visible (maybe never) —
|
|
928
|
+
// load initial data at build time, keep onOpen for re-entry.
|
|
929
|
+
const pager = UIPager(homeTab, searchTab, profileTab).style({ flexGrow: 1 })
|
|
930
|
+
Router.init(UIScreen(pager, tabBar)) // bar buttons: .onClick(() => pager.select(i))
|
|
931
|
+
|
|
742
932
|
// UIWidget — floating overlay, independent of screens, always position: fixed in device coordinates
|
|
743
933
|
// Persists across Router navigation — create ONCE at module scope, reuse; hidden by default.
|
|
744
|
-
UIWidget(children)
|
|
934
|
+
UIWidget(...children)
|
|
745
935
|
// .show(), .hide(), .isShow (getter), .onTouchStart(cb), .onBackPressed(cb)
|
|
746
936
|
// extra style: overlayColor — full-screen scrim BEHIND the widget that blocks taps underneath, turning it into
|
|
747
937
|
// a modal; null (default) = no layer, "transparent" = invisible but still blocks. A scrim tap fires
|
|
@@ -753,7 +943,7 @@ UIWidget(children)
|
|
|
753
943
|
// UIModal — a UIWidget prewired as a dialog: USE THIS for confirm/alert dialogs
|
|
754
944
|
// Scrim on by default (overlayColor "rgba(0,0,0,0.5)"), animated show/hide (200ms fade), scrim tap and
|
|
755
945
|
// back button close it automatically. Create ONCE at module scope, like any widget.
|
|
756
|
-
UIModal(children)
|
|
946
|
+
UIModal(...children)
|
|
757
947
|
// .show(), .hide() (animated on a modal), .isOpen (getter), .onOpen(cb), .onClose(cb), .dismissible(false)
|
|
758
948
|
// — plus the full UIWidget surface
|
|
759
949
|
// .transition(hidden) — replace the show/hide animation: `hidden` is the off-screen pose (show animates FROM
|
|
@@ -764,7 +954,7 @@ UIModal(children)
|
|
|
764
954
|
// UIBottomSheet — a UIModal pinned to the bottom edge: USE THIS for every bottom sheet, never hand-build one
|
|
765
955
|
// Content-sized by default (as tall as its children, capped at the screen) — one position, drag down to
|
|
766
956
|
// dismiss: the action-sheet shape. Native hosts own the drag (snap, velocity, scroll handoff); web shows it static.
|
|
767
|
-
UIBottomSheet(children)
|
|
957
|
+
UIBottomSheet(...children)
|
|
768
958
|
// .detents([0.3, 0.6, 1]) — snap positions, ascending fractions of screen height (the map-app model). Call
|
|
769
959
|
// BEFORE show(); sizes the sheet to the HIGHEST detent — lower detents show the top slice of the content.
|
|
770
960
|
// .setDetent(i) (animated), .detent (getter), .onDetentChange(cb(i)) — every settle: finger snap or setDetent()
|
|
@@ -777,30 +967,33 @@ UIBottomSheet(children)
|
|
|
777
967
|
// Transparent intercepting scrim (outside tap dismisses; content under it can't scroll), 120ms fade,
|
|
778
968
|
// automatic placement: below the anchor, flips above near the bottom edge, clamped into the viewport.
|
|
779
969
|
// Attaches itself to Presentable.current (hides with the page it opened on).
|
|
780
|
-
UIPopover(children)
|
|
970
|
+
UIPopover(...children)
|
|
781
971
|
// .show(anchor?) — anchor: any element, or { x: ev.clientX, y: ev.clientY } for long-press context menus
|
|
782
972
|
// .hide() — plus the full UIModal surface (isOpen, onOpen/onClose, dismissible, transition)
|
|
783
973
|
// Style the menu box yourself (width, bgColor, borderRadius); do NOT set left/top — show(anchor) owns them.
|
|
784
974
|
|
|
785
975
|
// UIScrollable — THE scroll container: a screen's scrolling body, a list under a pinned header, a carousel
|
|
786
|
-
UIScrollable(children)
|
|
976
|
+
UIScrollable(...children)
|
|
787
977
|
// extra styles: scrollDirection ("horizontal" | "vertical", default vertical), showScrollbar: boolean,
|
|
788
978
|
// overscrollMode ("none" | "absorb" | "default"), refreshControlColor — tints the pull-to-refresh spinner,
|
|
789
979
|
// keyboardDismissMode ("interactive" | "scroll" | "none") — "scroll": any drag dismisses the keyboard at once (search lists)
|
|
980
|
+
// snap ("none" | "start" | "center" | "end", default "none") — paging: a released drag settles on a
|
|
981
|
+
// direct child's boundary; the value picks where the child rests in the viewport. Snap targets are
|
|
982
|
+
// the children themselves, so item widths can differ. (Mobile hosts; web degrades to free scrolling.)
|
|
790
983
|
// .onScroll(cb(pos)), .onScrollRelease(cb), .onOverscroll(cb(delta))
|
|
791
984
|
// .onRefresh(async cb) — pull-to-refresh; spinner stays until the returned promise settles. Attach BEFORE the
|
|
792
985
|
// element mounts; vertical only; native hosts (web preview: no-op). UIVirtualizedList has the same contract.
|
|
793
986
|
// Note: NO programmatic scrolling (no scrollTo) — if you need scrollTo/scrollToEnd, use UIVirtualizedList
|
|
794
987
|
// Note: defaults flexShrink: 1 (scrolls instead of overflowing); wrapping ancestors still need flexShrink: 1
|
|
795
988
|
// themselves. flexGrow: 1 to fill the remaining space is still yours to set.
|
|
796
|
-
// Carousel = scrollDirection: "horizontal" + FIXED-width cards
|
|
989
|
+
// Carousel = scrollDirection: "horizontal" + FIXED-width cards + snap: "start" ("center" for a card-deck-with-peek)
|
|
797
990
|
|
|
798
991
|
// UIVirtualizedList<T> — windowed list for LONG or unbounded data (feeds, chats, search results): only the
|
|
799
992
|
// visible rows (plus a buffer) are mounted. Use it instead of UIScrollable + map() whenever the item count
|
|
800
993
|
// is large, grows over time, or is unknown.
|
|
801
994
|
UIVirtualizedList<T>({
|
|
802
995
|
keyOf: (item: T) => string, // STABLE unique id per item (never the array index)
|
|
803
|
-
render: (item: T) =>
|
|
996
|
+
render: (item: T) => UINodeChild, // builds one row; called lazily as rows enter the window
|
|
804
997
|
estimatedHeight: number | ((item: T) => number), // px guess per row (real height measured after mount)
|
|
805
998
|
overscan?: number, // extra px mounted above/below the viewport (default: one viewport)
|
|
806
999
|
inverted?: boolean, // true = chat mode: starts scrolled to the end, append at bottom auto-scrolls
|
|
@@ -849,7 +1042,7 @@ player.play() // stop playback in the screen's onClose; .dispose() when gone f
|
|
|
849
1042
|
|
|
850
1043
|
// UIButton — the only TAPPABLE container: a UIRow with children centered on both axes by default.
|
|
851
1044
|
// To make anything clickable (a card, a list row, an icon) — wrap it in a UIButton.
|
|
852
|
-
UIButton(children
|
|
1045
|
+
UIButton(...children)
|
|
853
1046
|
// .onClick(cb), .onTouchStart(cb), .isPressed() // gestures: see TOUCH GESTURES above
|
|
854
1047
|
// extra styles: onPressed: { bgColor, opacity, ..., duration? } — style while the finger is down;
|
|
855
1048
|
// rippleColor ("default" or a Color, Android only)
|
|
@@ -888,7 +1081,7 @@ UIInput() / UITextArea()
|
|
|
888
1081
|
|
|
889
1082
|
// UISpacer — flexible empty space (defaults flexGrow: 1), eats free space along the main axis.
|
|
890
1083
|
// Only when plain alignment can't express it (one item pushed to the far end while the rest stay put):
|
|
891
|
-
UIRow(
|
|
1084
|
+
UIRow(title, UISpacer(), closeButton)
|
|
892
1085
|
// If ALL children move together, justifyContent ("space-between", "flex-end", ...) does it with no extra element.
|
|
893
1086
|
|
|
894
1087
|
// @deprecated UIBox — legacy centered container: defaults justifyContent AND alignItems to "center"
|
|
@@ -903,9 +1096,13 @@ UIText("Hi").style({ color: "white" }).style({ fontSize: 20 }).onClick(...)
|
|
|
903
1096
|
// 1. .style({...}) → declarative merge, the default. Use this 99% of the time.
|
|
904
1097
|
// 2. el.style.foo = bar → direct single-property mutation after creation (hot paths),
|
|
905
1098
|
// e.g. el.style.transform = `translateY(${y}px)`; el.style.foo reads it back.
|
|
906
|
-
// 3. .animateTo({..., duration, delay?, commit?}) → tween current → given values (duration in MS).
|
|
1099
|
+
// 3. .animateTo({..., duration, delay?, commit?, loop?}) → tween current → given values (duration in MS).
|
|
907
1100
|
// Targets are COMMITTED into the style immediately; pass commit: false to play without persisting —
|
|
908
1101
|
// the exit-animation pattern (fade an overlay, then .hide(); next show() starts from the intact style).
|
|
1102
|
+
// loop: true | n repeats the tween — loopMode: "ping-pong" (default: there and back) or "restart"
|
|
1103
|
+
// (snap back + replay — full-turn spinners via transform: "rotate(360deg)", shimmers). A looping
|
|
1104
|
+
// animation is an effect, not a state change: it never commits, delay applies once, and it stops on
|
|
1105
|
+
// the element's next animateTo/animateFrom or when it leaves the screen. (web/iOS/desktop; Android plays once until its next runtime.)
|
|
909
1106
|
// 4. .animateFrom({..., duration, delay?}) → snap to given values, animate back to current (fade-in).
|
|
910
1107
|
// Never modifies the stored style.
|
|
911
1108
|
// For free-value tweens use animate() — see ANIMATION above.
|
|
@@ -983,9 +1180,28 @@ label.style({ color: T.primaryColor, pl: "var(--comfort-left)" })
|
|
|
983
1180
|
.style({ flexDirection: "column", p: 16, onLandscape: { flexDirection: "row", p: 32 } })
|
|
984
1181
|
// Keys: onLandscape, onPortrait.
|
|
985
1182
|
|
|
1183
|
+
// --- Style classes ($name) — named states that CASCADE ---
|
|
1184
|
+
// A $-prefixed key in .style() declares a named style state (like onPressed, but yours: selected,
|
|
1185
|
+
// checked, expanded); duration/delay inside the block animate the swap. Drive it via el.class:
|
|
1186
|
+
const item = UIButton(UIText("Wi-Fi")).style({ bgColor: "#151515", $selected: { bgColor: "#1d2b45", duration: 150 } })
|
|
1187
|
+
item.onClick(ev => ev.target.class.selected = !ev.target.class.selected)
|
|
1188
|
+
// el.class.selected reads/writes a boolean; el.class({ a: true, b: false }) is the chainable batch
|
|
1189
|
+
// form; names work with or without the $. Class state persists across screen close/reopen.
|
|
1190
|
+
// CASCADE: a class set on an element also activates same-name $ blocks on ALL its descendants —
|
|
1191
|
+
// one toggle restyles a whole composite control, each part declaring its own reaction:
|
|
1192
|
+
UIButton(
|
|
1193
|
+
UIImage(icon).style({ tintColor: "#888", $selected: { tintColor: "#5b8cff" } }),
|
|
1194
|
+
UIText("Label").style({ color: "#888", $selected: { color: "#5b8cff" } }),
|
|
1195
|
+
) // .class.selected = true → icon AND label restyle (the cascade stops at hosted screens/widgets)
|
|
1196
|
+
// $pressed / $focused are RESERVED — the system toggles them (finger down / input focused) and they
|
|
1197
|
+
// CASCADE, so a button's children can restyle during its press. onPressed/onFocused stay
|
|
1198
|
+
// own-element-only — use those on nested interactives (a button inside a clickable card):
|
|
1199
|
+
UIButton(UIText("Buy").style({ $pressed: { color: "#999" } })).style({ $pressed: { transform: "scale(0.97)" } })
|
|
1200
|
+
// Precedence on the same prop: base < $classes < $pressed/$focused < onPressed/onFocused.
|
|
1201
|
+
|
|
986
1202
|
// --- Defaults that surprise ---
|
|
987
|
-
// flexShrink: 0 — elements don't shrink to fit (exception: UIScrollable and
|
|
988
|
-
// flexShrink: 1 so they scroll instead of overflowing; wrapping ancestors still default to 0).
|
|
1203
|
+
// flexShrink: 0 — elements don't shrink to fit (exception: UIScrollable, UIVirtualizedList and UIPager
|
|
1204
|
+
// default flexShrink: 1 so they shrink/scroll instead of overflowing; wrapping ancestors still default to 0).
|
|
989
1205
|
// flexGrow: 0 — nothing grows along the main axis without asking; no implicit min-sizes either.
|
|
990
1206
|
// alignItems: "stretch" — children FILL the cross axis by default; set a size or alignSelf to opt out.
|
|
991
1207
|
// overflow: "hidden" — children are clipped to the parent's box; set overflow: "visible" to let them escape.
|
|
@@ -1002,10 +1218,10 @@ label.style({ color: T.primaryColor, pl: "var(--comfort-left)" })
|
|
|
1002
1218
|
// ===== REUSABLE COMPONENTS =====
|
|
1003
1219
|
// Extract repeated UI into factory functions — they return elements you can chain methods on:
|
|
1004
1220
|
|
|
1005
|
-
const ClickableCard = (title: string, subtitle: string) => UIButton(
|
|
1221
|
+
const ClickableCard = (title: string, subtitle: string) => UIButton(
|
|
1006
1222
|
UIText(title).style({ fontWeight: 700, color: "white" }),
|
|
1007
1223
|
UIText(subtitle).style({ color: "#888", fontSize: 13 })
|
|
1008
|
-
|
|
1224
|
+
).style({ px: 16, py: 12, gap: 4, flexDirection: "column", alignItems: "flex-start" })
|
|
1009
1225
|
|
|
1010
1226
|
// Use like any other element — chain after the call:
|
|
1011
1227
|
ClickableCard("Title", "Subtitle").style({ bgColor: "#111" }).onClick(() => ...)
|
|
@@ -1014,15 +1230,15 @@ ClickableCard("Title", "Subtitle").style({ bgColor: "#111" }).onClick(() => ...)
|
|
|
1014
1230
|
const headingStyle: Style<UIText> = { color: "#ffffff", fontSize: 24, fontWeight: 700 }
|
|
1015
1231
|
|
|
1016
1232
|
// ===== CAPTURING ELEMENT REFERENCES =====
|
|
1017
|
-
// Use an assignment expression
|
|
1233
|
+
// Use an assignment expression right in the children — standard TypeScript:
|
|
1018
1234
|
|
|
1019
1235
|
let label: UIText
|
|
1020
1236
|
let input: UIInput
|
|
1021
1237
|
|
|
1022
|
-
UIColumn(
|
|
1238
|
+
UIColumn(
|
|
1023
1239
|
label = UIText("Hello"), // = both assigns the variable AND adds the element to the column
|
|
1024
1240
|
input = UIInput(),
|
|
1025
|
-
|
|
1241
|
+
)
|
|
1026
1242
|
|
|
1027
1243
|
// Later:
|
|
1028
1244
|
label.text = "Updated"
|
|
@@ -1032,15 +1248,17 @@ input.value // read current value
|
|
|
1032
1248
|
// ((button.children[0] as UIText).text vs buttonText.text).
|
|
1033
1249
|
|
|
1034
1250
|
// ===== CONDITIONAL CHILDREN =====
|
|
1035
|
-
// null / undefined / false
|
|
1036
|
-
UIColumn(
|
|
1251
|
+
// A null / undefined / false child is skipped — no element, no layout slot.
|
|
1252
|
+
UIColumn(header, isLoading ? spinner : null, showFooter && footer)
|
|
1253
|
+
// Works for whole blocks too — a falsy argument is skipped, an array argument is flattened:
|
|
1254
|
+
UIColumn(header, showList && items.map(Row))
|
|
1037
1255
|
|
|
1038
1256
|
// ===== SIZING: the two axes behave differently =====
|
|
1039
1257
|
// MAIN axis (row → width, column → height): elements stay as small as their content — nothing grows
|
|
1040
1258
|
// without flexGrow: 1 (no implicit min-sizes).
|
|
1041
1259
|
// CROSS axis: children fill the parent by default (alignItems defaults to "stretch"); set an explicit size
|
|
1042
1260
|
// or alignSelf to opt out.
|
|
1043
|
-
// So UIRow(
|
|
1261
|
+
// So UIRow(UIInput()) leaves the input at placeholder width — give it flexGrow: 1 to fill the row.
|
|
1044
1262
|
// EQUAL-width children (tab bars, button pairs): flex: 1 on each — it grows from a ZERO basis, so they end up
|
|
1045
1263
|
// equal. flexGrow: 1 alone splits only the LEFTOVER space on top of content-sized bases — the child with the
|
|
1046
1264
|
// longer label stays wider.
|
|
@@ -1060,6 +1278,7 @@ UIButton().onLayout(({ width }) => { buttonWidth = width })
|
|
|
1060
1278
|
// Position once at an interaction — never poll per frame.
|
|
1061
1279
|
|
|
1062
1280
|
// ===== ROUTER (multi-page apps) =====
|
|
1281
|
+
// Tabs are UITabs' job, in-tab stacks UIPager's (see UI COMPONENTS) — the Router owns what sits ABOVE the shell.
|
|
1063
1282
|
Router.init(homeScreen, opts?: { showDefaultBackButton?: boolean }) // call once in the entry file (default false)
|
|
1064
1283
|
Router.push(screen) // push onto the stack, screen becomes active
|
|
1065
1284
|
Router.pop(to?: number) // default -1 = one back; negative = relative (-2 = back two), 0/positive = absolute
|
|
@@ -1101,6 +1320,14 @@ import heart from './assets/heart.svg' // or inline: asset('./assets/hear
|
|
|
1101
1320
|
UIImage(heart).style({ width: 24, height: 24, tintColor: "#666" }) // tintColor recolors the icon
|
|
1102
1321
|
// Keep inline SvgSource(`...`) only for SVG generated dynamically from data.
|
|
1103
1322
|
|
|
1323
|
+
// ===== ICONS (assetIcon) =====
|
|
1324
|
+
// Use real icons instead of emoji. assetIcon("pack:name") resolves the icon at COMPILE time and
|
|
1325
|
+
// inlines it as an image source (same shape as SvgSource) — no imports, no project files, offline.
|
|
1326
|
+
UIImage(assetIcon("lucide:bell")).style({ width: 24, height: 24, tintColor: "#8a8f98" })
|
|
1327
|
+
// The id must be a string literal; an unknown id is a compile error (with name suggestions).
|
|
1328
|
+
// Recolor via the tintColor style or the { color } option (hex literal bakes in; expression tints).
|
|
1329
|
+
// Packs: lucide, tabler, heroicons, feather, bi, carbon, mdi, ri, solar.
|
|
1330
|
+
|
|
1104
1331
|
// ===== COMMON MISTAKES — DO NOT DO THESE =====
|
|
1105
1332
|
|
|
1106
1333
|
// ❌ CSS that doesn't exist here
|
|
@@ -1109,16 +1336,13 @@ calc(100% - 20px) // WRONG — calc() can't mix with %
|
|
|
1109
1336
|
lineHeight: 1.5 // WRONG — number is px (=1.5px); for a multiplier use "1.5em"
|
|
1110
1337
|
|
|
1111
1338
|
// ❌ touch handler on a non-touch element
|
|
1112
|
-
UIColumn(
|
|
1339
|
+
UIColumn(...).onTouchStart(cb) // WRONG — only UIButton/UIScreen/UIWidget; wrap in UIButton
|
|
1113
1340
|
|
|
1114
|
-
// ❌
|
|
1115
|
-
|
|
1116
|
-
|
|
1117
|
-
// ❌ let/const inside children array — `let` is a statement, not an expression
|
|
1118
|
-
UIRow([ let input = UIInput() ]) // WRONG
|
|
1341
|
+
// ❌ let/const among the children — `let` is a statement, not an expression
|
|
1342
|
+
UIRow(let input = UIInput()) // WRONG
|
|
1119
1343
|
// ✅ declare outside, assign inside (assignment both sets the var AND appends)
|
|
1120
1344
|
let input: UIInput
|
|
1121
|
-
UIRow(
|
|
1345
|
+
UIRow(input = UIInput())
|
|
1122
1346
|
|
|
1123
1347
|
// ❌ setting a UIImage's content through bgImage
|
|
1124
1348
|
const img = UIImage("") // WRONG — empty source as a placeholder
|
|
@@ -1128,30 +1352,30 @@ const img = UIImage(url)
|
|
|
1128
1352
|
img.src = newUrl // updates the displayed image
|
|
1129
1353
|
|
|
1130
1354
|
// ❌ expecting an input to fill width like in CSS
|
|
1131
|
-
UIRow(
|
|
1355
|
+
UIRow(UIInput()) // WRONG — collapses to placeholder width
|
|
1132
1356
|
// ✅ stretch it explicitly
|
|
1133
|
-
UIColumn(
|
|
1134
|
-
UIRow(
|
|
1357
|
+
UIColumn(UIInput().style({ width: "100%" })) // cross axis
|
|
1358
|
+
UIRow(input = UIInput().style({ flexGrow: 1 }), sendBtn) // main axis
|
|
1135
1359
|
|
|
1136
1360
|
// ❌ a button that should match the input's height but shrinks to its text
|
|
1137
|
-
UIRow(
|
|
1361
|
+
UIRow(input.style({ height: 40 }), UIButton()) // button ends up shorter
|
|
1138
1362
|
// ✅ give controls the same explicit height
|
|
1139
|
-
UIRow(
|
|
1363
|
+
UIRow(input.style({ height: 40 }), UIButton().style({ height: 40 }))
|
|
1140
1364
|
|
|
1141
1365
|
// ❌ flexGrow: 1 for equal-width children — it splits only the LEFTOVER space, bases stay content-sized
|
|
1142
|
-
UIRow(
|
|
1366
|
+
UIRow(yes.style({ flexGrow: 1 }), no.style({ flexGrow: 1 })) // longer label = wider button
|
|
1143
1367
|
// ✅ flex: 1 — grows from a zero basis, children end up equal
|
|
1144
|
-
UIRow(
|
|
1368
|
+
UIRow(yes.style({ flex: 1 }), no.style({ flex: 1 }))
|
|
1145
1369
|
|
|
1146
1370
|
// ❌ empty containers as spacers to align children (web habit)
|
|
1147
|
-
UIRow(
|
|
1371
|
+
UIRow(UIColumn().style({ flexGrow: 1 }), label) // WRONG
|
|
1148
1372
|
// ✅ alignment is a CONTAINER property, not an extra element
|
|
1149
|
-
UIRow(
|
|
1373
|
+
UIRow(label).style({ justifyContent: "flex-end" })
|
|
1150
1374
|
|
|
1151
1375
|
// ❌ empty element as a placeholder for a conditional child
|
|
1152
|
-
UIRow(
|
|
1376
|
+
UIRow(isGroup ? button : UIColumn()) // WRONG
|
|
1153
1377
|
// ✅ null is skipped in children — no phantom element
|
|
1154
|
-
UIRow(
|
|
1378
|
+
UIRow(isGroup ? button : null)
|
|
1155
1379
|
|
|
1156
1380
|
// ❌ pointing UIImage / bgImage at a project file by bare path — it won't resolve to the bundled asset
|
|
1157
1381
|
UIImage("./photo.png") // WRONG (a plain string works only for remote http(s) URLs)
|
|
@@ -1165,7 +1389,7 @@ list.onEndReached(loadNextPage) // WRONG — threshold is th
|
|
|
1165
1389
|
list.onEndReached(600, loadNextPage)
|
|
1166
1390
|
|
|
1167
1391
|
// ❌ re-creating a UIWidget or UIVirtualizedList to "re-render"
|
|
1168
|
-
const openSheet = () => UIWidget(
|
|
1392
|
+
const openSheet = () => UIWidget(...).show() // WRONG — leaks a new widget every call
|
|
1169
1393
|
// ✅ create once at module scope; show()/hide() the widget, setData/append/update the list
|
|
1170
1394
|
|
|
1171
1395
|
// ===== EXAMPLES =====
|
|
@@ -1173,7 +1397,7 @@ const openSheet = () => UIWidget([...]).show() // WRONG — leaks a new wid
|
|
|
1173
1397
|
// === EXAMPLE 1: Single-file app ===
|
|
1174
1398
|
<file name="main.ts">
|
|
1175
1399
|
let text: UIText
|
|
1176
|
-
const screen = UIScreen(
|
|
1400
|
+
const screen = UIScreen(
|
|
1177
1401
|
text = UIText("Hello, world!").style({ mb: 16, fontWeight: 700, fontSize: 24, textAlign: "center" }),
|
|
1178
1402
|
UIText("Your name:").style({ textAlign: "center" }),
|
|
1179
1403
|
UIInput()
|
|
@@ -1181,91 +1405,188 @@ const screen = UIScreen([
|
|
|
1181
1405
|
.onChange(str => {
|
|
1182
1406
|
text.text = `Hello, ${str}!`
|
|
1183
1407
|
})
|
|
1184
|
-
|
|
1408
|
+
).style({ justifyContent: "center", p: 20, gap: 8 })
|
|
1185
1409
|
|
|
1186
1410
|
screen.open()
|
|
1187
1411
|
</file>
|
|
1188
1412
|
|
|
1189
|
-
// === EXAMPLE 2:
|
|
1413
|
+
// === EXAMPLE 2: Theme tokens + fetched list with loading / error states ===
|
|
1414
|
+
// A tokens module every screen imports, light-themed: theme({ color }) sets the default text
|
|
1415
|
+
// color ONCE — no color: "#111" on every label.
|
|
1416
|
+
<file name="tokens.ts">
|
|
1417
|
+
const palette = {
|
|
1418
|
+
bg: "#F4F6F5", card: "#FFFFFF", border: "#E4E8E6",
|
|
1419
|
+
text: "#131A17", muted: "#606B65",
|
|
1420
|
+
accent: "#15A34A", accentSoft: "#E7F6ED", onAccent: "#FFFFFF",
|
|
1421
|
+
}
|
|
1422
|
+
theme({ color: palette.text, primaryColor: palette.accent })
|
|
1423
|
+
// Accessors ARE "var(--x)" strings — re-calling theme() with new values restyles the live app.
|
|
1424
|
+
export const colors: { [K in keyof typeof palette]: string } = theme(palette)
|
|
1425
|
+
export const font = { // type scale — spread into styles: .style({ ...font.h2 })
|
|
1426
|
+
h2: { fontSize: 22, fontWeight: 700 }, bodyStrong: { fontSize: 16, fontWeight: 600 },
|
|
1427
|
+
small: { fontSize: 14 }, tiny: { fontSize: 12, fontWeight: 500 },
|
|
1428
|
+
}
|
|
1429
|
+
</file>
|
|
1190
1430
|
<file name="main.ts">
|
|
1431
|
+
import { colors, font } from './tokens'
|
|
1432
|
+
|
|
1191
1433
|
type User = { id: number; name: string; email: string }
|
|
1192
1434
|
|
|
1193
|
-
|
|
1194
|
-
|
|
1435
|
+
const Row = (u: User) => UIRow(
|
|
1436
|
+
UIColumn(UIText(u.name[0]).style({ ...font.bodyStrong, color: colors.accent }))
|
|
1437
|
+
.style({ width: 44, height: 44, borderRadius: 22, bgColor: colors.accentSoft,
|
|
1438
|
+
justifyContent: "center", alignItems: "center" }),
|
|
1439
|
+
UIColumn(
|
|
1440
|
+
UIText(u.name).style({ ...font.bodyStrong }),
|
|
1441
|
+
UIText(u.email).style({ ...font.small, color: colors.muted }),
|
|
1442
|
+
).style({ flexGrow: 1, flexShrink: 1, gap: 2, alignItems: "flex-start" }),
|
|
1443
|
+
).style({ alignItems: "center", gap: 12, bgColor: colors.card, borderRadius: 16,
|
|
1444
|
+
border: `1px solid ${colors.border}`, p: 14 })
|
|
1195
1445
|
|
|
1196
|
-
const
|
|
1197
|
-
|
|
1446
|
+
const Centered = (...children: UINodeChild[]) =>
|
|
1447
|
+
UIColumn(children).style({ flexGrow: 1, justifyContent: "center", alignItems: "center", gap: 12 })
|
|
1448
|
+
|
|
1449
|
+
let body: UIColumn
|
|
1198
1450
|
|
|
1451
|
+
const loadData = async () => {
|
|
1452
|
+
body.setContent([Centered(UIText("Loading…").style({ color: colors.muted }))])
|
|
1199
1453
|
const res = await fetch("https://jsonplaceholder.typicode.com/users")
|
|
1200
1454
|
if (res.status !== 200) {
|
|
1201
|
-
|
|
1455
|
+
body.setContent([Centered(
|
|
1456
|
+
UIText("Couldn't load users"),
|
|
1457
|
+
UIButton(UIText("Retry").style({ color: colors.onAccent, fontWeight: 600 }))
|
|
1458
|
+
.style({ height: 44, px: 24, borderRadius: 12, bgColor: colors.accent })
|
|
1459
|
+
.onClick(() => loadData()),
|
|
1460
|
+
)])
|
|
1202
1461
|
return
|
|
1203
1462
|
}
|
|
1204
|
-
|
|
1205
|
-
const users = res.json<User[]>() // sync — no await
|
|
1206
|
-
|
|
1207
|
-
statusText.text = ""
|
|
1208
|
-
list.setContent(
|
|
1209
|
-
users.map(user =>
|
|
1210
|
-
UIColumn([
|
|
1211
|
-
UIText(user.name).style({ fontWeight: 700, color: "white" }),
|
|
1212
|
-
UIText(user.email).style({ color: "#888", fontSize: 13 })
|
|
1213
|
-
]).style({ px: 16, py: 12, gap: 4 })
|
|
1214
|
-
)
|
|
1215
|
-
)
|
|
1463
|
+
body.setContent(res.json<User[]>().map(Row)) // res.json is sync — no await
|
|
1216
1464
|
}
|
|
1217
1465
|
|
|
1218
|
-
const screen = UIScreen(
|
|
1219
|
-
UIText("Users").style({
|
|
1220
|
-
|
|
1221
|
-
|
|
1222
|
-
|
|
1223
|
-
|
|
1224
|
-
|
|
1225
|
-
|
|
1226
|
-
.style({ bgColor: "black", p: 16, pt: "max(safe-top, 24px)" })
|
|
1227
|
-
.onOpen(() => loadData())
|
|
1466
|
+
const screen = UIScreen(
|
|
1467
|
+
UIText("Users").style({ ...font.h2, pb: 8, px: 16 }),
|
|
1468
|
+
UIScrollable(
|
|
1469
|
+
body = UIColumn().style({ flexGrow: 1, gap: 8 })
|
|
1470
|
+
).style({ flexGrow: 1, p: 16, pt: 0 }) // the ONE scrolling body — the screen itself never scrolls
|
|
1471
|
+
.onRefresh(() => loadData()), // pull-to-refresh; attached before screen.open()
|
|
1472
|
+
).style({ bgColor: colors.bg, pt: "comfort-top" })
|
|
1473
|
+
.onOpen(() => loadData())
|
|
1228
1474
|
|
|
1229
1475
|
screen.open()
|
|
1230
1476
|
</file>
|
|
1231
1477
|
|
|
1232
|
-
// === EXAMPLE 3:
|
|
1478
|
+
// === EXAMPLE 3: Tabbed app — UITabs, font(), in-tab detail ===
|
|
1233
1479
|
<file name="home.ts">
|
|
1234
|
-
|
|
1235
|
-
|
|
1236
|
-
|
|
1237
|
-
|
|
1238
|
-
|
|
1239
|
-
|
|
1240
|
-
|
|
1241
|
-
|
|
1242
|
-
|
|
1243
|
-
|
|
1244
|
-
|
|
1245
|
-
|
|
1246
|
-
|
|
1247
|
-
|
|
1248
|
-
|
|
1249
|
-
|
|
1250
|
-
|
|
1251
|
-
|
|
1252
|
-
UIText("
|
|
1253
|
-
])
|
|
1254
|
-
.style({ p:
|
|
1255
|
-
.onBackPressed(() => Router.pop())
|
|
1480
|
+
const detailScreen = (name: string) => UIScreen(
|
|
1481
|
+
UIButton(
|
|
1482
|
+
UIImage(assetIcon("lucide:chevron-left")).style({ width: 20, height: 20, tintColor: "white" }),
|
|
1483
|
+
UIText("Back")
|
|
1484
|
+
).style({ alignSelf: "flex-start", height: 32, gap: 4 }).onClick(() => UIPager.pop()),
|
|
1485
|
+
UIText(name).style({ fontSize: 24, fontWeight: 700 }),
|
|
1486
|
+
UIButton(
|
|
1487
|
+
UIImage(assetIcon("lucide:heart")).style({ width: 18, height: 18, tintColor: "#8a919e", $fav: { tintColor: "#ff453a" } }),
|
|
1488
|
+
UIText("Favorite").style({ color: "#8a919e", $fav: { color: "#ff453a" } })
|
|
1489
|
+
).style({ name: "fav", alignSelf: "flex-start", height: 36, px: 12, gap: 6, borderRadius: 18, bgColor: "#17181c", $fav: { bgColor: "#2a181a", duration: 150 } })
|
|
1490
|
+
.onClick(ev => ev.target.class.fav = !ev.target.class.fav) // one toggle — the $fav blocks on icon + label light up too (cascade)
|
|
1491
|
+
).style({ p: 16, pt: "comfort-top", gap: 16, bgColor: "black" })
|
|
1492
|
+
|
|
1493
|
+
const Item = (name: string) => UIButton(UIText(name).style({ color: "white" }))
|
|
1494
|
+
.style({ height: 52, px: 16, justifyContent: "flex-start", borderRadius: 12, bgColor: "#151515", onPressed: { opacity: 0.7 } })
|
|
1495
|
+
.onClick(() => UIPager.push(detailScreen(name))) // in-tab push: tab bar stays, back-swipe pops
|
|
1496
|
+
|
|
1497
|
+
export const homeScreen = UIScreen(
|
|
1498
|
+
UIText("Home").style({ fontSize: 28, fontWeight: 700, fontFamily: font("unbounded") }), // display face
|
|
1499
|
+
UIScrollable(["Alpha", "Beta", "Gamma"].map(Item)).style({ flexGrow: 1, gap: 8 })
|
|
1500
|
+
).style({ p: 16, pt: "comfort-top", gap: 16, bgColor: "black" })
|
|
1256
1501
|
</file>
|
|
1257
|
-
<file name="
|
|
1258
|
-
|
|
1259
|
-
|
|
1260
|
-
|
|
1502
|
+
<file name="profile.ts">
|
|
1503
|
+
export const profileScreen = UIScreen(
|
|
1504
|
+
UIText("Profile").style({ fontSize: 28, fontWeight: 700, fontFamily: font("unbounded") })
|
|
1505
|
+
).style({ p: 16, pt: "comfort-top", bgColor: "black" })
|
|
1261
1506
|
</file>
|
|
1262
1507
|
<file name="main.ts">
|
|
1263
1508
|
import { homeScreen } from './home'
|
|
1509
|
+
import { profileScreen } from './profile'
|
|
1264
1510
|
|
|
1265
|
-
|
|
1511
|
+
theme({ fontFamily: font("manrope") }) // app-wide default text font — one line, no loading code
|
|
1512
|
+
|
|
1513
|
+
const tabs = UITabs({
|
|
1514
|
+
home: { label: "Home", icon: assetIcon("lucide:house"), screen: homeScreen },
|
|
1515
|
+
profile: { label: "Profile", icon: assetIcon("lucide:user"), screen: profileScreen },
|
|
1516
|
+
})
|
|
1517
|
+
tabs.badge("profile", true) // notification dot on the tab
|
|
1518
|
+
Router.init(tabs)
|
|
1266
1519
|
</file>
|
|
1267
1520
|
|
|
1268
|
-
// === EXAMPLE 4:
|
|
1521
|
+
// === EXAMPLE 4: Form — field factory, return-key chain, validation, busy submit ===
|
|
1522
|
+
// The keyboard needs NO code beyond the enterKey chain: the host scrolls the focused field into
|
|
1523
|
+
// view and handles dismissal itself.
|
|
1524
|
+
<file name="main.ts">
|
|
1525
|
+
// Field anatomy: label above, styled input, a RESERVED message line below (minHeight — an
|
|
1526
|
+
// appearing error never jumps the form). Typing in an errored field clears it.
|
|
1527
|
+
const Field = (label: string, style: Style<UIInput> = {}) => {
|
|
1528
|
+
const input = UIInput().style({ height: 50, px: 14, borderRadius: 12, bgColor: "#161A22",
|
|
1529
|
+
border: "1px solid #262C3A", color: "white", placeholderColor: "#5A6272",
|
|
1530
|
+
onFocused: { borderColor: "#4C8DFF" }, ...style })
|
|
1531
|
+
const message = UIText("").style({ fontSize: 13, minHeight: 18, color: "#FF6B6B" })
|
|
1532
|
+
input.onChange(() => message.text = "")
|
|
1533
|
+
return {
|
|
1534
|
+
node: UIColumn(
|
|
1535
|
+
UIText(label).style({ fontSize: 13, fontWeight: 600, color: "#8A93A6" }),
|
|
1536
|
+
input, message,
|
|
1537
|
+
).style({ gap: 6 }),
|
|
1538
|
+
input,
|
|
1539
|
+
error: (text: string) => { message.text = text },
|
|
1540
|
+
}
|
|
1541
|
+
}
|
|
1542
|
+
|
|
1543
|
+
const name = Field("Name", { placeholder: "Jane Appleseed", autocapitalize: "words" })
|
|
1544
|
+
const email = Field("Email", { type: "email", placeholder: "you@example.com" })
|
|
1545
|
+
const password = Field("Password", { type: "password" })
|
|
1546
|
+
|
|
1547
|
+
// The return key walks the form; the last field submits. This is ALL the keyboard code.
|
|
1548
|
+
name.input.style({ enterKey: "next" }).onSubmit(() => email.input.focus())
|
|
1549
|
+
email.input.style({ enterKey: "next" }).onSubmit(() => password.input.focus())
|
|
1550
|
+
password.input.style({ enterKey: "go" }).onSubmit(() => submit())
|
|
1551
|
+
|
|
1552
|
+
let btnLabel: UIText
|
|
1553
|
+
let busy = false
|
|
1554
|
+
|
|
1555
|
+
// The submit button is never disabled — a tap on a bad form PAINTS the errors and focuses the
|
|
1556
|
+
// first offender, which beats a dead button that explains nothing. `busy` swallows double-taps.
|
|
1557
|
+
const submit = async () => {
|
|
1558
|
+
if (busy) return
|
|
1559
|
+
let bad: ReturnType<typeof Field> | null = null // checked bottom-up, so `bad` ends at the FIRST invalid field
|
|
1560
|
+
if (password.input.value.length < 8) { password.error("At least 8 characters"); bad = password }
|
|
1561
|
+
if (!email.input.value.includes("@")) { email.error("Enter a valid email"); bad = email }
|
|
1562
|
+
if (name.input.value.trim() === "") { name.error("Name is required"); bad = name }
|
|
1563
|
+
if (bad) { bad.input.focus(); return }
|
|
1564
|
+
busy = true
|
|
1565
|
+
btnLabel.text = "Creating…"
|
|
1566
|
+
const res = await fetch("https://api.example.com/register", {
|
|
1567
|
+
method: "POST", headers: { "Content-Type": "application/json" },
|
|
1568
|
+
body: JSON.stringify({ name: name.input.value.trim(), email: email.input.value, password: password.input.value }),
|
|
1569
|
+
})
|
|
1570
|
+
busy = false
|
|
1571
|
+
btnLabel.text = "Create account"
|
|
1572
|
+
if (res.status !== 200) { email.error("Registration failed — try again"); return }
|
|
1573
|
+
toast("Welcome!")
|
|
1574
|
+
}
|
|
1575
|
+
|
|
1576
|
+
const screen = UIScreen(
|
|
1577
|
+
UIScrollable( // no fixed chrome — the keyboard leaves ~460px of screen and a form wants all of them
|
|
1578
|
+
UIText("Create account").style({ fontSize: 28, fontWeight: 700, mb: 12 }),
|
|
1579
|
+
name.node, email.node, password.node,
|
|
1580
|
+
UIButton(btnLabel = UIText("Create account").style({ fontSize: 16, fontWeight: 700 }))
|
|
1581
|
+
.style({ name: "submit", height: 52, borderRadius: 14, bgColor: "#4C8DFF", mt: 8, onPressed: { opacity: 0.85 } })
|
|
1582
|
+
.onClick(() => submit())
|
|
1583
|
+
).style({ flexGrow: 1, px: 20, pt: "comfort-top", pb: 28, gap: 8 })
|
|
1584
|
+
).style({ bgColor: "#0C0F14" })
|
|
1585
|
+
|
|
1586
|
+
screen.open()
|
|
1587
|
+
</file>
|
|
1588
|
+
|
|
1589
|
+
// === EXAMPLE 5: UIBottomSheet — persistent map-style sheet with detents ===
|
|
1269
1590
|
<file name="main.ts">
|
|
1270
1591
|
type Place = { id: number; name: string; distance: string }
|
|
1271
1592
|
const places: Place[] = [
|
|
@@ -1274,32 +1595,32 @@ const places: Place[] = [
|
|
|
1274
1595
|
{ id: 3, name: "Riverside Park", distance: "1.2 km" },
|
|
1275
1596
|
]
|
|
1276
1597
|
|
|
1277
|
-
const Row = (p: Place) => UIRow(
|
|
1598
|
+
const Row = (p: Place) => UIRow(
|
|
1278
1599
|
UIText(p.name).style({ color: "#111", fontSize: 16 }),
|
|
1279
1600
|
UIText(p.distance).style({ color: "#888", fontSize: 14 })
|
|
1280
|
-
|
|
1601
|
+
).style({ px: 16, height: 52, alignItems: "center", justifyContent: "space-between" })
|
|
1281
1602
|
|
|
1282
|
-
const sheet = UIBottomSheet(
|
|
1283
|
-
UIColumn(
|
|
1603
|
+
const sheet = UIBottomSheet(
|
|
1604
|
+
UIColumn().style({ width: 50, height: 6, borderRadius: 3, bgColor: "#D9D9D9", mx: "auto", my: 12 }),
|
|
1284
1605
|
UIText("Nearby").style({ px: 16, fontWeight: 700, fontSize: 20, mb: 8, color: "black" }),
|
|
1285
1606
|
UIScrollable(places.map(Row)).style({ flexGrow: 1 }) // scrolls at the top detent, drags the sheet below it
|
|
1286
|
-
|
|
1607
|
+
)
|
|
1287
1608
|
.style({ bgColor: "white", borderRadius: 20, overlayColor: null }) // no scrim — the map stays interactive
|
|
1288
1609
|
.detents([0.25, 0.6, 1]) // collapsed / half / full
|
|
1289
1610
|
.dismissible(false) // drag below the lowest detent collapses, never closes
|
|
1290
1611
|
.onDetentChange(i => console.log("detent", i))
|
|
1291
1612
|
|
|
1292
|
-
const mapScreen = UIScreen(
|
|
1613
|
+
const mapScreen = UIScreen(
|
|
1293
1614
|
// the map / page content behind the sheet
|
|
1294
|
-
|
|
1615
|
+
).onOpen(() => sheet.show()).onClose(() => sheet.hide())
|
|
1295
1616
|
|
|
1296
1617
|
mapScreen.open()
|
|
1297
1618
|
|
|
1298
|
-
// An action sheet is even less: content-sized, no detents() — UIBottomSheet(
|
|
1619
|
+
// An action sheet is even less: content-sized, no detents() — UIBottomSheet(rows).show(),
|
|
1299
1620
|
// scrim and drag-down-to-dismiss included.
|
|
1300
1621
|
</file>
|
|
1301
1622
|
|
|
1302
|
-
// === EXAMPLE
|
|
1623
|
+
// === EXAMPLE 6: UIVirtualizedList — chat (inverted, imperative append) ===
|
|
1303
1624
|
<file name="main.ts">
|
|
1304
1625
|
type Msg = { id: string; text: string; mine: boolean }
|
|
1305
1626
|
|
|
@@ -1311,37 +1632,41 @@ const list = UIVirtualizedList<Msg>({
|
|
|
1311
1632
|
keyOf: m => m.id,
|
|
1312
1633
|
estimatedHeight: m => 44 + Math.ceil(m.text.length / 34) * 20,
|
|
1313
1634
|
inverted: true, // newest at the bottom
|
|
1314
|
-
render: m => UIRow(
|
|
1315
|
-
UIRow(
|
|
1635
|
+
render: m => UIRow(
|
|
1636
|
+
UIRow(
|
|
1316
1637
|
UIText(m.text).style({ color: m.mine ? "white" : "#111" })
|
|
1317
|
-
|
|
1638
|
+
).style({
|
|
1318
1639
|
bgColor: m.mine ? "#FF4032" : "#EEE",
|
|
1319
1640
|
px: 12, py: 8, borderRadius: 16, maxWidth: "75%"
|
|
1320
1641
|
})
|
|
1321
|
-
|
|
1642
|
+
).style({ px: 12, py: 4, justifyContent: m.mine ? "flex-end" : "flex-start" })
|
|
1322
1643
|
}).style({ flexGrow: 1 })
|
|
1323
1644
|
|
|
1324
|
-
let input:
|
|
1645
|
+
let input: UITextArea
|
|
1646
|
+
let sendBtn: UIButton
|
|
1325
1647
|
|
|
1326
1648
|
const send = () => {
|
|
1327
1649
|
const text = input.value.trim()
|
|
1328
1650
|
if (!text) return
|
|
1329
1651
|
list.append({ id: idOf(), text, mine: true }) // O(1); inverted list auto-scrolls to it
|
|
1330
1652
|
input.value = ""
|
|
1653
|
+
sendBtn.style.opacity = 0.4
|
|
1331
1654
|
}
|
|
1332
1655
|
|
|
1333
|
-
const screen = UIScreen(
|
|
1656
|
+
const screen = UIScreen(
|
|
1334
1657
|
list,
|
|
1335
|
-
UIRow(
|
|
1336
|
-
input =
|
|
1337
|
-
flexGrow: 1,
|
|
1338
|
-
|
|
1658
|
+
UIRow(
|
|
1659
|
+
input = UITextArea().style({ placeholder: "Message...", placeholderColor: "#999",
|
|
1660
|
+
color: "#111", flexGrow: 1, flexShrink: 1, px: 16, py: 10, bgColor: "#F0F0F0", borderRadius: 20, maxHeight: 110,
|
|
1661
|
+
keyboardDismiss: false
|
|
1339
1662
|
}),
|
|
1340
|
-
UIButton(
|
|
1341
|
-
.style({
|
|
1663
|
+
sendBtn = UIButton(UIImage(assetIcon("lucide:arrow-up")).style({ width: 20, height: 20, tintColor: "white" }))
|
|
1664
|
+
.style({ width: 40, height: 40, borderRadius: 20, bgColor: "#FF4032", opacity: 0.4 })
|
|
1342
1665
|
.onClick(send)
|
|
1343
|
-
|
|
1344
|
-
|
|
1666
|
+
).style({ p: 8, pb: "comfort-bottom", gap: 8, alignItems: "flex-end" })
|
|
1667
|
+
).style({ bgColor: "white" })
|
|
1668
|
+
|
|
1669
|
+
input.onChange(v => { sendBtn.style.opacity = v.trim() ? 1 : 0.4 }) // direct style write — the hot-path form
|
|
1345
1670
|
|
|
1346
1671
|
screen.open()
|
|
1347
1672
|
</file>
|