Events and input
.
The view describes the screen, and it also says which message each thing the user does turns into. This page builds a to-do list: a text field, a list that changes, and buttons in every row.
Note:
In the loop, this is the step from the screen back to update
: what the user does becomes a message. It is steps 1 and 2 of the tutorial. A to-do list
Live: this is the program below, running
Add
Read the first program
×
Write a view
×
2
left to do
Hide done
Type something and press Enter. Check an item, hide the done ones, remove one.
examples/src/core/todo.silk
Copy
//! A to-do list: a text field, a list that grows and shrinks, and a filter.
import
core.look { ACCENT
, INK
, LINE
, MUTED
, button, fieldLook, primary, rgb }
import
loom.css
import
loom.css { px, Align
, BorderStyle
, Keyword
}
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
Item
{
/// Never reused, so it can be the row's key.
pub
id: u64,
pub
title: String
,
pub
done: bool,
}
pub
struct
Todo
{
pub
items: List
<Item
>,
/// What is typed in the field and not added yet.
pub
draft: String
,
pub
hideDone: bool,
pub
nextId: u64,
}
pub
union
Message
{
ChangedDraft
{ pub
value: String
},
SubmittedDraft
,
ClickedToggle
{ pub
id: u64 },
ClickedRemove
{ pub
id: u64 },
ClickedHideDone
,
}
type
Next
= Update
<Todo
, NoCommand
, NoOutput
>
/// How many items are not done yet.
pub
fn
remaining
(model: &Todo
) -> usize {
let
items = model.items.asSlice
()
let
mut
count: usize = 0
let
mut
i: usize = 0
while
i < items.length {
if
!items[i].done {
count = count + 1
}
i = i + 1
}
return
count
}
effect
fn
add
(model: &mut
Todo
, title: string) -> ()
! OutOfMemoryError
? &mut
Allocator
{
let
id = model.nextId
model.nextId = id + 1
run
model.items.append
(Item
{ id: id, title: run
String
.copy
(title), done: false
})
}
impl
Program
<Message
, NoCommand
> for
Todo
{
effect
fn
init
() -> Next
! OutOfMemoryError
? &mut
Allocator
{
let
mut
model = Todo
{
items: List
<Item
>.make
(),
draft: String
.make
(),
hideDone: false
,
nextId: 1
,
}
run
add
(&mut
model, "Read the first program"
)
run
add
(&mut
model, "Write a view"
)
return
Next
.of
(move
model)
}
effect
fn
update
(mut
model: Todo
, message: Message
) -> Next
! OutOfMemoryError
? &mut
Allocator
{
match
move
message {
Message
.ChangedDraft
{ value } => {
model.draft = move
value
}
Message
.SubmittedDraft
=> {
// The draft leaves the model, and an empty one takes its place.
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 } => {
let
mut
i: usize = 0
while
i < model.items.length
() {
if
model.items.asSlice
()[i].id == id {
let
mut
item = model.items.remove
(i)
item.done = !item.done
run
model.items.insert
(i, move
item)
}
i = i + 1
}
}
Message
.ClickedRemove
{ id } => {
let
mut
i: usize = 0
while
i < model.items.length
() {
if
model.items.asSlice
()[i].id == id {
drop
model.items.remove
(i)
} else
{
i = i + 1
}
}
}
Message
.ClickedHideDone
=> {
model.hideDone = !model.hideDone
}
}
return
Next
.of
(move
model)
}
fn
view
(model: &Todo
, 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 item"
),
h.placeholder
("What needs doing?"
),
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.testId
("items"
), h.accessRole
(Role
.List
)],
&[
h.each
(
model.items.asSlice
(),
|item| if
model.hideDone && item.done {
h.empty
()
} else
{
h.keyed
(item.id, row
(h, item))
},
),
],
),
h.row
(
&[h.style
(&[css.alignItems
(Align
.Center
), css.columnGap
(px
(6.0
)), css.color
(rgb
(MUTED
))])],
&[
h.box
(&[h.testId
("remaining"
)], &[h.number
(usize.toI64
(remaining
(model)))]),
h.box
(&[h.style
(&[css.flexGrow
(1.0
)])], &[h.text
("left to do"
)]),
button
(
h,
if
model.hideDone {
"Show done"
} else
{
"Hide done"
},
Message
.ClickedHideDone
,
),
],
),
],
)
}
}
/// One item: a checkbox, its title, and a button that removes it.
fn
row
(h: &Document
<Message
>, item: &Item
) -> Node
{
return
h.row
(
&[
h.accessRole
(Role
.ListItem
),
h.style
(
&[
css.alignItems
(Align
.Center
),
css.columnGap
(px
(10.0
)),
css.paddingTop
(px
(8.0
)),
css.paddingBottom
(px
(8.0
)),
css.borderTopWidth
(px
(1.0
)),
css.borderStyle
(BorderStyle
.Solid
),
css.borderColor
(rgb
(LINE
)),
],
),
],
&[
h.button
(
&[
h.accessRole
(Role
.Checkbox
),
h.checked
(item.done),
h.label
(String
.view
(&item.title)),
h.onClick
(Message
.ClickedToggle
{ id: item.id }),
h.style
(
&[
css.width
(px
(18.0
)),
css.height
(px
(18.0
)),
css.borderWidth
(px
(1.0
)),
css.borderStyle
(BorderStyle
.Solid
),
css.borderRadius
(px
(5.0
)),
css.borderColor
(
if
item.done {
rgb
(ACCENT
)
} else
{
rgb
(LINE
)
},
),
css.backgroundColor
(
if
item.done {
rgb
(ACCENT
)
} else
{
rgb
(0xFFFFFF
)
},
),
],
),
],
&[],
),
h.box
(
&[
h.style
(
&[
css.flexGrow
(1.0
),
css.color
(
if
item.done {
rgb
(MUTED
)
} else
{
rgb
(INK
)
},
),
css.textDecorationLine
(
if
item.done {
Keyword
.LineThrough
} else
{
Keyword
.None
},
),
],
),
],
&[h.text
(String
.view
(&item.title))],
),
h.button
(
&[
h.label
("Remove"
),
h.onClick
(Message
.ClickedRemove
{ id: item.id }),
h.style
(&[css.color
(rgb
(MUTED
)), css.paddingLeft
(px
(6.0
)), css.paddingRight
(px
(6.0
))]),
h.hover
(&[css.color
(rgb
(0xB91C1C
))]),
],
&[h.text
("×"
)],
),
],
)
}Messages that carry data
examples/src/core/todo.silk
Copy
pub
union
Message
{
ChangedDraft
{ pub
value: String
},
SubmittedDraft
,
ClickedToggle
{ pub
id: u64 },
ClickedRemove
{ pub
id: u64 },
ClickedHideDone
,
}A message can carry what happened
to
. ClickedToggle
carries the id of the item, and ChangedDraft
carries the new text of the field.In the view, each row builds its own message:
Silk
Copy
h.
onClick
(Message
.ClickedToggle
{ id: item.id })Text fields
Silk
Copy
h.
input
(
String
.view
(&model.draft),
&[
h.placeholder
("What needs doing?"
),
h.onInput
(|value| Message
.ChangedDraft
{ value: move
value }),
h.onEnter
(Message
.SubmittedDraft
),
],
)A field shows the value the view gives it, here
model.draft
. When the user types, h.onInput
turns the field's new text into a message, update
stores it in the model, and the view gives it back. The model always knows what is in the field.That round trip is what lets
update
empty the field after an item is added: it sets model.draft
to an empty string, and the field follows.h.onEnter
sends a message when Enter is pressed in the field.Note:
Caret movement, selection, copy and paste, and input methods are handled by the field itself. Your program only hears what the value became. Lists that change
examples/src/core/todo.silk
Copy
fn
view
(model: &Todo
, 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 item"
),
h.placeholder
("What needs doing?"
),
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.testId
("items"
), h.accessRole
(Role
.List
)],
&[
h.each
(
model.items.asSlice
(),
|item| if
model.hideDone && item.done {
h.empty
()
} else
{
h.keyed
(item.id, row
(h, item))
},
),
],
),
h.row
(
&[h.style
(&[css.alignItems
(Align
.Center
), css.columnGap
(px
(6.0
)), css.color
(rgb
(MUTED
))])],
&[
h.box
(&[h.testId
("remaining"
)], &[h.number
(usize.toI64
(remaining
(model)))]),
h.box
(&[h.style
(&[css.flexGrow
(1.0
)])], &[h.text
("left to do"
)]),
button
(
h,
if
model.hideDone {
"Show done"
} else
{
"Hide done"
},
Message
.ClickedHideDone
,
),
],
),
],
)
}h.keyed(item.id, node)
gives a row an identity. Without keys, removing the first of three rows would look like "the first two rows changed their text and the third one went away". With keys, the runtime knows which row left, and the others keep their nodes, their focus and their scroll position.Use a key that belongs to the item and never changes, such as an id. The index in the list is not a key.
The events there are
Most programs need only a few.
Attribute
Sends a message when
h.onClick(message)
The node is clicked, or a focused button gets Enter or Space
h.onDoubleClick(message)
It is double clicked
h.onInput(\|value\| ...)
A field's value changes
h.onEnter(message)
Enter is pressed in the node
h.onFocus(message)
, h.onBlur(message)
The node gets or loses focus
h.onPointerEnter(message)
, h.onPointerLeave(message)
The pointer comes onto or leaves the node
The ones in the next table hand you the event itself, and you answer with a
Reply
.Attribute
Hears
h.onKeyDown
, h.onKeyUp
A key.
event.key
is its name, event.modifiers
the keys held with ith.onPointerDown
, h.onPointerMove
, h.onPointerUp
The pointer.
event.x
and event.y
are its positionh.onWheel
The wheel.
event.deltaX
and event.deltaY
h.onScroll(\|x, y\| ...)
A scroll container's new offsets
h.onLayout(\|box\| ...)
The node's size and position, when they change
Bubbling, and stopping it
Events travel as they do in a web page: from the node they happened on, up through its parents. A click on the text of a button reaches the button's
onClick
.A handler that takes the event answers with a
Reply
, which says two things at once: which message to send, if any, and whether the event goes on.Silk
Copy
h.
onKeyDown
(
|event| if
String
.view
(&event.key) == "Escape"
{
Reply
<Message
>.EmitAndStop
{ message: Message
.PressedEscape
}
} else
{
Reply
<Message
>.Pass
},
)Reply
A message
Parents see the event
Emit { message }
Yes
Yes
EmitAndStop { message }
Yes
No
Pass
No
Yes
Stop
No
No
Prevent
No
Yes, and the default action is skipped
Prevent
is preventDefault
: a wheel does not scroll, a press does not move focus, a key does not type.Keys that work everywhere
A shortcut that should work wherever focus is does not belong on a node. It is a subscription:
subs.keyBinding
.Recap
•
An event attribute pairs something the user does with the message to send.
•
A message is a value built while drawing. Nothing runs until the event happens.
•
Text being typed is state, so it lives in the model:
h.onInput
reports each change.•
Name messages for what happened, and let
update
decide what it means.Next: Commands.