ludic/examples/library/ui_hold.ludic
Orkuncakilkaya 19fcf60599 wip(0.S3): packages and examples migrated again from their pre-0.S sources in one run
ludic migrate state packages <every example program> packages/ludic.lab/example/plate.ludic
  1804 vars into 126 states, 64 into lets; 23498 edits in 460 files

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-25 15:31:34 +03:00

61 lines
2.5 KiB
Text

# ui_hold.ludic — on-hold fires every frame a button is held, by the pointer (still when it is dragged
# off, until let go) or by Enter or the pad's A on the focus, with event.dt and event.t on the ui clock,
# the same at 60 and 240 Hz; on-down and on-up still mark the ends.
import "ludic.ui"
program UiHold {
numbers float
state UiHoldState {
now: float = 0.0
held: float = 0.0
frames: int = 0
last_t: float = 0.0
ends: string = ""
}
view Craft (ui_hold_st: mut UiHoldState) {
on tick(dt: float, t: float) {
ui_hold_st.held = ui_hold_st.held + dt
ui_hold_st.frames = ui_hold_st.frames + 1
ui_hold_st.last_t = t
}
on down() { ui_hold_st.ends = ui_hold_st.ends + "d" }
on up() { ui_hold_st.ends = ui_hold_st.ends + "u" }
}
const PAGE: string = "<ui><screen name='h'><button on-hold='tick(event.dt, event.t)' on-down='down()' on-up='up()'>Make</button></screen></ui>"
function clock(ui_hold_st: UiHoldState) -> float { return ui_hold_st.now }
function frame(ui_st: mut UiState, i: UiInput) -> UiNode {
ui_input(ui_st, i)
ui_show(ui_st, "h", view_craft(), 0.0, 0.0, 400.0, 400.0)
let r: UiNode = ui_nodes(ui_st, "h", view_craft())
ui_place(ui_st, r, 0.0, 0.0, 400.0, 400.0)
return r.children[0]
}
# held for `secs` at `hz`, by the pointer (off the button after the first frame) or by A
function hold(ui_hold_st: mut UiHoldState, ui_st: mut UiState, b: UiNode, secs: float, hz: int, pad: bool) -> string {
ui_hold_st.held = 0.0
ui_hold_st.frames = 0
let n = int(secs * float(hz) + 0.5)
for k in 0 .. n + 1 {
let i = new UiInput
i.pad_a = pad
i.down = not pad
i.x = b.x + 5.0
i.y = b.y + 5.0
if k > 0 and not pad { i.x = 390.0 }
frame(ui_st, i)
ui_hold_st.now = ui_hold_st.now + 1.0 / float(hz)
}
frame(ui_st, new UiInput)
ui_hold_st.now = ui_hold_st.now + 1.0 / float(hz)
return `{ui_hold_st.frames} frames {int(Math.round(ui_hold_st.held * 1000.0))} ms t {int(Math.round(ui_hold_st.last_t * 1000.0))}`
}
entry (ui_hold_st: mut UiHoldState, ui_st: mut UiState) {
ui_backend(ui_st, new UiBackend)
ui_clock(ui_st, fn clock)
ui_load_text(ui_st, PAGE, "h.xml")
let b = frame(ui_st, new UiInput)
let slow = hold(ui_hold_st, ui_st, b, 0.5, 60, false)
let fast = hold(ui_hold_st, ui_st, b, 0.5, 240, false)
let pad = hold(ui_hold_st, ui_st, b, 0.25, 60, true)
print(`{slow} | {fast} | pad {pad} | {ui_hold_st.ends}`)
}
}