Skip to main content

glory_web/
view.rs

1//! Declarative template configuration implementing the portable Widget contract.
2//! Direct sparse display::App mounting is browser-only.
3use glory_core::{Bond, Cage, RuntimeId, Scope, Vary};
4pub use glory_html::view::{Click, Field, Outlet, Template};
5use glory_html::{template::Kind, view::Compiled};
6pub use glory_ui::Widget;
7use std::fmt::Display;
8mod content;
9mod flags;
10#[doc(hidden)]
11pub mod mounting;
12#[doc(hidden)]
13pub mod portable;
14pub use content::{Content, Show, content, empty, lazy, show};
15pub use flags::BoolValue;
16pub use glory_ui::{Each, EachBuilder, each};
17
18#[derive(Clone, Debug, PartialEq, Eq)]
19pub struct Error(pub String);
20impl Display for Error {
21    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
22        f.write_str(&self.0)
23    }
24}
25impl std::error::Error for Error {}
26impl From<glory_html::template::Error> for Error {
27    fn from(e: glory_html::template::Error) -> Self {
28        Self(e.to_string())
29    }
30}
31pub type Result<T> = std::result::Result<T, Error>;
32fn error(value: impl Display) -> Error {
33    Error(value.to_string())
34}
35
36mod sealed {
37    pub trait Actions {}
38    pub trait Text {}
39    pub trait Content {}
40    pub trait Flag {}
41}
42/// Sources are explicit: values initialize once, handles and Computed observe.
43pub trait TextValue: sealed::Text {
44    fn validate(&self, runtime: RuntimeId) -> Result<()>;
45    fn read_text(&mut self) -> Result<String>;
46    fn reactive_text(&self) -> bool {
47        false
48    }
49}
50macro_rules! scalar {
51    ($($ty:ty),*)=>{$(impl sealed::Text for $ty {}
52    impl TextValue for $ty {
53        fn read_text(&mut self)->Result<String>{Ok(self.to_string())}
54        fn validate(&self,_runtime:RuntimeId)->Result<()>{Ok(())}
55
56    })*};
57}
58scalar!(
59    bool, char, u8, u16, u32, u64, u128, usize, i8, i16, i32, i64, i128, isize, f32, f64
60);
61impl sealed::Text for String {}
62impl TextValue for String {
63    fn read_text(&mut self) -> Result<String> {
64        Ok(self.clone())
65    }
66    fn validate(&self, _runtime: RuntimeId) -> Result<()> {
67        if self.len() > 65536 {
68            Err(error("field payload budget"))
69        } else {
70            Ok(())
71        }
72    }
73}
74impl sealed::Text for &str {}
75impl TextValue for &str {
76    fn read_text(&mut self) -> Result<String> {
77        Ok(self.to_string())
78    }
79    fn validate(&self, _runtime: RuntimeId) -> Result<()> {
80        if self.len() > 65536 {
81            Err(error("field payload budget"))
82        } else {
83            Ok(())
84        }
85    }
86}
87macro_rules! handle {
88    ($ty:ident) => {
89        impl<T: Display + 'static> sealed::Text for $ty<T> {}
90        impl<T: Display + 'static> TextValue for $ty<T> {
91            fn read_text(&mut self) -> Result<String> {
92                self.try_with(ToString::to_string).map_err(error)
93            }
94            fn reactive_text(&self) -> bool {
95                true
96            }
97            fn validate(&self, runtime: RuntimeId) -> Result<()> {
98                if self.runtime() != runtime || !self.is_alive() {
99                    Err(error("foreign or disposed reactive input"))
100                } else {
101                    Ok(())
102                }
103            }
104        }
105    };
106}
107handle!(Cage);
108handle!(Bond);
109impl<T: Display + 'static> sealed::Text for Vary<T> {}
110impl<T: Display + 'static> TextValue for Vary<T> {
111    fn read_text(&mut self) -> Result<String> {
112        self.try_with(ToString::to_string).map_err(error)
113    }
114    fn reactive_text(&self) -> bool {
115        self.is_reactive()
116    }
117    fn validate(&self, runtime: RuntimeId) -> Result<()> {
118        match self {
119            Self::Value(_) => Ok(()),
120            Self::Cage(v) => v.validate(runtime),
121            Self::Bond(v) => v.validate(runtime),
122        }
123    }
124}
125pub struct Computed<F>(F);
126pub fn computed<F, T>(read: F) -> Computed<F>
127where
128    F: FnMut() -> T,
129    T: Display,
130{
131    Computed(read)
132}
133impl<F, T> sealed::Text for Computed<F>
134where
135    F: FnMut() -> T + 'static,
136    T: Display,
137{
138}
139impl<F, T> TextValue for Computed<F>
140where
141    F: FnMut() -> T + 'static,
142    T: Display,
143{
144    fn read_text(&mut self) -> Result<String> {
145        Ok((self.0)().to_string())
146    }
147    fn reactive_text(&self) -> bool {
148        true
149    }
150    fn validate(&self, _runtime: RuntimeId) -> Result<()> {
151        Ok(())
152    }
153}
154
155pub struct View<A = ()> {
156    template: &'static Template,
157    actions: Option<A>,
158}
159pub fn view(template: &'static Template) -> View {
160    View {
161        template,
162        actions: Some(()),
163    }
164}
165#[doc(hidden)]
166pub struct Bind<V> {
167    field: Field,
168    value: V,
169}
170#[doc(hidden)]
171pub struct On<F> {
172    click: Click,
173    #[cfg_attr(not(target_arch = "wasm32"), allow(dead_code))]
174    callback: F,
175}
176#[doc(hidden)]
177pub struct ChildValue<C> {
178    outlet: Outlet,
179    content: C,
180}
181#[doc(hidden)]
182pub struct Toggle<V> {
183    field: Field,
184    value: V,
185}
186impl<A> View<A> {
187    pub fn class_when<V: BoolValue>(self, field: Field, value: V) -> View<(A, Toggle<V>)> {
188        View {
189            template: self.template,
190            actions: Some((self.actions.expect("unbuilt view"), Toggle { field, value })),
191        }
192    }
193    pub fn child<C: Content>(self, outlet: Outlet, content: C) -> View<(A, ChildValue<C>)> {
194        View {
195            template: self.template,
196            actions: Some((
197                self.actions.expect("unbuilt view"),
198                ChildValue { outlet, content },
199            )),
200        }
201    }
202    pub fn bind<V: TextValue>(self, field: Field, value: V) -> View<(A, Bind<V>)> {
203        View {
204            template: self.template,
205            actions: Some((self.actions.expect("unbuilt view"), Bind { field, value })),
206        }
207    }
208    pub fn watch<F, T>(self, field: Field, read: F) -> View<(A, Bind<Computed<F>>)>
209    where
210        F: FnMut() -> T + 'static,
211        T: Display,
212    {
213        self.bind(field, computed(read))
214    }
215    pub fn on_click<F: FnMut() + 'static>(self, click: Click, callback: F) -> View<(A, On<F>)> {
216        View {
217            template: self.template,
218            actions: Some((self.actions.expect("unbuilt view"), On { click, callback })),
219        }
220    }
221    pub fn template(&self) -> &'static Template {
222        self.template
223    }
224}
225fn resolve(
226    definition: &Compiled,
227    name: &str,
228    expected: fn(Kind) -> bool,
229    seen: &mut Vec<u16>,
230) -> Result<u16> {
231    // Try declaration order first. Actions may omit slots or bind them in
232    // another order, so only accept the hint when the name matches.
233    let next = seen.len();
234    let (slot, kind) = definition
235        .slots
236        .get(next)
237        .filter(|slot| slot.name == Some(name))
238        .map(|slot| (next as u16, slot.kind))
239        .or_else(|| definition.slot(name))
240        .ok_or_else(|| error(format!("unknown slot: {name}")))?;
241    if !expected(kind) {
242        return Err(error(format!("wrong kind for slot: {name}")));
243    }
244    if seen.contains(&slot) {
245        return Err(error(format!("duplicate configuration: {name}")));
246    }
247    seen.push(slot);
248    Ok(slot)
249}
250/// Implemented only by built-in configuration actions; not a host extension API.
251#[doc(hidden)]
252pub trait Actions: sealed::Actions {
253    fn validate(&self, definition: &Compiled, scope: &Scope, seen: &mut Vec<u16>) -> Result<()>;
254    fn apply(self, mount: &impl mounting::Mount) -> glory_ui::Result;
255}
256impl sealed::Actions for () {}
257impl Actions for () {
258    fn validate(&self, _: &Compiled, _: &Scope, _: &mut Vec<u16>) -> Result<()> {
259        Ok(())
260    }
261    fn apply(self, _: &impl mounting::Mount) -> glory_ui::Result {
262        Ok(())
263    }
264}
265impl<A: Actions, B: Actions> sealed::Actions for (A, B) {}
266impl<A: Actions, B: Actions> Actions for (A, B) {
267    fn validate(&self, d: &Compiled, s: &Scope, seen: &mut Vec<u16>) -> Result<()> {
268        self.0.validate(d, s, seen)?;
269        self.1.validate(d, s, seen)
270    }
271    fn apply(self, m: &impl mounting::Mount) -> glory_ui::Result {
272        self.0.apply(m)?;
273        self.1.apply(m)
274    }
275}
276impl<V: TextValue> sealed::Actions for Bind<V> {}
277impl<V: TextValue + 'static> Actions for Bind<V> {
278    fn validate(&self, d: &Compiled, s: &Scope, seen: &mut Vec<u16>) -> Result<()> {
279        resolve(
280            d,
281            self.field.0,
282            |k| matches!(k, Kind::Text | Kind::Attribute(_)),
283            seen,
284        )?;
285        self.value.validate(s.runtime())
286    }
287    fn apply(self, m: &impl mounting::Mount) -> glory_ui::Result {
288        m.text(self.field, self.value)
289    }
290}
291impl<F: FnMut() + 'static> sealed::Actions for On<F> {}
292impl<F: FnMut() + 'static> Actions for On<F> {
293    fn validate(&self, d: &Compiled, _: &Scope, seen: &mut Vec<u16>) -> Result<()> {
294        resolve(d, self.click.0, |k| k == Kind::Click, seen)?;
295        Ok(())
296    }
297    fn apply(self, m: &impl mounting::Mount) -> glory_ui::Result {
298        m.on(self.click, self.callback)
299    }
300}
301impl<C: Content> sealed::Actions for ChildValue<C> {}
302impl<C: Content> Actions for ChildValue<C> {
303    fn validate(&self, d: &Compiled, s: &Scope, seen: &mut Vec<u16>) -> Result<()> {
304        resolve(
305            d,
306            self.outlet.0,
307            |k| matches!(k, Kind::Children | Kind::Range),
308            seen,
309        )?;
310        self.content.validate(s)
311    }
312    fn apply(self, m: &impl mounting::Mount) -> glory_ui::Result {
313        m.child(self.outlet, self.content)
314    }
315}
316impl<V: BoolValue> sealed::Actions for Toggle<V> {}
317impl<V: BoolValue> Actions for Toggle<V> {
318    fn validate(&self, d: &Compiled, s: &Scope, seen: &mut Vec<u16>) -> Result<()> {
319        resolve(d, self.field.0, |k| matches!(k, Kind::Class(..)), seen)?;
320        self.value.validate_bool(s.runtime())
321    }
322    fn apply(self, m: &impl mounting::Mount) -> glory_ui::Result {
323        m.flag(self.field, self.value)
324    }
325}
326impl<A: Actions> View<A> {
327    #[cfg(target_arch = "wasm32")]
328    pub fn mount(self, app: &crate::template::App, scope: &Scope) -> Result<Mounted>
329    where
330        A: 'static,
331    {
332        mount(self, app, scope)
333    }
334    pub fn validate(&self, scope: &Scope) -> Result<()> {
335        if !scope.is_alive() {
336            return Err(error("disposed view scope"));
337        }
338        let definition = self.template.cached()?;
339        self.actions
340            .as_ref()
341            .ok_or_else(|| error("view already built"))?
342            .validate(&definition, scope, &mut Vec::new())
343    }
344    #[cfg(target_arch = "wasm32")]
345    fn mount_direct(&mut self, app: &crate::template::App, scope: &Scope) -> Result<Mounted> {
346        if !scope.is_alive() || scope.runtime() != app.runtime().id() {
347            return Err(error("foreign or disposed view scope"));
348        }
349        let definition = app.prepare(self.template)?;
350        self.validate(scope)?;
351        let actions = self
352            .actions
353            .take()
354            .ok_or_else(|| error("view already built"))?;
355        let instance = app.mount(scope, self.template)?;
356        if let Err(e) = actions
357            .apply(&mounting::SparseMount {
358                definition: &definition,
359                app,
360                scope,
361                instance: &instance,
362            })
363            .map_err(error)
364        {
365            instance.fail(e.clone());
366            return Err(e);
367        }
368        Ok(Mounted { instance })
369    }
370}
371impl<A: Actions + 'static> Widget for View<A> {
372    #[inline(always)]
373    fn native_host(&self) -> Option<std::any::TypeId> {
374        #[cfg(target_arch = "wasm32")]
375        return Some(std::any::TypeId::of::<DisplayMount>());
376        #[cfg(not(target_arch = "wasm32"))]
377        None
378    }
379    fn build(&mut self, scope: &glory_ui::Scope) -> glory_ui::Result {
380        self.validate(scope).map_err(portable::failure)?;
381        let actions = self.actions.take().ok_or(glory_ui::Error::Gone)?;
382        portable::build(self.template, actions, scope)
383    }
384    fn mount_host(
385        &mut self,
386        scope: &Scope,
387        host: &mut dyn std::any::Any,
388    ) -> glory_ui::Result<bool> {
389        #[cfg(target_arch = "wasm32")]
390        if let Some(context) = host.downcast_mut::<DisplayMount>() {
391            context.result = Some(self.mount_direct(&context.app, scope));
392            return Ok(true);
393        }
394        let _ = (scope, host);
395        Ok(false)
396    }
397}
398#[cfg(target_arch = "wasm32")]
399struct DisplayMount {
400    app: crate::template::App,
401    result: Option<Result<Mounted>>,
402}
403/// Mount any Widget; raw views retain their sparse template fast path.
404#[cfg(target_arch = "wasm32")]
405pub fn mount(widget: impl Widget, app: &crate::template::App, scope: &Scope) -> Result<Mounted> {
406    app.ensure_live()?;
407    if !scope.is_alive() || scope.runtime() != app.runtime().id() {
408        return Err(error("foreign or disposed widget scope"));
409    }
410    widget.mount_with_host(Host { app, scope })
411}
412#[cfg(target_arch = "wasm32")]
413struct Host<'a> {
414    app: &'a crate::template::App,
415    scope: &'a Scope,
416}
417#[cfg(target_arch = "wasm32")]
418impl<'scope> glory_ui::WidgetHost<'scope> for Host<'scope> {
419    type Output = Result<Mounted>;
420    fn compose<W: Widget>(
421        self,
422        factory: impl FnOnce(&'scope Scope) -> glory_ui::Result<Option<W>>,
423    ) -> Self::Output {
424        let Self { scope, app } = self;
425        match glory_core::untracked(|| scope.enter(|| factory(scope))).map_err(error)? {
426            Some(child) => mount(child, app, scope),
427            None => mount(empty(), app, scope),
428        }
429    }
430    fn mount<W: Widget>(self, mut widget: W) -> Self::Output {
431        let Self { scope, app } = self;
432        let mut context = DisplayMount {
433            app: app.clone(),
434            result: None,
435        };
436        if widget.native_host() == Some(std::any::TypeId::of::<DisplayMount>()) {
437            if !widget.mount_host(scope, &mut context).map_err(error)? {
438                return Err(error("widget native host did not mount"));
439            }
440            return context
441                .result
442                .ok_or_else(|| error("widget host did not mount"))?;
443        }
444        if widget.is_empty() {
445            return mount(empty(), app, scope);
446        }
447        if let Some(child) =
448            glory_core::untracked(|| scope.enter(|| widget.compose(scope))).map_err(error)?
449        {
450            return mount(child, app, scope);
451        }
452        if widget.mount_host(scope, &mut context).map_err(error)? {
453            return context
454                .result
455                .ok_or_else(|| error("widget host did not mount"))?;
456        }
457        app.mount_widget(scope, widget)
458            .map(|instance| Mounted { instance })
459    }
460}
461#[cfg(target_arch = "wasm32")]
462#[derive(Clone)]
463pub struct Mounted {
464    instance: crate::template::Instance,
465}
466#[cfg(target_arch = "wasm32")]
467impl Mounted {
468    pub fn set(&self, field: Field, value: impl Display) -> Result<()> {
469        let slot = self
470            .instance
471            .named(field.0, |k| matches!(k, Kind::Text | Kind::Attribute(_)))?;
472        self.instance.set(slot, value.to_string())
473    }
474    pub fn on_click(&self, click: Click, callback: impl FnMut() + 'static) -> Result<()> {
475        self.instance.on_click(
476            self.instance.named(click.0, |k| k == Kind::Click)?,
477            callback,
478        )
479    }
480    pub fn children(&self, outlet: Outlet) -> Result<crate::template::Children> {
481        self.instance.children(
482            self.instance
483                .named(outlet.0, |k| matches!(k, Kind::Children | Kind::Range))?,
484        )
485    }
486    pub fn place(
487        &self,
488        parent: Option<&crate::template::Children>,
489        before: Option<&Mounted>,
490    ) -> Result<()> {
491        self.instance.place(parent, before.map(|b| &b.instance))
492    }
493}