1use std::fmt;
2use std::time::Duration;
3
4use futures_util::future::BoxFuture;
5use serde::Serialize;
6use serde_json::Value;
7
8use jiff::tz::TimeZone;
9use jiff::{Timestamp, ZonedDateTimeArithmetic};
10
11use super::{PropError, Props, ScrollMetadata};
12use crate::page::{LiveListener, LiveState};
13
14#[derive(Debug)]
27#[must_use]
28pub struct Prop {
29 pub(crate) source: Source,
30 pub(crate) options: Options,
31}
32
33pub(crate) enum Source {
35 Value(Value),
37 Props(Props),
39 Callback(Callback),
41 Failed(PropError),
43}
44
45type Callback = Box<dyn FnOnce() -> BoxFuture<'static, Result<Computed, PropError>> + Send>;
46
47pub(crate) struct Computed {
49 pub(crate) value: Value,
50 pub(crate) scroll: Option<ScrollMetadata>,
51}
52
53#[derive(Debug, Clone, Default)]
55pub(crate) struct Options {
56 pub(crate) loading: Loading,
57 pub(crate) always: bool,
58 pub(crate) rescue: bool,
59 pub(crate) merge: Option<Merge>,
60 pub(crate) once: Option<Once>,
61 pub(crate) scroll: Option<Scroll>,
62 pub(crate) live: Option<LiveState>,
63}
64
65#[derive(Debug, Clone, Default, PartialEq, Eq)]
67pub(crate) enum Loading {
68 #[default]
70 Eager,
71 Optional,
73 Deferred { group: String },
75}
76
77#[derive(Debug, Clone)]
79pub(crate) struct Merge {
80 pub(crate) deep: bool,
81 pub(crate) append: bool,
82 pub(crate) appends_at: Vec<String>,
83 pub(crate) prepends_at: Vec<String>,
84 pub(crate) match_on: Vec<String>,
85}
86
87impl Default for Merge {
88 fn default() -> Self {
89 Self {
90 deep: false,
91 append: true,
92 appends_at: Vec::new(),
93 prepends_at: Vec::new(),
94 match_on: Vec::new(),
95 }
96 }
97}
98
99impl Merge {
100 fn merges_at_root(&self) -> bool {
101 self.appends_at.is_empty() && self.prepends_at.is_empty()
102 }
103
104 pub(crate) fn appends_at_root(&self) -> bool {
105 self.append && self.merges_at_root()
106 }
107
108 pub(crate) fn prepends_at_root(&self) -> bool {
109 !self.append && self.merges_at_root()
110 }
111}
112
113#[derive(Debug, Clone, Default)]
115pub(crate) struct Once {
116 pub(crate) key: Option<String>,
117 pub(crate) ttl: Option<Duration>,
118 pub(crate) fresh: bool,
119}
120
121#[derive(Debug, Clone)]
123pub(crate) struct Scroll {
124 pub(crate) wrapper: String,
125 pub(crate) metadata: Option<ScrollMetadata>,
126}
127
128impl Prop {
129 pub(crate) fn from_source(source: Source) -> Self {
130 Self {
131 source,
132 options: Options::default(),
133 }
134 }
135
136 pub fn value(value: impl Serialize) -> Self {
138 Self::from_source(match serde_json::to_value(value) {
139 Ok(value) => Source::Value(value),
140 Err(error) => Source::Failed(error.into()),
141 })
142 }
143
144 pub fn optional(mut self) -> Self {
146 self.options.loading = Loading::Optional;
147 self
148 }
149
150 pub fn deferred(self) -> Self {
153 self.group("default")
154 }
155
156 pub fn group(mut self, group: impl Into<String>) -> Self {
158 self.options.loading = Loading::Deferred { group: group.into() };
159 self
160 }
161
162 pub fn rescue(mut self) -> Self {
165 self.options.rescue = true;
166 self
167 }
168
169 pub fn always(mut self) -> Self {
172 self.options.always = true;
173 self
174 }
175
176 pub fn merge(mut self) -> Self {
178 self.merge_options();
179 self
180 }
181
182 pub fn deep_merge(mut self) -> Self {
184 self.merge_options().deep = true;
185 self
186 }
187
188 pub fn append(mut self) -> Self {
190 self.merge_options().append = true;
191 self
192 }
193
194 pub fn prepend(mut self) -> Self {
196 self.merge_options().append = false;
197 self
198 }
199
200 pub fn append_at(mut self, path: impl Into<String>) -> Self {
202 self.merge_options().appends_at.push(path.into());
203 self
204 }
205
206 pub fn prepend_at(mut self, path: impl Into<String>) -> Self {
208 self.merge_options().prepends_at.push(path.into());
209 self
210 }
211
212 pub fn match_on(mut self, key: impl Into<String>) -> Self {
215 self.merge_options().match_on.push(key.into());
216 self
217 }
218
219 fn merge_options(&mut self) -> &mut Merge {
220 self.options.merge.get_or_insert_with(Merge::default)
221 }
222
223 pub fn once(mut self) -> Self {
225 self.once_options();
226 self
227 }
228
229 pub fn once_as(mut self, key: impl Into<String>) -> Self {
232 self.once_options().key = Some(key.into());
233 self
234 }
235
236 pub fn until(mut self, ttl: impl Into<ZonedDateTimeArithmetic>) -> Self {
246 self.once_options().ttl = Some(exact_duration(ttl));
247 self
248 }
249
250 pub fn fresh(mut self) -> Self {
252 self.once_options().fresh = true;
253 self
254 }
255
256 fn once_options(&mut self) -> &mut Once {
257 self.options.once.get_or_insert_with(Once::default)
258 }
259
260 pub fn live(mut self, listeners: impl IntoIterator<Item = LiveListener>) -> Self {
271 let live = self.live_options();
272
273 for LiveListener { channel, events } in listeners {
274 for event in events {
275 match live.listeners.iter_mut().find(|listener| listener.channel == channel) {
276 Some(listener) if listener.events.contains(&event) => {}
277 Some(listener) => listener.events.push(event),
278 None => live.listeners.push(LiveListener::new(channel.clone(), [event])),
279 }
280 }
281 }
282
283 self
284 }
285
286 pub fn throttle(mut self, throttle: impl Into<ZonedDateTimeArithmetic>) -> Self {
298 let throttle = exact_duration(throttle);
299 self.live_options().throttle = Some(u64::try_from(throttle.as_millis()).unwrap_or(u64::MAX));
300 self
301 }
302
303 fn live_options(&mut self) -> &mut LiveState {
304 self.options.live.get_or_insert_with(LiveState::default)
305 }
306
307 pub fn wrapper(mut self, wrapper: impl Into<String>) -> Self {
309 if let Some(scroll) = &mut self.options.scroll {
310 scroll.wrapper = wrapper.into();
311 }
312 self
313 }
314}
315
316fn exact_duration(span: impl Into<ZonedDateTimeArithmetic>) -> Duration {
319 let now = Timestamp::now().to_zoned_datetime(TimeZone::UTC);
320 let Ok(later) = now.checked_add(span) else {
321 return Duration::MAX;
322 };
323
324 Duration::try_from(later.timestamp().duration_since(now.timestamp())).unwrap_or(Duration::ZERO)
325}
326
327impl fmt::Debug for Source {
328 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
329 match self {
330 Self::Value(value) => f.debug_tuple("Value").field(value).finish(),
331 Self::Props(props) => f.debug_tuple("Props").field(props).finish(),
332 Self::Callback(_) => f.write_str("Callback"),
333 Self::Failed(error) => f.debug_tuple("Failed").field(error).finish(),
334 }
335 }
336}
337
338pub trait IntoProp {
342 fn into_prop(self) -> Prop;
344}
345
346impl IntoProp for Prop {
347 fn into_prop(self) -> Prop {
348 self
349 }
350}
351
352impl IntoProp for Props {
353 fn into_prop(self) -> Prop {
354 Prop::from_source(Source::Props(self))
355 }
356}
357
358impl<T: Serialize> IntoProp for T {
359 fn into_prop(self) -> Prop {
360 Prop::value(self)
361 }
362}