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