Skip to main content

toddstack_frontend_engine/
app.rs

1use std::collections::{BTreeMap, BTreeSet};
2
3use serde::Serialize;
4use serde::de::DeserializeOwned;
5use serde_json::{Value, json};
6
7use crate::effect::{Effect, EffectReq};
8
9/// One pointer sample on the typed fast path. `x` and `y` are in units the app chooses (cells,
10/// pixels, a 0..1 canvas); the engine never interprets them.
11#[derive(Debug, Clone, Copy, PartialEq)]
12pub struct Pointer {
13    pub phase: u8,
14    pub x: f32,
15    pub y: f32,
16    pub at_ms: u64,
17}
18
19impl Pointer {
20    pub const DOWN: u8 = 0;
21    pub const MOVE: u8 = 1;
22    pub const UP: u8 = 2;
23    pub const CANCEL: u8 = 3;
24}
25
26/// What `update` may do besides mutating the model: mark views dirty and request effects.
27#[derive(Debug)]
28pub struct Ctx<X> {
29    pub(crate) at: u64,
30    pub(crate) next_id: u64,
31    pub(crate) dirty: BTreeSet<String>,
32    pub(crate) effects: Vec<EffectReq<X>>,
33}
34
35impl<X> Default for Ctx<X> {
36    fn default() -> Self {
37        Self {
38            at: 0,
39            next_id: 0,
40            dirty: BTreeSet::new(),
41            effects: Vec::new(),
42        }
43    }
44}
45
46impl<X> Ctx<X> {
47    /// Wall clock of the input being handled (ms since epoch, UTC).
48    #[must_use]
49    pub const fn at(&self) -> u64 {
50        self.at
51    }
52
53    /// Mark a view key as changed; the shell pulls it.
54    pub fn dirty(&mut self, key: impl Into<String>) {
55        self.dirty.insert(key.into());
56    }
57
58    /// Request an effect. Returns its id; the answer arrives in [`App::resolve`].
59    pub fn emit(&mut self, effect: Effect<X>) -> u64 {
60        self.next_id += 1;
61        let id: u64 = self.next_id;
62        self.effects.push(EffectReq { id, effect });
63        id
64    }
65
66    /// Request an app-defined effect.
67    pub fn emit_app(&mut self, effect: X) -> u64 {
68        self.emit(Effect::App(effect))
69    }
70}
71
72/// Effect ids still waiting for their answer, each with what the app was doing when it asked.
73/// Keeps `resolve` a `match` on a state-machine enum instead of scattered flags.
74#[derive(Debug, Clone, PartialEq, Eq)]
75pub struct Pending<T> {
76    waiting: BTreeMap<u64, T>,
77}
78
79impl<T> Default for Pending<T> {
80    fn default() -> Self {
81        Self {
82            waiting: BTreeMap::new(),
83        }
84    }
85}
86
87impl<T> Pending<T> {
88    /// Emit `effect` and remember `what` under its id.
89    pub fn emit<X>(&mut self, ctx: &mut Ctx<X>, effect: Effect<X>, what: T) -> u64 {
90        let id: u64 = ctx.emit(effect);
91        self.waiting.insert(id, what);
92        id
93    }
94
95    /// The remembered state for an answered id; `None` for an id this app never tracked (or a
96    /// stale one).
97    pub fn take(&mut self, id: u64) -> Option<T> {
98        self.waiting.remove(&id)
99    }
100
101    #[must_use]
102    pub fn len(&self) -> usize {
103        self.waiting.len()
104    }
105
106    #[must_use]
107    pub fn is_empty(&self) -> bool {
108        self.waiting.is_empty()
109    }
110}
111
112/// JSON-schema type of one action field.
113#[derive(Debug, Clone, Copy)]
114pub enum FieldType {
115    String,
116    Integer,
117    Number,
118    Boolean,
119}
120
121impl FieldType {
122    const fn name(self) -> &'static str {
123        match self {
124            Self::String => "string",
125            Self::Integer => "integer",
126            Self::Number => "number",
127            Self::Boolean => "boolean",
128        }
129    }
130}
131
132/// A legal action with a hand-rolled JSON schema (an object whose fields are all required).
133#[derive(Debug, Clone)]
134pub struct ActionSpec {
135    pub name: String,
136    pub schema: Value,
137}
138
139impl ActionSpec {
140    /// An action with no fields.
141    #[must_use]
142    pub fn new(name: &str) -> Self {
143        Self {
144            name: name.to_owned(),
145            schema: json!({}),
146        }
147    }
148
149    /// Add a required field.
150    #[must_use]
151    pub fn field(mut self, field: &str, ty: FieldType) -> Self {
152        let mut props: Value = self.schema.get("properties").cloned().unwrap_or(json!({}));
153        let mut required: Value = self.schema.get("required").cloned().unwrap_or(json!([]));
154        props[field] = json!({"type": ty.name()});
155        if let Some(list) = required.as_array_mut() {
156            list.push(json!(field));
157        }
158        self.schema = json!({"type": "object", "properties": props, "required": required});
159        self
160    }
161}
162
163/// The app: a model plus pure transitions. All time comes from `ctx.at()`.
164pub trait App: Sized {
165    /// User intents, decoded from the `act` field (serde external tagging: `"Inc"`, `{"Add":{"n":2}}`).
166    type Action: DeserializeOwned;
167    /// The app's own effects, next to the built-in ones. [`NoEffect`](crate::NoEffect) for none.
168    type Effect: Serialize;
169
170    /// Build the model from the shell's boot facts.
171    fn boot(boot: &Value, ctx: &mut Ctx<Self::Effect>) -> Self;
172    fn update(&mut self, action: Self::Action, ctx: &mut Ctx<Self::Effect>);
173    /// The answer to effect `id`: `Ok(value)` or `Err(message)`.
174    fn resolve(&mut self, id: u64, result: Result<Value, String>, ctx: &mut Ctx<Self::Effect>);
175    /// Typed pointer fast path. Mark views dirty through `ctx`.
176    fn pointer(&mut self, _pointer: Pointer, _ctx: &mut Ctx<Self::Effect>) {}
177    /// Large binary input (`provide_blob`).
178    fn blob(&mut self, _name: &str, _bytes: &[u8], _ctx: &mut Ctx<Self::Effect>) {}
179    /// The JSON of one view key, or `None` when the key is unknown.
180    fn view(&self, key: &str) -> Option<Value>;
181    /// Current screen name; its view key is the same name.
182    fn screen(&self) -> String;
183    /// Actions legal right now.
184    fn actions(&self) -> Vec<ActionSpec>;
185}