garage44.eu/jeroen/frits

logclone: git clone https://garage44.eu/jeroen/frits.git

cartopolis-agent · 2026-11-26T12:27:14Z

feat(frits): views written as markup, drawn by the host

`<Column gap=8><Button on_press=Inc>"+"</Button></Column>` is an
expression of type `View<M>`, the prelude's enum, so views are built
with ordinary code (`{rows}`, `xs.map(fn(i) { <Text>"{i}"</Text> })`).
An attribute is a Str, Int, Float, Bool or a message of the script's
inbox type; pressing what the host drew posts that message to the
script's `on receive`, so state changes only in its own handler (the
Elm loop). `render(v)` needs the `Ui` effect; hosts read the tree with
`Process::take_view` and `frits::view::decode`.

Platform declarations may now declare enums, which take the first enum
ids in every script compiled against them; the prelude's `View` and
`Attr` are the first.

Tags and attribute names are not checked against the host's components
yet.
crates/bench/src/main.rs     |   2 +-
 crates/frits/src/ast.rs      |  13 ++-
 crates/frits/src/bytecode.rs |   4 +
 crates/frits/src/compile.rs  | 193 +++++++++++++++++++++++++++++++++++++++++--
 crates/frits/src/imports.rs  |   4 +
 crates/frits/src/lib.rs      |   1 +
 crates/frits/src/parser.rs   |  62 ++++++++++++++
 crates/frits/src/prelude.rs  |  10 +++
 crates/frits/src/tests.rs    |  55 ++++++++++++
 crates/frits/src/types.rs    |   8 ++
 crates/frits/src/view.rs     | 102 +++++++++++++++++++++++
 crates/frits/src/vm.rs       |  13 +++
 docs/design.md               |  44 +++++++++-
 13 files changed, 502 insertions(+), 9 deletions(-)

diff --git a/crates/bench/src/main.rs b/crates/bench/src/main.rs
index cc0001d..e8200bb 100644
--- a/crates/bench/src/main.rs
+++ b/crates/bench/src/main.rs
@@ -543,6 +543,6 @@ mod tests {
                 n += 1;
             }
         }
-        assert_eq!(n, 2);
+        assert_eq!(n, 3);
     }
 }
diff --git a/crates/frits/src/ast.rs b/crates/frits/src/ast.rs
index c3c0427..e83b256 100644
--- a/crates/frits/src/ast.rs
+++ b/crates/frits/src/ast.rs
@@ -44,7 +44,7 @@ pub struct FnDecl {
     pub line: u32,
 }
 
-#[derive(Debug)]
+#[derive(Debug, Clone)]
 pub struct EnumDecl {
     pub name: Name,
     /// `enum Tree<T> { … }`
@@ -84,6 +84,15 @@ pub enum TypeExpr {
     Fn(Vec<TypeExpr>, Option<Box<TypeExpr>>, Vec<Name>, u32),
 }
 
+/// A view element: its tag, attributes and children (markup, strings or
+/// `{expressions}`).
+#[derive(Debug)]
+pub struct Markup {
+    pub tag: Name,
+    pub attrs: Vec<(Name, Expr)>,
+    pub children: Vec<Expr>,
+}
+
 /// `fn(x: Int) -> Int { x * 2 }`, or `fn(x) { x * 2 }` where the types are known.
 #[derive(Debug)]
 pub struct Lambda {
@@ -176,6 +185,8 @@ pub enum ExprKind {
     Tuple(Vec<Expr>),
     /// `e?`: the value inside an Ok or Some, or return the Err or None.
     Try(Box<Expr>),
+    /// `<Column gap=8>…</Column>`
+    Markup(Box<Markup>),
 }
 
 #[derive(Debug)]
diff --git a/crates/frits/src/bytecode.rs b/crates/frits/src/bytecode.rs
index b26c63e..aa91b19 100644
--- a/crates/frits/src/bytecode.rs
+++ b/crates/frits/src/bytecode.rs
@@ -298,6 +298,10 @@ pub enum Op {
         base: Reg,
         dst: Reg,
     },
+    /// Show the view in `src`: the host takes it with `Process::take_view`.
+    Render {
+        src: Reg,
+    },
     /// This process's own address.
     Me {
         dst: Reg,
diff --git a/crates/frits/src/compile.rs b/crates/frits/src/compile.rs
index f909df1..e2b7d69 100644
--- a/crates/frits/src/compile.rs
+++ b/crates/frits/src/compile.rs
@@ -207,11 +207,23 @@ impl<'p, 'a> Compiler<'p, 'a> {
 
         // Types first, so signatures can name them; enums before aliases, so an
         // alias can name an enum.
-        for item in &m.items {
-            if let Item::Enum(e) = item {
+        // The platform's enums come first, with the ids its declaration gave them.
+        let plat = self.plat;
+        let decls: Vec<&EnumDecl> = plat
+            .enums
+            .iter()
+            .chain(
+                m.items
+                    .iter()
+                    .filter_map(|i| if let Item::Enum(e) = i { Some(e) } else { None }),
+            )
+            .collect();
+        for (i, e) in decls.iter().enumerate() {
+            {
                 let id = self.enums.len() as u32;
-                if self.env.enums.insert(e.name.clone(), id).is_some()
-                    || self.env.aliases.contains_key(&e.name)
+                if i >= plat.enums.len()
+                    && (self.env.enums.insert(e.name.clone(), id).is_some()
+                        || self.env.aliases.contains_key(&e.name))
                 {
                     self.error(e.line, format!("type `{}` is defined twice", e.name));
                 }
@@ -243,8 +255,8 @@ impl<'p, 'a> Compiler<'p, 'a> {
                 }
             }
         }
-        for item in &m.items {
-            if let Item::Enum(e) = item {
+        for e in &decls {
+            {
                 let id = self.env.enums[&e.name];
                 let mut vs = Vec::new();
                 for (tag, (v, payload)) in e.variants.iter().enumerate() {
@@ -1186,6 +1198,7 @@ impl<'p, 'a> Compiler<'p, 'a> {
             ExprKind::Tuple(items) => self.tuple(items, r, want),
             ExprKind::MapLit(entries) => self.map_lit(entries, r, want, line),
             ExprKind::Try(e) => self.try_expr(e, r, line),
+            ExprKind::Markup(mk) => self.markup(mk, r, want, line),
             ExprKind::If(..) | ExprKind::IfLet(..) | ExprKind::Match(..) | ExprKind::Block(_) => {
                 unreachable!()
             }
@@ -1513,6 +1526,21 @@ impl<'p, 'a> Compiler<'p, 'a> {
                 };
                 Type::Int
             }
+            "render" => {
+                if args.len() != 1 {
+                    self.error(line, "`render` takes one view");
+                    return Some(Type::Error);
+                }
+                if !self.f.effects.iter().any(|e| e == "Ui") {
+                    self.missing_effect("Ui", line);
+                }
+                let want = self.view_type(None);
+                let (v, t) = self.expr_any(&args[0], Some(&want));
+                self.expect(&t, &want, line);
+                self.emit(Op::Render { src: v });
+                self.emit(Op::LoadUnit { dst: r });
+                Type::Unit
+            }
             "me" => {
                 if !args.is_empty() {
                     self.error(line, "`me` takes no arguments");
@@ -2895,6 +2923,155 @@ impl<'p, 'a> Compiler<'p, 'a> {
         Type::Map(Rc::new(kt.unwrap()), Rc::new(vt.unwrap()))
     }
 
+    // ── Views ──
+
+    /// `View<M>`, where M is what is wanted, else what `on receive` takes, else Unit.
+    fn view_type(&self, want: Option<&Type>) -> Type {
+        let id = self.env.enums["View"];
+        if let Some(t @ Type::Enum(e, _)) = want
+            && *e == id
+        {
+            return t.clone();
+        }
+        let m = self.inbox.clone().unwrap_or(Type::Unit);
+        Type::Enum(id, Rc::from([m]))
+    }
+
+    fn tag_of(&self, variant: &str) -> u32 {
+        self.variants[variant].1
+    }
+
+    /// `<Tag attr=value …>children</Tag>`: a `ViewEl(tag, attributes, children)`.
+    fn markup(&mut self, mk: &Markup, r: Reg, want: Option<&Type>, line: u32) -> Type {
+        let view = self.view_type(want);
+        let Type::Enum(_, args) = &view else {
+            unreachable!()
+        };
+        let msg = args[0].clone();
+        let attrs = self.alloc();
+        self.emit(Op::MakeList {
+            dst: attrs,
+            base: attrs,
+            n: 0,
+        });
+        for (name, e) in &mk.attrs {
+            let pair = self.alloc_n(2);
+            let k = self.string(name);
+            self.emit(Op::LoadK { dst: pair, k });
+            let (v, t) = self.expr_any(e, Some(&msg));
+            let variant = match &t {
+                Type::Str => "AttrStr",
+                Type::Int => "AttrInt",
+                Type::Float => "AttrFloat",
+                Type::Bool => "AttrBool",
+                Type::Error => "AttrStr",
+                t if *t == msg => "AttrSend",
+                t => {
+                    let (s, m) = (self.show(t), self.show(&msg));
+                    self.error(
+                        e.line,
+                        format!(
+                            "`{name}` is a {s}; an attribute is a Str, Int, Float, Bool or a message ({m})"
+                        ),
+                    );
+                    "AttrStr"
+                }
+            };
+            let tag = self.tag_of(variant);
+            self.emit(Op::MakeVariant {
+                dst: pair + 1,
+                tag,
+                base: v,
+                n: 1,
+            });
+            let tuple = self.alloc();
+            self.emit(Op::MakeRecord {
+                dst: tuple,
+                base: pair,
+                n: 2,
+            });
+            self.emit(Op::ListPushMut {
+                list: attrs,
+                val: tuple,
+            });
+        }
+        let children = self.alloc();
+        self.emit(Op::MakeList {
+            dst: children,
+            base: children,
+            n: 0,
+        });
+        let text = self.tag_of("ViewText");
+        for c in &mk.children {
+            let (v, t) = self.expr_any(c, Some(&view));
+            match &t {
+                Type::Str => {
+                    let node = self.alloc();
+                    self.emit(Op::MakeVariant {
+                        dst: node,
+                        tag: text,
+                        base: v,
+                        n: 1,
+                    });
+                    self.emit(Op::ListPushMut {
+                        list: children,
+                        val: node,
+                    });
+                }
+                t if *t == view => {
+                    self.emit(Op::ListPushMut {
+                        list: children,
+                        val: v,
+                    });
+                }
+                Type::List(inner) if **inner == view => {
+                    let base = self.alloc_n(2);
+                    self.emit(Op::Move {
+                        dst: base,
+                        src: children,
+                    });
+                    self.emit(Op::Move {
+                        dst: base + 1,
+                        src: v,
+                    });
+                    self.emit(Op::Std {
+                        f: Std::ListConcat,
+                        base,
+                        dst: children,
+                    });
+                }
+                Type::Error => {}
+                t => {
+                    let (s, w) = (self.show(t), self.show(&view));
+                    self.error(
+                        c.line,
+                        format!("a child is a string, a {w} or a list of them, not {s}"),
+                    );
+                }
+            }
+        }
+        let base = self.alloc_n(3);
+        let k = self.string(&mk.tag);
+        self.emit(Op::LoadK { dst: base, k });
+        self.emit(Op::Move {
+            dst: base + 1,
+            src: attrs,
+        });
+        self.emit(Op::Move {
+            dst: base + 2,
+            src: children,
+        });
+        let el = self.tag_of("ViewEl");
+        self.emit(Op::MakeVariant {
+            dst: r,
+            tag: el,
+            base,
+            n: 3,
+        });
+        let _ = line;
+        view
+    }
+
     // ── Methods ──
 
     fn is_place(&self, e: &Expr) -> bool {
@@ -3354,6 +3531,10 @@ fn free_expr(e: &Expr, out: &mut Vec<String>) {
     match &e.kind {
         ExprKind::Ident(n) => out.push(n.clone()),
         ExprKind::Field(b, _) | ExprKind::Unary(_, b) | ExprKind::Try(b) => free_expr(b, out),
+        ExprKind::Markup(mk) => {
+            mk.attrs.iter().for_each(|(_, e)| free_expr(e, out));
+            mk.children.iter().for_each(|e| free_expr(e, out));
+        }
         ExprKind::Call(c, args) => {
             free_expr(c, out);
             args.iter().for_each(|a| free_expr(a, out));
diff --git a/crates/frits/src/imports.rs b/crates/frits/src/imports.rs
index 1bfa516..7bc52b4 100644
--- a/crates/frits/src/imports.rs
+++ b/crates/frits/src/imports.rs
@@ -339,6 +339,10 @@ impl<'a> Renamer<'a> {
                 }
             }
             ExprKind::Field(b, _) | ExprKind::Unary(_, b) | ExprKind::Try(b) => self.expr(b),
+            ExprKind::Markup(mk) => {
+                mk.attrs.iter_mut().for_each(|(_, e)| self.expr(e));
+                mk.children.iter_mut().for_each(|e| self.expr(e));
+            }
             ExprKind::Call(c, args) => {
                 self.expr(c);
                 args.iter_mut().for_each(|a| self.expr(a));
diff --git a/crates/frits/src/lib.rs b/crates/frits/src/lib.rs
index dab61a5..0697e54 100644
--- a/crates/frits/src/lib.rs
+++ b/crates/frits/src/lib.rs
@@ -22,6 +22,7 @@ pub mod runtime;
 pub mod stdlib;
 pub mod types;
 pub mod value;
+pub mod view;
 pub mod vm;
 
 #[cfg(test)]
diff --git a/crates/frits/src/parser.rs b/crates/frits/src/parser.rs
index 4b7ef42..b48ddc4 100644
--- a/crates/frits/src/parser.rs
+++ b/crates/frits/src/parser.rs
@@ -767,6 +767,7 @@ impl Parser {
                 ExprKind::Block(self.block()?)
             }
             Tok::Kw(Kw::If) => return self.if_expr(line),
+            Tok::Sym("<") => return self.markup(line),
             Tok::Kw(Kw::Match) => {
                 let scrut = self.expr()?;
                 self.expect_sym("{")?;
@@ -808,6 +809,67 @@ impl Parser {
         Ok(Expr { kind, line })
     }
 
+    /// After the `<` of `<Tag attr=value …>children</Tag>` or `<Tag … />`.
+    fn markup(&mut self, line: u32) -> R<Expr> {
+        let tag = self.ident()?;
+        let mut attrs = Vec::new();
+        let mut children = Vec::new();
+        let done = |tag, attrs, children| Expr {
+            kind: ExprKind::Markup(Box::new(Markup { tag, attrs, children })),
+            line,
+        };
+        loop {
+            self.skip_semis();
+            if self.eat_sym("/") {
+                self.expect_sym(">")?;
+                return Ok(done(tag, attrs, children));
+            }
+            if self.eat_sym(">") {
+                break;
+            }
+            let name = self.ident()?;
+            self.expect_sym("=")?;
+            let value = if self.eat_sym("{") {
+                let e = self.expr()?;
+                self.skip_semis();
+                self.expect_sym("}")?;
+                e
+            } else {
+                self.unary()?
+            };
+            attrs.push((name, value));
+        }
+        loop {
+            self.skip_semis();
+            let l = self.line();
+            if self.is_sym("<") && matches!(self.peek_at(1), Tok::Sym("/")) {
+                self.next();
+                self.next();
+                let close = self.ident()?;
+                if close != tag {
+                    return self.err(format!("`<{tag}>` is closed by `</{close}>`"));
+                }
+                self.expect_sym(">")?;
+                return Ok(done(tag, attrs, children));
+            }
+            if self.eat_sym("<") {
+                children.push(self.markup(l)?);
+            } else if self.eat_sym("{") {
+                let e = self.expr()?;
+                self.skip_semis();
+                self.expect_sym("}")?;
+                children.push(e);
+            } else if matches!(self.peek(), Tok::Str(_)) {
+                children.push(self.primary()?);
+            } else {
+                return self.err(format!(
+                    "expected `</{tag}>`, or a child: `<Tag>`, a string, or `{{expression}}`; found {}",
+                    describe(self.peek())
+                ));
+            }
+        }
+    }
+
     fn if_expr(&mut self, line: u32) -> R<Expr> {
         if self.eat_kw(Kw::Let) {
             let pat = self.pattern()?;
diff --git a/crates/frits/src/prelude.rs b/crates/frits/src/prelude.rs
index 05cf1d9..dd51f90 100644
--- a/crates/frits/src/prelude.rs
+++ b/crates/frits/src/prelude.rs
@@ -7,6 +7,16 @@ use crate::value::{HostValue, Value};
 pub const DECL: &str = "
 type Vec3 = { x: Float, y: Float, z: Float }
 
+// A user interface, written as markup: `<Column gap=8> <Button on_press=Inc>…</Button> </Column>`.
+// The host draws it with its own components. `M` is what pressing something
+// sends to the script's `on receive`.
+enum View<M> { ViewEl(Str, List<(Str, Attr<M>)>, List<View<M>>), ViewText(Str) }
+enum Attr<M> { AttrStr(Str), AttrInt(Int), AttrFloat(Float), AttrBool(Bool), AttrSend(M) }
+
+// Showing a view: `render(v)`.
+effect Ui {
+}
+
 // Sending to other scripts: `send(addr, msg)`.
 effect Mail {
 }
diff --git a/crates/frits/src/tests.rs b/crates/frits/src/tests.rs
index a88d9da..5631cc8 100644
--- a/crates/frits/src/tests.rs
+++ b/crates/frits/src/tests.rs
@@ -869,3 +869,58 @@ fn generic_types() {
     );
     assert!(e[0].contains("misses: Empty"), "{e:?}");
 }
+
+#[test]
+fn a_view_is_rendered_and_a_press_comes_back_as_a_message() {
+    let mut rt = Runtime::new(platform());
+    let m = rt
+        .platform
+        .compile(
+            "script / Out, Ui
+            enum Msg { Inc, Dec }
+            var n = 0
+            fn draw() -> View<Msg> {
+                let rows = [1, 2].map(fn(i) { <Text>\"row {i}\"</Text> })
+                <Column gap=8 wide=true>
+                    <Text size=1.5>\"Count: {n}\"</Text>
+                    <Row>
+                        <Button on_press=Dec>\"-\"</Button>
+                        <Button on_press=Inc label=\"plus\">\"+\"</Button>
+                    </Row>
+                    {rows}
+                    <Spacer/>
+                </Column>
+            }
+            on go() { render(draw()) }
+            on receive(m: Msg) {
+                match m { Inc => n += 1, Dec => n -= 1 }
+                render(draw())
+            }",
+        )
+        .unwrap_or_else(|e| panic!("{e:?}"));
+    let pid = rt.spawn(m, Log::default());
+    rt.post(pid, "go", Vec::new());
+    rt.tick();
+    let v = rt.get_mut(pid).unwrap().take_view().unwrap();
+    let tree = view::decode(&v).unwrap();
+    assert_eq!(tree.attr("gap"), Some(&view::AttrValue::Int(8)));
+    assert_eq!(tree.find("Text").unwrap().text(), "Count: 0");
+    assert_eq!(tree.text(), "Count: 0-+row 1row 2");
+    let Some(view::AttrValue::Send(press)) = tree.find("Row").unwrap().find("Button").map(|_| {
+        // The second button is "+".
+        let view::Node::El { children, .. } = tree.find("Row").unwrap() else {
+            unreachable!()
+        };
+        children[1].attr("on_press").unwrap().clone()
+    }) else {
+        panic!()
+    };
+    rt.post(pid, "receive", vec![press]);
+    rt.tick();
+    let v = rt.get_mut(pid).unwrap().take_view().unwrap();
+    assert_eq!(view::decode(&v).unwrap().find("Text").unwrap().text(), "Count: 1");
+    let e = errors("script / Out\non go() { render(<Text>\"x\"</Text>) }");
+    assert!(e[0].contains("`Ui`"), "{e:?}");
+    let e = errors("script / Out, Ui\non go() { render(<Text>\"x\"</Tex>) }");
+    assert!(e[0].contains("closed by `</Tex>`"), "{e:?}");
+}
diff --git a/crates/frits/src/types.rs b/crates/frits/src/types.rs
index 3daa9a1..896f113 100644
--- a/crates/frits/src/types.rs
+++ b/crates/frits/src/types.rs
@@ -477,6 +477,8 @@ pub struct PlatformDecl {
     pub effects: Vec<String>,
     pub modules: Vec<String>,
     pub events: Vec<(String, Vec<Type>)>,
+    /// Enums the platform declares (the prelude's `View`), ids 0, 1, … in order.
+    pub enums: Vec<ast::EnumDecl>,
 }
 
 impl PlatformDecl {
@@ -533,6 +535,12 @@ impl PlatformDecl {
                         });
                     }
                 }
+                ast::Item::Enum(e) => {
+                    let id = self.enums.len() as u32;
+                    self.env.enums.insert(e.name.clone(), id);
+                    self.env.enum_params.insert(id, e.generics.len());
+                    self.enums.push(e);
+                }
                 ast::Item::Opaque(name, _) => {
                     self.env
                         .aliases
diff --git a/crates/frits/src/view.rs b/crates/frits/src/view.rs
new file mode 100644
index 0000000..6e9623f
--- /dev/null
+++ b/crates/frits/src/view.rs
@@ -0,0 +1,102 @@
+//! What a host does with a rendered view: read the tree a script built with
+//! markup (`Process::take_view`) into plain Rust, and find what pressing an
+//! element sends back.
+
+use crate::value::HostValue;
+
+#[derive(Clone, Debug, PartialEq)]
+pub enum Node {
+    El {
+        tag: String,
+        attrs: Vec<(String, AttrValue)>,
+        children: Vec<Node>,
+    },
+    Text(String),
+}
+
+#[derive(Clone, Debug, PartialEq)]
+pub enum AttrValue {
+    Str(String),
+    Int(i64),
+    Float(f64),
+    Bool(bool),
+    /// A message: post it to the script as `receive` when this is used.
+    Send(HostValue),
+}
+
+/// The tree in a rendered view, or None if it is not one.
+pub fn decode(v: &HostValue) -> Option<Node> {
+    match v {
+        // ViewEl(tag, attrs, children): tag 0; ViewText(text): tag 1.
+        HostValue::Variant(0, f) => {
+            let [
+                HostValue::Str(tag),
+                HostValue::List(attrs),
+                HostValue::List(children),
+            ] = f.as_slice()
+            else {
+                return None;
+            };
+            let attrs = attrs
+                .iter()
+                .map(|a| {
+                    let HostValue::Record(pair) = a else { return None };
+                    let [HostValue::Str(name), HostValue::Variant(t, val)] = pair.as_slice() else {
+                        return None;
+                    };
+                    let val = val.first()?;
+                    let value = match (t, val) {
+                        (0, HostValue::Str(s)) => AttrValue::Str(s.clone()),
+                        (1, HostValue::Int(i)) => AttrValue::Int(*i),
+                        (2, HostValue::Float(x)) => AttrValue::Float(*x),
+                        (3, HostValue::Bool(b)) => AttrValue::Bool(*b),
+                        (4, m) => AttrValue::Send(m.clone()),
+                        _ => return None,
+                    };
+                    Some((name.clone(), value))
+                })
+                .collect::<Option<Vec<_>>>()?;
+            let children = children.iter().map(decode).collect::<Option<Vec<_>>>()?;
+            Some(Node::El {
+                tag: tag.clone(),
+                attrs,
+                children,
+            })
+        }
+        HostValue::Variant(1, f) => match f.as_slice() {
+            [HostValue::Str(s)] => Some(Node::Text(s.clone())),
+            _ => None,
+        },
+        _ => None,
+    }
+}
+
+impl Node {
+    /// The first element (depth first) with this tag.
+    pub fn find(&self, tag: &str) -> Option<&Node> {
+        match self {
+            Node::El { tag: t, children, .. } => {
+                if t == tag {
+                    return Some(self);
+                }
+                children.iter().find_map(|c| c.find(tag))
+            }
+            Node::Text(_) => None,
+        }
+    }
+
+    pub fn attr(&self, name: &str) -> Option<&AttrValue> {
+        match self {
+            Node::El { attrs, .. } => attrs.iter().find(|(n, _)| n == name).map(|(_, v)| v),
+            Node::Text(_) => None,
+        }
+    }
+
+    /// All the text inside, joined.
+    pub fn text(&self) -> String {
+        match self {
+            Node::El { children, .. } => children.iter().map(|c| c.text()).collect::<Vec<_>>().join(""),
+            Node::Text(s) => s.clone(),
+        }
+    }
+}
diff --git a/crates/frits/src/vm.rs b/crates/frits/src/vm.rs
index 8cd44e6..e2cc6fa 100644
--- a/crates/frits/src/vm.rs
+++ b/crates/frits/src/vm.rs
@@ -70,6 +70,8 @@ pub struct Process<S> {
     pub addr: i64,
     /// Messages sent and not yet delivered: (to, message type, message).
     pub outbox: Vec<(i64, String, HostValue)>,
+    /// The view last rendered and not yet taken by the host.
+    view: Option<HostValue>,
 }
 
 /// Events a process holds before more are refused: a script flooded with
@@ -108,6 +110,7 @@ impl<S> Process<S> {
             restore: Vec::new(),
             addr: 0,
             outbox: Vec::new(),
+            view: None,
             module,
         };
         let init = p.module.init;
@@ -165,6 +168,12 @@ impl<S> Process<S> {
         self.rng = (z ^ (z >> 31)) | 1;
     }
 
+    /// The view the script rendered last, if the host has not taken it yet
+    /// (`frits::view::decode` reads it).
+    pub fn take_view(&mut self) -> Option<HostValue> {
+        self.view.take()
+    }
+
     /// The lines logged since the last call.
     pub fn take_log(&mut self) -> Vec<LogLine> {
         std::mem::take(&mut self.log)
@@ -647,6 +656,10 @@ impl<S> Process<S> {
                         }
                     }
                     Op::Me { dst } => r!(dst) = Value::Int(self.addr),
+                    Op::Render { src } => {
+                        let v = r!(src);
+                        self.view = Some(self.heap.export(v, &m.strings));
+                    }
                     Op::Send { to, msg, ty } => {
                         let hv = self.heap.export(r!(msg), &m.strings);
                         let ty = m.strings[ty as usize].to_string();
diff --git a/docs/design.md b/docs/design.md
index 73baa40..0c74ae7 100644
--- a/docs/design.md
+++ b/docs/design.md
@@ -120,6 +120,47 @@ on timer() {
   (a value the script holds and passes back, never builds or looks into). This
   is the capability: a script that was never given a `Door` cannot open one.
 
+## Views
+
+A script describes a user interface with markup, and the host draws it with
+its own components (on Pinnacle, the component library):
+
+```frits
+script / Ui
+
+enum Msg { Inc, Dec }
+var n = 0
+
+fn draw() -> View<Msg> {
+    <Column gap=8>
+        <Text size=1.5>"Count: {n}"</Text>
+        <Row>
+            <Button on_press=Dec>"-"</Button>
+            <Button on_press=Inc>"+"</Button>
+        </Row>
+    </Column>
+}
+
+on receive(m: Msg) {
+    match m {
+        Inc => n += 1,
+        Dec => n -= 1,
+    }
+    render(draw())
+}
+```
+
+- Markup is an expression of type `View<M>` (the prelude's enum: `ViewEl(tag,
+  attributes, children)` or `ViewText`), so a view is built with ordinary code:
+  `{rows}` takes a list of views, `.map(fn(i) { <Text>"{i}"</Text> })` makes one.
+- An attribute is a Str, Int, Float, Bool, or a message `M`; `M` is what the
+  script's `on receive` takes. Pressing something the host drew posts that
+  message back: the script's state changes only in its own handler (the Elm
+  loop).
+- `render(v)` needs the `Ui` effect; the host takes the tree with
+  `Process::take_view` and reads it with `frits::view::decode`.
+- Tags and attribute names are the host's: Frits does not check them yet.
+
 ## Tools
 
 - `frits fmt [--check] <file>…` gives every script one layout. It works on the
@@ -227,7 +268,8 @@ In the order they are likely to matter:
 - `spawn` from inside a script, and supervisors; the host starts processes.
 - A debugger (breakpoints, stepping): the VM's state is plain data, so it is
   within reach, but nothing is built.
-- `view` markup on the component library; AOT for Pinnacle apps; wasm.
+- Checking markup tags and attributes against what the host's components take.
+- wasm (deliberately left for later).
 
 Known gaps in what is built: