Composition
.
Most of the time, splitting a program means splitting its view into functions, as in Views. Sometimes a part of the screen is a small program of its own, with its own model and messages, and you want to use it more than once. That is a
submodel
.
Note:
This is question 6 of Thinking in Silk UI, and it comes last for a reason: most apps need few submodels or none.
An order
Live: this is the program below, running
Flat white
$4.50
-
0
+
$0.00
Almond croissant
$3.75
-
0
+
$0.00
Orange juice
$5.00
-
0
+
$0.00
$20.00
more for free delivery
0
items
$0.00
Clear
The three lines are the same stepper, used three times. Each knows its own price and quantity. The count, the total, the delivery bar and the Clear button belong to the parent.
examples/src/core/order.silk
Copy
//! An order: a parent program that embeds the same child three times. The child is one line
//! of the order, with a quantity stepper, and knows nothing about its parent.
import
core.look {
ACCENT
,
INK
,
LINE
,
MUTED
, button, rgb }
import
loom.css
import
loom.css { percent, px,
Align
,
BorderStyle
}
import
loom.lib {
Document
, fold, foldInput,
Node
,
NoCommand
,
NoOutput
,
Program
,
Receives
,
Submodel
,
Update
}
import
silk.collections.list {
List
}
import
silk.core.option {
Option
}
import
silk.mem.allocator {
Allocator
,
OutOfMemoryError
}
import
silk.num.i64
// The child.
pub
struct
Stepper
{
pub
label: string<'
static
>,
/// The price of one, in cents.
pub
price: i64,
pub
quantity: i64, }
pub
union
StepperMessage
{
ClickedMore
,
ClickedFewer
, }
/// What a stepper tells its parent.
pub
union
StepperOutput
{
/// The quantity changed by `by`, which changes the line's cost by `cost` cents.
Changed
{
pub
by: i64,
pub
cost: i64 }, }
/// What a parent may ask of a stepper.
pub
union
StepperInput
{
Clear
, }
type
Step
=
Update
<
Stepper
,
NoCommand
,
StepperOutput
>
impl
Submodel
<
StepperMessage
,
NoCommand
,
StepperOutput
>
for
Stepper
{
effect
fn
start
(model: &
Stepper
) ->
List
<
NoCommand
> !
OutOfMemoryError
? &
mut
Allocator
{
return
List
<
NoCommand
>.
make
() }
effect
fn
update
(
mut
model:
Stepper
, message:
StepperMessage
) ->
Step
!
OutOfMemoryError
? &
mut
Allocator
{
match
move
message {
StepperMessage
.
ClickedMore
=> { model.quantity = model.quantity +
1
let
cost = model.price
return
Step
.
of
(
move
model).
reporting
(
StepperOutput
.
Changed
{ by:
1
, cost: cost }) }
StepperMessage
.
ClickedFewer
=> {
if
model.quantity >
0
{ model.quantity = model.quantity -
1
let
cost = model.price
return
Step
.
of
(
move
model).
reporting
(
StepperOutput
.
Changed
{ by: -
1
, cost:
0
- cost }) } } }
return
Step
.
of
(
move
model) }
fn
view
(model: &
Stepper
, h: &
Document
<
StepperMessage
>) ->
Node
{
return
h.
row
( &[h.
style
(&[css.
alignItems
(
Align
.
Center
), css.
columnGap
(
px
(
10.0
))])], &[ h.
column
( &[h.
style
(&[css.
flexGrow
(
1.0
)])], &[ h.
text
(model.label), h.
box
( &[h.
style
(&[css.
fontSize
(
px
(
13.0
)), css.
color
(
rgb
(
MUTED
))])], &[money<
StepperMessage
>(h, model.price)], ), ], ),
button
(h,
"-"
,
StepperMessage
.
ClickedFewer
), h.
row
( &[h.
style
(&[css.
minWidth
(
px
(
24.0
)), css.
justifyContent
(
Align
.
Center
)])], &[h.
number
(model.quantity)], ),
button
(h,
"+"
,
StepperMessage
.
ClickedMore
), h.
row
( &[ h.
style
( &[ css.
minWidth
(
px
(
64.0
)), css.
justifyContent
(
Align
.
End
), css.
fontVariantNumeric
(
"tabular-nums"
), css.
color
(
rgb
(
if
model.quantity ==
0
{
MUTED
}
else
{
INK
}, ), ), ], ), ], &[money<
StepperMessage
>(h, model.price * model.quantity)], ), ], ) } }
/// Cents as dollars: `$4.50`.
fn
money<
M
>(h: &
Document
<
M
>, cents: i64) ->
Node
{
return
h.
row
( &[], &[ h.
text
(
"$"
), h.
number
(cents /
100
), h.
text
(
"."
),
if
cents %
100
<
10
{ h.
text
(
"0"
) }
else
{ h.
empty
() }, h.
number
(cents %
100
), ], ) }
impl
Receives
<
StepperInput
,
NoCommand
,
StepperOutput
>
for
Stepper
{
effect
fn
receive
(
mut
model:
Stepper
, input:
StepperInput
) ->
Step
!
OutOfMemoryError
? &
mut
Allocator
{
match
move
input {
StepperInput
.
Clear
=> { model.quantity =
0
} }
return
Step
.
of
(
move
model) } }
// The parent.
pub
struct
Order
{
pub
coffee:
Stepper
,
pub
croissant:
Stepper
,
pub
juice:
Stepper
,
/// How many things are in the order and what they cost, in cents. Both are kept up to date
/// from what the steppers report.
pub
pieces: i64,
pub
total: i64, }
pub
union
Message
{
GotCoffeeMessage
{
pub
message:
StepperMessage
},
GotCroissantMessage
{
pub
message:
StepperMessage
},
GotJuiceMessage
{
pub
message:
StepperMessage
},
ClickedClear
, }
type
Next
=
Update
<
Order
,
NoCommand
,
NoOutput
>
/// Delivery is free from this many cents.
const
FREE_FROM
: i64 =
2000
/// Adds what a stepper reported to the order.
fn
count
(model: &
mut
Order
, out:
Option
<
StepperOutput
>) -> () {
if
let
Option
<
StepperOutput
>.
Some
{ value:
StepperOutput
.
Changed
{ by, cost } } =
move
out { model.pieces = model.pieces + by model.total = model.total + cost } }
impl
Program
<
Message
,
NoCommand
>
for
Order
{
effect
fn
init
() ->
Next
!
OutOfMemoryError
? &
mut
Allocator
{
return
Next
.
of
(
Order
{ coffee:
Stepper
{ label:
"Flat white"
, price:
450
, quantity:
0
}, croissant:
Stepper
{ label:
"Almond croissant"
, price:
375
, quantity:
0
}, juice:
Stepper
{ label:
"Orange juice"
, price:
500
, quantity:
0
}, pieces:
0
, total:
0
, }, ) }
effect
fn
update
(
mut
model:
Order
, message:
Message
) ->
Next
!
OutOfMemoryError
? &
mut
Allocator
{
match
move
message {
Message
.
GotCoffeeMessage
{ message: inner } => {
let
folded =
run
fold
(&
mut
model.coffee,
move
inner)
count
(&
mut
model,
move
folded.out) }
Message
.
GotCroissantMessage
{ message: inner } => {
let
folded =
run
fold
(&
mut
model.croissant,
move
inner)
count
(&
mut
model,
move
folded.out) }
Message
.
GotJuiceMessage
{ message: inner } => {
let
folded =
run
fold
(&
mut
model.juice,
move
inner)
count
(&
mut
model,
move
folded.out) }
Message
.
ClickedClear
=> {
drop
run
foldInput
(&
mut
model.coffee,
StepperInput
.
Clear
)
drop
run
foldInput
(&
mut
model.croissant,
StepperInput
.
Clear
)
drop
run
foldInput
(&
mut
model.juice,
StepperInput
.
Clear
) model.pieces =
0
model.total =
0
} }
return
Next
.
of
(
move
model) }
fn
view
(model: &
Order
, 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
(
380.0
))], ), ], &[ h.
submodel
( &model.coffee, |message:
StepperMessage
|
Message
.
GotCoffeeMessage
{ message:
move
message }, ), h.
submodel
( &model.croissant, |message:
StepperMessage
|
Message
.
GotCroissantMessage
{ message:
move
message }, ), h.
submodel
( &model.juice, |message:
StepperMessage
|
Message
.
GotJuiceMessage
{ message:
move
message }, ),
delivery
(h, model), h.
row
( &[ h.
style
( &[ css.
alignItems
(
Align
.
Center
), css.
columnGap
(
px
(
6.0
)), css.
paddingTop
(
px
(
12.0
)), css.
borderTopWidth
(
px
(
1.0
)), css.
borderStyle
(
BorderStyle
.
Solid
), css.
borderColor
(
rgb
(
LINE
)), ], ), ], &[ h.
row
( &[h.
style
(&[css.
columnGap
(
px
(
4.0
)), css.
color
(
rgb
(
MUTED
)), css.
flexGrow
(
1.0
)])], &[ h.
box
(&[h.
testId
(
"pieces"
)], &[h.
number
(model.pieces)]), h.
text
(
if
model.pieces ==
1
{
"item"
}
else
{
"items"
}, ), ], ), h.
box
( &[ h.
testId
(
"total"
), h.
style
( &[css.
fontSize
(
px
(
20.0
)), css.
fontWeight
(
700.0
), css.
fontVariantNumeric
(
"tabular-nums"
)], ), ], &[money<
Message
>(h, model.total)], ), ], ), h.
row
( &[h.
style
(&[css.
columnGap
(
px
(
8.0
)), css.
justifyContent
(
Align
.
End
)])], &[
button
(h,
"Clear"
,
Message
.
ClickedClear
)], ), ], ) } }
/// How far the order is from free delivery: a line of text over a bar that fills up.
fn
delivery
(h: &
Document
<
Message
>, model: &
Order
) ->
Node
{
let
short =
FREE_FROM
- model.total
let
share: f32 =
if
short <=
0
{
100.0
}
else
{ i64.
toF32
(model.total) *
100.0
/ i64.
toF32
(
FREE_FROM
) }
return
h.
column
( &[h.
style
(&[css.
rowGap
(
px
(
6.0
)), css.
fontSize
(
px
(
13.0
)), css.
color
(
rgb
(
MUTED
))])], &[
if
short <=
0
{ h.
box
(&[h.
style
(&[css.
color
(
rgb
(
ACCENT
))])], &[h.
text
(
"Delivery is free"
)]) }
else
{ h.
row
( &[h.
style
(&[css.
columnGap
(
px
(
4.0
))])], &[money<
Message
>(h, short), h.
text
(
"more for free delivery"
)], ) }, h.
box
( &[h.
style
(&[css.
height
(
px
(
6.0
)), css.
borderRadius
(
px
(
3.0
)), css.
backgroundColor
(
rgb
(
0xE5E7EB
))])], &[ h.
box
( &[ h.
style
( &[ css.
height
(
px
(
6.0
)), css.
width
(
percent
(share)), css.
borderRadius
(
px
(
3.0
)), css.
backgroundColor
(
rgb
(
ACCENT
)), ], ), h.
transition
(
"width 200ms ease"
), ], &[], ), ], ), ], ) }
The child
examples/src/core/order.silk
Copy
impl
Submodel
<
StepperMessage
,
NoCommand
,
StepperOutput
>
for
Stepper
{
effect
fn
start
(model: &
Stepper
) ->
List
<
NoCommand
> !
OutOfMemoryError
? &
mut
Allocator
{
return
List
<
NoCommand
>.
make
() }
effect
fn
update
(
mut
model:
Stepper
, message:
StepperMessage
) ->
Step
!
OutOfMemoryError
? &
mut
Allocator
{
match
move
message {
StepperMessage
.
ClickedMore
=> { model.quantity = model.quantity +
1
let
cost = model.price
return
Step
.
of
(
move
model).
reporting
(
StepperOutput
.
Changed
{ by:
1
, cost: cost }) }
StepperMessage
.
ClickedFewer
=> {
if
model.quantity >
0
{ model.quantity = model.quantity -
1
let
cost = model.price
return
Step
.
of
(
move
model).
reporting
(
StepperOutput
.
Changed
{ by: -
1
, cost:
0
- cost }) } } }
return
Step
.
of
(
move
model) }
fn
view
(model: &
Stepper
, h: &
Document
<
StepperMessage
>) ->
Node
{
return
h.
row
( &[h.
style
(&[css.
alignItems
(
Align
.
Center
), css.
columnGap
(
px
(
10.0
))])], &[ h.
column
( &[h.
style
(&[css.
flexGrow
(
1.0
)])], &[ h.
text
(model.label), h.
box
( &[h.
style
(&[css.
fontSize
(
px
(
13.0
)), css.
color
(
rgb
(
MUTED
))])], &[money<
StepperMessage
>(h, model.price)], ), ], ),
button
(h,
"-"
,
StepperMessage
.
ClickedFewer
), h.
row
( &[h.
style
(&[css.
minWidth
(
px
(
24.0
)), css.
justifyContent
(
Align
.
Center
)])], &[h.
number
(model.quantity)], ),
button
(h,
"+"
,
StepperMessage
.
ClickedMore
), h.
row
( &[ h.
style
( &[ css.
minWidth
(
px
(
64.0
)), css.
justifyContent
(
Align
.
End
), css.
fontVariantNumeric
(
"tabular-nums"
), css.
color
(
rgb
(
if
model.quantity ==
0
{
MUTED
}
else
{
INK
}, ), ), ], ), ], &[money<
StepperMessage
>(h, model.price * model.quantity)], ), ], ) } }
A submodel looks like a program: a model, messages,
update
and
view
. It knows nothing about who uses it.
start
returns the commands a new child begins with. This one has none.
Putting the child in the parent
There are three places where the parent mentions its child. The model holds it:
examples/src/core/order.silk
Copy
pub
struct
Order
{
pub
coffee:
Stepper
,
pub
croissant:
Stepper
,
pub
juice:
Stepper
,
/// How many things are in the order and what they cost, in cents. Both are kept up to date
/// from what the steppers report.
pub
pieces: i64,
pub
total: i64, }
The parent's messages have a variant that carries the child's messages:
examples/src/core/order.silk
Copy
pub
union
Message
{
GotCoffeeMessage
{
pub
message:
StepperMessage
},
GotCroissantMessage
{
pub
message:
StepperMessage
},
GotJuiceMessage
{
pub
message:
StepperMessage
},
ClickedClear
, }
And the parent's view embeds the child's view:
Silk
Copy
h.
submodel
( &model.coffee, |message:
StepperMessage
|
Message
.
GotCoffeeMessage
{ message:
move
message }, )
The second argument wraps each of the child's messages as one of the parent's. That is how a click inside the coffee stepper arrives at the parent's
update
as
GotCoffeeMessage
.
Passing messages down
examples/src/core/order.silk
Copy
effect
fn
update
(
mut
model:
Stepper
, message:
StepperMessage
) ->
Step
!
OutOfMemoryError
? &
mut
Allocator
{
match
move
message {
StepperMessage
.
ClickedMore
=> { model.quantity = model.quantity +
1
let
cost = model.price
return
Step
.
of
(
move
model).
reporting
(
StepperOutput
.
Changed
{ by:
1
, cost: cost }) }
StepperMessage
.
ClickedFewer
=> {
if
model.quantity >
0
{ model.quantity = model.quantity -
1
let
cost = model.price
return
Step
.
of
(
move
model).
reporting
(
StepperOutput
.
Changed
{ by: -
1
, cost:
0
- cost }) } } }
return
Step
.
of
(
move
model) }
When the parent gets one of those messages, it hands the inner message to the child with
fold
.
fold
runs the child's
update
on the child where it sits in the parent's model.
Everything the child does goes through the parent this way. Nothing is hidden: when you read the parent's
update
, you see every way the order can change.
The child reports
examples/src/core/order.silk
Copy
/// What a stepper tells its parent.
pub
union
StepperOutput
{
/// The quantity changed by `by`, which changes the line's cost by `cost` cents.
Changed
{
pub
by: i64,
pub
cost: i64 }, }
A child sometimes has news for its parent. It does not call the parent. It attaches a
report
to what its
update
returns:
Silk
Copy
return
Step
.
of
(
move
model).
reporting
(
StepperOutput
.
Changed
{ by:
1
, cost: cost })
fold
gives the report to the parent, in
folded.out
, and the parent does what it likes with it:
examples/src/core/order.silk
Copy
/// Adds what a stepper reported to the order.
fn
count
(model: &
mut
Order
, out:
Option
<
StepperOutput
>) -> () {
if
let
Option
<
StepperOutput
>.
Some
{ value:
StepperOutput
.
Changed
{ by, cost } } =
move
out { model.pieces = model.pieces + by model.total = model.total + cost } }
The parent asks
examples/src/core/order.silk
Copy
impl
Receives
<
StepperInput
,
NoCommand
,
StepperOutput
>
for
Stepper
{
effect
fn
receive
(
mut
model:
Stepper
, input:
StepperInput
) ->
Step
!
OutOfMemoryError
? &
mut
Allocator
{
match
move
input {
StepperInput
.
Clear
=> { model.quantity =
0
} }
return
Step
.
of
(
move
model) } }
The other direction is a request. The child says which requests it takes, and the parent sends one with
foldInput
. That is how Clear empties every line.
Three channels
Direction
What travels
How
Child to itself
The child's messages
h.submodel
wraps them,
fold
delivers them
Child to parent
Reports
.reporting(...)
, read from
folded.out
Parent to child
Requests
Receives
, sent with
foldInput
A child with commands or subscriptions passes those through its parent as well:
lift
wraps the child's commands as the parent's, and
subs.submodel
does the same for subscriptions.
Note:
Reach for a submodel when a part has state of its own
and
is used in more than one place. For everything else, a view function and a few fields in the parent's model are simpler.
Recap
•
A submodel is a program used inside another: its own model, messages and view.
•
The parent holds the child's model and passes its messages through.
•
A child tells its parent something with an output, and the parent asks the child with an input.
•
Prefer view functions until a part has private state and several uses.
Next: Testing.