1use std::collections::BTreeMap;
2use std::rc::Rc;
3
4use glory_core::{Cage, Vary};
5use glory_render::{
6 ButtonProps, Change, CheckProps, Descriptor, Event, EventKind, FocusMode, ImageProps,
7 InputProps, ItemPosition, LinkProps, NodeId, Patch, Props, Purpose, Role, TextKind, TextProps,
8};
9use glory_style::{Display, FlexDirection, Style};
10
11use crate::app::{Result, Scope, Widget};
12
13type Bind = Box<dyn FnOnce(&Scope, NodeId) -> Result>;
14type Prepare = Box<dyn FnOnce(&Scope) -> Result<(Patch, Bind)>>;
15type Handler = Box<dyn FnMut(Event)>;
16#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
17enum Slot {
18 Classes,
19 Style,
20 Name,
21 Role,
22 Focus,
23 Item,
24 Semantics,
25 Text,
26 Kind,
27 Selectable,
28 Label,
29 Enabled,
30 Value,
31 SelectSelection,
32 RichDocument,
33 Purpose,
34 Multiline,
35 Checked,
36 CheckMode,
37 Source,
38 Alternative,
39 Graphic,
40 Target,
41}
42
43fn seed_graphic(descriptor: &mut Descriptor, patches: &mut BTreeMap<Slot, Patch>) {
47 if let (Props::Graphic(props), Some(Patch::Graphic(Change::Set(value)))) =
48 (&mut descriptor.props, patches.remove(&Slot::Graphic))
49 {
50 *props = *value;
51 }
52}
53struct Element {
54 descriptor: Option<Descriptor>,
55 initial: BTreeMap<Slot, Patch>,
56 bindings: BTreeMap<Slot, Prepare>,
57 handlers: BTreeMap<EventKind, Handler>,
58 children: Vec<Box<dyn Widget>>,
59 needs_alt: bool,
60 node_ref: Option<Cage<Option<NodeId>>>,
61 mark: Option<&'static str>,
62}
63impl Element {
64 fn new(props: Props) -> Self {
65 let needs_alt = matches!(props, Props::Image(_));
66 Self {
67 descriptor: Some(Descriptor::new(props)),
68 initial: BTreeMap::new(),
69 bindings: BTreeMap::new(),
70 handlers: BTreeMap::new(),
71 children: Vec::new(),
72 needs_alt,
73 node_ref: None,
74 mark: None,
75 }
76 }
77 fn set<T: Clone + PartialEq + 'static>(
78 &mut self,
79 slot: Slot,
80 value: impl Into<Vary<T>>,
81 mut patch: impl FnMut(T) -> Patch + 'static,
82 ) {
83 self.initial.remove(&slot);
84 self.bindings.remove(&slot);
85 match value.into() {
86 Vary::Value(value) => {
87 self.initial.insert(slot, patch(value));
88 }
89 value => {
90 self.bindings.insert(
91 slot,
92 Box::new(move |_| {
93 let initial = glory_core::untracked(|| value.try_get())?;
97 let initial_patch = patch(initial.clone());
98 let install: Bind = Box::new(move |scope, node| {
99 let session = Rc::downgrade(&scope.session()?);
100 let mut previous = Some(initial);
101 scope.binding(move || {
102 let Some(session) = session.upgrade() else {
103 return;
104 };
105 let value = match value.try_get() {
106 Ok(value) => value,
107 Err(error) => {
108 session.report(error.into());
109 return;
110 }
111 };
112 if previous.as_ref() == Some(&value) {
113 return;
114 }
115 let update = patch(value.clone());
116 let result = session.bound_patch(node, update);
117 match result {
118 Ok(()) => previous = Some(value),
119 Err(error) => session.report(error),
120 }
121 });
122 Ok(())
123 });
124 Ok((initial_patch, install))
125 }),
126 );
127 }
128 }
129 }
130 fn set_fn<T: Clone + PartialEq + 'static>(
131 &mut self,
132 slot: Slot,
133 mut read: impl FnMut() -> T + 'static,
134 mut patch: impl FnMut(T) -> Patch + 'static,
135 ) {
136 self.initial.remove(&slot);
137 self.bindings.insert(
138 slot,
139 Box::new(move |scope| {
140 let initial = scope.owner().compute(&mut read)?;
141 let update = patch(initial.clone());
142 let install: Bind = Box::new(move |scope, node| {
143 crate::plan::bind_fn(scope, node, read, patch, Some(initial))
144 });
145 Ok((update, install))
146 }),
147 );
148 }
149 fn build(&mut self, scope: &Scope) -> Result {
150 if self.needs_alt {
151 return Err(glory_render::Error::InvalidProps(
152 "image requires alt text or explicit decorative()",
153 )
154 .into());
155 }
156 let mut descriptor = self.descriptor.take().ok_or(crate::app::Error::Gone)?;
157 if let Props::File(props) = &descriptor.props {
158 props.configuration.validate()?;
159 }
160 let mut initial = std::mem::take(&mut self.initial);
161 let mut bindings = Vec::with_capacity(self.bindings.len());
162 for (slot, prepare) in std::mem::take(&mut self.bindings) {
163 let (patch, install) = prepare(scope)?;
164 initial.insert(slot, patch);
165 bindings.push(install);
166 }
167 seed_graphic(&mut descriptor, &mut initial);
170 descriptor.patches(initial.into_values())?;
171 let node = scope.create(descriptor)?;
172 for bind in bindings {
173 bind(scope, node)?;
174 }
175 for (kind, handler) in std::mem::take(&mut self.handlers) {
176 scope.on(node, kind, handler)?;
177 }
178 for child in self.children.drain(..) {
179 scope.fill(node, child)?;
180 }
181 if let Some(reference) = self.node_ref.take() {
182 reference.try_revise(|value| *value = Some(node))?;
183 scope.on_cleanup(move || {
184 let _ = reference.try_revise(|value| {
185 if *value == Some(node) {
186 *value = None;
187 }
188 });
189 })?;
190 }
191 Ok(())
192 }
193 fn options<T: 'static>(&mut self, value: T) {
194 self.descriptor
195 .as_mut()
196 .expect("unmounted builder")
197 .options
198 .insert(value);
199 }
200 fn static_plan(&mut self) -> Result<crate::Plan> {
201 if self.needs_alt
202 || !self.bindings.is_empty()
203 || !self.handlers.is_empty()
204 || self.node_ref.is_some()
205 {
206 return Err(glory_render::Error::InvalidProps(
207 "plan requires static declarations; bind events/values on the instance",
208 )
209 .into());
210 }
211 let mut descriptor = self.descriptor.take().ok_or(crate::Error::Gone)?;
212 if let Props::File(props) = &descriptor.props {
213 props.configuration.validate()?;
214 }
215 let mut initial = std::mem::take(&mut self.initial);
216 seed_graphic(&mut descriptor, &mut initial);
217 descriptor.patches(initial.into_values())?;
218 let mut nodes = vec![glory_render::PlanNode {
219 parent: None,
220 descriptor,
221 }];
222 let mut marks = self
223 .mark
224 .take()
225 .map(|name| vec![(name, 0)])
226 .unwrap_or_default();
227 for mut child in self.children.drain(..) {
228 child.static_plan()?.append(0, &mut nodes, &mut marks);
229 }
230 crate::Plan::from_nodes(nodes, marks)
231 }
232}
233
234pub struct Children(Vec<Box<dyn Widget>>);
235pub struct Fragment(Children);
237pub fn fragment(children: impl IntoChildren) -> Fragment {
238 Fragment(children.into_children())
239}
240impl Widget for Fragment {
241 fn is_empty(&self) -> bool {
242 self.0.0.is_empty()
243 }
244 fn compose(&mut self, _: &glory_core::Scope) -> Result<Option<Box<dyn Widget>>> {
245 if self.0.0.len() == 1 {
246 Ok(self.0.0.pop())
247 } else {
248 Ok(None)
249 }
250 }
251 fn build(&mut self, scope: &Scope) -> Result {
252 for child in std::mem::take(&mut self.0.0) {
253 child.show_in(scope)?;
254 }
255 Ok(())
256 }
257}
258impl Children {
259 #[doc(hidden)]
260 pub fn into_widgets(self) -> Vec<Box<dyn Widget>> {
261 self.0
262 }
263}
264impl IntoChildren for Children {
265 fn into_children(self) -> Children {
266 self
267 }
268}
269pub trait IntoChildren {
270 fn into_children(self) -> Children;
271}
272impl<W: Widget> IntoChildren for W {
273 fn into_children(self) -> Children {
274 Children(vec![Box::new(self)])
275 }
276}
277impl<W: Widget> IntoChildren for Vec<W> {
278 fn into_children(self) -> Children {
279 Children(
280 self.into_iter()
281 .map(|value| Box::new(value) as Box<dyn Widget>)
282 .collect(),
283 )
284 }
285}
286impl IntoChildren for () {
287 fn into_children(self) -> Children {
288 Children(Vec::new())
289 }
290}
291macro_rules! children_tuple {
292 ($($name:ident),+) => {
293 impl<$($name: Widget),+> IntoChildren for ($($name,)+) {
294 #[allow(non_snake_case)]
295 fn into_children(self) -> Children { let ($($name,)+) = self; Children(vec![$(Box::new($name)),+]) }
296 }
297 };
298}
299children_tuple!(A, B);
300children_tuple!(A, B, C);
301children_tuple!(A, B, C, D);
302children_tuple!(A, B, C, D, E);
303children_tuple!(A, B, C, D, E, F);
304children_tuple!(A, B, C, D, E, F, G);
305children_tuple!(A, B, C, D, E, F, G, H);
306children_tuple!(A, B, C, D, E, F, G, H, I);
307children_tuple!(A, B, C, D, E, F, G, H, I, J);
308children_tuple!(A, B, C, D, E, F, G, H, I, J, K);
309children_tuple!(A, B, C, D, E, F, G, H, I, J, K, L);
310
311macro_rules! element {
312 ($name:ident, $factory:ident, $props:expr) => {
313 pub struct $name {
314 inner: Element,
315 }
316 pub fn $factory() -> $name {
317 $name {
318 inner: Element::new($props),
319 }
320 }
321 impl Default for $name {
322 fn default() -> Self {
323 $factory()
324 }
325 }
326 impl Widget for $name {
327 fn static_plan(&mut self) -> Result<crate::Plan> {
328 self.inner.static_plan()
329 }
330 fn build(&mut self, scope: &Scope) -> Result {
331 self.inner.build(scope)
332 }
333 }
334 impl $name {
335 pub fn mark(mut self, name: &'static str) -> Self {
337 self.inner.mark = Some(name);
338 self
339 }
340 pub fn backend_options<T: 'static>(mut self, value: T) -> Self {
341 self.inner.options(value);
342 self
343 }
344 }
345 };
346}
347element!(View, view, Props::View);
348element!(Group, group, Props::Group);
349element!(Text, text, Props::Text(TextProps::default()));
350element!(Button, button, Props::Button(ButtonProps::default()));
351element!(Input, input, Props::Input(InputProps::default()));
352element!(
353 RichEditor,
354 rich_editor,
355 Props::RichEditor(Default::default())
356);
357element!(File, file, Props::File(glory_render::FileProps::default()));
358element!(
359 Select,
360 select,
361 Props::Select(glory_render::SelectProps::default())
362);
363element!(Check, check, Props::Check(CheckProps::default()));
364element!(Image, image, Props::Image(ImageProps::default()));
365element!(
366 Graphic,
367 graphic,
368 Props::Graphic(glory_render::GraphicProps::default())
369);
370element!(Link, link, Props::Link(LinkProps::default()));
371
372macro_rules! common {
373 ($($name:ident),+) => {$ (
374 impl $name {
375 pub fn class(mut self, value: impl Into<Vary<String>>) -> Self {
377 self.inner.set(Slot::Classes, value, |value: String| Patch::Classes(Change::Set(value.split_whitespace().map(str::to_owned).collect()))); self
378 }
379 pub fn class_fn(mut self, read: impl FnMut() -> String + 'static) -> Self {
381 self.inner.set_fn(Slot::Classes, read, |value: String| Patch::Classes(Change::Set(value.split_whitespace().map(str::to_owned).collect()))); self
382 }
383 pub fn style_fn(mut self, read: impl FnMut() -> Style + 'static) -> Self {
384 self.inner.set_fn(Slot::Style, read, |value| Patch::Style(Change::Set(Box::new(value)))); self
385 }
386 pub fn style(mut self, value: impl Into<Vary<Style>>) -> Self {
387 self.inner.set(Slot::Style, value, |value| Patch::Style(Change::Set(Box::new(value)))); self
388 }
389 pub fn name(mut self, value: impl Into<Vary<String>>) -> Self {
393 self.inner.set(Slot::Name, value, |value| Patch::Name(Change::Set(Some(value)))); self
394 }
395 pub fn focus(mut self, mode: impl Into<Vary<FocusMode>>) -> Self { self.inner.set(Slot::Focus, mode, |value| Patch::Focus(Change::Set(value))); self }
396 pub fn semantics(mut self, value: impl Into<Vary<Option<Box<glory_render::Semantics>>>>) -> Self {
398 self.inner.set(Slot::Semantics, value, |value| Patch::Semantics(Change::Set(value))); self
399 }
400 pub fn on(mut self, kind: EventKind, handler: impl FnMut(Event) + 'static) -> Self { self.inner.handlers.insert(kind, Box::new(handler)); self }
401 pub fn node_ref(mut self, reference: Cage<Option<NodeId>>) -> Self { self.inner.node_ref = Some(reference); self }
403 }
404 )+};
405}
406common!(
407 View, Text, Button, Input, File, Select, Check, Image, Graphic, Link, RichEditor
408);
409impl RichEditor {
410 pub fn document(mut self, value: impl Into<Vary<Rc<glory_render::RichDocument>>>) -> Self {
411 self.inner
412 .set(Slot::RichDocument, value, |document| Patch::RichDocument {
413 document: Change::Set(document),
414 revision: 1,
415 });
416 self
417 }
418 pub fn enabled(mut self, value: impl Into<Vary<bool>>) -> Self {
419 self.inner.set(Slot::Enabled, value, |value| {
420 Patch::Enabled(Change::Set(value))
421 });
422 self
423 }
424}
425impl Graphic {
426 pub fn drawing(mut self, value: impl Into<Vary<glory_render::GraphicProps>>) -> Self {
427 self.inner.set(Slot::Graphic, value, |value| {
428 Patch::Graphic(Change::Set(Box::new(value)))
429 });
430 self
431 }
432}
433impl View {
434 pub fn document_part(mut self, part: glory_render::DocumentPart) -> Self {
437 self.inner
438 .descriptor
439 .as_mut()
440 .expect("unmounted builder")
441 .semantics
442 .get_or_insert_with(Default::default)
443 .document_part = Some(part);
444 self
445 }
446 pub fn field_part(mut self, part: glory_render::FieldPart) -> Self {
448 self.inner
449 .descriptor
450 .as_mut()
451 .expect("unmounted builder")
452 .semantics
453 .get_or_insert_with(Default::default)
454 .field_part = Some(part);
455 self
456 }
457 pub fn role(mut self, role: Role) -> Self {
459 self.inner.set(Slot::Role, Some(role), |value| {
460 Patch::Role(Change::Set(value))
461 });
462 self
463 }
464 pub fn item(mut self, value: impl Into<Vary<Option<ItemPosition>>>) -> Self {
465 self.inner
466 .set(Slot::Item, value, |value| Patch::Item(Change::Set(value)));
467 self
468 }
469}
470macro_rules! fill {
471 ($($name:ident),+) => {$ (
472 impl $name { pub fn fill(mut self, children: impl IntoChildren) -> Self { self.inner.children.extend(children.into_children().0); self } }
473 )+};
474}
475fill!(View, Group, Button, Link);
476macro_rules! label {
477 ($($name:ident),+) => {$ (
478 impl $name {
479 pub fn label_fn(mut self, read: impl FnMut() -> String + 'static) -> Self {
480 self.inner.set_fn(Slot::Label, read, |value| Patch::Label(Change::Set(value))); self
481 }
482 pub fn label(mut self, value: impl Into<Vary<String>>) -> Self { self.inner.set(Slot::Label, value, |value| Patch::Label(Change::Set(value))); self } }
483 )+};
484}
485label!(Button, Check, Link);
486macro_rules! enabled {
487 ($($name:ident),+) => {$ (
488 impl $name { pub fn enabled(mut self, value: impl Into<Vary<bool>>) -> Self { self.inner.set(Slot::Enabled, value, |value| Patch::Enabled(Change::Set(value))); self } }
489 )+};
490}
491enabled!(Button, Input, File, Check);
492impl File {
493 pub fn label(mut self, value: impl Into<String>) -> Self {
494 self.inner.set(Slot::Label, value.into(), |value| {
495 Patch::Label(Change::Set(value))
496 });
497 self
498 }
499 pub fn configuration(mut self, value: glory_render::FileConfig) -> Self {
502 let Props::File(props) = &mut self
503 .inner
504 .descriptor
505 .as_mut()
506 .expect("unmounted file builder")
507 .props
508 else {
509 unreachable!()
510 };
511 props.configuration = value;
512 self
513 }
514}
515impl Text {
516 pub fn content_fn(mut self, read: impl FnMut() -> String + 'static) -> Self {
517 self.inner
518 .set_fn(Slot::Text, read, |value| Patch::Text(Change::Set(value)));
519 self
520 }
521 pub fn content(mut self, value: impl Into<Vary<String>>) -> Self {
522 self.inner
523 .set(Slot::Text, value, |value| Patch::Text(Change::Set(value)));
524 self
525 }
526 pub fn kind(mut self, value: TextKind) -> Self {
527 self.inner.set(Slot::Kind, value, |value| {
528 Patch::TextKind(Change::Set(value))
529 });
530 self
531 }
532 pub fn selectable(mut self, value: impl Into<Vary<bool>>) -> Self {
533 self.inner.set(Slot::Selectable, value, |value| {
534 Patch::Selectable(Change::Set(value))
535 });
536 self
537 }
538}
539impl Input {
540 pub fn value(mut self, value: impl Into<Vary<String>>) -> Self {
541 self.inner.set(Slot::Value, value, |value| Patch::Value {
544 value: Change::Set(value),
545 revision: 1,
546 });
547 self
548 }
549 pub fn purpose(mut self, value: impl Into<Vary<Purpose>>) -> Self {
550 self.inner.set(Slot::Purpose, value, |value| {
551 Patch::Purpose(Change::Set(value))
552 });
553 self
554 }
555 pub fn multiline(mut self, value: bool) -> Self {
556 self.inner.set(Slot::Multiline, value, |value| {
557 Patch::Multiline(Change::Set(value))
558 });
559 self
560 }
561}
562impl Check {
563 pub fn mode(mut self, value: impl Into<Vary<glory_render::CheckMode>>) -> Self {
564 self.inner.set(Slot::CheckMode, value, |value| {
565 Patch::CheckMode(Change::Set(value))
566 });
567 self
568 }
569
570 pub fn checked(mut self, value: impl Into<Vary<bool>>) -> Self {
571 self.inner.set(Slot::Checked, value, |value| {
572 Patch::Checked(Change::Set(value))
573 });
574 self
575 }
576}
577impl Image {
578 pub fn source(mut self, value: impl Into<Vary<String>>) -> Self {
579 self.inner.set(Slot::Source, value, |value| Patch::Source {
580 source: Change::Set(value),
581 revision: 1,
582 });
583 self
584 }
585 pub fn responsive(mut self, value: glory_render::ResponsiveImage) -> Self {
586 let Props::Image(props) = &mut self
587 .inner
588 .descriptor
589 .as_mut()
590 .expect("unmounted builder")
591 .props
592 else {
593 unreachable!()
594 };
595 props.responsive = value;
596 self
597 }
598 pub fn loading(mut self, value: glory_render::ImageLoading) -> Self {
599 let Props::Image(props) = &mut self
600 .inner
601 .descriptor
602 .as_mut()
603 .expect("unmounted builder")
604 .props
605 else {
606 unreachable!()
607 };
608 props.loading = value;
609 self
610 }
611 pub fn alt(mut self, value: impl Into<Vary<String>>) -> Self {
612 self.inner.needs_alt = false;
613 self.inner.set(Slot::Alternative, value, |value| {
614 Patch::Alternative(Change::Set(Some(value)))
615 });
616 self
617 }
618 pub fn decorative(mut self) -> Self {
619 self.inner.needs_alt = false;
620 self.inner.set(Slot::Alternative, None::<String>, |value| {
621 Patch::Alternative(Change::Set(value))
622 });
623 self
624 }
625}
626impl Link {
627 pub fn target(mut self, value: impl Into<Vary<String>>) -> Self {
628 self.inner.set(Slot::Target, value, |value| {
629 Patch::Target(Change::Set(value))
630 });
631 self
632 }
633}
634
635pub fn row() -> View {
636 view().style(
637 Style::new()
638 .display(Display::Flex)
639 .flex_direction(FlexDirection::Row),
640 )
641}
642pub fn col() -> View {
643 view().style(
644 Style::new()
645 .display(Display::Flex)
646 .flex_direction(FlexDirection::Column),
647 )
648}
649
650pub struct WidgetFn<F>(F);
652pub fn widget<F: FnMut(&Scope) -> Result + 'static>(build: F) -> WidgetFn<F> {
654 WidgetFn(build)
655}
656impl<F: FnMut(&Scope) -> Result + 'static> Widget for WidgetFn<F> {
657 fn build(&mut self, scope: &Scope) -> Result {
658 (self.0)(scope)
659 }
660}
661
662pub mod events {
663 pub use glory_render::Event;
664 use glory_render::EventKind;
665 #[allow(non_upper_case_globals)]
666 pub const activate: EventKind = EventKind::Activate;
667 #[allow(non_upper_case_globals)]
668 pub const value_changed: EventKind = EventKind::ValueChanged;
669 #[allow(non_upper_case_globals)]
670 pub const checked_changed: EventKind = EventKind::CheckedChanged;
671 #[allow(non_upper_case_globals)]
672 pub const select_changed: EventKind = EventKind::SelectChanged;
673 #[allow(non_upper_case_globals)]
674 pub const choice_command: EventKind = EventKind::Choice;
675 #[allow(non_upper_case_globals)]
676 pub const tags_command: EventKind = EventKind::Tags;
677 #[allow(non_upper_case_globals)]
678 pub const context_menu: EventKind = EventKind::ContextMenu;
679 #[allow(non_upper_case_globals)]
680 pub const commit: EventKind = EventKind::Commit;
681 #[allow(non_upper_case_globals)]
682 pub const focus_changed: EventKind = EventKind::FocusChanged;
683 #[allow(non_upper_case_globals)]
684 pub const focus_within: EventKind = EventKind::FocusWithin;
685 #[allow(non_upper_case_globals)]
686 pub const navigate: EventKind = EventKind::Navigate;
687 #[allow(non_upper_case_globals)]
688 pub const typeahead: EventKind = EventKind::Typeahead;
689 #[allow(non_upper_case_globals)]
690 pub const menu_command: EventKind = EventKind::Menu;
691 #[allow(non_upper_case_globals)]
692 pub const pointer_boundary: EventKind = EventKind::Pointer;
693 #[allow(non_upper_case_globals)]
694 pub const pointer_within: EventKind = EventKind::PointerWithin;
695 #[allow(non_upper_case_globals)]
696 pub const keyboard: EventKind = EventKind::Keyboard;
697 #[allow(non_upper_case_globals)]
698 pub const drag: EventKind = EventKind::Drag;
699 #[allow(non_upper_case_globals)]
700 pub const composition: EventKind = EventKind::Composition;
701 #[allow(non_upper_case_globals)]
702 pub const scroll: EventKind = EventKind::Scroll;
703 #[allow(non_upper_case_globals)]
704 pub const resize: EventKind = EventKind::Resize;
705}
706
707impl Select {
708 pub fn configuration(mut self, value: glory_render::SelectProps) -> Self {
710 self.inner
711 .descriptor
712 .as_mut()
713 .expect("unmounted builder")
714 .props = Props::Select(value);
715 self
716 }
717 pub fn selected(mut self, value: impl Into<Vary<Vec<glory_render::SemanticId>>>) -> Self {
718 self.inner.set(Slot::SelectSelection, value, |keys| {
719 Patch::SelectSelection {
720 keys: Change::Set(keys),
721 revision: 1,
722 }
723 });
724 self
725 }
726 pub fn enabled(mut self, value: impl Into<Vary<bool>>) -> Self {
727 self.inner
728 .set(Slot::Enabled, value, |v| Patch::Enabled(Change::Set(v)));
729 self
730 }
731}