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 return match patch(value) {
160 Patch::RichDocument {
161 document: Change::Set(value),
162 ..
163 } => scope.session()?.rich_document(node, value),
164 Patch::Value {
165 value: Change::Set(value),
166 ..
167 } => scope.session()?.input_value(node, value),
168 Patch::SelectSelection {
169 keys: Change::Set(keys),
170 ..
171 } => scope.session()?.select_selection(node, keys),
172 Patch::Source {
173 source: Change::Set(value),
174 ..
175 } => scope.session()?.image_source(node, value),
176 update => scope.patch(node, update),
177 };
178 }
179 let session = Rc::downgrade(&scope.session()?);
180 let mut previous = None;
181 scope.binding(move || {
182 let Some(session) = session.upgrade() else {
183 return;
184 };
185 let value = match value.try_get() {
186 Ok(value) => value,
187 Err(error) => {
188 session.report(error.into());
189 return;
190 }
191 };
192 if previous.as_ref() == Some(&value) {
193 return;
194 }
195 let update = patch(value.clone());
196 let result = match update {
197 Patch::RichDocument {
198 document: Change::Set(value),
199 ..
200 } => session.rich_document(node, value),
201 Patch::Value {
202 value: Change::Set(value),
203 ..
204 } => session.input_value(node, value),
205 Patch::SelectSelection {
206 keys: Change::Set(keys),
207 ..
208 } => session.select_selection(node, keys),
209 Patch::Source {
210 source: Change::Set(value),
211 ..
212 } => session.image_source(node, value),
213 update => session.patch(node, update),
214 };
215 match result {
216 Ok(()) => previous = Some(value),
217 Err(error) => session.report(error),
218 }
219 });
220 Ok(())
221}
222
223pub(crate) fn bind_fn<T: Clone + PartialEq + 'static>(
224 scope: &Scope,
225 node: NodeId,
226 mut read: impl FnMut() -> T + 'static,
227 mut patch: impl FnMut(T) -> Patch + 'static,
228 mut previous: Option<T>,
229) -> Result {
230 let session = Rc::downgrade(&scope.session()?);
231 scope.binding(move || {
232 let Some(session) = session.upgrade() else {
233 return;
234 };
235 let value = read();
236 if previous.as_ref() == Some(&value) {
237 return;
238 }
239 let result = match patch(value.clone()) {
240 Patch::RichDocument {
241 document: Change::Set(value),
242 ..
243 } => session.rich_document(node, value),
244 Patch::Value {
245 value: Change::Set(value),
246 ..
247 } => session.input_value(node, value),
248 Patch::SelectSelection {
249 keys: Change::Set(keys),
250 ..
251 } => session.select_selection(node, keys),
252 Patch::Source {
253 source: Change::Set(value),
254 ..
255 } => session.image_source(node, value),
256 update => session.patch(node, update),
257 };
258 match result {
259 Ok(()) => previous = Some(value),
260 Err(error) => session.report(error),
261 }
262 });
263 Ok(())
264}