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    let (slot, kind) = definition
232        .slot(name)
233        .ok_or_else(|| error(format!("unknown slot: {name}")))?;
234    if !expected(kind) {
235        return Err(error(format!("wrong kind for slot: {name}")));
236    }
237    if seen.contains(&slot) {
238        return Err(error(format!("duplicate configuration: {name}")));
239    }
240    seen.push(slot);
241    Ok(slot)
242}
243/// Implemented only by built-in configuration actions; not a host extension API.
244#[doc(hidden)]
245pub trait Actions: sealed::Actions {
246    fn validate(&self, definition: &Compiled, scope: &Scope, seen: &mut Vec<u16>) -> Result<()>;
247    fn apply(self, mount: &impl mounting::Mount) -> glory_ui::Result;
248}
249impl sealed::Actions for () {}
250impl Actions for () {
251    fn validate(&self, _: &Compiled, _: &Scope, _: &mut Vec<u16>) -> Result<()> {
252        Ok(())
253    }
254    fn apply(self, _: &impl mounting::Mount) -> glory_ui::Result {
255        Ok(())
256    }
257}
258impl<A: Actions, B: Actions> sealed::Actions for (A, B) {}
259impl<A: Actions, B: Actions> Actions for (A, B) {
260    fn validate(&self, d: &Compiled, s: &Scope, seen: &mut Vec<u16>) -> Result<()> {
261        self.0.validate(d, s, seen)?;
262        self.1.validate(d, s, seen)
263    }
264    fn apply(self, m: &impl mounting::Mount) -> glory_ui::Result {
265        self.0.apply(m)?;
266        self.1.apply(m)
267    }
268}
269impl<V: TextValue> sealed::Actions for Bind<V> {}
270impl<V: TextValue + 'static> Actions for Bind<V> {
271    fn validate(&self, d: &Compiled, s: &Scope, seen: &mut Vec<u16>) -> Result<()> {
272        resolve(
273            d,
274            self.field.0,
275            |k| matches!(k, Kind::Text | Kind::Attribute(_)),
276            seen,
277        )?;
278        self.value.validate(s.runtime())
279    }
280    fn apply(self, m: &impl mounting::Mount) -> glory_ui::Result {
281        m.text(self.field, self.value)
282    }
283}
284impl<F: FnMut() + 'static> sealed::Actions for On<F> {}
285impl<F: FnMut() + 'static> Actions for On<F> {
286    fn validate(&self, d: &Compiled, _: &Scope, seen: &mut Vec<u16>) -> Result<()> {
287        resolve(d, self.click.0, |k| k == Kind::Click, seen)?;
288        Ok(())
289    }
290    fn apply(self, m: &impl mounting::Mount) -> glory_ui::Result {
291        m.on(self.click, self.callback)
292    }
293}
294impl<C: Content> sealed::Actions for ChildValue<C> {}
295impl<C: Content> Actions for ChildValue<C> {
296    fn validate(&self, d: &Compiled, s: &Scope, seen: &mut Vec<u16>) -> Result<()> {
297        resolve(
298            d,
299            self.outlet.0,
300            |k| matches!(k, Kind::Children | Kind::Range),
301            seen,
302        )?;
303        self.content.validate(s)
304    }
305    fn apply(self, m: &impl mounting::Mount) -> glory_ui::Result {
306        m.child(self.outlet, self.content)
307    }
308}
309impl<V: BoolValue> sealed::Actions for Toggle<V> {}
310impl<V: BoolValue> Actions for Toggle<V> {
311    fn validate(&self, d: &Compiled, s: &Scope, seen: &mut Vec<u16>) -> Result<()> {
312        resolve(d, self.field.0, |k| matches!(k, Kind::Class(..)), seen)?;
313        self.value.validate_bool(s.runtime())
314    }
315    fn apply(self, m: &impl mounting::Mount) -> glory_ui::Result {
316        m.flag(self.field, self.value)
317    }
318}
319impl<A: Actions> View<A> {
320    #[cfg(target_arch = "wasm32")]
321    pub fn mount(self, app: &crate::template::App, scope: &Scope) -> Result<Mounted>
322    where
323        A: 'static,
324    {
325        mount(self, app, scope)
326    }
327    pub fn validate(&self, scope: &Scope) -> Result<()> {
328        if !scope.is_alive() {
329            return Err(error("disposed view scope"));
330        }
331        let definition = self.template.cached()?;
332        self.actions
333            .as_ref()
334            .ok_or_else(|| error("view already built"))?
335            .validate(&definition, scope, &mut Vec::new())
336    }
337    #[cfg(target_arch = "wasm32")]
338    fn mount_direct(&mut self, app: &crate::template::App, scope: &Scope) -> Result<Mounted> {
339        if !scope.is_alive() || scope.runtime() != app.runtime().id() {
340            return Err(error("foreign or disposed view scope"));
341        }
342        let definition = app.prepare(self.template)?;
343        self.validate(scope)?;
344        let actions = self
345            .actions
346            .take()
347            .ok_or_else(|| error("view already built"))?;
348        let instance = app.mount(scope, self.template)?;
349        if let Err(e) = actions
350            .apply(&mounting::SparseMount {
351                definition: &definition,
352                app,
353                scope,
354                instance: &instance,
355            })
356            .map_err(error)
357        {
358            instance.fail(e.clone());
359            return Err(e);
360        }
361        Ok(Mounted { instance })
362    }
363}
364impl<A: Actions + 'static> Widget for View<A> {
365    #[inline(always)]
366    fn native_host(&self) -> Option<std::any::TypeId> {
367        #[cfg(target_arch = "wasm32")]
368        return Some(std::any::TypeId::of::<DisplayMount>());
369        #[cfg(not(target_arch = "wasm32"))]
370        None
371    }
372    fn build(&mut self, scope: &glory_ui::Scope) -> glory_ui::Result {
373        self.validate(scope).map_err(portable::failure)?;
374        let actions = self.actions.take().ok_or(glory_ui::Error::Gone)?;
375        portable::build(self.template, actions, scope)
376    }
377    fn mount_host(
378        &mut self,
379        scope: &Scope,
380        host: &mut dyn std::any::Any,
381    ) -> glory_ui::Result<bool> {
382        #[cfg(target_arch = "wasm32")]
383        if let Some(context) = host.downcast_mut::<DisplayMount>() {
384            context.result = Some(self.mount_direct(&context.app, scope));
385            return Ok(true);
386        }
387        let _ = (scope, host);
388        Ok(false)
389    }
390}
391#[cfg(target_arch = "wasm32")]
392struct DisplayMount {
393    app: crate::template::App,
394    result: Option<Result<Mounted>>,
395}
396/// Mount any Widget; raw views retain their sparse template fast path.
397#[cfg(target_arch = "wasm32")]
398pub fn mount(
399    mut widget: impl Widget,
400    app: &crate::template::App,
401    scope: &Scope,
402) -> Result<Mounted> {
403    app.ensure_live()?;
404    if !scope.is_alive() || scope.runtime() != app.runtime().id() {
405        return Err(error("foreign or disposed widget scope"));
406    }
407    let mut context = DisplayMount {
408        app: app.clone(),
409        result: None,
410    };
411    if widget.native_host() == Some(std::any::TypeId::of::<DisplayMount>()) {
412        if !widget.mount_host(scope, &mut context).map_err(error)? {
413            return Err(error("widget native host did not mount"));
414        }
415        return context
416            .result
417            .ok_or_else(|| error("widget host did not mount"))?;
418    }
419    if widget.is_empty() {
420        return mount(empty(), app, scope);
421    }
422    if let Some(child) =
423        glory_core::untracked(|| scope.enter(|| widget.compose(scope))).map_err(error)?
424    {
425        return mount(child, app, scope);
426    }
427    if widget.mount_host(scope, &mut context).map_err(error)? {
428        return context
429            .result
430            .ok_or_else(|| error("widget host did not mount"))?;
431    }
432    app.mount_widget(scope, widget)
433        .map(|instance| Mounted { instance })
434}
435#[cfg(target_arch = "wasm32")]
436#[derive(Clone)]
437pub struct Mounted {
438    instance: crate::template::Instance,
439}
440#[cfg(target_arch = "wasm32")]
441impl Mounted {
442    pub fn set(&self, field: Field, value: impl Display) -> Result<()> {
443        let slot = self
444            .instance
445            .named(field.0, |k| matches!(k, Kind::Text | Kind::Attribute(_)))?;
446        self.instance.set(slot, value.to_string())
447    }
448    pub fn on_click(&self, click: Click, callback: impl FnMut() + 'static) -> Result<()> {
449        self.instance.on_click(
450            self.instance.named(click.0, |k| k == Kind::Click)?,
451            callback,
452        )
453    }
454    pub fn children(&self, outlet: Outlet) -> Result<crate::template::Children> {
455        self.instance.children(
456            self.instance
457                .named(outlet.0, |k| matches!(k, Kind::Children | Kind::Range))?,
458        )
459    }
460    pub fn place(
461        &self,
462        parent: Option<&crate::template::Children>,
463        before: Option<&Mounted>,
464    ) -> Result<()> {
465        self.instance.place(parent, before.map(|b| &b.instance))
466    }
467}