glory-web 0.8.0

Browser DOM and frame host for Glory semantic UI
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
//! Declarative template configuration implementing the portable Widget contract.
//! Direct sparse display::App mounting is browser-only.
use glory_core::{Bond, Cage, RuntimeId, Scope, Vary};
pub use glory_html::view::{Click, Field, Outlet, Template};
use glory_html::{template::Kind, view::Compiled};
pub use glory_ui::Widget;
use std::fmt::Display;
mod content;
mod flags;
#[doc(hidden)]
pub mod mounting;
#[doc(hidden)]
pub mod portable;
pub use content::{Content, Show, content, empty, lazy, show};
pub use flags::BoolValue;
pub use glory_ui::{Each, EachBuilder, each};

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Error(pub String);
impl Display for Error {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(&self.0)
    }
}
impl std::error::Error for Error {}
impl From<glory_html::template::Error> for Error {
    fn from(e: glory_html::template::Error) -> Self {
        Self(e.to_string())
    }
}
pub type Result<T> = std::result::Result<T, Error>;
fn error(value: impl Display) -> Error {
    Error(value.to_string())
}

mod sealed {
    pub trait Actions {}
    pub trait Text {}
    pub trait Content {}
    pub trait Flag {}
}
/// Sources are explicit: values initialize once, handles and Computed observe.
pub trait TextValue: sealed::Text {
    fn validate(&self, runtime: RuntimeId) -> Result<()>;
    fn read_text(&mut self) -> Result<String>;
    fn reactive_text(&self) -> bool {
        false
    }
}
macro_rules! scalar {
    ($($ty:ty),*)=>{$(impl sealed::Text for $ty {}
    impl TextValue for $ty {
        fn read_text(&mut self)->Result<String>{Ok(self.to_string())}
        fn validate(&self,_runtime:RuntimeId)->Result<()>{Ok(())}

    })*};
}
scalar!(
    bool, char, u8, u16, u32, u64, u128, usize, i8, i16, i32, i64, i128, isize, f32, f64
);
impl sealed::Text for String {}
impl TextValue for String {
    fn read_text(&mut self) -> Result<String> {
        Ok(self.clone())
    }
    fn validate(&self, _runtime: RuntimeId) -> Result<()> {
        if self.len() > 65536 {
            Err(error("field payload budget"))
        } else {
            Ok(())
        }
    }
}
impl sealed::Text for &str {}
impl TextValue for &str {
    fn read_text(&mut self) -> Result<String> {
        Ok(self.to_string())
    }
    fn validate(&self, _runtime: RuntimeId) -> Result<()> {
        if self.len() > 65536 {
            Err(error("field payload budget"))
        } else {
            Ok(())
        }
    }
}
macro_rules! handle {
    ($ty:ident) => {
        impl<T: Display + 'static> sealed::Text for $ty<T> {}
        impl<T: Display + 'static> TextValue for $ty<T> {
            fn read_text(&mut self) -> Result<String> {
                self.try_with(ToString::to_string).map_err(error)
            }
            fn reactive_text(&self) -> bool {
                true
            }
            fn validate(&self, runtime: RuntimeId) -> Result<()> {
                if self.runtime() != runtime || !self.is_alive() {
                    Err(error("foreign or disposed reactive input"))
                } else {
                    Ok(())
                }
            }
        }
    };
}
handle!(Cage);
handle!(Bond);
impl<T: Display + 'static> sealed::Text for Vary<T> {}
impl<T: Display + 'static> TextValue for Vary<T> {
    fn read_text(&mut self) -> Result<String> {
        self.try_with(ToString::to_string).map_err(error)
    }
    fn reactive_text(&self) -> bool {
        self.is_reactive()
    }
    fn validate(&self, runtime: RuntimeId) -> Result<()> {
        match self {
            Self::Value(_) => Ok(()),
            Self::Cage(v) => v.validate(runtime),
            Self::Bond(v) => v.validate(runtime),
        }
    }
}
pub struct Computed<F>(F);
pub fn computed<F, T>(read: F) -> Computed<F>
where
    F: FnMut() -> T,
    T: Display,
{
    Computed(read)
}
impl<F, T> sealed::Text for Computed<F>
where
    F: FnMut() -> T + 'static,
    T: Display,
{
}
impl<F, T> TextValue for Computed<F>
where
    F: FnMut() -> T + 'static,
    T: Display,
{
    fn read_text(&mut self) -> Result<String> {
        Ok((self.0)().to_string())
    }
    fn reactive_text(&self) -> bool {
        true
    }
    fn validate(&self, _runtime: RuntimeId) -> Result<()> {
        Ok(())
    }
}

pub struct View<A = ()> {
    template: &'static Template,
    actions: Option<A>,
}
pub fn view(template: &'static Template) -> View {
    View {
        template,
        actions: Some(()),
    }
}
#[doc(hidden)]
pub struct Bind<V> {
    field: Field,
    value: V,
}
#[doc(hidden)]
pub struct On<F> {
    click: Click,
    #[cfg_attr(not(target_arch = "wasm32"), allow(dead_code))]
    callback: F,
}
#[doc(hidden)]
pub struct ChildValue<C> {
    outlet: Outlet,
    content: C,
}
#[doc(hidden)]
pub struct Toggle<V> {
    field: Field,
    value: V,
}
impl<A> View<A> {
    pub fn class_when<V: BoolValue>(self, field: Field, value: V) -> View<(A, Toggle<V>)> {
        View {
            template: self.template,
            actions: Some((self.actions.expect("unbuilt view"), Toggle { field, value })),
        }
    }
    pub fn child<C: Content>(self, outlet: Outlet, content: C) -> View<(A, ChildValue<C>)> {
        View {
            template: self.template,
            actions: Some((
                self.actions.expect("unbuilt view"),
                ChildValue { outlet, content },
            )),
        }
    }
    pub fn bind<V: TextValue>(self, field: Field, value: V) -> View<(A, Bind<V>)> {
        View {
            template: self.template,
            actions: Some((self.actions.expect("unbuilt view"), Bind { field, value })),
        }
    }
    pub fn watch<F, T>(self, field: Field, read: F) -> View<(A, Bind<Computed<F>>)>
    where
        F: FnMut() -> T + 'static,
        T: Display,
    {
        self.bind(field, computed(read))
    }
    pub fn on_click<F: FnMut() + 'static>(self, click: Click, callback: F) -> View<(A, On<F>)> {
        View {
            template: self.template,
            actions: Some((self.actions.expect("unbuilt view"), On { click, callback })),
        }
    }
    pub fn template(&self) -> &'static Template {
        self.template
    }
}
fn resolve(
    definition: &Compiled,
    name: &str,
    expected: fn(Kind) -> bool,
    seen: &mut Vec<u16>,
) -> Result<u16> {
    let (slot, kind) = definition
        .slot(name)
        .ok_or_else(|| error(format!("unknown slot: {name}")))?;
    if !expected(kind) {
        return Err(error(format!("wrong kind for slot: {name}")));
    }
    if seen.contains(&slot) {
        return Err(error(format!("duplicate configuration: {name}")));
    }
    seen.push(slot);
    Ok(slot)
}
/// Implemented only by built-in configuration actions; not a host extension API.
#[doc(hidden)]
pub trait Actions: sealed::Actions {
    fn validate(&self, definition: &Compiled, scope: &Scope, seen: &mut Vec<u16>) -> Result<()>;
    fn apply(self, mount: &impl mounting::Mount) -> glory_ui::Result;
}
impl sealed::Actions for () {}
impl Actions for () {
    fn validate(&self, _: &Compiled, _: &Scope, _: &mut Vec<u16>) -> Result<()> {
        Ok(())
    }
    fn apply(self, _: &impl mounting::Mount) -> glory_ui::Result {
        Ok(())
    }
}
impl<A: Actions, B: Actions> sealed::Actions for (A, B) {}
impl<A: Actions, B: Actions> Actions for (A, B) {
    fn validate(&self, d: &Compiled, s: &Scope, seen: &mut Vec<u16>) -> Result<()> {
        self.0.validate(d, s, seen)?;
        self.1.validate(d, s, seen)
    }
    fn apply(self, m: &impl mounting::Mount) -> glory_ui::Result {
        self.0.apply(m)?;
        self.1.apply(m)
    }
}
impl<V: TextValue> sealed::Actions for Bind<V> {}
impl<V: TextValue + 'static> Actions for Bind<V> {
    fn validate(&self, d: &Compiled, s: &Scope, seen: &mut Vec<u16>) -> Result<()> {
        resolve(
            d,
            self.field.0,
            |k| matches!(k, Kind::Text | Kind::Attribute(_)),
            seen,
        )?;
        self.value.validate(s.runtime())
    }
    fn apply(self, m: &impl mounting::Mount) -> glory_ui::Result {
        m.text(self.field, self.value)
    }
}
impl<F: FnMut() + 'static> sealed::Actions for On<F> {}
impl<F: FnMut() + 'static> Actions for On<F> {
    fn validate(&self, d: &Compiled, _: &Scope, seen: &mut Vec<u16>) -> Result<()> {
        resolve(d, self.click.0, |k| k == Kind::Click, seen)?;
        Ok(())
    }
    fn apply(self, m: &impl mounting::Mount) -> glory_ui::Result {
        m.on(self.click, self.callback)
    }
}
impl<C: Content> sealed::Actions for ChildValue<C> {}
impl<C: Content> Actions for ChildValue<C> {
    fn validate(&self, d: &Compiled, s: &Scope, seen: &mut Vec<u16>) -> Result<()> {
        resolve(
            d,
            self.outlet.0,
            |k| matches!(k, Kind::Children | Kind::Range),
            seen,
        )?;
        self.content.validate(s)
    }
    fn apply(self, m: &impl mounting::Mount) -> glory_ui::Result {
        m.child(self.outlet, self.content)
    }
}
impl<V: BoolValue> sealed::Actions for Toggle<V> {}
impl<V: BoolValue> Actions for Toggle<V> {
    fn validate(&self, d: &Compiled, s: &Scope, seen: &mut Vec<u16>) -> Result<()> {
        resolve(d, self.field.0, |k| matches!(k, Kind::Class(..)), seen)?;
        self.value.validate_bool(s.runtime())
    }
    fn apply(self, m: &impl mounting::Mount) -> glory_ui::Result {
        m.flag(self.field, self.value)
    }
}
impl<A: Actions> View<A> {
    #[cfg(target_arch = "wasm32")]
    pub fn mount(self, app: &crate::template::App, scope: &Scope) -> Result<Mounted>
    where
        A: 'static,
    {
        mount(self, app, scope)
    }
    pub fn validate(&self, scope: &Scope) -> Result<()> {
        if !scope.is_alive() {
            return Err(error("disposed view scope"));
        }
        let definition = self.template.cached()?;
        self.actions
            .as_ref()
            .ok_or_else(|| error("view already built"))?
            .validate(&definition, scope, &mut Vec::new())
    }
    #[cfg(target_arch = "wasm32")]
    fn mount_direct(&mut self, app: &crate::template::App, scope: &Scope) -> Result<Mounted> {
        if !scope.is_alive() || scope.runtime() != app.runtime().id() {
            return Err(error("foreign or disposed view scope"));
        }
        let definition = app.prepare(self.template)?;
        self.validate(scope)?;
        let actions = self
            .actions
            .take()
            .ok_or_else(|| error("view already built"))?;
        let instance = app.mount(scope, self.template)?;
        if let Err(e) = actions
            .apply(&mounting::SparseMount {
                definition: &definition,
                app,
                scope,
                instance: &instance,
            })
            .map_err(error)
        {
            instance.fail(e.clone());
            return Err(e);
        }
        Ok(Mounted { instance })
    }
}
impl<A: Actions + 'static> Widget for View<A> {
    #[inline(always)]
    fn native_host(&self) -> Option<std::any::TypeId> {
        #[cfg(target_arch = "wasm32")]
        return Some(std::any::TypeId::of::<DisplayMount>());
        #[cfg(not(target_arch = "wasm32"))]
        None
    }
    fn build(&mut self, scope: &glory_ui::Scope) -> glory_ui::Result {
        self.validate(scope).map_err(portable::failure)?;
        let actions = self.actions.take().ok_or(glory_ui::Error::Gone)?;
        portable::build(self.template, actions, scope)
    }
    fn mount_host(
        &mut self,
        scope: &Scope,
        host: &mut dyn std::any::Any,
    ) -> glory_ui::Result<bool> {
        #[cfg(target_arch = "wasm32")]
        if let Some(context) = host.downcast_mut::<DisplayMount>() {
            context.result = Some(self.mount_direct(&context.app, scope));
            return Ok(true);
        }
        let _ = (scope, host);
        Ok(false)
    }
}
#[cfg(target_arch = "wasm32")]
struct DisplayMount {
    app: crate::template::App,
    result: Option<Result<Mounted>>,
}
/// Mount any Widget; raw views retain their sparse template fast path.
#[cfg(target_arch = "wasm32")]
pub fn mount(
    mut widget: impl Widget,
    app: &crate::template::App,
    scope: &Scope,
) -> Result<Mounted> {
    app.ensure_live()?;
    if !scope.is_alive() || scope.runtime() != app.runtime().id() {
        return Err(error("foreign or disposed widget scope"));
    }
    let mut context = DisplayMount {
        app: app.clone(),
        result: None,
    };
    if widget.native_host() == Some(std::any::TypeId::of::<DisplayMount>()) {
        if !widget.mount_host(scope, &mut context).map_err(error)? {
            return Err(error("widget native host did not mount"));
        }
        return context
            .result
            .ok_or_else(|| error("widget host did not mount"))?;
    }
    if widget.is_empty() {
        return mount(empty(), app, scope);
    }
    if let Some(child) =
        glory_core::untracked(|| scope.enter(|| widget.compose(scope))).map_err(error)?
    {
        return mount(child, app, scope);
    }
    if widget.mount_host(scope, &mut context).map_err(error)? {
        return context
            .result
            .ok_or_else(|| error("widget host did not mount"))?;
    }
    app.mount_widget(scope, widget)
        .map(|instance| Mounted { instance })
}
#[cfg(target_arch = "wasm32")]
#[derive(Clone)]
pub struct Mounted {
    instance: crate::template::Instance,
}
#[cfg(target_arch = "wasm32")]
impl Mounted {
    pub fn set(&self, field: Field, value: impl Display) -> Result<()> {
        let slot = self
            .instance
            .named(field.0, |k| matches!(k, Kind::Text | Kind::Attribute(_)))?;
        self.instance.set(slot, value.to_string())
    }
    pub fn on_click(&self, click: Click, callback: impl FnMut() + 'static) -> Result<()> {
        self.instance.on_click(
            self.instance.named(click.0, |k| k == Kind::Click)?,
            callback,
        )
    }
    pub fn children(&self, outlet: Outlet) -> Result<crate::template::Children> {
        self.instance.children(
            self.instance
                .named(outlet.0, |k| matches!(k, Kind::Children | Kind::Range))?,
        )
    }
    pub fn place(
        &self,
        parent: Option<&crate::template::Children>,
        before: Option<&Mounted>,
    ) -> Result<()> {
        self.instance.place(parent, before.map(|b| &b.instance))
    }
}