Subscriptions
.
Some messages come from neither the view nor a command: a timer ticks, a key is pressed while nothing has focus, the window changes size. A program gets those by
subscribing
.Note:
A command is for something that happens once because you asked. A subscription is for something that keeps happening while a condition holds. Step 3 of the tutorial shows one driving a countdown. A stopwatch
Live: this is the program below, running
00
:00
.0Start
Reset
Start it and press Lap a few times. The quickest lap turns green and the slowest red.
examples/src/core/stopwatch.silk
Copy
//! A stopwatch: a timer subscription that exists only while the watch runs.
import
core.look { ACCENT
, INK
, LINE
, MUTED
, button, primary, rgb }
import
loom.css
import
loom.css { px, BorderStyle
, Overflow
}
import
loom.lib { Document
, Node
, NoCommand
, NoOutput
, Program
, Subscriptions
, Update
}
import
silk.collections.list { List
}
import
silk.mem.allocator { Allocator
, OutOfMemoryError
}
import
silk.num.i64
import
silk.num.usize
pub
struct
Stopwatch
{
/// Tenths of a second.
pub
tenths: i64,
pub
running: bool,
pub
laps: List
<Lap
>,
}
pub
struct
Lap
{
pub
number: i64,
/// What the watch showed when the lap ended.
pub
at: i64,
/// How long the lap took: `at`, less the `at` of the lap before.
pub
took: i64,
}
pub
union
Message
{
ClickedStartStop
,
ClickedLap
,
ClickedReset
,
Ticked
,
}
type
Next
= Update
<Stopwatch
, NoCommand
, NoOutput
>
impl
Program
<Message
, NoCommand
> for
Stopwatch
{
effect
fn
init
() -> Next
! OutOfMemoryError
? &mut
Allocator
{
return
Next
.of
(Stopwatch
{ tenths: 0
, running: false
, laps: List
<Lap
>.make
() })
}
effect
fn
update
(mut
model: Stopwatch
, message: Message
) -> Next
! OutOfMemoryError
? &mut
Allocator
{
match
move
message {
Message
.ClickedStartStop
=> {
model.running = !model.running
}
Message
.ClickedLap
=> {
let
count = model.laps.length
()
let
before = if
count == 0
{
0
} else
{
model.laps.asSlice
()[count - 1
].at
}
let
now = model.tenths
run
model.laps.append
(Lap
{ number: usize.toI64
(count) + 1
, at: now, took: now - before })
}
Message
.ClickedReset
=> {
model.tenths = 0
model.running = false
model.laps.clear
()
}
Message
.Ticked
=> {
model.tenths = model.tenths + 1
}
}
return
Next
.of
(move
model)
}
fn
view
(model: &Stopwatch
, h: &Document
<Message
>) -> Node
{
return
h.column
(
&[
h.style
(
&[css.padding
(px
(16.0
)), css.rowGap
(px
(12.0
)), css.color
(rgb
(INK
)), css.maxWidth
(px
(320.0
))],
),
],
&[
h.row
(
&[
h.testId
("time"
),
h.style
(
&[
css.fontSize
(px
(40.0
)),
css.fontWeight
(700.0
),
css.fontVariantNumeric
("tabular-nums"
),
],
),
],
&[clock
(h, model.tenths)],
),
h.row
(
&[h.style
(&[css.columnGap
(px
(8.0
))])],
&[
primary
(
h,
if
model.running {
"Stop"
} else
{
"Start"
},
Message
.ClickedStartStop
,
),
if
model.running {
button
(h, "Lap"
, Message
.ClickedLap
)
} else
{
button
(h, "Reset"
, Message
.ClickedReset
)
},
],
),
h.column
(
&[
h.testId
("laps"
),
h.style
(
&[
css.maxHeight
(px
(132.0
)),
css.overflowY
(Overflow
.Auto
),
css.fontVariantNumeric
("tabular-nums"
),
],
),
],
&[h.each
(model.laps.asSlice
(), |lap| h.keyed
(i64.toU64
(lap.number), row
(h, model, lap)))],
),
],
)
}
/// What the program listens to right now. The runtime asks after every update: the timer
/// starts when `running` turns true and stops when it turns false.
fn
subscriptions
(model: &Stopwatch
, subs: &mut
Subscriptions
<Message
>) -> () {
if
model.running {
subs.every
(1
, 0.1
, |time| Message
.Ticked
)
}
}
}
/// Whether a lap is the quickest of them (`quickest`) or the slowest. With fewer than two
/// laps there is nothing to compare.
fn
extreme
(model: &Stopwatch
, lap: &Lap
, quickest: bool) -> bool {
if
model.laps.length
() < 2
{
return
false
}
let
laps = model.laps.asSlice
()
let
mut
i: usize = 0
while
i < laps.length {
let
other = laps[i].took
if
quickest && other < lap.took || !quickest && other > lap.took {
return
false
}
i = i + 1
}
return
true
}
/// One lap: its number, how long it took, and what the watch showed.
fn
row
(h: &Document
<Message
>, model: &Stopwatch
, lap: &Lap
) -> Node
{
let
ink = if
extreme
(model, lap, true
) {
ACCENT
} else
if
extreme
(model, lap, false
) {
0xB91C1C
} else
{
INK
}
return
h.row
(
&[
h.style
(
&[
css.columnGap
(px
(12.0
)),
css.paddingTop
(px
(6.0
)),
css.paddingBottom
(px
(6.0
)),
css.borderTopWidth
(px
(1.0
)),
css.borderStyle
(BorderStyle
.Solid
),
css.borderColor
(rgb
(LINE
)),
css.fontSize
(px
(14.0
)),
],
),
],
&[
h.row
(
&[h.style
(&[css.columnGap
(px
(4.0
)), css.color
(rgb
(MUTED
)), css.minWidth
(px
(56.0
))])],
&[h.box
(&[], &[h.text
("Lap"
)]), h.box
(&[], &[h.number
(lap.number)])],
),
h.box
(&[h.style
(&[css.flexGrow
(1.0
), css.color
(rgb
(ink))])], &[clock
(h, lap.took)]),
h.box
(&[h.style
(&[css.color
(rgb
(MUTED
))])], &[clock
(h, lap.at)]),
],
)
}
/// Tenths of a second as minutes, seconds and tenths: `01:07.3`.
fn
clock
(h: &Document
<Message
>, tenths: i64) -> Node
{
let
minutes = tenths / 600
let
seconds = tenths / 10
% 60
return
h.row
(
&[],
&[
two
(h, minutes),
h.text
(":"
),
two
(h, seconds),
h.text
("."
),
h.number
(tenths % 10
),
],
)
}
/// A number in two digits.
fn
two
(h: &Document
<Message
>, value: i64) -> Node
{
if
value < 10
{
return
h.row
(&[], &[h.text
("0"
), h.number
(value)])
}
return
h.number
(value)
}Subscriptions are a function of the model
examples/src/core/stopwatch.silk
Copy
/// What the program listens to right now. The runtime asks after every update: the timer
/// starts when `running` turns true and stops when it turns false.
fn
subscriptions
(model: &Stopwatch
, subs: &mut
Subscriptions
<Message
>) -> () {
if
model.running {
subs.every
(1
, 0.1
, |time| Message
.Ticked
)
}
}There is no
startTimer
and no stopTimer
. The program says what it is listening to for this model
. The runtime asks again after every update, starts what is new, and stops what is gone.So the timer cannot leak. It runs exactly while
model.running
is true, because that is the only thing the code says.subs.every(1, 0.1, ...)
asks for a message every 0.1 seconds. The first argument is a key
: a number, unique in this program, that tells the runtime which subscription is which from one update to the next.The subscriptions there are
Call
Sends a message
subs.every(key, seconds, \|time\| ...)
Every
seconds
secondssubs.animationFrame(key, \|time\| ...)
Once per display frame, for motion the model drives
subs.keyBinding(key, "k", modifiers, \|\| ...)
When a key goes down, wherever focus is
subs.resize(key, \|width, height\| ...)
When the window or page changes size
subs.location(key, \|path\| ...)
When the address changes. See Routing
subs.port(key, "name", \|text\| ...)
When the host posts text to a named port
A native app has a few more, for its menu bar, file dialogs and window: see The shell.
Keyboard shortcuts
Silk
Copy
import
loom.keys { MOD_CONTROL
}
fn
subscriptions
(model: &Editor
, subs: &mut
Subscriptions
<Message
>) -> () {
subs.keyBinding
(1
, "s"
, MOD_CONTROL
, || Message
.PressedSave
)
subs.keyBinding
(2
, "Escape"
, 0
, || Message
.PressedEscape
)
}The key is named as the web names it:
"s"
, "Escape"
, "ArrowUp"
. The modifiers must match exactly.While a text field has focus, plain keys belong to the field, so only Escape and chords with Control, Alt or Meta fire. A handler in the view that stops the key wins over a binding.
Ports
A port is how the outside world sends your program a message at a time of its own choosing: a response arrived, a worker finished, a socket received something.
Silk
Copy
subs.
port
(1
, "news"
, |text| Message
.GotNews
{ text: move
text })The host posts a string to the port's name, and the program gets a message. In a page that is
page.post("news", text)
from JavaScript. In a native app a worker thread posts through a Poster
. Background work shows the native side from start to end.Recap
•
subscriptions
is a function of the model. It runs after every update.•
The runtime starts what the function newly asks for and stops what it no longer asks for. There is no cleanup to write.
•
Timers, frames, keys, window size and the address are all subscriptions.
•
A port brings in messages from code outside the program.
Next: Routing.