1use crate::{Result, Scope, WeakScope, Widget};
3use glory_core::Vary;
4use glory_render::{Change, Event, EventKind, NodeId, Patch};
5use std::rc::Rc;
6
7#[derive(Clone, Debug)]
8pub struct Plan {
9 pub(crate) semantic: glory_render::Plan,
10 marks: Rc<[(&'static str, usize)]>,
11}
12#[derive(Clone, Debug)]
13pub struct PlanPart {
14 plan: glory_render::Plan,
15 index: usize,
16}
17
18pub fn plan(mut widget: impl Widget) -> Result<Plan> {
21 widget.static_plan()
22}
23impl Plan {
24 pub(crate) fn from_nodes(
25 nodes: Vec<glory_render::PlanNode>,
26 marks: Vec<(&'static str, usize)>,
27 ) -> Result<Self> {
28 let mut names = std::collections::HashSet::new();
29 if marks.iter().any(|(name, _)| !names.insert(*name)) {
30 return Err(glory_render::Error::InvalidProps("duplicate plan mark").into());
31 }
32 Ok(Self {
33 semantic: glory_render::Plan::new(nodes)?,
34 marks: marks.into(),
35 })
36 }
37 pub fn part(&self, name: &str) -> Result<PlanPart> {
38 let index = self
39 .marks
40 .iter()
41 .find(|(key, _)| *key == name)
42 .map(|(_, index)| *index)
43 .ok_or(glory_render::Error::InvalidProps("unknown plan mark"))?;
44 Ok(PlanPart {
45 plan: self.semantic.clone(),
46 index,
47 })
48 }
49 pub(crate) fn append(
50 &self,
51 parent: usize,
52 nodes: &mut Vec<glory_render::PlanNode>,
53 marks: &mut Vec<(&'static str, usize)>,
54 ) {
55 let offset = nodes.len();
56 nodes.extend(
57 self.semantic
58 .nodes()
59 .iter()
60 .map(|node| glory_render::PlanNode {
61 parent: Some(node.parent.map_or(parent, |p| p + offset)),
62 descriptor: node.descriptor.clone(),
63 }),
64 );
65 marks.extend(
66 self.marks
67 .iter()
68 .map(|(name, index)| (*name, index + offset)),
69 );
70 }
71}
72
73pub struct PlanInstance {
76 pub(crate) scope: WeakScope,
77 pub(crate) plan: glory_render::Plan,
78 pub(crate) ids: Vec<NodeId>,
79}
80impl PlanInstance {
81 fn resolve(&self, part: &PlanPart) -> Result<(Scope, NodeId)> {
82 if !self.plan.same(&part.plan) {
83 return Err(glory_render::Error::InvalidProps("part belongs to another plan").into());
84 }
85 let scope = self.scope.upgrade().ok_or(crate::Error::Gone)?;
86 Ok((scope, self.ids[part.index]))
87 }
88 pub fn node(&self, part: &PlanPart) -> Result<NodeId> {
89 self.resolve(part).map(|(_, id)| id)
90 }
91 pub fn patch(&self, part: &PlanPart, patch: Patch) -> Result {
92 let (scope, id) = self.resolve(part)?;
93 scope.patch(id, patch)
94 }
95 pub fn bind<T: Clone + PartialEq + 'static>(
96 &self,
97 part: &PlanPart,
98 value: impl Into<Vary<T>>,
99 patch: impl FnMut(T) -> Patch + 'static,
100 ) -> Result {
101 let (scope, id) = self.resolve(part)?;
102 bind(&scope, id, value.into(), patch)
103 }
104 pub fn bind_fn<T: Clone + PartialEq + 'static>(
107 &self,
108 part: &PlanPart,
109 read: impl FnMut() -> T + 'static,
110 patch: impl FnMut(T) -> Patch + 'static,
111 ) -> Result {
112 let (scope, id) = self.resolve(part)?;
113 bind_fn(&scope, id, read, patch, None)
114 }
115 pub fn text_fn(&self, part: &PlanPart, read: impl FnMut() -> String + 'static) -> Result {
116 self.bind_fn(part, read, |v| Patch::Text(Change::Set(v)))
117 }
118 pub fn label_fn(&self, part: &PlanPart, read: impl FnMut() -> String + 'static) -> Result {
119 self.bind_fn(part, read, |v| Patch::Label(Change::Set(v)))
120 }
121 pub fn class_fn(&self, part: &PlanPart, read: impl FnMut() -> String + 'static) -> Result {
122 self.bind_fn(part, read, |v| {
123 Patch::Classes(Change::Set(
124 v.split_whitespace().map(str::to_owned).collect(),
125 ))
126 })
127 }
128 pub fn text(&self, part: &PlanPart, value: impl Into<Vary<String>>) -> Result {
129 self.bind(part, value, |v| Patch::Text(Change::Set(v)))
130 }
131 pub fn label(&self, part: &PlanPart, value: impl Into<Vary<String>>) -> Result {
132 self.bind(part, value, |v| Patch::Label(Change::Set(v)))
133 }
134 pub fn class(&self, part: &PlanPart, value: impl Into<Vary<String>>) -> Result {
135 self.bind(part, value, |v| {
136 Patch::Classes(Change::Set(
137 v.split_whitespace().map(str::to_owned).collect(),
138 ))
139 })
140 }
141 pub fn on(
142 &self,
143 part: &PlanPart,
144 kind: EventKind,
145 handler: impl FnMut(Event) + 'static,
146 ) -> Result {
147 let (scope, id) = self.resolve(part)?;
148 scope.on(id, kind, handler)
149 }
150}
151
152pub(crate) fn bind<T: Clone + PartialEq + 'static>(
153 scope: &Scope,
154 node: NodeId,
155 value: Vary<T>,
156 mut patch: impl FnMut(T) -> Patch + 'static,
157) -> Result {
158 if let Vary::Value(value) = value {
159 let update = patch(value);
160 return scope.session()?.bound_patch(node, update);
161 }
162 let session = Rc::downgrade(&scope.session()?);
163 let mut previous = None;
164 scope.binding(move || {
165 let Some(session) = session.upgrade() else {
166 return;
167 };
168 let value = match value.try_get() {
169 Ok(value) => value,
170 Err(error) => {
171 session.report(error.into());
172 return;
173 }
174 };
175 if previous.as_ref() == Some(&value) {
176 return;
177 }
178 let update = patch(value.clone());
179 let result = session.bound_patch(node, update);
180 match result {
181 Ok(()) => previous = Some(value),
182 Err(error) => session.report(error),
183 }
184 });
185 Ok(())
186}
187
188pub(crate) fn bind_fn<T: Clone + PartialEq + 'static>(
189 scope: &Scope,
190 node: NodeId,
191 mut read: impl FnMut() -> T + 'static,
192 mut patch: impl FnMut(T) -> Patch + 'static,
193 mut previous: Option<T>,
194) -> Result {
195 let session = Rc::downgrade(&scope.session()?);
196 scope.binding(move || {
197 let Some(session) = session.upgrade() else {
198 return;
199 };
200 let value = read();
201 if previous.as_ref() == Some(&value) {
202 return;
203 }
204 let result = session.bound_patch(node, patch(value.clone()));
205 match result {
206 Ok(()) => previous = Some(value),
207 Err(error) => session.report(error),
208 }
209 });
210 Ok(())
211}