Tutorial: build Focus
.
In this tutorial you build one small app from an empty file: a task list with a focus timer and a log. It takes five steps, and each step adds one idea to a program that already runs. By the end you will have used every core concept, and seen how they depend on each other.
What you are building
Live: this is the program below, running
Add
Read the tutorial
Focus
Build something small
Focus
2
openAdd a task, press
Focus
, and let the fifteen seconds run out. That is the finished app.Step
You add
You learn
1
A list you can check off
Model, message,
update
, view
2
A field to add tasks, and a count
Input, and what does not belong in the model
3
A countdown
Subscriptions
4
A log with the time of day
Commands and services
5
A test of a whole session
Why the rules pay off
You do not need to have read anything else. If a step feels fast, each one links to the page that goes deeper.
Note:
Every listing here is a real file under docs/examples/src/focus
, one per step, and each demo is that file running. Styling lives in a separate look.silk
so the steps stay about behavior. Styling covers it. Step 1: a list you can check off
Live: this is the program below, running
Read the tutorial
Build something small
Start with the question every Silk UI program starts with:
what does this app have to remember?
For a list of tasks, it is the tasks. That is the model.examples/src/focus/step1.silk
Copy
pub
struct
Task
{
/// Never reused, so it can be the row's key.
pub
id: u64,
pub
title: String
,
pub
done: bool,
}examples/src/focus/step1.silk
Copy
pub
struct
Focus
{
pub
tasks: List
<Task
>,
pub
nextId: u64,
}nextId
is there so every task gets an id that is never reused. Rows need a stable identity, and a position in the list is not one: positions shift when a task is removed.Next question:
what can happen?
So far, one thing. The user can click a checkbox.examples/src/focus/step1.silk
Copy
pub
union
Message
{
ClickedToggle
{ pub
id: u64 },
}A message is named for what happened, in the past tense:
ClickedToggle
, and not ToggleTask
. It reports. It does not command. The difference starts to matter in step 3, when messages arrive that no user sent.Now the two functions.
update
says what each message does to the model:examples/src/focus/step1.silk
Copy
effect
fn
update
(mut
model: Focus
, message: Message
) -> Next
! OutOfMemoryError
? &mut
Allocator
{
match
move
message {
Message
.ClickedToggle
{ id } => {
run
toggle
(&mut
model, id)
}
}
return
Next
.of
(move
model)
}And
view
says what the model looks like:examples/src/focus/step1.silk
Copy
fn
view
(model: &Focus
, h: &Document
<Message
>) -> Node
{
return
h.column
(
&[h.style
(&[css.padding
(px
(16.0
)), css.rowGap
(px
(12.0
)), css.color
(rgb
(INK
))])],
&[
h.column
(
&[h.accessRole
(Role
.List
)],
&[h.each
(model.tasks.asSlice
(), |task| h.keyed
(task.id, row
(h, task)))],
),
],
)
}examples/src/focus/step1.silk
Copy
/// One task: a checkbox and its title.
fn
row
(h: &Document
<Message
>, task: &Task
) -> Node
{
return
h.row
(
&[h.accessRole
(Role
.ListItem
), rowLook<Message
>(h)],
&[
check
(h, task.done, String
.view
(&task.title), Message
.ClickedToggle
{ id: task.id }),
h.box
(&[titleLook<Message
>(h, task.done)], &[h.text
(String
.view
(&task.title))]),
],
)
}Three things to notice in the view.
•
row
is an ordinary function. There is no component system to learn: a piece of UI is a function that returns a Node
.•
h.each
builds one node per task, and h.keyed(task.id, ...)
tells the runtime which row is which, so a row keeps its identity when the list changes.•
Message.ClickedToggle { id: task.id }
is a value, built while drawing. Nothing runs when the view is built. If the user clicks, the runtime hands that value to update
.The last piece is
init
, the model the program starts with:examples/src/focus/step1.silk
Copy
effect
fn
init
() -> Next
! OutOfMemoryError
? &mut
Allocator
{
let
mut
model = Focus
{
tasks: List
<Task
>.make
(),
nextId: 1
,
}
run
add
(&mut
model, "Read the tutorial"
)
run
add
(&mut
model, "Build something small"
)
return
Next
.of
(move
model)
}That is a complete program. Click a checkbox above: the message goes to
update
, update
returns a model with that task flipped, and view
draws it struck through.The whole file at this point:
examples/src/focus/step1.silk
Copy
//! Focus, step 1: a list of tasks you can check off. A model, a message, an update, a view.
import
core.look { INK
, rgb }
import
focus.look { check, rowLook, titleLook }
import
loom.css
import
loom.css { px }
import
loom.lib { Document
, Node
, NoCommand
, NoOutput
, Program
, Role
, Update
}
import
silk.collections.list { List
}
import
silk.mem.allocator { Allocator
, OutOfMemoryError
}
import
silk.num.usize
import
silk.text.string { String
}
pub
struct
Task
{
/// Never reused, so it can be the row's key.
pub
id: u64,
pub
title: String
,
pub
done: bool,
}
pub
struct
Focus
{
pub
tasks: List
<Task
>,
pub
nextId: u64,
}
pub
union
Message
{
ClickedToggle
{ pub
id: u64 },
}
type
Next
= Update
<Focus
, NoCommand
, NoOutput
>
effect
fn
add
(model: &mut
Focus
, title: string) -> ()
! OutOfMemoryError
? &mut
Allocator
{
let
id = model.nextId
model.nextId = id + 1
run
model.tasks.append
(Task
{ id: id, title: run
String
.copy
(title), done: false
})
}
/// Checks or unchecks the task with this id.
effect
fn
toggle
(model: &mut
Focus
, id: u64) -> ()
! OutOfMemoryError
? &mut
Allocator
{
let
mut
i: usize = 0
while
i < model.tasks.length
() {
if
model.tasks.asSlice
()[i].id == id {
let
mut
task = model.tasks.remove
(i)
task.done = !task.done
run
model.tasks.insert
(i, move
task)
}
i = i + 1
}
}
impl
Program
<Message
, NoCommand
> for
Focus
{
effect
fn
init
() -> Next
! OutOfMemoryError
? &mut
Allocator
{
let
mut
model = Focus
{
tasks: List
<Task
>.make
(),
nextId: 1
,
}
run
add
(&mut
model, "Read the tutorial"
)
run
add
(&mut
model, "Build something small"
)
return
Next
.of
(move
model)
}
effect
fn
update
(mut
model: Focus
, message: Message
) -> Next
! OutOfMemoryError
? &mut
Allocator
{
match
move
message {
Message
.ClickedToggle
{ id } => {
run
toggle
(&mut
model, id)
}
}
return
Next
.of
(move
model)
}
fn
view
(model: &Focus
, h: &Document
<Message
>) -> Node
{
return
h.column
(
&[h.style
(&[css.padding
(px
(16.0
)), css.rowGap
(px
(12.0
)), css.color
(rgb
(INK
))])],
&[
h.column
(
&[h.accessRole
(Role
.List
)],
&[h.each
(model.tasks.asSlice
(), |task| h.keyed
(task.id, row
(h, task)))],
),
],
)
}
}
/// One task: a checkbox and its title.
fn
row
(h: &Document
<Message
>, task: &Task
) -> Node
{
return
h.row
(
&[h.accessRole
(Role
.ListItem
), rowLook<Message
>(h)],
&[
check
(h, task.done, String
.view
(&task.title), Message
.ClickedToggle
{ id: task.id }),
h.box
(&[titleLook<Message
>(h, task.done)], &[h.text
(String
.view
(&task.title))]),
],
)
}More on these: Your first program, Views.
Step 2: adding tasks
Live: this is the program below, running
Add
Read the tutorial
Build something small
2
openA text field raises a question that trips people up in every framework: where does the text live while it is being typed? Here the answer is always the same. It is state, so it lives in the model.
examples/src/focus/step2.silk
Copy
pub
struct
Focus
{
pub
tasks: List
<Task
>,
/// What is typed in the field and not added yet.
pub
draft: String
,
pub
nextId: u64,
}Two more things can happen now: the text changed, and the user asked to add it.
examples/src/focus/step2.silk
Copy
pub
union
Message
{
ChangedDraft
{ pub
value: String
},
SubmittedDraft
,
ClickedToggle
{ pub
id: u64 },
}The field shows
model.draft
and reports every change:Silk
Copy
h.
input
(
String
.view
(&model.draft),
&[
h.onInput
(|value| Message
.ChangedDraft
{ value: move
value }),
h.onEnter
(Message
.SubmittedDraft
),
...
],
),
primary
(h, "Add"
, Message
.SubmittedDraft
),Notice that Enter and the Add button send the same message.
update
does not care how the user asked. It handles "the draft was submitted" once:examples/src/focus/step2.silk
Copy
effect
fn
update
(mut
model: Focus
, message: Message
) -> Next
! OutOfMemoryError
? &mut
Allocator
{
match
move
message {
Message
.ChangedDraft
{ value } => {
model.draft = move
value
}
Message
.SubmittedDraft
=> {
let
draft = move
model.draft
model.draft = String
.make
()
let
title = String
.trim
(String
.view
(&draft))
if
String
.byteLength
(title) != 0
{
run
add
(&mut
model, title)
}
}
Message
.ClickedToggle
{ id } => {
run
toggle
(&mut
model, id)
}
}
return
Next
.of
(move
model)
}After adding,
update
puts an empty draft in the model, and the field clears. You did not clear the field. You changed the model, and the field shows the model.What stays out of the model
The line under the list says how many tasks are open. It would be easy to add an
openCount
field and keep it up to date. Do not. The count can be computed from the tasks, so storing it would create two places that must agree, and one day they would not.examples/src/focus/step2.silk
Copy
/// How many tasks are not done yet. Nothing stores this number: it is counted when asked.
pub
fn
open
(model: &Focus
) -> usize {
let
tasks = model.tasks.asSlice
()
let
mut
count: usize = 0
let
mut
i: usize = 0
while
i < tasks.length {
if
!tasks[i].done {
count = count + 1
}
i = i + 1
}
return
count
}The view calls
open(model)
when it draws. The rule: the model holds the smallest state that everything else can be computed from.
Candidate
In the model?
Why
The tasks
Yes
Nothing else can produce them
The draft text
Yes
It changes over time and nothing else knows it
How many are open
No
Computed from the tasks
Whether the draft is empty
No
Computed from the draft
Whether a row is hovered
No
The runtime tracks it. See Styling
More on this: Events and input.
Step 3: a countdown
Live: this is the program below, running
Add
Read the tutorial
Focus
Build something small
Focus
2
openPress Focus on a task and watch it count down from fifteen. When it reaches zero the session is counted on the task.
First the model. A session needs two facts: which task, and how much time is left.
examples/src/focus/step3.silk
Copy
pub
struct
Focus
{
pub
tasks: List
<Task
>,
/// What is typed in the field and not added yet.
pub
draft: String
,
pub
nextId: u64,
/// The id of the task being worked on, or zero when there is none.
pub
focused: u64,
pub
secondsLeft: i64,
}Then what can happen. The user can start and stop. And for the first time, something happens that the user did not do: a second passes.
examples/src/focus/step3.silk
Copy
pub
union
Message
{
ChangedDraft
{ pub
value: String
},
SubmittedDraft
,
ClickedToggle
{ pub
id: u64 },
ClickedFocus
{ pub
id: u64 },
ClickedStop
,
Ticked
,
}update
treats Ticked
like any other message:examples/src/focus/step3.silk
Copy
effect
fn
update
(mut
model: Focus
, message: Message
) -> Next
! OutOfMemoryError
? &mut
Allocator
{
match
move
message {
Message
.ChangedDraft
{ value } => {
model.draft = move
value
}
Message
.SubmittedDraft
=> {
let
draft = move
model.draft
model.draft = String
.make
()
let
title = String
.trim
(String
.view
(&draft))
if
String
.byteLength
(title) != 0
{
run
add
(&mut
model, title)
}
}
Message
.ClickedToggle
{ id } => {
run
toggle
(&mut
model, id)
}
Message
.ClickedFocus
{ id } => {
model.focused = id
model.secondsLeft = SESSION
}
Message
.ClickedStop
=> {
model.focused = 0
}
Message
.Ticked
=> {
model.secondsLeft = model.secondsLeft - 1
if
model.secondsLeft <= 0
{
// The session is over: count it, and stop focusing. The timer stops by itself.
let
id = model.focused
model.focused = 0
run
finish
(&mut
model, id)
}
}
}
return
Next
.of
(move
model)
}So where do ticks come from? You might expect a
startTimer()
call in the ClickedFocus
branch and a stopTimer()
in three other places. That is the kind of code that leaks timers. Silk UI turns it around. You write one function that says what the program wants to listen to, given the model
:examples/src/focus/step3.silk
Copy
/// The timer runs only while a task is focused.
fn
subscriptions
(model: &Focus
, subs: &mut
Subscriptions
<Message
>) -> () {
if
model.focused != 0
{
subs.every
(1
, 1.0
, |time| Message
.Ticked
)
}
}The runtime calls this after every update and compares the answer with the last one. When
focused
becomes non-zero, the answer starts to include a timer, so the runtime starts one. When focused
goes back to zero, for any reason, the timer is gone from the answer, so the runtime stops it.Look at the
Ticked
branch again. When the time runs out it sets focused
to zero and does nothing else. It does not stop the timer. It cannot forget to.The view follows the same pattern. Each row decides what to show on its right side from the model:
examples/src/focus/step3.silk
Copy
/// One task. What is on its right depends on the model: the countdown and Stop on the task
/// being worked on, Focus on the others while nothing is running.
fn
row
(h: &Document
<Message
>, model: &Focus
, task: &Task
) -> Node
{
return
h.row
(
&[h.accessRole
(Role
.ListItem
), rowLook<Message
>(h)],
&[
check
(h, task.done, String
.view
(&task.title), Message
.ClickedToggle
{ id: task.id }),
h.box
(&[titleLook<Message
>(h, task.done)], &[h.text
(String
.view
(&task.title))]),
if
task.sessions > 0
{
h.row
(&[h.style
(&[css.color
(rgb
(MUTED
))])], &[h.text
("×"
), h.number
(task.sessions)])
} else
{
h.empty
()
},
if
model.focused == task.id {
h.row
(
&[h.style
(&[css.alignItems
(Align
.Center
), css.columnGap
(px
(10.0
))])],
&[
pair
(h, model.secondsLeft / 60
, model.secondsLeft % 60
),
button
(h, "Stop"
, Message
.ClickedStop
),
],
)
} else
if
model.focused == 0
&& !task.done {
button
(h, "Focus"
, Message
.ClickedFocus
{ id: task.id })
} else
{
h.empty
()
},
],
)
}The Focus buttons disappear during a session because the view does not include them while
model.focused != 0
. There is no "hide the buttons" step anywhere.That is the idea worth taking from this step:
the timer, like the screen, is a function of the model.
You describe what should exist now, and the runtime makes it so.More on this: Subscriptions.
Step 4: a log, and the time of day
Live: this is the program below, running
Add
Read the tutorial
Focus
Build something small
Focus
2
openWhen a session ends, a line appears under the list with the time it ended. That needs the time of day, and here you hit a wall on purpose:
update
cannot read the clock. Its signature allows it to allocate memory and nothing else, and the compiler holds it to that.So
update
asks. It returns a command
next to the model: a value that describes what it wants.examples/src/focus/step4.silk
Copy
/// What the program asks to have done.
pub
union
Command
{
/// Find out what time it is, for the session that just ended on the task called `title`.
StampSession
{ pub
title: String
},
}In the
Ticked
branch, the end of a session now looks like this:Silk
Copy
let
title = run
finish
(&mut
model, id)
return
run
Next
.with
(move
model, Command
.StampSession
{ title: move
title })The runtime takes the command and runs it. Running a command is the one place in the program that reaches outside:
examples/src/focus/step4.silk
Copy
impl
CommandSet
<Message
? &mut
Clock
> for
Command
{
/// Does the work of a command and says how it ended.
effect
fn
execute
(self: Self
) -> Message
! OutOfMemoryError
? &mut
Clock
{
match
move
self {
Command
.StampSession
{ title } => {
return
Message
.GotTime
{ title: move
title, minutes: run
Clock
.minutes
() }
}
}
}
}execute
gets the time and returns a message with it. That message goes to update
like every other one:examples/src/focus/step4.silk
Copy
pub
union
Message
{
ChangedDraft
{ pub
value: String
},
SubmittedDraft
,
ClickedToggle
{ pub
id: u64 },
ClickedFocus
{ pub
id: u64 },
ClickedStop
,
Ticked
,
GotTime
{ pub
title: String
, pub
minutes: u32 },
}Silk
Copy
Message
.GotTime
{ title, minutes } => {
run
model.log.append
(Entry
{ title: move
title, minutes: minutes })
}So a command is a round trip:
update
returns a request, the runtime does the work, and the answer comes back as a message. A command always ends in a message.Who has a clock?
execute
does not call the system clock either. It calls Clock.minutes()
, and Clock
is a service
: a small interface the program declares and somebody else implements.examples/src/focus/step4.silk
Copy
/// The time of day. The program only says it needs one: a page, a native app and a test
/// each provide their own.
pub
service
Clock
{
/// Minutes since midnight.
effect
fn
minutes
() -> u32 ? &mut
Clock
}Whoever starts the program provides it. In this page, the clock is three lines that call the browser's
Date
. In a native app it would read the system clock. In the test in the next step it always says 14:32.Piece
Knows about the outside world?
update
, view
, subscriptions
No. Plain functions of their arguments
Command
No. It is data that describes a wish
execute
Only through services it names
The service's implementation
Yes. This is the only code that differs per platform
This is the same shape you would use to save the tasks to disk or to fetch them from a server: a
Store
service with load
and save
, a Command.Save
, and a Message.Loaded
that brings the answer back.The whole file at this point:
examples/src/focus/step4.silk
Copy
//! Focus, step 4: when a session ends the program asks what time it is, and keeps a log.
import
core.look { INK
, MUTED
, button, fieldLook, primary, rgb }
import
focus.look { check, pair, rowLook, titleLook }
import
loom.css
import
loom.css { px, Align
}
import
loom.lib { CommandSet
, Document
, Node
, NoOutput
, Program
, Role
, Subscriptions
, Update
}
import
silk.collections.list { List
}
import
silk.mem.allocator { Allocator
, OutOfMemoryError
}
import
silk.num.u32
import
silk.num.usize
import
silk.text.string { String
}
/// How long a session lasts, in seconds. A real one would be 25 minutes: this one is short
/// so that you can watch it end.
pub
const
SESSION
: i64 = 15
/// The time of day. The program only says it needs one: a page, a native app and a test
/// each provide their own.
pub
service
Clock
{
/// Minutes since midnight.
effect
fn
minutes
() -> u32 ? &mut
Clock
}
pub
struct
Task
{
/// Never reused, so it can be the row's key.
pub
id: u64,
pub
title: String
,
pub
done: bool,
/// How many sessions were finished on this task.
pub
sessions: i64,
}
/// A finished session, for the log.
pub
struct
Entry
{
pub
title: String
,
/// When it ended, in minutes since midnight.
pub
minutes: u32,
}
pub
struct
Focus
{
pub
tasks: List
<Task
>,
/// What is typed in the field and not added yet.
pub
draft: String
,
pub
nextId: u64,
/// The id of the task being worked on, or zero when there is none.
pub
focused: u64,
pub
secondsLeft: i64,
pub
log: List
<Entry
>,
}
pub
union
Message
{
ChangedDraft
{ pub
value: String
},
SubmittedDraft
,
ClickedToggle
{ pub
id: u64 },
ClickedFocus
{ pub
id: u64 },
ClickedStop
,
Ticked
,
GotTime
{ pub
title: String
, pub
minutes: u32 },
}
/// What the program asks to have done.
pub
union
Command
{
/// Find out what time it is, for the session that just ended on the task called `title`.
StampSession
{ pub
title: String
},
}
impl
CommandSet
<Message
? &mut
Clock
> for
Command
{
/// Does the work of a command and says how it ended.
effect
fn
execute
(self: Self
) -> Message
! OutOfMemoryError
? &mut
Clock
{
match
move
self {
Command
.StampSession
{ title } => {
return
Message
.GotTime
{ title: move
title, minutes: run
Clock
.minutes
() }
}
}
}
}
type
Next
= Update
<Focus
, Command
, NoOutput
>
/// How many tasks are not done yet. Nothing stores this number: it is counted when asked.
pub
fn
open
(model: &Focus
) -> usize {
let
tasks = model.tasks.asSlice
()
let
mut
count: usize = 0
let
mut
i: usize = 0
while
i < tasks.length {
if
!tasks[i].done {
count = count + 1
}
i = i + 1
}
return
count
}
effect
fn
add
(model: &mut
Focus
, title: string) -> ()
! OutOfMemoryError
? &mut
Allocator
{
let
id = model.nextId
model.nextId = id + 1
run
model.tasks.append
(Task
{ id: id, title: run
String
.copy
(title), done: false
, sessions: 0
})
}
/// Checks or unchecks the task with this id.
effect
fn
toggle
(model: &mut
Focus
, id: u64) -> ()
! OutOfMemoryError
? &mut
Allocator
{
let
mut
i: usize = 0
while
i < model.tasks.length
() {
if
model.tasks.asSlice
()[i].id == id {
let
mut
task = model.tasks.remove
(i)
task.done = !task.done
run
model.tasks.insert
(i, move
task)
}
i = i + 1
}
}
/// Counts one more session on the task with this id, and returns the task's title.
effect
fn
finish
(model: &mut
Focus
, id: u64) -> String
! OutOfMemoryError
? &mut
Allocator
{
let
mut
title = String
.make
()
let
mut
i: usize = 0
while
i < model.tasks.length
() {
if
model.tasks.asSlice
()[i].id == id {
let
mut
task = model.tasks.remove
(i)
task.sessions = task.sessions + 1
title = run
String
.copy
(String
.view
(&task.title))
run
model.tasks.insert
(i, move
task)
}
i = i + 1
}
return
move
title
}
impl
Program
<Message
, Command
> for
Focus
{
effect
fn
init
() -> Next
! OutOfMemoryError
? &mut
Allocator
{
let
mut
model = Focus
{
tasks: List
<Task
>.make
(),
draft: String
.make
(),
nextId: 1
,
focused: 0
,
secondsLeft: 0
,
log: List
<Entry
>.make
(),
}
run
add
(&mut
model, "Read the tutorial"
)
run
add
(&mut
model, "Build something small"
)
return
Next
.of
(move
model)
}
effect
fn
update
(mut
model: Focus
, message: Message
) -> Next
! OutOfMemoryError
? &mut
Allocator
{
match
move
message {
Message
.ChangedDraft
{ value } => {
model.draft = move
value
}
Message
.SubmittedDraft
=> {
let
draft = move
model.draft
model.draft = String
.make
()
let
title = String
.trim
(String
.view
(&draft))
if
String
.byteLength
(title) != 0
{
run
add
(&mut
model, title)
}
}
Message
.ClickedToggle
{ id } => {
run
toggle
(&mut
model, id)
}
Message
.ClickedFocus
{ id } => {
model.focused = id
model.secondsLeft = SESSION
}
Message
.ClickedStop
=> {
model.focused = 0
}
Message
.Ticked
=> {
model.secondsLeft = model.secondsLeft - 1
if
model.secondsLeft <= 0
{
// The session is over. Updating cannot look at a clock, so it asks.
let
id = model.focused
model.focused = 0
let
title = run
finish
(&mut
model, id)
return
run
Next
.with
(move
model, Command
.StampSession
{ title: move
title })
}
}
Message
.GotTime
{ title, minutes } => {
run
model.log.append
(Entry
{ title: move
title, minutes: minutes })
}
}
return
Next
.of
(move
model)
}
fn
view
(model: &Focus
, h: &Document
<Message
>) -> Node
{
return
h.column
(
&[h.style
(&[css.padding
(px
(16.0
)), css.rowGap
(px
(12.0
)), css.color
(rgb
(INK
))])],
&[
h.row
(
&[h.style
(&[css.columnGap
(px
(8.0
))])],
&[
h.input
(
String
.view
(&model.draft),
&[
h.testId
("draft"
),
h.label
("New task"
),
h.placeholder
("What will you work on?"
),
h.onInput
(|value| Message
.ChangedDraft
{ value: move
value }),
h.onEnter
(Message
.SubmittedDraft
),
fieldLook<Message
>(h),
h.style
(&[css.flexGrow
(1.0
)]),
],
),
primary
(h, "Add"
, Message
.SubmittedDraft
),
],
),
h.column
(
&[h.accessRole
(Role
.List
)],
&[h.each
(model.tasks.asSlice
(), |task| h.keyed
(task.id, row
(h, model, task)))],
),
h.row
(
&[h.style
(&[css.columnGap
(px
(6.0
)), css.color
(rgb
(MUTED
))])],
&[h.box
(&[h.testId
("open"
)], &[h.number
(usize.toI64
(open
(model)))]), h.text
("open"
)],
),
h.column
(
&[h.testId
("log"
), h.style
(&[css.rowGap
(px
(4.0
)), css.color
(rgb
(MUTED
))])],
&[h.each
(model.log.asSlice
(), |entry| logged
(h, entry))],
),
],
)
}
/// The timer runs only while a task is focused.
fn
subscriptions
(model: &Focus
, subs: &mut
Subscriptions
<Message
>) -> () {
if
model.focused != 0
{
subs.every
(1
, 1.0
, |time| Message
.Ticked
)
}
}
}
/// One task. What is on its right depends on the model: the countdown and Stop on the task
/// being worked on, Focus on the others while nothing is running.
fn
row
(h: &Document
<Message
>, model: &Focus
, task: &Task
) -> Node
{
return
h.row
(
&[h.accessRole
(Role
.ListItem
), rowLook<Message
>(h)],
&[
check
(h, task.done, String
.view
(&task.title), Message
.ClickedToggle
{ id: task.id }),
h.box
(&[titleLook<Message
>(h, task.done)], &[h.text
(String
.view
(&task.title))]),
if
task.sessions > 0
{
h.row
(&[h.style
(&[css.color
(rgb
(MUTED
))])], &[h.text
("×"
), h.number
(task.sessions)])
} else
{
h.empty
()
},
if
model.focused == task.id {
h.row
(
&[h.style
(&[css.alignItems
(Align
.Center
), css.columnGap
(px
(10.0
))])],
&[
pair
(h, model.secondsLeft / 60
, model.secondsLeft % 60
),
button
(h, "Stop"
, Message
.ClickedStop
),
],
)
} else
if
model.focused == 0
&& !task.done {
button
(h, "Focus"
, Message
.ClickedFocus
{ id: task.id })
} else
{
h.empty
()
},
],
)
}
/// One line of the log: the task and when its session ended.
fn
logged
(h: &Document
<Message
>, entry: &Entry
) -> Node
{
return
h.row
(
&[h.style
(&[css.columnGap
(px
(6.0
)), css.fontSize
(px
(13.0
))])],
&[
pair
(h, u32.toI64
(entry.minutes / 60
), u32.toI64
(entry.minutes % 60
)),
h.text
(String
.view
(&entry.title)),
],
)
}More on this: Commands.
Step 5: test a whole session
Everything so far had a purpose beyond tidiness. Because the model is the only state, messages are the only input, and the world is behind a service, you can run the whole app in a test, with no window, in milliseconds.
tests/src/focus.silk
Copy
//! The test of the tutorial's finished app: a whole session, from typing a task to the log.
import
examples.focus.step4 { Clock
, Command
, Focus
, Message
, SESSION
, open }
import
loom.lib { drain, tick, TreeError
}
import
loom.program as
program
import
loom_dom.html { Html
}
import
silk.core.effect
{ Effect
}
import
silk.mem.allocator { Allocator
, OutOfMemoryError
}
import
silk.num.i64
import
silk.testing.testing { Testing
, AssertionError
}
import
silk.text.string { String
}
/// A clock that always says the same time.
struct
Stopped
{
minutes: u32,
}
impl
Clock
for
Stopped
{
effect
fn
minutes
(self: &mut
Self
) -> u32 {
return
self.minutes
}
}
effect
fn
sessionBody
() -> ()
! AssertionError
<'static
> | TreeError
| OutOfMemoryError
? &mut
Clock
| &mut
Allocator
{
let
mut
page = Html
.make
()
let
mut
app = run
program.make<Focus
, Message
, Command
>()
run
app.start
(&mut
page, 0.0
)
run
drain
(&mut
app, &mut
page)
run
Testing
.expect
(open
(&app.model.value) == 2
, "starts with two open tasks"
)
// Typing and adding are messages, exactly as the view would send them.
app.send
(Message
.ChangedDraft
{ value: run
String
.copy
("Write the report"
) })
app.send
(Message
.SubmittedDraft
)
run
drain
(&mut
app, &mut
page)
run
Testing
.expect
(open
(&app.model.value) == 3
, "the new task is open"
)
run
Testing
.expect
(app.nextDeadline
().isNone
(), "no timer while nothing is focused"
)
// Focus on it, and let the whole session pass.
app.send
(Message
.ClickedFocus
{ id: 3
})
run
drain
(&mut
app, &mut
page)
let
mut
second: i64 = 1
while
second <= SESSION
{
run
tick
(&mut
app, &mut
page, i64.toF64
(second) + 0.05
, false
)
second = second + 1
}
run
drain
(&mut
app, &mut
page)
run
Testing
.expect
(app.model.value.focused == 0
, "the session ended by itself"
)
run
Testing
.expect
(app.nextDeadline
().isNone
(), "and the timer with it"
)
run
Testing
.expect
(app.model.value.tasks.asSlice
()[2
].sessions == 1
, "the task counts it"
)
let
log = app.model.value.log.asSlice
()
run
Testing
.expect
(log.length == 1
, "the log has one line"
)
run
Testing
.expect
(log[0
].minutes == 872
, "stamped with the clock's time"
)
run
Testing
.expect
(String
.view
(&log[0
].title) == "Write the report"
, "and the task's title"
)
}
test effect
fn
aWholeSession
() -> ()
! AssertionError
<'static
> | TreeError
| OutOfMemoryError
{
let
mut
allocator = Allocator
.systemAllocatorProvider
()
let
mut
clock = Stopped
{ minutes: 872
}
run
sessionBody
()
|> Effect
.provideMut<Clock
>(&mut
clock)
|> Effect
.provideMut<Allocator
>(&mut
allocator)
}Read
sessionBody
as a script of what a user would do:1.
program.make
builds the same program the demo runs, and app.start
runs init
.2.
app.send(...)
delivers a message as if the view had sent it. drain
lets the loop run until it is idle.3.
tick
moves time forward. Fifteen ticks are a whole session, and they take no real time at all.4.
app.model.value
is the model. The test reads it directly.And
Stopped
is the clock. The test provides it the same way the page provides its real one, so the log's time is known in advance: 872 minutes after midnight, which is 14:32.Notice what the test checks that would be hard to check by hand: after the session,
app.nextDeadline()
is empty. The timer really did stop.More on this: Testing.
What you built, and what you used
Concept
Where it showed up
Model
Tasks, draft, focused task, seconds left, log
Messages
Three from the view, one from a timer, one from a command
update
One
match
with every behavior of the appview
Functions of the model, with
row
and logged
as helpersDerived data
open(model)
, never storedSubscription
A timer that exists exactly while a task is focused
Command
StampSession
, a request returned from update
Service
Clock
, real in the page and fixed in the testTest
A full session with no screen
The order you added things in is also a good order to design in: state first, then what can happen, then what it looks like, then how the world gets in. Thinking in Silk UI turns that into a method.
Make it yours
Changes to try, from easy to hard. Each one is a small edit if you ask the same questions: what must be remembered, what can happen, what does it look like?
1.
Remove a task.
One new message and a button in row
. What should happen if the removed task is the focused one?2.
Pause and resume.
Does this need new state, or only a new message? What does subscriptions
look at now?3.
Session length.
Let the user choose between 15 and 25 minutes. Where does the choice live?4.
Hide finished tasks.
A toggle and a filter in the view. Should the filtered list be stored?5.
Remember the tasks.
Add a Store
service with load
and save
. init
can return a command too, so loading starts with the program.6.
Put the filter in the address.
/open
shows open tasks only. Routing shows how the address becomes a message.