1use std::any::TypeId;
2
3use crate::{
4 Applier, ChildList, Command, CommandQueue, Composer, DirtyBubble, EmittedNode, MutableState,
5 Node, NodeError, NodeId, OwnedMutableState, ParentAttachMode, ParentFrame, debug_scope_label,
6 join_made_children, recompose::RecomposeChildCursor, slot::NodeSlotUpdate,
7};
8
9#[expect(clippy::multiple_inherent_impl, reason = "one file per concern")]
10impl Composer {
11 fn planned_node_parent(&self, id: NodeId) -> Option<NodeId> {
12 if let Some(parent) = self.current_parent_hint().filter(|parent| *parent != id) {
13 return Some(parent);
14 }
15 let mut applier = self.borrow_applier();
16 applier.get_mut(id).ok().and_then(|node| node.parent())
17 }
18
19 fn queue_replaced_slot_node_removal(&self, old_id: NodeId, old_generation: u32) {
20 let current_generation = self.borrow_applier().node_generation(old_id);
21 if current_generation != old_generation {
22 log::trace!(
23 target: "cranpose::compose::emit",
24 "skipping stale replacement cleanup for node #{old_id} (slot_generation={old_generation} current_generation={current_generation})",
25 );
26 return;
27 }
28
29 log::trace!(
30 target: "cranpose::compose::emit",
31 "removing replaced node #{old_id} (generation={old_generation})",
32 );
33 self.commands_mut().push(Command::RemoveNode { id: old_id });
34 }
35
36 #[track_caller]
39 pub fn use_state<T: Clone + 'static>(&self, init: impl FnOnce() -> T) -> MutableState<T> {
40 let source = crate::caller_location_key();
41 let runtime = self.runtime_handle();
42 let state = self.with_slot_session_mut(|slots| {
43 slots.remember(source, || {
44 OwnedMutableState::with_runtime(init(), runtime.clone())
45 })
46 });
47 state.with(OwnedMutableState::handle)
48 }
49
50 fn trace_scope(&self) -> (usize, Option<&'static str>) {
52 self.peek_recompose_scope().map_or((0, None), |scope| {
53 (scope.id(), debug_scope_label(scope.id()))
54 })
55 }
56
57 fn emit_node_box<N: Node + 'static>(
58 &self,
59 source: crate::Key,
60 make_node: impl FnOnce(&mut dyn Applier) -> EmittedNode,
61 ) -> NodeId {
62 let adopted = {
63 let mut skip = 0;
64 loop {
65 let Some(found) = self
66 .with_slot_session_mut(|slots| slots.peek_node_record_by_source(source, skip))
67 else {
68 break None;
69 };
70 let (type_ok, gen_ok) = {
71 let mut applier = self.borrow_applier();
72 let gen_ok = applier.node_generation(found.id) == found.generation;
73 let type_ok = match applier.get_mut(found.id) {
74 Ok(node) => node.as_any_mut().downcast_ref::<N>().is_some(),
75 Err(_) => false,
76 };
77 (type_ok, gen_ok)
78 };
79 if type_ok && gen_ok {
80 break Some(found);
81 }
82 skip += 1;
83 }
84 };
85
86 let Some(found) = adopted else {
87 return self.emit_new_node::<N>(source, make_node);
88 };
89 let id = found.id;
90 if log::log_enabled!(target: "cranpose::compose::emit", log::Level::Trace) {
91 self.trace_reused_node::<N>(id);
92 }
93 self.attach_to_parent(id);
94 let parent_id = self.planned_node_parent(id);
95 let recorded =
96 self.with_slot_session_mut(|slots| slots.adopt_node_record(found, parent_id, source));
97 match recorded {
98 NodeSlotUpdate::Reused {
99 id: recorded_id,
100 generation,
101 } => {
102 debug_assert_eq!(recorded_id, id);
103 debug_assert_eq!(generation, found.generation);
104 }
105 NodeSlotUpdate::Inserted { .. } => {
106 log::warn!(
107 target: "cranpose::compose::emit",
108 "slot writer inserted node #{id} while reusing the same node identity",
109 );
110 }
111 NodeSlotUpdate::Replaced {
112 old_id,
113 old_generation,
114 ..
115 } => {
116 log::warn!(
117 target: "cranpose::compose::emit",
118 "slot writer replaced node #{old_id} while reusing node #{id}",
119 );
120 self.queue_replaced_slot_node_removal(old_id, old_generation);
121 }
122 }
123 id
124 }
125
126 #[cold]
127 #[inline(never)]
128 fn trace_reused_node<N: Node + 'static>(&self, id: NodeId) {
129 let (scope_id, scope_label) = self.trace_scope();
130 log::trace!(
131 target: "cranpose::compose::emit",
132 "reusing node #{id} as {} [scope_id={scope_id} scope_label={scope_label:?}]",
133 std::any::type_name::<N>(),
134 );
135 }
136
137 #[inline(never)]
141 fn emit_new_node<N: Node + 'static>(
142 &self,
143 source: crate::Key,
144 make_node: impl FnOnce(&mut dyn Applier) -> EmittedNode,
145 ) -> NodeId {
146 let (id, generation) = {
147 let mut applier = self.borrow_applier();
148 let emitted = make_node(&mut *applier);
149 let id = match emitted {
150 EmittedNode::Fresh(node) => applier.create(node),
151 EmittedNode::Recycled(recycled) => {
152 let (stable_id, node, origin) = recycled.into_parts();
153 let insertion = applier.insert_recycled_node_or_create(stable_id, node);
154 if let Some(error) = insertion.fallback_error.as_ref() {
155 log::warn!(
156 target: "cranpose::compose::emit",
157 "discarding stale recycled stable id #{stable_id}: {error}",
158 );
159 }
160 applier.set_recycled_node_origin(insertion.id, origin);
161 insertion.id
162 }
163 };
164 let generation = applier.node_generation(id);
165 (id, generation)
166 };
167 if log::log_enabled!(target: "cranpose::compose::emit", log::Level::Trace) {
168 let (scope_id, scope_label) = self.trace_scope();
169 log::trace!(
170 target: "cranpose::compose::emit",
171 "creating node #{} (gen={}) as {} [scope_id={} scope_label={:?}]",
172 id,
173 generation,
174 std::any::type_name::<N>(),
175 scope_id,
176 scope_label,
177 );
178 }
179 self.mount_made_node(id);
180 let parent_id = self.planned_node_parent(id);
181 let recorded = self.with_slot_session_mut(|slots| {
182 slots.record_node_with_parent(id, generation, parent_id, source)
183 });
184 match recorded {
185 NodeSlotUpdate::Inserted {
186 id: recorded_id,
187 generation: recorded_generation,
188 } => {
189 debug_assert_eq!(recorded_id, id);
190 debug_assert_eq!(recorded_generation, generation);
191 }
192 NodeSlotUpdate::Replaced {
193 old_id,
194 old_generation,
195 new_id,
196 new_generation,
197 } => {
198 debug_assert_eq!(new_id, id);
199 debug_assert_eq!(new_generation, generation);
200 self.queue_replaced_slot_node_removal(old_id, old_generation);
201 }
202 NodeSlotUpdate::Reused { .. } => {
203 log::warn!(
204 target: "cranpose::compose::emit",
205 "slot writer reported reuse for newly emitted node #{id}",
206 );
207 }
208 }
209 id
210 }
211
212 fn mount_made_node(&self, id: NodeId) {
216 let made_parent = {
217 let mut parent_stack = self.parent_stack();
218 parent_stack
219 .last_mut()
220 .filter(|frame| frame.id != id)
221 .and_then(|frame| {
222 frame.last_made = Some(id);
223 (frame.attach_mode == ParentAttachMode::Made).then(|| {
224 frame.new_children.push(id);
225 frame.id
226 })
227 })
228 };
229 if made_parent.is_none() {
230 self.attach_to_parent(id);
231 }
232 let mut applier = self.borrow_applier();
233 let Ok(node) = applier.get_mut(id) else {
234 return;
235 };
236 match made_parent {
237 Some(parent) => node.mount_under(parent, id),
238 None => {
239 node.set_node_id(id);
240 node.mount();
241 }
242 }
243 }
244
245 #[track_caller]
249 pub fn emit_node<N: Node + 'static>(&self, init: impl FnOnce() -> N) -> NodeId {
250 let source = crate::caller_location_key();
251 self.emit_node_box::<N>(source, |_| EmittedNode::Fresh(Box::new(init())))
252 }
253
254 #[track_caller]
257 pub fn emit_recyclable_node<N: Node + 'static>(
258 &self,
259 init: impl FnOnce() -> N,
260 reset: impl FnOnce(&mut N),
261 ) -> NodeId {
262 let source = crate::caller_location_key();
263 self.emit_node_box::<N>(source, |applier| {
264 let key = TypeId::of::<N>();
265 if let Some(mut recycled) = applier.take_recycled_node(key) {
266 if let Some(typed) = recycled.node_mut().as_any_mut().downcast_mut::<N>() {
267 reset(typed);
268 return EmittedNode::Recycled(recycled);
269 }
270 log::warn!(
271 target: "cranpose::compose::emit",
272 "discarding recycled node shell with mismatched type for {}",
273 std::any::type_name::<N>(),
274 );
275 }
276
277 let node = Box::new(init());
278 applier.record_fresh_recyclable_creation(key);
279 if let Some(shell) = node.rehouse_for_recycle() {
280 applier.seed_recycled_node_shell(key, node.recycle_pool_limit(), shell);
281 }
282 EmittedNode::Fresh(node)
283 })
284 }
285
286 fn skip_recompose_child(&self) {
287 let cursor = match self.core.recompose_child_cursor.get() {
288 RecomposeChildCursor::After { first, placed } => RecomposeChildCursor::After {
289 first,
290 placed: placed + 1,
291 },
292 RecomposeChildCursor::At(index) => RecomposeChildCursor::At(index + 1),
293 RecomposeChildCursor::Unknown => return,
294 };
295 self.core.recompose_child_cursor.set(cursor);
296 }
297
298 fn next_recompose_insert_index(&self) -> Option<usize> {
299 let RecomposeChildCursor::At(index) = self.resolve_recompose_child_cursor() else {
300 return None;
301 };
302 self.core
303 .recompose_child_cursor
304 .set(RecomposeChildCursor::At(index + 1));
305 Some(index)
306 }
307
308 pub(crate) fn attach_to_parent(&self, id: NodeId) {
309 if self.attach_to_current_parent(id) {
310 return;
311 }
312 self.attach_without_parent_frame(id);
313 }
314
315 fn attach_to_current_parent(&self, id: NodeId) -> bool {
316 let mut parent_stack = self.parent_stack();
317 if let Some(parent_id) = parent_stack.last().map(|frame| frame.id) {
318 let stale_root_parent = self.core.root.get() == Some(parent_id) && {
319 let mut applier = self.borrow_applier();
320 applier.get_mut(parent_id).is_err()
321 };
322 if stale_root_parent {
323 parent_stack.pop();
324 self.set_root(None);
325 } else {
326 let Some(frame) = parent_stack.last_mut() else {
327 return false;
328 };
329 if parent_id == id {
330 return true;
331 }
332 if frame.attach_mode == ParentAttachMode::Made {
335 frame.attach_mode = ParentAttachMode::DeferredSync;
336 }
337 let attach_mode = frame.attach_mode;
338 let attached_before = frame.previous.get(frame.new_children.len()) == Some(&id);
341 if matches!(attach_mode, ParentAttachMode::DeferredSync) {
342 frame.new_children.push(id);
343 }
344 drop(parent_stack);
345
346 if attached_before {
347 debug_assert!(
348 self.borrow_applier()
349 .get_mut(id)
350 .map_or(true, |node| node.parent().is_none_or(|p| p == parent_id)),
351 "a parent's previous child must name no other parent"
352 );
353 } else {
354 let mut applier = self.borrow_applier();
355 if let Ok(child_node) = applier.get_mut(id) {
356 child_node.set_parent_for_bubbling(parent_id);
357 }
358 }
359 if matches!(attach_mode, ParentAttachMode::ImmediateAppend) {
360 self.commands_mut().push(Command::AttachChild {
361 parent_id,
362 child_id: id,
363 insert_index: None,
364 bubble: DirtyBubble::LAYOUT_AND_MEASURE,
365 });
366 }
367 return true;
368 }
369 }
370 false
371 }
372
373 fn attach_without_parent_frame(&self, id: NodeId) {
374 let in_subcompose = !self.subcompose_stack().is_empty();
375 if in_subcompose {
376 let has_parent = {
377 let mut applier = self.borrow_applier();
378 applier
379 .get_mut(id)
380 .is_ok_and(|node| node.parent().is_some())
381 };
382
383 if !has_parent {
384 let mut subcompose_stack = self.subcompose_stack();
385 if let Some(frame) = subcompose_stack.last_mut() {
386 frame.nodes.push(id);
387 }
388 }
389 return;
390 }
391
392 if let Some(parent_hint) = self.core.recompose_parent_hint.get() {
393 if parent_hint == id {
394 debug_assert_ne!(
395 parent_hint, id,
396 "a node cannot be attached as its own parent"
397 );
398 return;
399 }
400 let parent_status = {
401 let mut applier = self.borrow_applier();
402 applier.get_mut(id).map_or(None, |node| node.parent())
403 };
404 match parent_status {
405 Some(existing) if existing == parent_hint => {
406 self.skip_recompose_child();
407 }
408 None => {
409 let insert_index = self.next_recompose_insert_index();
410 self.commands_mut().push(Command::AttachChild {
411 parent_id: parent_hint,
412 child_id: id,
413 insert_index,
414 bubble: DirtyBubble::LAYOUT_AND_MEASURE,
415 });
416 }
417 Some(_) => {}
418 }
419 return;
420 }
421
422 let has_parent = {
423 let mut applier = self.borrow_applier();
424 applier
425 .get_mut(id)
426 .is_ok_and(|node| node.parent().is_some())
427 };
428 if has_parent {
429 return;
430 }
431
432 self.set_root(Some(id));
433 }
434
435 pub fn with_node_mut<N: Node + 'static, R>(
438 &self,
439 id: NodeId,
440 f: impl FnOnce(&mut N) -> R,
441 ) -> Result<R, NodeError> {
442 let mut applier = self.borrow_applier();
443 let node = applier.get_mut(id)?;
444 let typed =
445 node.as_any_mut()
446 .downcast_mut::<N>()
447 .ok_or_else(|| NodeError::TypeMismatch {
448 id,
449 expected: std::any::type_name::<N>(),
450 })?;
451 Ok(f(typed))
452 }
453
454 pub fn push_parent(&self, id: NodeId) {
457 let made = self
458 .parent_stack()
459 .last_mut()
460 .is_some_and(|frame| frame.last_made.take() == Some(id));
461 if made {
462 self.parent_stack().push(ParentFrame {
463 id,
464 previous: ChildList::new(),
465 new_children: ChildList::new(),
466 attach_mode: ParentAttachMode::Made,
467 synthetic_root: false,
468 last_made: None,
469 });
470 return;
471 }
472 let in_subcompose = !self.core.subcompose_stack.borrow().is_empty();
473
474 let children = self.get_node_children(id);
475 let previous = if children.is_empty() {
476 ChildList::new()
477 } else {
478 ChildList::from_slice(&children)
479 };
480 let attach_mode = if in_subcompose || !previous.is_empty() {
481 ParentAttachMode::DeferredSync
482 } else {
483 ParentAttachMode::ImmediateAppend
484 };
485
486 self.parent_stack().push(ParentFrame {
487 id,
488 previous,
489 new_children: ChildList::new(),
490 attach_mode,
491 synthetic_root: false,
492 last_made: None,
493 });
494 }
495
496 pub fn compose_no_children(&self, id: NodeId, holds_children: bool) {
502 if holds_children || !self.core.subcompose_stack.borrow().is_empty() {
503 self.push_parent(id);
504 self.pop_parent();
505 }
506 }
507
508 pub fn pop_parent(&self) {
511 let frame_opt = {
512 let mut stack = self.parent_stack();
513 stack.pop()
514 };
515 if let Some(frame) = frame_opt {
516 let ParentFrame {
517 id,
518 previous,
519 new_children,
520 attach_mode,
521 synthetic_root: _synthetic_root,
522 last_made: _,
523 } = frame;
524
525 log::trace!(target: "cranpose::compose::parent", "pop_parent: node #{id}");
526 log::trace!(
527 target: "cranpose::compose::parent",
528 "previous children: {previous:?}"
529 );
530 log::trace!(
531 target: "cranpose::compose::parent",
532 "new children: {new_children:?}"
533 );
534 match attach_mode {
535 ParentAttachMode::Made => {
536 join_made_children(&mut *self.borrow_applier(), id, &new_children);
537 }
538 ParentAttachMode::DeferredSync => {
539 let kept = !previous.is_empty() && new_children == previous;
544 let expected_children = (!kept).then_some(new_children);
545 self.commands_mut().push(Command::SyncChildren {
546 parent_id: id,
547 expected_children,
548 });
549 }
550 ParentAttachMode::ImmediateAppend => {}
551 }
552 }
553 }
554
555 pub(crate) fn take_commands(&self) -> CommandQueue {
556 std::mem::take(&mut *self.commands_mut())
557 }
558
559 pub(crate) fn with_commands<R>(&self, f: impl FnOnce(&mut CommandQueue) -> R) -> R {
562 f(&mut self.commands_mut())
563 }
564
565 pub fn apply_pending_commands(&self) -> Result<(), NodeError> {
570 self.resolve_recompose_child_cursor();
571 let mut commands = self.take_commands();
572 let runtime_handle = self.runtime_handle();
573 let result = {
574 let mut applier = self.borrow_applier();
575 let mut result = commands.apply(&mut *applier);
576 if result.is_ok() {
577 for update in runtime_handle.take_updates() {
578 if let Err(err) = update.apply(&mut *applier) {
579 result = Err(err);
580 break;
581 }
582 }
583 }
584 result
585 };
586 let mut queued = self.commands_mut();
588 if queued.len() == 0 {
589 std::mem::swap(&mut *queued, &mut commands);
590 }
591 drop(queued);
592 if result.is_err() {
593 let host = self.active_slots_host();
594 if !host.has_active_pass() {
595 host.abandon_after_apply_failure();
596 }
597 }
598 result
599 }
600
601 pub fn register_side_effect(&self, effect: impl FnOnce() + 'static) {
603 self.queue_side_effect(Box::new(effect));
604 }
605
606 pub fn take_side_effects(&self) -> Vec<Box<dyn FnOnce()>> {
608 std::mem::take(&mut *self.side_effects_mut())
609 }
610
611 pub(crate) fn root(&self) -> Option<NodeId> {
612 self.core.root.get()
613 }
614
615 pub(crate) fn set_root(&self, node: Option<NodeId>) {
616 self.core.root.set(node);
617 }
618}