1use std::collections::{BTreeMap, BTreeSet};
12use std::sync::atomic::{AtomicBool, Ordering};
13use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
14
15use laravel_core::context::{Context, Internals};
16use serde_json::{Map, Value};
17
18#[derive(Debug, Clone, PartialEq, Eq)]
20pub struct Download {
21 pub name: String,
23 pub content: Vec<u8>,
25 pub content_type: String,
27}
28
29#[derive(Debug, Clone, PartialEq)]
31pub struct Stream {
32 pub id: String,
34 pub chunk_type: String,
36 pub content: String,
38 pub mode: String,
40 pub selector: Option<String>,
42 pub island: Option<String>,
44}
45
46#[derive(Debug, Clone, PartialEq, Eq)]
48pub struct Child {
49 pub key: String,
51 pub tag: String,
53 pub id: String,
55}
56
57#[derive(Debug, Clone, PartialEq, Eq)]
59pub struct PageContext {
60 pub path: String,
62 pub method: String,
64 pub origin: String,
66}
67
68#[derive(Debug, Clone, Default)]
71pub struct ComponentState {
72 pub name: String,
74 pub parent: Option<String>,
76 pub effects: Map<String, Value>,
79 pub memo: Map<String, Value>,
81 pub provided_props: Option<Map<String, Value>>,
84 pub slot_fragments: Vec<String>,
86 pub children: Vec<Child>,
88 pub scripts: Vec<String>,
90 pub assets: Vec<String>,
92 pub islands: Map<String, Value>,
94 pub slots: Map<String, Value>,
96 pub errors: Map<String, Value>,
98 pub download: Option<Download>,
100}
101
102impl ComponentState {
103 pub fn push_effect(&mut self, name: &str, value: Value) {
105 match self.effects.get_mut(name) {
106 Some(Value::Array(values)) => values.push(value),
107 Some(existing) => {
108 let first = std::mem::replace(existing, Value::Array(Vec::new()));
109 if let Some(Value::Array(values)) = self.effects.get_mut(name) {
110 values.push(first);
111 values.push(value);
112 }
113 }
114 None => {
115 self.effects.insert(name.to_owned(), value);
116 }
117 }
118 }
119}
120
121#[derive(Debug, Default)]
123pub struct LivewireRequest {
124 components: Mutex<BTreeMap<String, ComponentState>>,
125 rendering: Mutex<Vec<String>>,
127 mounting: Mutex<Vec<String>>,
129 checksum_checked: AtomicBool,
131 styles_rendered: AtomicBool,
133 scripts_rendered: AtomicBool,
134 rendered_assets: Mutex<BTreeSet<String>>,
136 rendered_scripts: Mutex<BTreeSet<String>>,
138 response_assets: Mutex<BTreeSet<String>>,
140 streams: Mutex<Vec<Stream>>,
142 computed: Mutex<BTreeMap<String, Value>>,
144 persistent: Mutex<Map<String, Value>>,
146 http: Mutex<Option<Arc<laravel::http::Request>>>,
148 page: Mutex<Option<PageContext>>,
150}
151
152impl LivewireRequest {
153 #[must_use]
160 pub fn current() -> Option<Arc<Self>> {
161 Some(Context::current()?.local::<Self>())
162 }
163
164 fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
165 mutex.lock().unwrap_or_else(PoisonError::into_inner)
166 }
167
168 pub fn push_mounting(&self, id: &str) -> StackGuard<'_> {
170 let mut stack = Self::lock(&self.mounting);
171 let parent = stack.last().cloned();
172 stack.push(id.to_owned());
173 drop(stack);
174
175 if let Some(state) = Self::lock(&self.components).get_mut(id) {
176 state.parent = parent;
177 }
178
179 StackGuard { stack: &self.mounting }
180 }
181
182 #[must_use]
185 pub fn mounting(&self) -> Option<String> {
186 Self::lock(&self.mounting).last().cloned()
187 }
188
189 pub fn push_rendering(&self, id: &str) -> StackGuard<'_> {
191 Self::lock(&self.rendering).push(id.to_owned());
192 StackGuard { stack: &self.rendering }
193 }
194
195 #[must_use]
197 pub fn rendering(&self) -> Option<String> {
198 Self::lock(&self.rendering).last().cloned()
199 }
200
201 #[must_use]
203 pub fn render_depth(&self) -> usize {
204 Self::lock(&self.rendering).len()
205 }
206
207 pub fn register(&self, id: &str, state: ComponentState) {
209 Self::lock(&self.components).insert(id.to_owned(), state);
210 }
211
212 pub fn remember_page(&self, path: &str, method: &str, origin: &str) {
214 *Self::lock(&self.page) = Some(PageContext {
215 path: path.to_owned(),
216 method: method.to_owned(),
217 origin: origin.to_owned(),
218 });
219 }
220
221 #[must_use]
223 pub fn page(&self) -> Option<PageContext> {
224 Self::lock(&self.page).clone()
225 }
226
227 pub fn read<T>(&self, id: &str, read: impl FnOnce(&ComponentState) -> T) -> Option<T> {
229 Self::lock(&self.components).get(id).map(read)
230 }
231
232 pub fn change(&self, id: &str, change: impl FnOnce(&mut ComponentState)) {
234 let mut components = Self::lock(&self.components);
235 change(components.entry(id.to_owned()).or_default());
236 }
237
238 #[must_use]
241 pub fn has_rendered(&self) -> bool {
242 !Self::lock(&self.components).is_empty()
243 }
244
245 pub fn forget(&self, id: &str) {
247 Self::lock(&self.components).remove(id);
248 }
249
250 pub fn add_child(&self, parent: &str, child: Child) {
252 self.change(parent, |state| {
253 if let Some(existing) = state.children.iter_mut().find(|existing| existing.key == child.key) {
254 *existing = child;
255 } else {
256 state.children.push(child);
257 }
258 });
259 }
260
261 #[must_use]
263 pub fn children(&self, parent: &str) -> Vec<Child> {
264 self.read(parent, |state| state.children.clone()).unwrap_or_default()
265 }
266
267 pub fn add_asset(&self, asset: &str) -> bool {
269 Self::lock(&self.response_assets).insert(asset.to_owned())
270 }
271
272 #[must_use]
274 pub fn take_assets(&self) -> Vec<String> {
275 let mut assets = Self::lock(&self.response_assets);
276 std::mem::take(&mut *assets).into_iter().collect()
277 }
278
279 pub fn mark_styles_rendered(&self) {
282 self.styles_rendered.store(true, Ordering::Release);
283 }
284
285 #[must_use]
287 pub fn styles_rendered(&self) -> bool {
288 self.styles_rendered.load(Ordering::Acquire)
289 }
290
291 pub fn mark_scripts_rendered(&self) {
294 self.scripts_rendered.store(true, Ordering::Release);
295 }
296
297 #[must_use]
299 pub fn scripts_rendered(&self) -> bool {
300 self.scripts_rendered.load(Ordering::Acquire)
301 }
302
303 pub fn first_asset_render(&self, asset: &str) -> bool {
305 Self::lock(&self.rendered_assets).insert(asset.to_owned())
306 }
307
308 pub fn first_script_render(&self, script: &str) -> bool {
310 Self::lock(&self.rendered_scripts).insert(script.to_owned())
311 }
312
313 pub fn add_stream(&self, stream: Stream) {
315 Self::lock(&self.streams).push(stream);
316 }
317
318 #[must_use]
320 pub fn take_streams(&self) -> Vec<Stream> {
321 std::mem::take(&mut *Self::lock(&self.streams))
322 }
323
324 #[must_use]
326 pub fn is_streaming(&self) -> bool {
327 !Self::lock(&self.streams).is_empty()
328 }
329
330 #[must_use]
332 pub fn computed(&self, component: &str, name: &str) -> Option<Value> {
333 Self::lock(&self.computed).get(&format!("{component}:{name}")).cloned()
334 }
335
336 pub fn set_computed(&self, component: &str, name: &str, value: Value) {
338 Self::lock(&self.computed).insert(format!("{component}:{name}"), value);
339 }
340
341 pub fn forget_computed(&self, component: &str, name: &str) {
343 Self::lock(&self.computed).remove(&format!("{component}:{name}"));
344 }
345
346 #[must_use]
349 pub fn first_checksum_check(&self) -> bool {
350 !self.checksum_checked.swap(true, Ordering::AcqRel)
351 }
352
353 pub fn set_http_request(&self, request: Arc<laravel::http::Request>) {
355 *Self::lock(&self.http) = Some(request);
356 }
357
358 #[must_use]
360 pub fn http_request(&self) -> Option<Arc<laravel::http::Request>> {
361 Self::lock(&self.http).clone()
362 }
363
364 pub fn set_persistent(&self, key: &str, value: Value) {
366 Self::lock(&self.persistent).insert(key.to_owned(), value);
367 }
368
369 #[must_use]
371 pub fn persistent(&self, key: &str) -> Option<Value> {
372 Self::lock(&self.persistent).get(key).cloned()
373 }
374}
375
376#[derive(Debug)]
378pub struct StackGuard<'a> {
379 stack: &'a Mutex<Vec<String>>,
380}
381
382impl Drop for StackGuard<'_> {
383 fn drop(&mut self) {
384 LivewireRequest::lock(self.stack).pop();
385 }
386}
387
388#[cfg(test)]
389mod tests {
390 use super::*;
391
392 #[test]
393 fn a_render_stack_pops_even_when_a_render_fails() {
394 let request = LivewireRequest::default();
395 {
396 let _outer = request.push_rendering("a");
397 assert_eq!(request.rendering().as_deref(), Some("a"));
398 assert_eq!(request.render_depth(), 1);
399 let inner = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
400 let _inner = request.push_rendering("b");
401 assert_eq!(request.render_depth(), 2);
402 panic!("the component's view failed");
403 }));
404 assert!(inner.is_err());
405 }
406 assert_eq!(request.render_depth(), 0);
407 }
408
409 #[test]
410 fn a_mounting_component_records_its_parent() {
411 let request = LivewireRequest::default();
412 request.register("parent", ComponentState::default());
413 request.register("child", ComponentState::default());
414
415 {
416 let _parent = request.push_mounting("parent");
417 assert_eq!(request.mounting().as_deref(), Some("parent"));
418 {
419 let _child = request.push_mounting("child");
420 assert_eq!(request.mounting().as_deref(), Some("child"));
421 }
422 }
423
424 assert_eq!(request.mounting(), None);
425 assert_eq!(
426 request.read("child", |state| state.parent.clone()),
427 Some(Some("parent".to_owned()))
428 );
429 }
430
431 #[test]
432 fn child_records_replace_by_key_and_keep_order() {
433 let request = LivewireRequest::default();
434 request.register("parent", ComponentState::default());
435
436 for (key, id) in [("a", "1"), ("b", "2")] {
437 request.add_child(
438 "parent",
439 Child {
440 key: key.to_owned(),
441 tag: "div".to_owned(),
442 id: id.to_owned(),
443 },
444 );
445 }
446 request.add_child(
447 "parent",
448 Child {
449 key: "a".to_owned(),
450 tag: "div".to_owned(),
451 id: "3".to_owned(),
452 },
453 );
454
455 let children = request.children("parent");
456 assert_eq!(children.len(), 2);
457 assert_eq!(children[0].id, "3");
458 assert_eq!(children[1].id, "2");
459 }
460
461 #[test]
462 fn assets_and_scripts_render_once_per_request() {
463 let request = LivewireRequest::default();
464
465 assert!(request.first_asset_render("chart.js"));
466 assert!(!request.first_asset_render("chart.js"));
467 assert!(request.first_script_render("counter"));
468
469 assert!(request.add_asset("chart.js"));
470 assert!(!request.add_asset("chart.js"));
471 assert_eq!(request.take_assets(), ["chart.js"]);
472 assert!(request.take_assets().is_empty());
473 }
474
475 #[test]
476 fn the_checksum_allowance_is_checked_once_per_batch() {
477 let request = LivewireRequest::default();
478
479 assert!(request.first_checksum_check());
480 assert!(!request.first_checksum_check());
481 }
482
483 #[test]
484 fn effects_collect_into_lists() {
485 let mut state = ComponentState::default();
486
487 state.push_effect("dispatches", Value::from("first"));
488 state.push_effect("dispatches", Value::from("second"));
489
490 assert_eq!(state.effects["dispatches"], serde_json::json!(["first", "second"]));
491 }
492
493 #[test]
494 fn computed_values_are_keyed_by_component_and_name() {
495 let request = LivewireRequest::default();
496
497 request.set_computed("a", "total", Value::from(1));
498 request.set_computed("b", "total", Value::from(2));
499
500 assert_eq!(request.computed("a", "total"), Some(Value::from(1)));
501 assert_eq!(request.computed("b", "total"), Some(Value::from(2)));
502
503 request.forget_computed("a", "total");
504 assert_eq!(request.computed("a", "total"), None);
505 assert_eq!(request.computed("b", "total"), Some(Value::from(2)));
506 }
507}