← Back to Demos & Examples

42_mobile_declarative_view_and_bridge.vk

Raw .vk
// examples/42_mobile_declarative_view_and_bridge.vk
// Homoiconic Mobile Declarative UI (`ui/view`) & Zero-GC Native Bridge (`mobile`):
//   1. Strictly-typed primary `ui/view` tree construction (`iPhone 16 Pro` & `Pixel 9` viewports)
//   2. Homoiconic `quote [...]` dynamic OTA view evaluation (`v/eval-quoted`)
//   3. Homoiconic `quote [...]` bridge contract (`mob/parse-bridge-quote`), RPC dispatch & `<secret>` redaction
//   4. Offscreen RFC 2083 PNG mobile viewport rendering (zero capabilities required — runs on VM, Wasm 3.0 & Native).

use [
	mob = mobile
	png = image/png
	v   = ui/view
]

pub InspectionItem = struct {
	id    str
	title str
	done  bool = false
}

pub AppState = struct {
	site_name   str                   = 'Substation North-04'
	online      bool                  = false
	sync_pct    i64                   = 82
	active_tab  str                   = 'tasks'
	sheet_open  bool                  = false
	vault_token secret str            = ''
	latency_ms  block                 = [11 14 9 12 8 10]
	items       block[InspectionItem] = []
}

pub render-inspector = fn [st AppState] v/Node [
	done_cnt = len (filter st.items fn [it InspectionItem] bool [ it.done ])
	total_cnt = len st.items

	v/screen 'FieldSync Mobile' { subtitle = st.site_name, trailing_label = 'Sync', trailing_action = 'sync_now' } [
		(v/vstack { gap = 12, pad = 14 } [
			(v/banner .warning 'Offline mode — queued in local ORO CRDT log' (not st.online))
			(v/grid 2 10 [
				(v/stat 'Completed' `{done_cnt}/{total_cnt}` 'Zero GC pauses' .success)
				(v/stat 'Queue Sync' `{st.sync_pct}%` '16 KiB ARM64 ABI' .accent)
			])
			(v/card 'Security & Telemetry' {} [
				(v/secret-field-badge 'Session Vault Token')
				(v/toggle-switch 'Online Replication' st.online 'toggle_online')
				(v/progress st.sync_pct 'CRDT Delta Sync' .accent)
				(v/sparkline 'Frame Time (ms x10)' st.latency_ms .success)
			])
			(v/section 'Inspection Checklist' [
				(v/list-view st.items fn [item] v/Node [
					v/checkbox (str/append '' item.title) (item.done == true) `toggle:{item.id}`
				])
				(v/hstack { gap = 8 } [
					(v/button 'Add Note' 'open_note_sheet')
					(v/button-styled 'Flush Queue' { style = .secondary } 'sync_now')
				])
			])
		])
		(v/tab-bar st.active_tab 'tab:' [
			(v/TabItem { id = 'tasks', label = 'Checklist', badge = `{total_cnt}` })
			(v/TabItem { id = 'telemetry', label = 'Metrics' })
			(v/TabItem { id = 'vault', label = 'Vault' })
		])
		(v/sheet st.sheet_open 'New Inspection Entry' 'close_sheet' [
			(v/text 'Captured deterministically in local SQLite + CRDT log.')
			(v/button 'Confirm Entry' 'confirm_note')
		])
	]
]

main = fn [] any [
	// 1. Build initial typed mobile state (including a `.secret` bearer token)
	tok_secret = bytes/to-str (bytes/with-secret 16)
	init_state = AppState {
		vault_token = tok_secret
		items = [
			(InspectionItem { id = 'chk-1', title = 'Verify transformer thermal seal', done = true })
			(InspectionItem { id = 'chk-2', title = 'Audit TLS 1.3 mTLS edge pinning', done = true })
			(InspectionItem { id = 'chk-3', title = 'Capture relay harmonic baseline', done = false })
		]
	}

	// 2. Render typed `ui/view` tree onto an offscreen iPhone 16 Pro PNG buffer
	root_node  = render-inspector init_state
	iphone_png = v/render-preview-png/scale root_node (v/iphone-viewport) false 4
	dec_img    = png/decode iphone_png
	if err? dec_img [ return dec_img ]

	// 3. Evaluate homoiconic `quote [...]` dynamic OTA workflow banner view
	ota_quote = quote [
		screen 'OTA Safety Bulletin' { subtitle = 'Signed .vkp Rule Bundle' } [
			vstack { gap = 10, pad = 12 } [
				banner .warning 'High-voltage lockout verification required' (not state.online)
				stat 'Pending Checks' (state.pending_str) 'Mandatory' .warning
				button 'Acknowledge Bulletin' .ack_bulletin
			]
		]
	]
	ota_node = v/eval-quoted ota_quote { online = false, pending_str = '1 remaining' }

	// 4. Parse homoiconic `quote [...]` BridgeSpec & dispatch JSON RPC with `<secret>` redaction
	bridge = mob/parse-bridge-quote 'FieldSyncCore' (quote [
		package 'org.vekolang.fieldsync'
		model InspectionItem [
			field id str
			field title str
			field done bool false
		]
		state AppState [
			field site_name str 'Substation North-04'
			field online bool false
			secret vault_token str
		]
		command toggle-online [] AppState
		query get-status [] AppState
	])

	mut handlers = {}
	raw_vault_tok = str/join ['raw-sensitive-' 'value-redacted-by-spec'] ''
	map/set mut handlers 'get-status' fn [_req map] any [
		{
			site_name   = init_state.site_name
			online      = true
			vault_token = raw_vault_tok
		}
	]
	rpc_json = mob/dispatch-json handlers bridge 'get-status' '{}'
	if (str/contains? rpc_json 'raw-sensitive-value') or (not (str/contains? rpc_json '<secret>')) [
		return (err 'secret field was not redacted by mobile/dispatch-json')
	]

	println `Typed view rendered -> iPhone 16 Pro PNG ({dec_img.width}x{dec_img.height}, {len iphone_png} bytes)`
	println `OTA quoted view     -> root={ota_node.kind}, title="{ota_node.text}", children={len ota_node.children}`
	println `Mobile bridge RPC   -> {bridge.name} ({len bridge.endpoints} endpoints): {rpc_json}`
	.ok
]

res = main
if err? res [
	println (mold res)
	res
] else [
	.ok
]