1use std::{any::Any, cell::RefCell, rc::Rc, sync::Arc};
15
16use rustc_hash::{FxHashMap, FxHashSet};
17
18use super::{Core, Key, Kind, NO_KEY, views::Anchor};
19use crate::{
20 ApplyError, Command, EdgeInsets, EventKind, EventMask, EventPayload, NodeId, Op, Prop, ROOT_ID,
21 Tag, TextEngine,
22 element::{
23 Action, AnswerSlot, AnyInstance, AnyValue, Attrs, Child, ClipboardRead, ComponentError,
24 ComponentSpec, ElKind, ElNode, Environment, Executor, FileAnswer, ImageSize, IntoElement,
25 JsEvent, JsResult, ListConfig, Listener, ModuleCx, ParentElement, PlaceFn, Position, Posts,
26 Reactive, Registry, Root, RustCall, RustOp, SharedString, StyleRefinement, Task, Tokens,
27 caught,
28 responder::ResponderEl,
29 services::FetchFailure,
30 view,
31 virtual_list::{self, RowFn, SeparatorFn, VirtualListEl},
32 },
33 geometry::Points,
34 list_diff::ListDiff,
35 tailwind::ClassList,
36};
37
38const STYLE_CACHE: usize = 4096;
41
42const MAX_TASK_ROUNDS: u32 = 64;
44
45struct ByName {
47 id: std::any::TypeId,
48 props: Box<dyn crate::element::builder::AnyProps>,
49 owner: crate::element::Owner,
51}
52
53thread_local! {
54 static PART_REQUESTER: std::cell::Cell<Option<fn(&str)>> = const { std::cell::Cell::new(None) };
57}
58
59#[doc(hidden)]
65pub fn set_part_requester(request: fn(&str)) {
66 PART_REQUESTER.with(|r| r.set(Some(request)));
67}
68
69enum Inner {
71 Missing,
73 Component(Box<dyn AnyInstance>),
74 Row {
77 place: PlaceFn,
78 index: usize,
79 },
80 VirtualRow {
83 list: NodeId,
84 index: usize,
85 },
86}
87
88type Rows = (u32, Option<Rc<[u64]>>);
90
91type CellRows = Rc<RefCell<CellRowMap>>;
94
95type CellRowMap = FxHashMap<NodeId, (crate::element::Signal<usize>, crate::element::Owner)>;
97
98struct VirtualListState {
100 owner: NodeId,
102 scope: Rc<std::cell::Cell<Option<crate::element::Owner>>>,
107 row: RowFn,
108 count: u32,
109 keys: Option<Rc<[u64]>>,
110 separator: Option<SeparatorFn>,
111 cells: Vec<NodeId>,
113 rows: CellRows,
116 moves: Option<crate::element::reactive::Node>,
119 items: bool,
126 place: Option<PlaceFn>,
127 contents: Vec<NodeId>,
128 min_view: Option<std::time::Duration>,
131 reported: Option<(u32, u32)>,
132 latest: Option<(u32, u32)>,
133 report: Option<Task<()>>,
134}
135
136#[derive(Debug, Clone, Copy, PartialEq)]
138pub(super) enum Placement {
139 None,
141 At(NodeId, Anchor),
144 Each,
147 Nested(NodeId, Anchor),
151}
152
153#[derive(Default)]
160pub(super) struct Handlers {
161 by_node: FxHashMap<NodeId, Vec<(EventKind, Listener<EventPayload>)>>,
162}
163
164impl Handlers {
165 pub(super) fn of(&self, node: NodeId) -> &[(EventKind, Listener<EventPayload>)] {
167 self.by_node.get(&node).map_or(&[], Vec::as_slice)
168 }
169
170 pub(super) fn push(&mut self, node: NodeId, kind: EventKind, listener: Listener<EventPayload>) {
172 self.by_node.entry(node).or_default().push((kind, listener));
173 }
174
175 pub(super) fn remove(&mut self, node: NodeId) {
177 self.by_node.remove(&node);
178 }
179
180 pub(super) fn retain_nodes(&mut self, mut keep: impl FnMut(&NodeId) -> bool) {
182 self.by_node.retain(|node, _| keep(node));
183 }
184
185 pub(super) fn rename(&mut self, old: NodeId, new: NodeId) {
188 if old == new {
189 return;
190 }
191 if let Some(moved) = self.by_node.remove(&old) {
192 self.by_node.entry(new).or_default().extend(moved);
193 }
194 }
195
196 pub(super) fn clear(&mut self) {
197 self.by_node.clear();
198 }
199
200 #[cfg(test)]
202 pub(super) fn len(&self) -> usize {
203 self.by_node.values().map(Vec::len).sum()
204 }
205}
206
207pub(super) struct Instance {
209 inner: Inner,
210 spec: Option<Arc<ComponentSpec>>,
211 pub(super) class: Box<str>,
213 pub(super) class_list: Vec<Box<str>>,
214 pub(super) user: Option<std::rc::Rc<ClassList>>,
217 js_events: EventMask,
219 given_handlers: Vec<(EventKind, Listener<EventPayload>)>,
223 given_events: EventMask,
225 root: Option<Expanded>,
228 pub(super) js_children: Vec<NodeId>,
230 js_texts: FxHashSet<NodeId>,
233 pub(super) children_at: Placement,
234 children_wanted: bool,
236 slots: Vec<(&'static str, NodeId)>,
238 pub(super) handlers: Handlers,
240 pub(super) event_handlers: Vec<(NodeId, Listener<dyn Any>)>,
243 pub(super) responders: Vec<(NodeId, Rc<ResponderEl>)>,
245 pub(super) app_style: Option<crate::StylePatch>,
248 dirty: bool,
249 remake: bool,
252 pub(super) bound: FxHashMap<NodeId, Box<super::views::BoundNode>>,
256 pub(super) js_kids: Option<crate::element::Signal<Vec<(NodeId, bool)>>>,
259 cell_owner: Option<crate::element::Owner>,
261 row_index: Option<crate::element::Signal<usize>>,
264 lazy_wanted: Option<crate::element::Signal<bool>>,
267 children_owner: Option<crate::element::Owner>,
270 joined: bool,
277 rooted: Option<NodeId>,
280 pub(super) above: Option<NodeId>,
282 pub(super) fills: Vec<Fill>,
284 pub(super) given: Option<Box<Attrs>>,
288 given_changed: bool,
290 pub(super) root_insets_applied: (Option<crate::EdgeInsets>, Option<crate::EdgeInsets>),
292 pub(super) root_host_applied: Vec<Prop>,
295 pub(super) js_host: Vec<Prop>,
299}
300
301pub(super) fn js_host_attribute(prop: &Prop) -> bool {
306 use crate::AccessibilityProp as A;
307 match prop {
308 Prop::TestId(_) | Prop::Tooltip(_) | Prop::Focusable(_) => true,
309 Prop::Accessibility(a) => !matches!(a, A::Role(_) | A::State(_) | A::Orientation(_)),
310 _ => false,
311 }
312}
313
314pub(super) fn given_host(given: &Attrs, host: &mut Vec<Prop>) {
321 use crate::AccessibilityProp as A;
322 for prop in &given.props {
323 if matches!(
324 prop,
325 Prop::TestId(Some(_))
326 | Prop::Tooltip(_)
327 | Prop::Focusable(_)
328 | Prop::Accessibility(
329 A::Actions(_) | A::ActiveDescendant(Some(_)) | A::Controls(Some(_))
330 )
331 ) {
332 give_host(host, prop.clone());
333 }
334 }
335 if let Some(label) = &given.label {
336 give_host(host, Prop::Accessibility(A::Label(Some(label.to_arc()))));
337 }
338 if let Some(rare) = &given.rare {
339 if let Some(description) = &rare.description {
340 give_host(
341 host,
342 Prop::Accessibility(A::Description(Some(description.to_arc()))),
343 );
344 }
345 if let Some(value) = &rare.value {
346 give_host(host, Prop::Accessibility(A::Value(Some(value.clone()))));
347 }
348 }
349}
350
351fn give_host(props: &mut Vec<Prop>, prop: Prop) {
355 use crate::AccessibilityProp as A;
356 let Prop::Accessibility(A::Actions(given)) = prop else {
357 return crate::element::host::set_in(props, prop);
358 };
359 let own = props.iter_mut().find_map(|p| match p {
360 Prop::Accessibility(A::Actions(own)) => Some(own),
361 _ => None,
362 });
363 let Some(own) = own else {
364 return props.push(Prop::Accessibility(A::Actions(given)));
365 };
366 for action in given {
367 match own.iter_mut().find(|a| a.name == action.name) {
368 Some(same) => *same = action,
369 None => own.push(action),
370 }
371 }
372}
373
374pub(super) fn with_host(mut attrs: Attrs, host: &[Prop]) -> Attrs {
377 use crate::AccessibilityProp as A;
378 for prop in host {
379 match prop {
380 Prop::Accessibility(A::Label(label)) => {
381 attrs.label = label.clone().map(SharedString::from);
382 }
383 Prop::Accessibility(A::Description(description)) => {
384 attrs.rare_mut().description = description.clone().map(SharedString::from);
385 }
386 Prop::Accessibility(A::Value(value)) => attrs.rare_mut().value = value.clone(),
387 Prop::Accessibility(A::Hint(hint)) => {
388 attrs.rare_mut().hint = hint.clone().map(SharedString::from);
389 }
390 Prop::Accessibility(A::Accessible(accessible)) => {
391 attrs.rare_mut().accessible = *accessible;
392 }
393 prop => give_host(&mut attrs.props, prop.clone()),
394 }
395 }
396 attrs
397}
398
399pub(super) struct RootContext {
402 pub(super) user: Option<std::rc::Rc<ClassList>>,
404 pub(super) combined: bool,
407 pub(super) app: Option<crate::StylePatch>,
410 pub(super) js: Option<EventMask>,
412 pub(super) given_events: EventMask,
415 inset_padding: Option<crate::EdgeInsets>,
417 inset_margin: Option<crate::EdgeInsets>,
418 pub(super) host: Vec<Prop>,
421 given: bool,
423}
424
425impl RootContext {
426 pub(super) fn over(&self, mut attrs: Attrs) -> Attrs {
428 if let Some(insets) = self.inset_padding {
429 attrs.rare_mut().inset_padding = Some(insets);
430 }
431 if let Some(insets) = self.inset_margin {
432 attrs.rare_mut().inset_margin = Some(insets);
433 }
434 with_host(attrs, &self.host)
435 }
436}
437
438pub(super) struct Fill {
444 pub(super) name: &'static str,
445 parts: Vec<FillPart>,
448 from: NodeId,
450 pub(super) at: Placement,
452 forwarded: Option<(NodeId, &'static str)>,
455}
456
457#[derive(Debug, Clone, Copy, PartialEq)]
459pub(super) enum FillPart {
460 Node(NodeId),
461 Region(u32),
462 Filled(&'static str),
464}
465
466impl Instance {
467 fn new(
468 inner: Inner,
469 spec: Option<Arc<ComponentSpec>>,
470 js_children: Vec<NodeId>,
471 app_style: Option<crate::StylePatch>,
472 ) -> Self {
473 Self {
474 inner,
475 spec,
476 class: "".into(),
477 class_list: Vec::new(),
478 user: None,
479 js_events: EventMask::default(),
480 given_handlers: Vec::new(),
481 given_events: EventMask::default(),
482 root: None,
483 js_children,
484 js_texts: FxHashSet::default(),
485 children_at: Placement::None,
486 children_wanted: false,
487 slots: Vec::new(),
488 handlers: Handlers::default(),
489 event_handlers: Vec::new(),
490 responders: Vec::new(),
491 app_style,
492 dirty: false,
493 remake: false,
494 bound: FxHashMap::default(),
495 js_kids: None,
496 cell_owner: None,
497 row_index: None,
498 lazy_wanted: None,
499 children_owner: None,
500 joined: false,
501 rooted: None,
502 above: None,
503 fills: Vec::new(),
504 given: None,
505 given_changed: false,
506 root_insets_applied: (None, None),
507 root_host_applied: Vec::new(),
508 js_host: Vec::new(),
509 }
510 }
511
512 fn js_children_changed(&self) {
514 if let Some(children) = self.js_kids {
515 children.try_set(self.js_kids());
522 }
523 }
524
525 fn js_kids(&self) -> Vec<(NodeId, bool)> {
527 self.js_children
528 .iter()
529 .map(|&c| (c, self.js_texts.contains(&c)))
530 .collect()
531 }
532
533 fn forget_js_child(&mut self, child: NodeId) {
535 self.js_children.retain(|&c| c != child);
536 self.js_texts.remove(&child);
537 }
538}
539
540#[derive(Debug, Clone, Copy, PartialEq, Eq)]
541pub(super) enum Part {
542 Node,
543 Slot,
545 Children,
547 Component(&'static str),
549 VirtualList,
551 JsChild,
553 Raw,
555 Region(u32),
558 Fill(&'static str),
561 Filled(&'static str),
563 Tooltip,
566}
567
568pub(super) type AppClass = (
571 Option<std::rc::Rc<ClassList>>,
572 SharedString,
573 Option<std::rc::Rc<ClassList>>,
574);
575
576pub(super) type Classes = (
578 Option<std::rc::Rc<ClassList>>,
579 Option<std::rc::Rc<ClassList>>,
580);
581
582pub(super) struct Expanded {
584 pub(super) id: NodeId,
585 pub(super) tag: Tag,
586 pub(super) key: Option<SharedString>,
587 text: Option<(SharedString, NodeId)>,
589 attrs: Attrs,
590 style: StyleRefinement,
591 classes: Classes,
592 events: EventMask,
593 list: Option<Box<ListConfig>>,
595 pub(super) part: Part,
596 pub(super) children: Vec<Expanded>,
597}
598
599impl Expanded {
600 pub(super) fn js(id: NodeId, part: Part) -> Self {
602 Self {
603 id,
604 tag: Tag::View,
605 key: None,
606 text: None,
607 attrs: Attrs::default(),
608 style: StyleRefinement::default(),
609 classes: (None, None),
610 events: EventMask::default(),
611 list: None,
612 part,
613 children: Vec::new(),
614 }
615 }
616}
617
618#[allow(
621 clippy::large_enum_variant,
622 reason = "elements are matched as they come: a box for each would allocate for every child"
623)]
624pub(super) enum NewChild {
625 Made(Option<crate::element::Owner>, ElNode),
627 Kept(SharedString),
630}
631
632#[derive(Default)]
638pub(super) struct OldKeys {
639 first: FxHashMap<SharedString, usize>,
641 next: Vec<usize>,
644 indexed: bool,
645}
646
647impl OldKeys {
648 const SEARCHED: usize = 16;
650
651 fn find(
653 &mut self,
654 old: &[Option<Expanded>],
655 key: &SharedString,
656 ok: impl Fn(&Expanded) -> bool,
657 ) -> Option<usize> {
658 let is = |o: &Option<Expanded>| {
659 o.as_ref()
660 .is_some_and(|o| o.key.as_ref() == Some(key) && ok(o))
661 };
662 if old.len() <= Self::SEARCHED {
663 return old.iter().position(is);
664 }
665 if !self.indexed {
666 self.indexed = true;
667 self.next = vec![usize::MAX; old.len()];
668 for (at, o) in old.iter().enumerate().rev() {
670 if let Some(k) = o.as_ref().and_then(|o| o.key.as_ref())
671 && let Some(next) = self.first.insert(k.clone(), at)
672 {
673 self.next[at] = next;
674 }
675 }
676 }
677 let first = self.first.get_mut(key)?;
680 while *first != usize::MAX && old[*first].is_none() {
681 *first = self.next[*first];
682 }
683 let mut at = *first;
684 while at != usize::MAX {
685 if is(&old[at]) {
686 return Some(at);
687 }
688 at = self.next[at];
689 }
690 None
691 }
692}
693
694fn is_plain(el: &ElNode) -> bool {
697 el.attrs == Attrs::default()
698 && el.style.is_empty()
699 && !el.is_bound()
700 && el.handlers.is_empty()
701 && el.responder.is_none()
702 && el.children.is_empty()
703 && el.text.is_none()
704}
705
706enum Awaited {
708 End(AnswerSlot<bool>),
710 Value(AnswerSlot<f32>),
712}
713
714#[derive(Default)]
717pub(super) struct ClipboardAnswer {
718 pub(super) has: bool,
720 pub(super) text: Option<String>,
722 pub(super) denied: bool,
725 pub(super) image: Option<crate::element::ClipboardImage>,
727 pub(super) too_large: Option<usize>,
731 pub(super) files: Vec<String>,
733}
734
735impl ClipboardAnswer {
736 pub(super) fn from_payload(payload: &EventPayload) -> ClipboardAnswer {
737 let mut answer = ClipboardAnswer::default();
738 let EventPayload::Map(entries) = payload else {
739 return answer;
740 };
741 let (mut uri, mut width, mut height) = (None, 0.0, 0.0);
742 for (k, v) in entries {
743 match (*k, v) {
744 ("has", crate::PayloadValue::Bool(b)) => answer.has = *b,
745 ("text", crate::PayloadValue::Str(t)) => answer.text = Some(t.clone()),
746 ("denied", crate::PayloadValue::Bool(b)) => answer.denied = *b,
747 ("uri", crate::PayloadValue::Str(u)) => uri = Some(u.clone()),
748 ("width", crate::PayloadValue::Number(n)) => width = *n,
749 ("height", crate::PayloadValue::Number(n)) => height = *n,
750 ("tooLarge", crate::PayloadValue::Number(n)) => {
751 answer.too_large = Some(*n as usize)
752 }
753 ("files", crate::PayloadValue::Str(f)) => {
754 answer.files = f
755 .lines()
756 .filter(|l| !l.is_empty())
757 .map(str::to_owned)
758 .collect()
759 }
760 _ => {}
761 }
762 }
763 let uri = uri.filter(|u| u.starts_with("data:"));
766 let bytes = uri.as_deref().map(crate::platform::clipboard::data_uri_len);
767 if let Some(bytes) = bytes.filter(|&b| b > crate::platform::clipboard::MAX_IMAGE_BYTES) {
768 answer.too_large = Some(bytes);
769 } else {
770 answer.image = uri.map(|url| crate::element::ClipboardImage {
771 url,
772 size: crate::geometry::Size::new(pixels(width), pixels(height)),
773 });
774 }
775 answer
776 }
777}
778
779struct PendingFetch {
781 response: crate::element::HttpResponse,
783 answer: AnswerSlot<Result<crate::element::HttpResponse, FetchFailure>>,
784}
785
786#[derive(Default)]
788struct Notifications {
789 next: u32,
791 permissions: FxHashMap<u32, AnswerSlot<crate::notifications::NotificationPermission>>,
793 shows: FxHashMap<u32, AnswerSlot<bool>>,
795 listening: bool,
797 presses: std::collections::VecDeque<String>,
799 next_press: Option<AnswerSlot<String>>,
801}
802
803#[derive(Default)]
805struct UrlScheme {
806 links: crate::url_scheme::AppLinks,
808 recent: std::collections::VecDeque<(u64, String)>,
812 next_number: u64,
814 unheard: u64,
817 listeners: Vec<(u64, u64)>,
821 next: Vec<(Option<u64>, AnswerSlot<String>)>,
824 next_of_scheme: Vec<(String, AnswerSlot<String>)>,
828 changes: std::collections::VecDeque<crate::url_scheme::AppUrlChange>,
832 next_change: Option<AnswerSlot<crate::url_scheme::AppUrlChange>>,
834 hears_changes: bool,
837 address: crate::url_scheme::AppUrlCell,
841}
842
843impl UrlScheme {
844 fn open(&mut self, url: String, alive: impl Fn(u64) -> bool) {
848 let number = self.next_number;
849 self.next_number += 1;
850 self.listeners.retain(|&(task, _)| alive(task));
851 if self.recent.len() == crate::url_scheme::MAX_PENDING
852 && let Some((dropped, _)) = self.recent.pop_front()
853 && dropped >= self.unheard
854 {
855 log::warn!(
856 "link dropped: {} came while nothing listened",
857 crate::url_scheme::MAX_PENDING
858 );
859 self.unheard = dropped + 1;
860 }
861 self.recent.push_back((number, url.clone()));
862 self.next
865 .retain(|(_, answer)| crate::element::task::awaited(answer));
866 if !self.next.is_empty() || !self.listeners.is_empty() {
870 self.unheard = number + 1;
871 }
872 if !self.next.is_empty() {
873 for (task, answer) in std::mem::take(&mut self.next) {
874 if let Some(task) = task {
875 self.heard(task, number);
876 }
877 answer.borrow_mut().deliver(url.clone());
878 }
879 }
880 self.trim();
881 }
882
883 fn listen(
887 &mut self,
888 task: Option<u64>,
889 answer: AnswerSlot<String>,
890 alive: impl Fn(u64) -> bool,
891 ) {
892 self.listeners.retain(|&(task, _)| alive(task));
893 let known = task.and_then(|task| {
894 self.listeners
895 .iter()
896 .find(|&&(listener, _)| listener == task)
897 .map(|&(_, next)| next)
898 });
899 let from = known.unwrap_or(self.unheard);
900 if let Some((number, url)) = self.recent.iter().find(|(n, _)| *n >= from).cloned() {
901 self.unheard = self.unheard.max(number + 1);
902 if let Some(task) = task {
903 self.heard(task, number);
904 }
905 answer.borrow_mut().deliver(url);
906 } else {
907 if let Some(task) = task
908 && known.is_none()
909 {
910 self.listeners.push((task, self.next_number));
911 }
912 self.next
913 .retain(|(_, answer)| crate::element::task::awaited(answer));
914 self.next.push((task, answer));
915 }
916 self.trim();
917 }
918
919 fn heard(&mut self, task: u64, number: u64) {
921 match self
922 .listeners
923 .iter_mut()
924 .find(|(listener, _)| *listener == task)
925 {
926 Some((_, next)) => *next = number + 1,
927 None => self.listeners.push((task, number + 1)),
928 }
929 }
930
931 fn trim(&mut self) {
933 let keep = self
934 .listeners
935 .iter()
936 .map(|&(_, next)| next)
937 .fold(self.unheard, u64::min);
938 while self
939 .recent
940 .front()
941 .is_some_and(|&(number, _)| number < keep)
942 {
943 self.recent.pop_front();
944 }
945 }
946}
947
948#[derive(Default)]
950struct OpenFiles {
951 pending: std::collections::VecDeque<std::path::PathBuf>,
953 next: Option<AnswerSlot<Vec<std::path::PathBuf>>>,
955}
956
957#[derive(Default)]
959struct SecondInstances {
960 pending: std::collections::VecDeque<crate::single_instance::SecondInstance>,
963 next: Option<AnswerSlot<crate::single_instance::SecondInstance>>,
965}
966
967pub(super) struct Components {
969 pub(super) web_evaluations: super::web_evaluation::Evaluations,
970 pub(super) canvas_renders: super::canvas_render::Renders,
971 registry: Registry,
972 specs: FxHashMap<&'static str, Arc<ComponentSpec>>,
975 pub(super) tokens: Arc<Tokens>,
977 app_tokens: Arc<Tokens>,
981 host_tokens: Option<Arc<Tokens>>,
983 pub(super) instances: FxHashMap<NodeId, Box<Instance>>,
986 by_name: FxHashMap<NodeId, ByName>,
989 pub(super) owners: FxHashMap<NodeId, NodeId>,
991 pub(super) release_generation: u64,
995 pub(super) released_hosts: FxHashSet<NodeId>,
998 #[cfg(test)]
999 pub(super) cleanup_work: super::views::CleanupWork,
1000 #[cfg(test)]
1003 pub(super) handler_visits: std::cell::Cell<usize>,
1004 #[cfg(test)]
1007 pub(super) placing_work: std::cell::Cell<usize>,
1008 #[cfg(test)]
1011 pub(super) position_work: std::cell::Cell<usize>,
1012 #[cfg(test)]
1015 pub(super) watch_work: std::cell::Cell<usize>,
1016 #[cfg(test)]
1019 pub(super) retag_work: std::cell::Cell<usize>,
1020 #[cfg(test)]
1023 pub(super) retag_rounds: std::cell::Cell<usize>,
1024 slot_names: FxHashMap<NodeId, Arc<str>>,
1026 pub(super) slot_hosts: FxHashMap<NodeId, NodeId>,
1028 pub(super) slot_targets: FxHashMap<NodeId, super::slots::SlotTarget>,
1031 pub(super) adopted: FxHashMap<NodeId, NodeId>,
1033 pub(super) fill_holders: FxHashSet<NodeId>,
1037 styles: FxHashMap<StyleRefinement, std::rc::Rc<ClassList>>,
1038 pub(super) merges: FxHashMap<(usize, usize), [std::rc::Rc<ClassList>; 3]>,
1041 pub(super) filling: Option<(NodeId, &'static str)>,
1044 pub(super) moved: Vec<NodeId>,
1049 lists: FxHashMap<NodeId, (PlaceFn, u32)>,
1053 pub(super) environment: Environment,
1054 pub(super) executor: Rc<Executor>,
1056 js_windows: FxHashMap<NodeId, (crate::element::Owner, crate::element::desktop::WindowRef)>,
1059 window_reports: FxHashMap<
1062 NodeId,
1063 (
1064 Option<crate::desktop::WindowState>,
1065 crate::geometry::Edges<Points>,
1066 ),
1067 >,
1068 pub(super) status_bars: crate::element::status_bar::StatusBars,
1070 dialogs: FxHashMap<u32, AnswerSlot<crate::element::DialogReply>>,
1072 next_dialog: u32,
1073 image_infos: FxHashMap<u32, AnswerSlot<Result<ImageSize, String>>>,
1075 next_image_info: u32,
1076 clipboard_reads: FxHashMap<u32, ClipboardRead>,
1079 next_clipboard_read: u32,
1080 #[allow(clippy::type_complexity)]
1082 picks: FxHashMap<
1083 u32,
1084 (
1085 crate::picker::Pick,
1086 AnswerSlot<Vec<crate::picker::PickedFile>>,
1087 ),
1088 >,
1089 next_pick: u32,
1090 audio: FxHashMap<u32, crate::audio::AudioSink>,
1092 notifications: Notifications,
1094 url_schemes: UrlScheme,
1096 second_instances: SecondInstances,
1097 open_files: OpenFiles,
1098 host_calls:
1101 FxHashMap<u64, AnswerSlot<Result<crate::JsonValue, crate::host_channel::HostError>>>,
1102 next_host_call: u64,
1103 host_requests: Vec<crate::host_channel::HostRequest>,
1106 host_inbox: crate::host_channel::HostInbox,
1109 url_opens: FxHashMap<u32, AnswerSlot<bool>>,
1111 pub(super) clipboard_writes:
1114 std::collections::VecDeque<AnswerSlot<crate::element::ClipboardWrite>>,
1115 url_requests: Vec<(u32, String)>,
1117 pub(super) locale_request: Option<Option<crate::platform::Locale>>,
1120 text_locale: Option<crate::platform::Locale>,
1123 asks_quit: bool,
1127 main_thread: Vec<crate::main_thread::MainThreadTask>,
1130 next_url_open: u32,
1131 app_settings_opens: FxHashMap<u32, AnswerSlot<Result<bool, crate::mobile::AppSettingsError>>>,
1134 next_app_settings_open: u32,
1135 screen_colors: FxHashMap<u32, AnswerSlot<Option<crate::Hsla>>>,
1137 next_screen_color: u32,
1138 file_requests: FxHashMap<u32, FileAnswer>,
1141 next_file_request: u32,
1142 fetches: FxHashMap<u32, PendingFetch>,
1145 fetch_requests: Vec<(u32, crate::platform::HttpRequest)>,
1147 next_fetch: u32,
1148 animations: FxHashMap<crate::animation::AnimationId, Awaited>,
1151 pub(super) measures: Vec<(NodeId, AnswerSlot<Option<crate::Measurement>>)>,
1154 pub(super) scroll_positions: Vec<(NodeId, AnswerSlot<Option<crate::ListScrollPosition>>)>,
1157 pub(super) transition_times: Vec<(NodeId, AnswerSlot<std::time::Duration>)>,
1160 pub(super) text_contents: Vec<(NodeId, AnswerSlot<String>)>,
1163 pub(super) presses: Vec<(NodeId, crate::PressEvent, AnswerSlot<bool>)>,
1166 pub(super) hovers: Vec<(NodeId, Option<crate::MouseEvent>)>,
1169 pub(super) downloads: crate::webview::downloads::Downloads,
1172 next_webview_request: u64,
1175 virtual_lists: FxHashMap<NodeId, VirtualListState>,
1177 waiting: Vec<NodeId>,
1179 parked_methods: Vec<(NodeId, u32, crate::element::MethodCall)>,
1183 list_counts: FxHashMap<NodeId, (crate::element::Owner, crate::element::Signal<usize>)>,
1186 pub(super) list_layouts: FxHashMap<NodeId, ListConfig>,
1188 insets: FxHashMap<NodeId, EdgeInsets>,
1190 js_back: bool,
1192 js_back_progress: bool,
1195 back_gesture: bool,
1198 js_keymap: Arc<crate::keymap::Keymap>,
1201 js_keys: bool,
1203 pub(super) touch: super::touch::TouchState,
1205 pub(super) services: super::services::Services,
1207 next_id: NodeId,
1208 dirty: Vec<NodeId>,
1209 props: Vec<Prop>,
1211 pub(super) runtime: crate::element::Runtime,
1213 pub(super) patches: super::views::Patches,
1215 pub(super) regions: FxHashMap<u32, super::views::RegionState>,
1217 pub(super) next_region: u32,
1218 posts: Posts,
1222 pub(super) renders: super::renders::Renders,
1225 pub(super) app_classes: FxHashMap<NodeId, AppClass>,
1229}
1230
1231impl Default for Components {
1232 fn default() -> Self {
1233 Self {
1234 registry: Registry::default(),
1235 specs: FxHashMap::default(),
1236 tokens: Arc::new(Tokens::default()),
1237 app_tokens: Arc::new(Tokens::default()),
1238 host_tokens: None,
1239 instances: FxHashMap::default(),
1240 by_name: FxHashMap::default(),
1241 owners: FxHashMap::default(),
1242 release_generation: 0,
1243 released_hosts: FxHashSet::default(),
1244 #[cfg(test)]
1245 cleanup_work: Default::default(),
1246 #[cfg(test)]
1247 handler_visits: Default::default(),
1248 #[cfg(test)]
1249 placing_work: Default::default(),
1250 #[cfg(test)]
1251 position_work: Default::default(),
1252 #[cfg(test)]
1253 watch_work: Default::default(),
1254 #[cfg(test)]
1255 retag_work: Default::default(),
1256 #[cfg(test)]
1257 retag_rounds: Default::default(),
1258 slot_names: FxHashMap::default(),
1259 slot_hosts: FxHashMap::default(),
1260 slot_targets: FxHashMap::default(),
1261 adopted: FxHashMap::default(),
1262 fill_holders: FxHashSet::default(),
1263 styles: FxHashMap::default(),
1264 merges: FxHashMap::default(),
1265 filling: None,
1266 moved: Vec::new(),
1267 lists: FxHashMap::default(),
1268 environment: Environment::default(),
1269 executor: Rc::new(Executor::default()),
1270 js_windows: FxHashMap::default(),
1271 window_reports: FxHashMap::default(),
1272 status_bars: Default::default(),
1273 dialogs: FxHashMap::default(),
1274 next_dialog: 1,
1275 image_infos: FxHashMap::default(),
1276 next_image_info: 1,
1277 clipboard_reads: FxHashMap::default(),
1278 url_opens: FxHashMap::default(),
1279 clipboard_writes: Default::default(),
1280 url_requests: Vec::new(),
1281 locale_request: None,
1282 text_locale: None,
1283 asks_quit: false,
1284 main_thread: Vec::new(),
1285 next_url_open: 0,
1286 app_settings_opens: FxHashMap::default(),
1287 next_app_settings_open: 1,
1288 screen_colors: FxHashMap::default(),
1289 next_screen_color: 1,
1290 file_requests: FxHashMap::default(),
1291 next_file_request: 1,
1292 next_clipboard_read: 1,
1293 picks: FxHashMap::default(),
1294 next_pick: 1,
1295 audio: FxHashMap::default(),
1296 notifications: Notifications::default(),
1297 url_schemes: UrlScheme::default(),
1298 second_instances: SecondInstances::default(),
1299 open_files: OpenFiles::default(),
1300 host_calls: FxHashMap::default(),
1301 next_host_call: 1,
1302 host_requests: Vec::new(),
1303 host_inbox: Default::default(),
1304 web_evaluations: Default::default(),
1305 canvas_renders: Default::default(),
1306 fetches: FxHashMap::default(),
1307 fetch_requests: Vec::new(),
1308 next_fetch: 1,
1309 animations: FxHashMap::default(),
1310 measures: Vec::new(),
1311 scroll_positions: Vec::new(),
1312 transition_times: Vec::new(),
1313 text_contents: Vec::new(),
1314 presses: Vec::new(),
1315 hovers: Vec::new(),
1316 downloads: crate::webview::downloads::Downloads::default(),
1317 next_webview_request: 1,
1318 virtual_lists: FxHashMap::default(),
1319 list_counts: FxHashMap::default(),
1320 waiting: Vec::new(),
1321 parked_methods: Vec::new(),
1322 list_layouts: FxHashMap::default(),
1323 insets: FxHashMap::default(),
1324 js_back: false,
1325 js_back_progress: false,
1326 back_gesture: false,
1327 js_keymap: Arc::new(crate::keymap::Keymap::default()),
1328 js_keys: false,
1329 touch: super::touch::TouchState::default(),
1330 services: Default::default(),
1331 next_id: 3,
1333 dirty: Vec::new(),
1334 props: Vec::new(),
1335 runtime: crate::element::Runtime::default(),
1336 patches: super::views::Patches::default(),
1337 regions: FxHashMap::default(),
1338 next_region: 1,
1339 posts: Posts::default(),
1340 renders: Default::default(),
1341 app_classes: FxHashMap::default(),
1342 }
1343 }
1344}
1345
1346impl Components {
1347 pub(super) fn is_virtual_list(&self, list: NodeId) -> bool {
1350 self.virtual_lists.contains_key(&list)
1351 }
1352
1353 pub(super) fn for_viewport(viewport: crate::Size<crate::Points>) -> Self {
1354 let mut components = Self::default();
1355 components.environment.window = viewport;
1356 components.runtime.set_services(components.executor.clone());
1358 components
1359 .runtime
1360 .set_app_url(components.url_schemes.address.clone());
1361 components.runtime.set_environment(components.environment);
1362 components.runtime.set_tokens(components.tokens.clone());
1363 components
1364 }
1365
1366 pub(super) fn alloc(&mut self) -> NodeId {
1367 let id = self.next_id;
1368 self.next_id += 2;
1369 id
1370 }
1371
1372 pub(super) fn mark(&mut self, host: NodeId) {
1373 if let Some(inst) = self.instances.get_mut(&host)
1374 && !inst.dirty
1375 {
1376 inst.dirty = true;
1377 self.dirty.push(host);
1378 }
1379 }
1380
1381 pub(super) fn lowered(&mut self, style: &StyleRefinement) -> std::rc::Rc<ClassList> {
1384 if style.is_bound() {
1385 return self.lowered(&style.static_part());
1386 }
1387 if let Some(list) = self.styles.get(style) {
1388 return list.clone();
1389 }
1390 if self.styles.len() >= STYLE_CACHE {
1391 self.styles.clear();
1392 }
1393 let list = std::rc::Rc::new(style.lower());
1394 self.styles.insert(style.clone(), list.clone());
1395 list
1396 }
1397}
1398
1399fn inline_style(
1402 id: NodeId,
1403 inline: Option<&crate::StylePatch>,
1404 animated: &[(crate::StyleDecl, crate::element::LiveNode)],
1405 app: Option<&crate::StylePatch>,
1406) -> Op {
1407 let mut style = Box::<crate::Style>::default();
1408 let mut patch = crate::StylePatch::default();
1409 let inline = inline.map(|p| p.decls()).unwrap_or_default();
1410 let app = app.map(|p| p.decls()).unwrap_or_default();
1411 for decl in inline
1412 .iter()
1413 .chain(animated.iter().map(|(d, _)| d))
1414 .chain(app)
1415 {
1416 let _ = patch.push(&mut style, decl.clone());
1417 }
1418 Op::SetStyle { id, style, patch }
1419}
1420
1421fn same(a: &Option<std::rc::Rc<ClassList>>, b: &Option<std::rc::Rc<ClassList>>) -> bool {
1422 match (a, b) {
1423 (Some(a), Some(b)) => std::rc::Rc::ptr_eq(a, b),
1424 (None, None) => true,
1425 _ => false,
1426 }
1427}
1428
1429impl Components {
1430 pub(super) fn gpu_renderer(&self, name: &str) -> Option<crate::gpu::GpuSource> {
1432 self.registry.registered_gpu_renderer(name).cloned()
1433 }
1434}
1435
1436impl<M: TextEngine> Core<M> {
1437 pub fn set_components(&mut self, registry: Registry) {
1442 if let Some(Ok((tokens, _))) = registry.tokens(None) {
1443 self.set_tokens(tokens);
1444 }
1445 {
1446 let _entered = self.components.runtime.enter();
1447 registry.run_setups();
1448 }
1449 self.components.registry = registry;
1450 }
1451
1452 pub fn extend_components(&mut self, registry: Registry) {
1458 {
1459 let _entered = self.components.runtime.enter();
1460 registry.run_setups_not_in(&self.components.registry);
1461 }
1462 self.components.registry = registry;
1463 self.make_by_name();
1464 }
1465
1466 fn make_by_name(&mut self) {
1468 if self.components.by_name.is_empty() {
1469 return;
1470 }
1471 let _entered = self.components.runtime.enter();
1472 let hosts: Vec<NodeId> = self.components.by_name.keys().copied().collect();
1473 for host in hosts {
1474 let Some(waiting) = self.components.by_name.get(&host) else {
1475 continue;
1476 };
1477 let still = self
1478 .components
1479 .instances
1480 .get(&host)
1481 .is_some_and(|i| matches!(i.inner, Inner::Missing));
1482 if !still {
1483 self.components.by_name.remove(&host);
1484 continue;
1485 }
1486 let Some((spec, mut inner)) = self.components.registry.make_type(waiting.id) else {
1487 continue;
1488 };
1489 let waiting = self.components.by_name.remove(&host).expect("waiting");
1490 inner.place(host, waiting.owner);
1491 inner.set_props(waiting.props.as_any());
1492 if let Some(inst) = self.components.instances.get_mut(&host) {
1494 inst.inner = Inner::Component(inner);
1495 inst.spec = Some(spec);
1496 inst.remake = true;
1497 }
1498 self.components.mark(host);
1499 }
1500 }
1501
1502 fn create_instance_for(&mut self, host: NodeId, c: &crate::element::builder::ComponentEl) {
1505 let Some(id) = c.by_name else {
1506 self.create_instance_of(host, c.name, c.make, c.spec);
1507 return;
1508 };
1509 if self.is_host(host) {
1510 return;
1511 }
1512 match self.components.registry.make_type(id) {
1513 Some((spec, inner)) => self.insert_instance(host, Some(spec), Inner::Component(inner)),
1514 None => {
1515 self.insert_instance(host, None, Inner::Missing);
1516 self.components.by_name.insert(
1517 host,
1518 ByName {
1519 id,
1520 props: c.props.clone_box(),
1521 owner: crate::element::Owner::current(),
1522 },
1523 );
1524 let name = crate::element::component::export_name(c.name);
1525 match PART_REQUESTER.with(|r| r.get()) {
1526 Some(request) => request(name),
1527 None => log::debug!("`{name}` waits for the part that registers it"),
1528 }
1529 }
1530 }
1531 }
1532
1533 fn set_element_props(&mut self, host: NodeId, props: &dyn crate::element::builder::AnyProps) {
1535 if let Some(waiting) = self.components.by_name.get_mut(&host) {
1536 waiting.props = props.clone_box();
1537 return;
1538 }
1539 if let Some(inst) = self.components.instances.get_mut(&host)
1540 && let Inner::Component(inner) = &mut inst.inner
1541 {
1542 inner.set_props(props.as_any());
1543 }
1544 }
1545
1546 pub(super) fn set_ui_theme(&mut self, json: &str) {
1551 match self.components.registry.tokens(Some(json)) {
1552 Some(Ok((tokens, left_out))) => {
1553 for what in left_out {
1554 log::warn!("theme: {what}, ignored");
1555 }
1556 self.set_tokens(tokens);
1557 }
1558 Some(Err(e)) => log::warn!("theme: {e}"),
1559 None => log::warn!("theme: no UI set reads themes"),
1560 }
1561 }
1562
1563 pub fn set_tokens(&mut self, tokens: Tokens) {
1566 self.components.app_tokens = Arc::new(tokens);
1567 self.tokens_changed();
1568 }
1569
1570 pub fn set_translations(&mut self, translations: crate::i18n::Translations) {
1573 let _entered = self.components.runtime.enter();
1574 let stored = crate::element::global::<crate::i18n::Translations>();
1575 let env = self.components.environment;
1576 let before =
1577 crate::i18n::text_locale(&stored.get(), env.locale, env.locale_settings.languages);
1578 stored.set(translations);
1579 if crate::i18n::text_locale(&stored.get(), env.locale, env.locale_settings.languages)
1580 != before
1581 {
1582 self.localize_platform();
1583 }
1584 }
1585
1586 pub(crate) fn add_translations(
1589 &mut self,
1590 map: std::collections::HashMap<String, std::collections::HashMap<String, String>>,
1591 ) {
1592 if map.is_empty() {
1593 return;
1594 }
1595 let next = {
1596 let _entered = self.components.runtime.enter();
1597 crate::element::global::<crate::i18n::Translations>()
1598 .get_untracked()
1599 .extend(map)
1600 };
1601 self.set_translations(next);
1602 }
1603
1604 fn translations_changed(&mut self, before: &crate::i18n::Translations) {
1607 let _entered = self.components.runtime.enter();
1608 let current = crate::element::global::<crate::i18n::Translations>().get_untracked();
1609 let env = self.components.environment;
1610 if crate::i18n::text_locale(¤t, env.locale, env.locale_settings.languages)
1611 != crate::i18n::text_locale(before, env.locale, env.locale_settings.languages)
1612 {
1613 self.localize_platform();
1614 }
1615 }
1616
1617 fn localize_platform(&mut self) {
1621 use crate::platform::Os;
1622 let _entered = self.components.runtime.enter();
1623 let env = self.components.environment;
1624 let desktop = matches!(env.os, Os::MacOs | Os::Windows)
1625 && env.idiom != crate::platform::Idiom::Terminal;
1626 if !desktop && !matches!(env.os, Os::Ios | Os::Android) {
1627 return;
1628 }
1629 let translations = crate::element::global::<crate::i18n::Translations>().get();
1630 let locale =
1631 crate::i18n::text_locale(&translations, env.locale, env.locale_settings.languages);
1632 if !desktop {
1633 if self.components.text_locale != Some(locale) {
1634 self.components.text_locale = Some(locale);
1635 self.commands
1636 .push((crate::ROOT_ID, Command::TextLocale(locale)));
1637 }
1638 return;
1639 }
1640 let labels = crate::desktop::MenuLabels::for_locale(
1641 locale,
1642 self.components.environment.os == crate::platform::Os::MacOs,
1643 );
1644 let _ = self.apply_op(crate::Op::Command {
1645 id: crate::ROOT_ID,
1646 command: crate::Command::Desktop(Box::new(
1647 crate::desktop::DesktopCommand::SetMenuLabels(Box::new(labels)),
1648 )),
1649 });
1650 }
1651
1652 pub fn take_locale_request(&mut self) -> Option<Option<crate::platform::Locale>> {
1656 self.components.locale_request.take()
1657 }
1658
1659 #[doc(hidden)]
1664 pub fn take_main_thread_tasks(&mut self) -> Vec<crate::main_thread::MainThreadTask> {
1665 std::mem::take(&mut self.components.main_thread)
1666 }
1667
1668 pub fn set_host_tokens(&mut self, tokens: Option<Tokens>) {
1672 self.components.host_tokens = tokens.map(Arc::new);
1673 self.tokens_changed();
1674 let classes = if self.components.host_tokens.is_some() {
1676 vec!["text-foreground".into()]
1677 } else {
1678 Vec::new()
1679 };
1680 self.set_classes(self.root, None, Some(classes));
1681 }
1682
1683 pub fn theme_tokens(&self) -> crate::element::ThemeTokens {
1687 crate::element::ThemeTokens::new(
1688 self.components.registry.token_source(),
1689 self.components.host_tokens.clone(),
1690 )
1691 }
1692
1693 pub fn tokens(&self) -> &Arc<Tokens> {
1696 &self.components.tokens
1697 }
1698
1699 fn tokens_changed(&mut self) {
1702 let tokens = match &self.components.host_tokens {
1703 Some(host) => Arc::new(host.over(&self.components.app_tokens)),
1705 None => self.components.app_tokens.clone(),
1706 };
1707 if *tokens == *self.components.tokens {
1708 self.components.tokens = tokens;
1709 return;
1710 }
1711 {
1712 let _entered = self.components.runtime.enter();
1713 self.components.tokens = tokens;
1714 self.components
1715 .runtime
1716 .set_tokens(self.components.tokens.clone());
1717 }
1718 self.commands.push((
1721 crate::ROOT_ID,
1722 Command::Tokens(self.components.tokens.clone()),
1723 ));
1724 let font = self
1725 .components
1726 .tokens
1727 .font(crate::element::FONT_SANS)
1728 .map(|f| crate::style::FontFamily::new(f));
1729 self.set_default_font(font);
1730 self.class_tokens_changed();
1731 }
1732
1733 pub fn mount_root(&mut self, root: &Root) {
1736 if let Some(setting) = root.status_bar_ref() {
1737 self.components.status_bars.set_base(setting);
1738 }
1739 let _entered = self.components.runtime.enter();
1740 let Some(id) = self.make_component(root.element(), |_, _| {}) else {
1741 return log::error!("the root is not a component");
1742 };
1743 let _ = self.apply_op(Op::Insert {
1744 parent: ROOT_ID,
1745 child: id,
1746 before: None,
1747 });
1748 self.mount_opened_windows();
1749 self.own_direction();
1750 }
1751
1752 pub fn mount_opened_windows(&mut self) {
1756 let _entered = self.components.runtime.enter();
1757 if !crate::element::os().is_desktop() {
1758 return;
1759 }
1760 use crate::element::Component as _;
1761 let host = crate::element::desktop::OpenedWindowsHost::element(()).into_element();
1762 if let Some(host) = self.make_component(host, |_, _| {}) {
1763 let _ = self.apply_op(Op::Insert {
1764 parent: ROOT_ID,
1765 child: host,
1766 before: None,
1767 });
1768 }
1769 }
1770
1771 pub(super) fn make_component(
1775 &mut self,
1776 el: crate::element::AnyElement,
1777 made: impl FnOnce(&mut Self, NodeId),
1778 ) -> Option<NodeId> {
1779 let mut el = el.0;
1780 let ElKind::Component(c) = std::mem::replace(&mut el.kind, ElKind::Plain) else {
1781 return None;
1782 };
1783 let id = self.components.alloc();
1784 let _ = self.apply_op(Op::Create { id, tag: el.tag });
1785 made(self, id);
1786 self.create_instance_for(id, &c);
1787 self.set_element_props(id, c.props.as_ref());
1788 Some(id)
1789 }
1790
1791 pub(super) fn scrollbar_source(&self) -> Option<crate::element::ScrollbarSource> {
1793 self.components.registry.scrollbar_source()
1794 }
1795
1796 pub fn set_environment(&mut self, mut environment: Environment) {
1801 let _entered = self.components.runtime.enter();
1802 environment.rtl = self.surface_rtl(environment.rtl);
1803 self.system_dark = environment.dark;
1804 environment.dark = self.shown_dark();
1805 self.apply_environment(environment);
1806 }
1807
1808 pub fn set_perf_monitor(&mut self, enabled: bool) {
1811 self.components.runtime.set_perf_monitor(enabled);
1812 }
1813
1814 pub fn set_perf_stats(&mut self, stats: Option<crate::platform::PerfStats>) {
1817 self.components.runtime.set_perf_stats(stats);
1818 }
1819
1820 pub fn set_displays(&mut self, displays: Arc<[crate::desktop::Display]>) {
1823 self.components.runtime.set_displays(displays);
1824 }
1825
1826 pub(super) fn apply_environment(&mut self, environment: Environment) {
1828 let _entered = self.components.runtime.enter();
1829 let changed = self.components.environment != environment;
1830 let language_changed = self.components.environment.idiom != environment.idiom
1831 || self.components.environment.os != environment.os
1832 || self.components.environment.locale != environment.locale
1833 || self.components.environment.locale_settings.languages
1834 != environment.locale_settings.languages;
1835 let keyboard_moved =
1836 self.components.environment.keyboard_height != environment.keyboard_height;
1837 self.keyboard_moved |= keyboard_moved;
1838 if keyboard_moved && self.root_overlay_shown() {
1841 self.needs_layout = true;
1842 }
1843 let ratio = self.components.environment.pixel_ratio;
1844 let window = self.components.environment.window;
1845 self.components.environment = environment;
1846 if window != environment.window {
1849 self.restyle_where(crate::tailwind::deps::WIDTH | crate::tailwind::deps::HEIGHT);
1850 }
1851 if ratio != environment.pixel_ratio {
1852 self.repick_images(ratio, environment.pixel_ratio);
1853 }
1854 self.pixel_ratio_changed(environment.pixel_ratio);
1856 self.cell_changed(environment.cell, environment.dark);
1858 if changed {
1859 self.components.runtime.set_environment(environment);
1861 }
1862 if language_changed {
1863 self.localize_platform();
1864 }
1865 if let Some(state) = environment.window_state {
1867 self.keep_window_placement(crate::ROOT_ID, &state);
1868 }
1869 }
1870
1871 pub(super) fn components_viewport(&mut self, size: crate::Size<crate::Points>) {
1873 let environment = Environment {
1874 window: size,
1875 ..self.components.environment
1876 };
1877 self.apply_environment(environment);
1878 }
1879
1880 pub fn discard_ops(&mut self, ops: impl IntoIterator<Item = Op>) {
1885 for op in ops {
1886 if let Op::Rust(RustOp { call, run }) = op {
1887 drop_caught(run);
1890 self.settle(call, Err("the script stopped before the call ran".into()));
1891 }
1892 }
1893 }
1894
1895 pub fn set_posts(&mut self, posts: Posts) {
1898 self.components.posts = posts;
1899 }
1900
1901 pub fn set_task_notify(&mut self, notify: Arc<dyn Fn() + Send + Sync>) {
1904 self.components.executor.set_notify(notify.clone());
1905 self.components.downloads.set_notify(notify);
1906 }
1907
1908 #[doc(hidden)]
1912 pub fn set_download_cleanup(&mut self, cleanup: crate::webview::downloads::DownloadCleanup) {
1913 self.components.downloads.set_cleanup(cleanup);
1914 }
1915
1916 pub fn set_task_runtime(&mut self, runtime: tokio::runtime::Handle) {
1919 self.components.executor.set_runtime(runtime);
1920 }
1921
1922 pub fn next_task_timer(&self) -> Option<crate::time::Instant> {
1925 self.components.executor.next_timer()
1926 }
1927
1928 pub fn run_component_tasks(&mut self) {
1931 let _entered = self.components.runtime.enter();
1932 let executor = self.components.executor.clone();
1933 executor.fire_timers(crate::time::now());
1934 for _ in 0..MAX_TASK_ROUNDS {
1936 let polled = executor.poll_ready();
1937 let actions = executor.take_actions();
1938 if !polled && actions.is_empty() {
1939 return;
1940 }
1941 for action in actions {
1942 self.apply_action(action);
1943 }
1944 for (host, message) in executor.take_failures() {
1945 self.component_failed(host, message);
1946 }
1947 }
1948 }
1949
1950 pub fn has_quit_listeners(&self) -> bool {
1953 !self.components.executor.quit.borrow().is_empty()
1954 }
1955
1956 pub fn start_quit(&mut self) -> bool {
1962 let _entered = self.components.runtime.enter();
1963 let executor = self.components.executor.clone();
1964 let listeners = executor.quit.borrow().all();
1965 for listener in listeners {
1966 match caught(|| listener()) {
1967 Ok(future) => {
1968 let pending = crate::element::quit::Pending::new(&executor.quitting);
1969 drop(crate::element::task::spawn_future(&executor, async move {
1971 future.await;
1972 drop(pending);
1973 }));
1974 }
1975 Err(message) => log::error!(target: "js", "a quit listener failed: {message}"),
1976 }
1977 }
1978 self.apply_actions();
1979 self.quit_pending()
1980 }
1981
1982 fn quit_requested(&mut self) {
1985 let _entered = self.components.runtime.enter();
1986 let listeners = self.components.executor.quit_requests.borrow().all();
1987 for listener in listeners {
1988 if let Err(message) = caught(|| listener()) {
1989 log::error!(target: "js", "a quit request listener failed: {message}");
1990 }
1991 }
1992 self.apply_actions();
1993 }
1994
1995 #[doc(hidden)]
1998 pub fn reopened(&mut self) {
1999 let _entered = self.components.runtime.enter();
2000 let listeners = self.components.executor.reopens.borrow().all();
2001 for listener in listeners {
2002 if let Err(message) = caught(|| listener()) {
2003 log::error!(target: "js", "a reopen listener failed: {message}");
2004 }
2005 }
2006 self.apply_actions();
2007 }
2008
2009 pub(crate) fn last_window_closed(&mut self) {
2011 let _entered = self.components.runtime.enter();
2012 let listeners = self.components.executor.last_window_closed.borrow().all();
2013 for listener in listeners {
2014 if let Err(message) = caught(|| listener()) {
2015 log::error!(target: "js", "a last window closed listener failed: {message}");
2016 }
2017 }
2018 self.apply_actions();
2019 }
2020
2021 pub(super) fn sync_quit_requests(&mut self) -> bool {
2025 let asks = !self.components.executor.quit_requests.borrow().is_empty();
2026 if asks == self.components.asks_quit {
2027 return false;
2028 }
2029 self.components.asks_quit = asks;
2030 let _ = self.apply_op(crate::Op::Command {
2031 id: crate::ROOT_ID,
2032 command: crate::Command::Desktop(Box::new(
2033 crate::desktop::DesktopCommand::SetQuitOnRequest(!asks),
2034 )),
2035 });
2036 true
2037 }
2038
2039 pub fn quit_pending(&self) -> bool {
2041 self.components.executor.quitting.get() > 0
2042 }
2043
2044 pub fn async_calls_pending(&self) -> bool {
2048 self.components.executor.calls.get() > 0
2049 }
2050
2051 pub(super) fn run_answers(&mut self) {
2055 let _entered = self.components.runtime.enter();
2056 for answer in self.components.executor.take_due_answers() {
2057 let crate::element::AfterAnswer { owner, f } = answer;
2058 let result = if owner == crate::element::Owner::detached() {
2059 caught(f)
2060 } else if owner.is_live() {
2061 caught(|| owner.scope(f))
2062 } else {
2063 drop_caught(f);
2064 continue;
2065 };
2066 if let Err(message) = result {
2067 match self.host_of_owner(owner) {
2068 Some(host) => self.component_failed(host, message),
2069 None => {
2070 log::error!(target: "js", "a closure after the app's answer failed: {message}")
2071 }
2072 }
2073 }
2074 self.apply_actions();
2075 }
2076 }
2077
2078 pub(super) fn is_host(&self, id: NodeId) -> bool {
2080 self.components.instances.contains_key(&id)
2081 }
2082
2083 pub(super) fn intercept(&mut self, op: Op) -> Result<Option<Op>, ApplyError> {
2086 if !self.components.adopted.is_empty()
2091 && let Op::SetProp { id, .. } | Op::Listen { id, .. } | Op::Release { id } = &op
2092 && self.components.adopted.contains_key(id)
2093 && !self.is_host(*id)
2094 {
2095 return Ok(self.js_slot_op(op));
2096 }
2097 match op {
2098 Op::SetStyle { id, patch, .. } if self.is_host(id) => {
2100 let inst = self.components.instances.get_mut(&id).expect("host");
2101 inst.app_style = (!patch.is_empty()).then_some(patch);
2102 let base = self.base_of(id);
2105 let cx = self.root_context_of(base).expect("a host");
2106 let app = if cx.combined {
2107 cx.app
2108 } else {
2109 self.components.instances[&base].app_style.clone()
2110 };
2111 let (inline, animated) = match &self.components.instances[&base].root {
2112 Some(root) => (root.attrs.inline.clone(), root.attrs.animated().to_vec()),
2113 None => (None, Vec::new()),
2114 };
2115 Ok(Some(inline_style(
2116 id,
2117 inline.as_deref(),
2118 &animated,
2119 app.as_ref(),
2120 )))
2121 }
2122 Op::Insert { parent, child, .. }
2124 if self.is_host(parent) && self.is_render_holder(child) =>
2125 {
2126 self.insert_render_holder(parent, child);
2127 Ok(None)
2128 }
2129 Op::Remove { parent, child }
2130 if self.is_host(parent) && self.is_render_holder(child) =>
2131 {
2132 self.remove_render_holder(child, false);
2133 Ok(None)
2134 }
2135 Op::Release { id } if self.is_render_holder(id) => {
2136 self.remove_render_holder(id, true);
2137 Ok(Some(Op::Release { id }))
2138 }
2139 Op::Insert { parent, child, .. }
2141 if self.is_host(parent) && self.components.slot_names.contains_key(&child) =>
2142 {
2143 let name = self.components.slot_names[&child].clone();
2144 let inst = self.components.instances.get_mut(&parent).expect("host");
2145 let Some(slot) = inst.spec.as_ref().and_then(|s| s.holder(&name)) else {
2146 log::warn!(target: "js", "the component has no slot `{name}`");
2147 self.detach_id(child);
2148 return Ok(None);
2149 };
2150 inst.slots.retain(|(_, n)| *n != child);
2151 inst.slots.push((slot, child));
2152 self.components.slot_hosts.insert(child, parent);
2153 self.components.mark(parent);
2154 Ok(None)
2155 }
2156 Op::Remove { parent, child }
2157 if self.is_host(parent) && self.components.slot_names.contains_key(&child) =>
2158 {
2159 self.unslot(child);
2160 self.detach_id(child);
2161 Ok(None)
2162 }
2163 Op::Insert { parent, child, .. }
2165 if self.components.slot_hosts.contains_key(&parent) && self.is_list(parent) =>
2166 {
2167 self.apply_op(op)?;
2168 if let Some((place, _)) = self.components.lists.get(&parent).cloned() {
2169 self.wrap_row(child, place);
2170 }
2171 Ok(None)
2172 }
2173 Op::Remove { parent, .. }
2174 if self.components.slot_hosts.contains_key(&parent) && self.is_list(parent) =>
2175 {
2176 Ok(Some(op))
2177 }
2178 Op::Insert { parent, .. } | Op::Remove { parent, .. }
2181 if self.components.slot_hosts.contains_key(&parent) =>
2182 {
2183 let empty = |core: &Self| {
2184 core.key(parent)
2185 .map_or(true, |k| core.nodes[k as usize].children.is_empty())
2186 };
2187 let before = empty(self);
2188 self.apply_op(op)?;
2189 if empty(self) != before {
2190 let host = self.components.slot_hosts[&parent];
2191 self.components.mark(host);
2192 }
2193 self.retarget_slot(parent, None);
2195 Ok(None)
2196 }
2197 Op::Release { id } if self.components.slot_names.contains_key(&id) => {
2198 self.unslot(id);
2199 self.components.slot_names.remove(&id);
2200 self.components.lists.remove(&id);
2201 self.forget_list_count(id);
2202 Ok(Some(Op::Release { id }))
2203 }
2204 Op::SetProp {
2208 id,
2209 prop: Prop::Count(count),
2210 } if self.components.lists.contains_key(&id) => {
2211 let key = self.key(id)?;
2212 self.apply_op(Op::SetProp {
2213 id,
2214 prop: Prop::Count(count),
2215 })?;
2216 let seen = &mut self.components.lists.get_mut(&id).expect("list").1;
2218 if std::mem::replace(seen, count) != count {
2219 if let Some(&(_, signal)) = self.components.list_counts.get(&id) {
2221 signal.set(count as usize);
2222 }
2223 let cells: Vec<NodeId> = self.nodes[key as usize]
2224 .children
2225 .iter()
2226 .map(|&c| self.nodes[c as usize].id)
2227 .collect();
2228 for cell in cells {
2229 let binds = self.components.instances.get(&cell).is_some_and(|inst| {
2230 inst.row_index.is_some() && inst.cell_owner.is_some_and(|o| o.is_live())
2231 });
2232 if !binds {
2233 self.components.mark(cell);
2234 }
2235 }
2236 }
2237 Ok(None)
2238 }
2239 Op::SetProp {
2242 id,
2243 prop: Prop::CellIndex(index),
2244 } if self.is_host(id) => {
2245 let inst = self.components.instances.get_mut(&id).expect("host");
2246 if let Inner::Row { index: current, .. } = &mut inst.inner
2247 && *current != index as usize
2248 {
2249 *current = index as usize;
2250 match inst.row_index {
2251 Some(row) if inst.cell_owner.is_some_and(|o| o.is_live()) => {
2253 row.set(index as usize);
2254 }
2255 _ => self.components.mark(id),
2256 }
2257 }
2258 Ok(Some(op))
2259 }
2260 Op::Insert {
2261 parent,
2262 child,
2263 before,
2264 } if self.is_host(parent) => {
2265 let run = self.runs.contains_key(&child);
2268 self.materialize_run(child)?;
2269 let key = self.key(child)?;
2270 let is_text = matches!(self.nodes[key as usize].kind, Kind::Text | Kind::RawText);
2271 let inst = self.components.instances.get_mut(&parent).expect("host");
2272 let was_empty = inst.js_children.is_empty();
2273 let moved = inst.js_children.contains(&child);
2274 inst.forget_js_child(child);
2275 let at = before.and_then(|b| inst.js_children.iter().position(|&c| c == b));
2276 inst.js_children
2277 .insert(at.unwrap_or(inst.js_children.len()), child);
2278 if is_text {
2279 inst.js_texts.insert(child);
2280 }
2281 let place = inst.children_at;
2282 inst.js_children_changed();
2283 if was_empty || place == Placement::Each {
2284 self.components.mark(parent);
2285 }
2286 self.join_content(child);
2287 match place {
2288 Placement::At(p, anchor) => {
2291 let anchor = self.anchor_node(anchor);
2292 self.apply_op(Op::Insert {
2293 parent: p,
2294 child,
2295 before: at.and(before).or(anchor),
2296 })?;
2297 if run
2298 && self
2299 .key(p)
2300 .is_ok_and(|k| self.nodes[k as usize].kind != Kind::Text)
2301 {
2302 let text = self.key(child).map_or("", |k| &self.nodes[k as usize].text);
2303 log::warn!(
2304 target: "js",
2305 "text in a component's children is not shown: text shows in a <Text> (`<Text>{text}</Text>`)"
2306 );
2307 }
2308 }
2309 Placement::Nested(nested, anchor) => {
2310 let anchor = self.anchor_node(anchor);
2311 self.join_nested_at(nested, child, at.and(before).or(anchor));
2312 }
2313 Placement::Each if moved => {}
2317 Placement::Each => self.detach_id(child),
2318 Placement::None => self.detach_id(child),
2319 }
2320 Ok(None)
2321 }
2322 Op::Remove { parent, child } if self.is_host(parent) => {
2323 let inst = self.components.instances.get_mut(&parent).expect("host");
2324 inst.forget_js_child(child);
2325 inst.js_children_changed();
2326 let place = inst.children_at;
2327 if inst.js_children.is_empty() || place == Placement::Each {
2328 self.components.mark(parent);
2329 }
2330 self.unplace(place, child);
2331 Ok(None)
2332 }
2333 Op::SetProp { id, prop }
2335 if js_host_attribute(&prop)
2336 && self
2337 .components
2338 .instances
2339 .get(&id)
2340 .is_some_and(|i| matches!(i.inner, Inner::Component(_))) =>
2341 {
2342 let inst = self.components.instances.get_mut(&id).expect("host");
2343 let before = inst.js_host.len();
2344 if crate::element::host::reset(&prop).as_ref() == Some(&prop) {
2347 inst.js_host
2348 .retain(|p| !crate::element::host::same_kind(p, &prop));
2349 if inst.js_host.len() == before {
2350 return Ok(None);
2351 }
2352 } else if inst.js_host.contains(&prop) {
2353 return Ok(None);
2354 } else {
2355 crate::element::host::set_in(&mut inst.js_host, prop);
2356 }
2357 if inst.root.is_some() {
2359 inst.given_changed = true;
2360 self.components.mark(id);
2361 }
2362 Ok(None)
2363 }
2364 Op::SetProp {
2365 id,
2366 prop: Prop::Class(class),
2367 } if self.is_host(id) => {
2368 let inst = self.components.instances.get_mut(&id).expect("host");
2369 inst.class = class;
2370 self.update_user_class(id);
2371 Ok(None)
2372 }
2373 Op::SetProp {
2374 id,
2375 prop: Prop::ClassList(list),
2376 } if self.is_host(id) => {
2377 let inst = self.components.instances.get_mut(&id).expect("host");
2378 inst.class_list = list;
2379 self.update_user_class(id);
2380 Ok(None)
2381 }
2382 Op::Listen {
2385 id: crate::ROOT_ID,
2386 event: EventKind::BackPress,
2387 enabled,
2388 } => {
2389 self.components.js_back = enabled;
2390 let rust = !self.components.executor.back.borrow().list.is_empty();
2391 Ok(Some(Op::Listen {
2392 id: crate::ROOT_ID,
2393 event: EventKind::BackPress,
2394 enabled: enabled || rust,
2395 }))
2396 }
2397 Op::Listen {
2400 id: crate::ROOT_ID,
2401 event: EventKind::BackProgress,
2402 enabled,
2403 } => {
2404 self.components.js_back_progress = enabled;
2405 let rust = !self
2406 .components
2407 .executor
2408 .back_progress
2409 .borrow()
2410 .list
2411 .is_empty();
2412 Ok(Some(Op::Listen {
2413 id: crate::ROOT_ID,
2414 event: EventKind::BackProgress,
2415 enabled: enabled || rust,
2416 }))
2417 }
2418 Op::SetProp {
2420 id: crate::ROOT_ID,
2421 prop: Prop::Keymap(keymap),
2422 } => {
2423 self.components.js_keymap = keymap;
2424 Ok(Some(Op::SetProp {
2425 id: crate::ROOT_ID,
2426 prop: Prop::Keymap(self.keymap()),
2427 }))
2428 }
2429 Op::Listen {
2430 id: crate::ROOT_ID,
2431 event: EventKind::KeyCommand,
2432 enabled,
2433 } => {
2434 self.components.js_keys = enabled;
2435 let rust = !self.components.executor.keys.borrow().list.is_empty();
2436 Ok(Some(Op::Listen {
2437 id: crate::ROOT_ID,
2438 event: EventKind::KeyCommand,
2439 enabled: enabled || rust,
2440 }))
2441 }
2442 Op::Listen {
2444 id,
2445 event: EventKind::NativeEvent,
2446 ..
2447 } if self.is_host(id) => Ok(None),
2448 Op::Listen { id, event, enabled } if self.is_host(id) => {
2449 let inst = self.components.instances.get_mut(&id).expect("host");
2450 inst.js_events.set(event, enabled);
2451 Ok(Some(self.host_listen(id, event)))
2452 }
2453 Op::Rust(op) => {
2454 self.run_rust(op);
2455 Ok(None)
2456 }
2457 Op::Release { id } if self.is_host(id) => {
2458 self.release_instance(id);
2459 Ok(Some(Op::Release { id }))
2460 }
2461 op => Ok(Some(op)),
2462 }
2463 }
2464
2465 fn outside_listens(&self, id: NodeId, event: EventKind) -> bool {
2469 let mut at = Some(self.base_of(id));
2470 while let Some(host) = at {
2471 let Some(inst) = self.components.instances.get(&host) else {
2472 break;
2473 };
2474 if inst.js_events.contains(event) || inst.given_events.contains(event) {
2475 return true;
2476 }
2477 at = inst.above;
2478 }
2479 false
2480 }
2481
2482 fn host_listen(&mut self, id: NodeId, event: EventKind) -> Op {
2485 let outside = self.outside_listens(id, event);
2486 let base = self.base_of(id);
2487 let own = self.components.instances[&base]
2488 .root
2489 .as_ref()
2490 .is_some_and(|r| r.events.contains(event));
2491 let slot = self.target_listens(base, event, outside || own);
2492 Op::Listen {
2493 id,
2494 event,
2495 enabled: outside || own || slot,
2496 }
2497 }
2498
2499 pub(super) fn set_given_handlers(
2503 &mut self,
2504 id: NodeId,
2505 handlers: Vec<(EventKind, Listener<EventPayload>)>,
2506 ) {
2507 let mut events = EventMask::default();
2508 for (kind, _) in &handlers {
2509 events.set(*kind, true);
2510 }
2511 let Some(inst) = self.components.instances.get_mut(&id) else {
2512 return;
2513 };
2514 let old = std::mem::replace(&mut inst.given_events, events);
2515 inst.given_handlers = handlers;
2516 let mut changed = old.bits() ^ events.bits();
2517 while changed != 0 {
2518 let kind = EventKind::ALL[changed.trailing_zeros() as usize];
2519 changed &= changed - 1;
2520 let op = self.host_listen(id, kind);
2521 let _ = self.apply_op(op);
2522 }
2523 }
2524
2525 fn handle_given(&mut self, base: NodeId, kind: EventKind, payload: &EventPayload) -> bool {
2529 let mut listeners = Vec::new();
2530 let mut at = Some(base);
2531 while let Some(host) = at {
2532 let Some(inst) = self.components.instances.get(&host) else {
2533 break;
2534 };
2535 if inst.given_events.contains(kind)
2536 && let Some(&owner) = self.components.owners.get(&host)
2537 {
2538 listeners.extend(
2539 inst.given_handlers
2540 .iter()
2541 .filter(|(k, _)| *k == kind)
2542 .map(|(_, l)| (owner, l.clone())),
2543 );
2544 }
2545 at = inst.above;
2546 }
2547 let mut handled = false;
2548 for (owner, listener) in listeners {
2549 handled |= self.run_listener(owner, &listener, payload);
2550 }
2551 handled
2552 }
2553
2554 fn js_listens(&self, base: NodeId, kind: EventKind) -> bool {
2557 let mut at = Some(base);
2558 while let Some(host) = at {
2559 let Some(inst) = self.components.instances.get(&host) else {
2560 break;
2561 };
2562 if inst.js_events.contains(kind) {
2563 return true;
2564 }
2565 at = inst.above;
2566 }
2567 false
2568 }
2569
2570 fn rows_of_cell(&self, cell: NodeId) -> usize {
2572 let Ok(key) = self.key(cell) else { return 0 };
2573 self.nodes
2574 .get(self.nodes[key as usize].parent as usize)
2575 .and_then(|list| list.list.as_ref())
2576 .map_or(0, |list| list.count as usize)
2577 }
2578
2579 fn rows_of_list(&self, list: NodeId) -> u32 {
2581 self.key(list)
2582 .ok()
2583 .and_then(|k| self.nodes[k as usize].list.as_ref())
2584 .map_or(0, |l| l.count)
2585 }
2586
2587 fn is_list(&self, id: NodeId) -> bool {
2589 self.key(id)
2590 .is_ok_and(|k| self.nodes[k as usize].list.is_some())
2591 }
2592
2593 fn wrap_row(&mut self, cell: NodeId, place: PlaceFn) {
2596 let Ok(key) = self.key(cell) else { return };
2597 let node = &self.nodes[key as usize];
2598 if !matches!(node.slot, Some(crate::CellSlot::Item(_))) {
2599 return;
2600 }
2601 if let Some(inst) = self.components.instances.get_mut(&cell) {
2602 if let Inner::Row { place: current, .. } = &mut inst.inner {
2603 *current = place;
2604 }
2605 self.components.mark(cell);
2606 return;
2607 }
2608 let js_children = node
2611 .children
2612 .iter()
2613 .map(|&c| self.nodes[c as usize].id)
2614 .collect();
2615 let instance = Instance::new(Inner::Row { place, index: 0 }, None, js_children, None);
2616 self.components.instances.insert(cell, Box::new(instance));
2617 self.components.mark(cell);
2618 }
2619
2620 pub(super) fn run_rust(&mut self, op: RustOp) {
2623 let posts = self.components.posts.clone();
2624 posts.in_op(|| self.run_rust_op(op));
2625 }
2626
2627 fn run_rust_op(&mut self, op: RustOp) {
2628 let RustOp { call, run } = op;
2629 match run {
2630 RustCall::Op(run) => {
2631 let mut cx = ModuleCx::default();
2632 let ran = {
2637 let _entered = self.components.runtime.enter();
2638 caught(|| run(&mut cx))
2639 };
2640 let result = match ran {
2641 Ok(result) => {
2642 for action in std::mem::take(&mut cx.actions) {
2643 self.apply_action(action);
2644 }
2645 result
2646 }
2647 Err(message) => Err(message.into()),
2648 };
2649 self.apply_actions();
2650 self.settle(call, result);
2651 }
2652 RustCall::Task(start) => match caught(start) {
2653 Ok(future) => {
2654 let executor = Rc::downgrade(&self.components.executor);
2655 let pending =
2656 crate::element::quit::Pending::new(&self.components.executor.calls);
2657 crate::element::task::spawn_raw(
2659 &self.components.executor,
2660 ROOT_ID,
2661 Box::pin(async move {
2662 let result = crate::element::module::catching(future).await;
2663 drop(pending);
2664 match executor.upgrade() {
2665 Some(executor) if call != 0 => {
2666 executor.act(Action::Return(call, result));
2667 }
2668 _ => {
2669 if let Err(e) = &result {
2670 log::warn!(target: "js", "an async call into Rust failed: {e}");
2671 }
2672 }
2673 }
2674 }),
2675 );
2676 }
2677 Err(message) => self.settle(call, Err(message.into())),
2678 },
2679 RustCall::Method(host, method) if self.view_pending(host) => {
2680 self.components.parked_methods.push((host, call, method));
2683 }
2684 RustCall::Method(host, method) => {
2685 let mut failed = None;
2686 let result = match self
2687 .components
2688 .instances
2689 .get_mut(&host)
2690 .map(|i| &mut i.inner)
2691 {
2692 Some(Inner::Component(inner)) => match caught(|| inner.call(method)) {
2693 Ok(Some(result)) => result,
2694 Ok(None) => {
2695 Err(format!("{} has no ref of this method's type", inner.name()).into())
2696 }
2697 Err(message) => {
2698 failed = Some(message.clone());
2699 Err(message.into())
2700 }
2701 },
2702 _ => {
2703 drop_caught(method);
2704 Err(format!("node {host} hosts no Rust component").into())
2705 }
2706 };
2707 self.apply_actions();
2708 if let Some(message) = failed {
2709 self.component_failed(host, message);
2710 }
2711 self.settle(call, result);
2712 }
2713 RustCall::Post(place) => drop(place),
2715 }
2716 }
2717
2718 pub(super) fn settle(&mut self, call: u32, result: JsResult) {
2721 if call == 0 {
2722 if let Err(e) = &result {
2723 log::warn!(target: "js", "a call into Rust failed: {e}");
2724 }
2725 drop_caught(result);
2726 return;
2727 }
2728 self.events.push(JsEvent::Reply { call, result });
2729 }
2730
2731 pub(super) fn update_user_class(&mut self, host: NodeId) {
2733 let inst = &self.components.instances[&host];
2734 let mut combined = String::with_capacity(inst.class.len() + 16 * inst.class_list.len());
2735 combined.push_str(&inst.class);
2736 for name in &inst.class_list {
2737 combined.push(' ');
2738 combined.push_str(name);
2739 }
2740 let user = (!combined.trim().is_empty()).then(|| self.tailwind.get(&combined).0);
2741 self.set_user(host, user);
2742 }
2743
2744 pub(super) fn set_user(&mut self, host: NodeId, user: Option<std::rc::Rc<ClassList>>) {
2746 let inst = self.components.instances.get_mut(&host).expect("host");
2747 if !same(&inst.user, &user) {
2748 inst.user = user;
2749 self.components.mark(host);
2750 }
2751 }
2752
2753 fn unslot(&mut self, id: NodeId) {
2755 self.drop_slot_target(id);
2756 if let Some(host) = self.components.slot_hosts.remove(&id) {
2757 if let Some(inst) = self.components.instances.get_mut(&host) {
2758 inst.slots.retain(|(_, n)| *n != id);
2759 }
2760 self.components.mark(host);
2761 }
2762 }
2763
2764 pub(super) fn set_slot_name(&mut self, id: NodeId, name: Arc<str>) {
2766 self.components.slot_names.insert(id, name);
2767 }
2768
2769 pub(super) fn create_instance(&mut self, host: NodeId, name: Arc<str>) {
2771 if self.is_host(host) {
2772 return;
2773 }
2774 let (spec, inner) = match self.components.registry.make(&name) {
2775 Some((spec, inner)) => (Some(spec), Inner::Component(inner)),
2776 None => {
2777 self.deny(format!(
2778 "no component is registered as `{name}`: it renders nothing"
2779 ));
2780 (None, Inner::Missing)
2781 }
2782 };
2783 self.insert_instance(host, spec, inner);
2784 }
2785
2786 pub(super) fn create_instance_of(
2789 &mut self,
2790 host: NodeId,
2791 name: &'static str,
2792 make: fn() -> Box<dyn AnyInstance>,
2793 spec: fn() -> ComponentSpec,
2794 ) {
2795 if self.is_host(host) {
2796 return;
2797 }
2798 let spec = self
2799 .components
2800 .specs
2801 .entry(name)
2802 .or_insert_with(|| Arc::new(spec()))
2803 .clone();
2804 self.insert_instance(host, Some(spec), Inner::Component(make()));
2805 }
2806
2807 fn insert_instance(
2808 &mut self,
2809 host: NodeId,
2810 spec: Option<Arc<ComponentSpec>>,
2811 mut inner: Inner,
2812 ) {
2813 let app_style = self
2815 .key(host)
2816 .ok()
2817 .map(|k| self.nodes[k as usize].inline_style.clone())
2818 .filter(|p| !p.is_empty());
2819 if let Inner::Component(c) = &mut inner {
2822 c.place(host, crate::element::Owner::current());
2823 }
2824 let instance = Instance::new(inner, spec, Vec::new(), app_style);
2825 self.components.instances.insert(host, Box::new(instance));
2826 self.components.mark(host);
2827 if let Ok(k) = self.key(host) {
2832 self.lay_out_through(k);
2833 }
2834 }
2835
2836 pub(super) fn set_component_prop(
2838 &mut self,
2839 host: NodeId,
2840 name: &str,
2841 value: Option<AnyValue>,
2842 ) -> bool {
2843 let Some(inst) = self.components.instances.get_mut(&host) else {
2844 return false;
2845 };
2846 let Inner::Component(inner) = &mut inst.inner else {
2847 return true;
2848 };
2849 match inner.set_prop(name, value) {
2850 Ok(true) => self.components.mark(host),
2851 Ok(false) => {}
2852 Err(e) => {
2853 let component = inst.spec.as_ref().map_or("", |s| s.name);
2854 log::warn!(target: "js", "{component}: {e}");
2855 }
2856 }
2857 true
2858 }
2859
2860 pub(super) fn render_components(&mut self) {
2863 let _entered = self.components.runtime.enter();
2864 loop {
2867 let changed = self.drain_views();
2868 let rendered = self.render_dirty();
2869 let failed = self.report_failures();
2870 let woke = self.wake_waiting();
2871 let called = self.run_parked_methods();
2872 if !changed && !rendered && !failed && !woke && !called && !self.run_after_render() {
2873 break;
2874 }
2875 }
2876 self.flush_renders();
2877 self.end_retags();
2878 }
2879
2880 fn run_after_render(&mut self) -> bool {
2884 let rendered = self.components.executor.take_rendered();
2885 if rendered.is_empty() {
2886 return false;
2887 }
2888 for crate::element::AfterAnswer { f, .. } in rendered {
2889 if let Err(message) = caught(f) {
2890 log::error!(target: "js", "a closure after the views rendered failed: {message}");
2891 }
2892 }
2893 true
2894 }
2895
2896 fn forget_node_extras(&mut self, id: NodeId) {
2899 if !self.components.renders.is_empty() {
2900 self.forget_render_place(id);
2901 }
2902 if !self.components.app_classes.is_empty() {
2903 self.components.app_classes.remove(&id);
2904 }
2905 }
2906
2907 fn report_failures(&mut self) -> bool {
2911 let failures = self.components.runtime.take_failures();
2912 let any = !failures.is_empty();
2913 for (owner, message) in failures {
2914 let host = self.host_of_owner(owner);
2915 let component = host
2916 .and_then(|h| match &self.components.instances.get(&h)?.inner {
2917 Inner::Component(inner) => Some(inner.name()),
2918 _ => None,
2919 })
2920 .unwrap_or("a binding");
2921 if let Some(boundary) = crate::element::reactive::boundary_of(owner) {
2922 boundary.set(Some(ComponentError { component, message }));
2923 continue;
2924 }
2925 match host {
2926 Some(host) => self.component_failed(host, message),
2927 None => log::error!(target: "js", "a binding failed: {message}"),
2928 }
2929 }
2930 any
2931 }
2932
2933 fn render_dirty(&mut self) -> bool {
2937 for action in self.components.executor.take_actions() {
2939 self.apply_action(action);
2940 }
2941 if self.components.dirty.is_empty() {
2942 return false;
2943 }
2944 while let Some(host) = self.components.dirty.pop() {
2945 if self.waits_for_tree(host) {
2948 if let Some(inst) = self.components.instances.get_mut(&host) {
2949 inst.dirty = false;
2950 }
2951 if !self.components.waiting.contains(&host) {
2952 self.components.waiting.push(host);
2953 }
2954 continue;
2955 }
2956 let Some(mut inst) = self.components.instances.remove(&host) else {
2957 continue;
2958 };
2959 inst.dirty = false;
2960 let rooted = inst.rooted;
2961 let failed = self.render(host, &mut inst);
2962 let rerooted = inst.rooted != rooted;
2963 self.components.instances.insert(host, inst);
2964 if rerooted {
2965 self.follow_base(host, rooted);
2966 }
2967 if let Some(message) = failed {
2968 self.component_failed(host, message);
2969 }
2970 }
2971 true
2972 }
2973
2974 fn restyle_view(&mut self, host: NodeId, inst: &mut Instance) {
2977 if let Some(rooted) = inst.rooted {
2979 if std::mem::take(&mut inst.given_changed)
2980 && let Some(rooted) = self.components.instances.get_mut(&rooted)
2981 {
2982 rooted.given_changed = true;
2983 }
2984 self.components.mark(rooted);
2985 return;
2986 }
2987 let cx = self.root_context(inst);
2988 let given_changed = std::mem::take(&mut inst.given_changed);
2989 let attrs = if let Some(node) = inst.bound.get_mut(&host) {
2990 let (style, classes) = (node.style.clone(), node.classes.clone());
2991 let class = node.attrs.class.clone();
2992 let classes = self.apply_el_styles(
2993 host,
2994 &style,
2995 &style,
2996 classes,
2997 class.as_ref(),
2998 cx.user.clone(),
2999 );
3000 if let Some(node) = inst.bound.get_mut(&host) {
3001 node.classes = classes;
3002 given_changed.then(|| node.attrs.clone())
3003 } else {
3004 None
3005 }
3006 } else if let Some(root) = inst.root.as_mut() {
3007 let (style, classes) = (root.style.clone(), root.classes.clone());
3008 let class = root.attrs.class.clone();
3009 root.classes = self.apply_el_styles(
3010 host,
3011 &style,
3012 &style,
3013 classes,
3014 class.as_ref(),
3015 cx.user.clone(),
3016 );
3017 given_changed.then(|| root.attrs.clone())
3018 } else {
3019 None
3020 };
3021 if let Some(attrs) = attrs {
3024 let app = if cx.combined {
3025 cx.app.as_ref()
3026 } else {
3027 inst.app_style.as_ref()
3028 };
3029 let _ = self.apply_op(inline_style(
3030 host,
3031 attrs.inline.as_deref(),
3032 attrs.animated(),
3033 app,
3034 ));
3035 let applied = inst.root_insets_applied;
3036 let own_insets = attrs.insets();
3037 let insets = (
3038 cx.inset_padding.or(own_insets.0),
3039 cx.inset_margin.or(own_insets.1),
3040 );
3041 if insets.0 != applied.0 {
3042 let _ = self.apply_op(Op::SetProp {
3043 id: host,
3044 prop: Prop::InsetPadding(insets.0.unwrap_or_default()),
3045 });
3046 }
3047 if insets.1 != applied.1 {
3048 let _ = self.apply_op(Op::SetProp {
3049 id: host,
3050 prop: Prop::InsetMargin(insets.1.unwrap_or_default()),
3051 });
3052 }
3053 inst.root_insets_applied = insets;
3054 if cx.host != inst.root_host_applied {
3055 let mut attrs = attrs;
3058 attrs.set_insets(insets);
3059 let old = with_host(attrs.clone(), &inst.root_host_applied);
3060 let new = with_host(attrs, &cx.host);
3061 if !self.apply_target_attrs(host, &new, &old, app) {
3062 self.apply_attrs_over(host, &new, &old, app);
3063 }
3064 inst.root_host_applied = cx.host;
3065 }
3066 }
3067 }
3068
3069 fn join_content(&mut self, id: NodeId) {
3076 let mut stack = vec![id];
3077 while let Some(id) = stack.pop() {
3078 if let Some(inst) = self.components.instances.get_mut(&id) {
3079 inst.joined = true;
3080 continue;
3081 }
3082 if let Ok(k) = self.key(id) {
3083 stack.extend(
3084 self.nodes[k as usize]
3085 .children
3086 .iter()
3087 .map(|&c| self.nodes[c as usize].id),
3088 );
3089 }
3090 }
3091 }
3092
3093 fn waits_for_tree(&self, host: NodeId) -> bool {
3098 let Some(inst) = self.components.instances.get(&host) else {
3099 return false;
3100 };
3101 let Inner::Component(inner) = &inst.inner else {
3102 return false;
3103 };
3104 inst.root.is_none()
3105 && (inst.joined || !inner.failure_owner().is_live())
3106 && !self.id_in_tree(host)
3107 }
3108
3109 fn id_in_tree(&self, id: NodeId) -> bool {
3111 self.key(id).is_ok_and(|k| self.in_tree(k))
3112 }
3113
3114 fn wake_waiting(&mut self) -> bool {
3117 let waiting = std::mem::take(&mut self.components.waiting);
3118 let mut woke = false;
3119 for host in waiting {
3120 if !self.components.instances.contains_key(&host) {
3121 continue;
3122 }
3123 if self.id_in_tree(host) {
3124 self.components.mark(host);
3125 woke = true;
3126 } else {
3127 self.components.waiting.push(host);
3128 }
3129 }
3130 woke
3131 }
3132
3133 fn run_parked_methods(&mut self) -> bool {
3136 if self.components.parked_methods.is_empty() {
3137 return false;
3138 }
3139 let parked = std::mem::take(&mut self.components.parked_methods);
3140 let mut ran = false;
3141 for (host, call, method) in parked {
3142 if self.view_pending(host) {
3143 self.components.parked_methods.push((host, call, method));
3144 } else {
3145 ran = true;
3146 self.run_rust(RustOp {
3147 call,
3148 run: RustCall::Method(host, method),
3149 });
3150 }
3151 }
3152 ran
3153 }
3154
3155 fn view_pending(&self, host: NodeId) -> bool {
3157 self.components
3158 .instances
3159 .get(&host)
3160 .is_some_and(|i| matches!(&i.inner, Inner::Component(inner) if inner.owner().is_none()))
3161 }
3162
3163 fn owner_above(&self, host: NodeId) -> crate::element::Owner {
3166 let mut key = self.key(host).ok();
3167 while let Some(k) = key {
3168 let parent = self.nodes[k as usize].parent;
3169 if parent == NO_KEY {
3170 break;
3171 }
3172 key = Some(parent);
3173 let id = self.base_of(self.nodes[parent as usize].id);
3176 let owner = self
3179 .components
3180 .instances
3181 .get(&id)
3182 .and_then(|inst| match &inst.inner {
3183 Inner::Component(inner) => inst
3184 .children_owner
3185 .filter(|o| o.is_live())
3186 .or_else(|| inner.owner().filter(|o| o.is_live())),
3187 _ => inst.cell_owner,
3188 });
3189 if let Some(owner) = owner {
3190 return owner;
3191 }
3192 }
3193 crate::element::Owner::detached()
3194 }
3195
3196 fn js_window_owner(&mut self, host: NodeId) -> Option<crate::element::Owner> {
3201 let key = self.key(host).ok()?;
3202 let window = self.key_window(key);
3203 if window == ROOT_ID {
3204 return None;
3205 }
3206 if let Some((owner, _)) = self.components.js_windows.get(&window)
3207 && owner.is_live()
3208 {
3209 return Some(*owner);
3210 }
3211 let id = self
3212 .window_ids
3213 .iter()
3214 .find_map(|(id, (node, _))| (*node == window).then(|| id.clone()))?;
3215 let reported = self
3216 .components
3217 .window_reports
3218 .get(&window)
3219 .copied()
3220 .unwrap_or_default();
3221 let (owner, this) =
3222 crate::element::desktop::js_window(&id, window, &self.components.executor, reported);
3223 self.components.js_windows.insert(window, (owner, this));
3224 Some(owner)
3225 }
3226
3227 fn host_of_owner(&self, owner: crate::element::Owner) -> Option<NodeId> {
3230 let mut at = Some(owner);
3231 while let Some(owner) = at {
3232 let host =
3233 self.components
3234 .instances
3235 .iter()
3236 .find_map(|(&host, inst)| match &inst.inner {
3237 Inner::Component(inner) if inner.owner() == Some(owner) => Some(host),
3238 _ => None,
3239 });
3240 if host.is_some() {
3241 return host;
3242 }
3243 at = owner.parent();
3244 }
3245 None
3246 }
3247
3248 fn window_of_owner(&self, owner: crate::element::Owner) -> NodeId {
3251 if self.window_ids.is_empty() {
3252 return crate::ROOT_ID;
3253 }
3254 self.host_of_owner(owner)
3255 .and_then(|host| self.key(host).ok())
3256 .map_or(crate::ROOT_ID, |key| self.key_window(key))
3257 }
3258
3259 fn render(&mut self, host: NodeId, inst: &mut Instance) -> Option<String> {
3263 let mut failure = None;
3264 let el = match &mut inst.inner {
3265 Inner::Component(inner) => {
3266 if let Some(spec) = &inst.spec {
3268 for name in spec.slots() {
3269 let filled = inst.slots.iter().any(|(s, node)| {
3270 *s == name
3271 && self
3272 .key(*node)
3273 .is_ok_and(|k| !self.nodes[k as usize].children.is_empty())
3274 }) || inst
3275 .fills
3276 .iter()
3277 .any(|f| f.name == name && !self.fill_nodes(f).is_empty());
3278 inner.set_slot(name, filled);
3279 }
3280 }
3281 inner.set_children(!inst.js_children.is_empty());
3282 if inst.root.is_some() && !std::mem::take(&mut inst.remake) {
3285 self.restyle_view(host, inst);
3286 return None;
3287 }
3288 let owner = self.owner_above(host);
3289 let owner = if owner.is_live() {
3290 owner
3291 } else {
3292 self.js_window_owner(host).unwrap_or(owner)
3293 };
3294 inner.adopt(owner);
3295 caught(|| inner.view()).unwrap_or_else(|message| {
3297 failure = Some(message);
3298 ElNode::empty_view()
3299 })
3300 }
3301 Inner::Row { place, index } => {
3303 let (place, index) = (place.clone(), *index);
3304 let count = self.rows_of_cell(host);
3305 let list = self.list_of(host);
3306 let count_signal = list.map(|list| self.list_count(list, count));
3308 let moves = list
3309 .and_then(|list| self.components.virtual_lists.get(&list))
3310 .and_then(|state| state.moves);
3311 let made = std::cell::Cell::new(None);
3312 let build = || {
3313 let at = row_position(index, count, count_signal, moves, &made);
3314 view().child(place(Child::row(), at)).into_element().0
3315 };
3316 let parent = self.list_component_owner(list);
3318 let el = self.build_cell(parent, inst, build);
3319 inst.row_index = made.take();
3320 if let (Some(list), Some(index), Some(owner)) =
3321 (list, inst.row_index, inst.cell_owner)
3322 && let Some(state) = self.components.virtual_lists.get(&list)
3323 {
3324 state.rows.borrow_mut().insert(host, (index, owner));
3325 }
3326 match el {
3327 Ok(el) => el,
3328 Err(message) => {
3329 failure = Some(message);
3330 ElNode::empty_view()
3331 }
3332 }
3333 }
3334 Inner::VirtualRow { list, index } => {
3335 let (list, index) = (*list, *index);
3336 let inverted = self
3337 .key(list)
3338 .ok()
3339 .and_then(|k| self.nodes[k as usize].list.as_ref())
3340 .is_some_and(|l| l.inverted);
3341 let state = self.components.virtual_lists.get(&list).map(|state| {
3342 let scope = state.scope.get();
3345 let gone = scope.is_some_and(|s| !s.is_live());
3346 (
3347 if gone { 0 } else { state.count as usize },
3348 state.row.clone(),
3349 state.separator.clone(),
3350 state.rows.clone(),
3351 scope,
3352 state.moves,
3353 )
3354 });
3355 match state {
3356 Some((count, ..)) if index >= count => {
3361 if let Some(owner) = inst.cell_owner.take() {
3362 owner.dispose();
3363 }
3364 inst.row_index = None;
3365 ElNode::empty_view()
3366 }
3367 Some((count, row, separator, rows, scope, moves)) => {
3368 let count_signal = Some(self.list_count(list, count));
3369 let made = std::cell::Cell::new(None);
3370 let build = || {
3371 let at = row_position(index, count, count_signal, moves, &made);
3372 let row = row(at);
3373 let separator = separator.map(|s| {
3376 crate::element::when(move || !at.is_last(), move || s())
3377 .into_element()
3378 });
3379 match separator {
3380 Some(s) if inverted => view().child(s).child(row),
3381 Some(s) => view().child(row).child(s),
3382 None => view().child(row),
3383 }
3384 .into_element()
3385 .0
3386 };
3387 let parent = scope.unwrap_or_else(|| self.list_component_owner(Some(list)));
3392 let el = self.build_cell(parent, inst, build);
3393 inst.row_index = made.take();
3394 if let (Some(index), Some(owner)) = (inst.row_index, inst.cell_owner) {
3395 rows.borrow_mut().insert(host, (index, owner));
3396 }
3397 match el {
3398 Ok(el) => el,
3399 Err(message) => {
3400 failure = Some(message);
3401 ElNode::empty_view()
3402 }
3403 }
3404 }
3405 None => ElNode::empty_view(),
3406 }
3407 }
3408 Inner::Missing => ElNode::empty_view(),
3409 };
3410 let owner = match &inst.inner {
3412 Inner::Component(inner) => inner.owner(),
3413 _ => inst.cell_owner,
3414 };
3415 match owner {
3416 Some(owner) => owner.run(|| self.expand_root(host, inst, el)),
3417 None => self.expand_root(host, inst, el),
3418 }
3419 failure
3420 }
3421
3422 fn build_cell(
3426 &mut self,
3427 parent: crate::element::Owner,
3428 inst: &mut Instance,
3429 build: impl FnOnce() -> ElNode,
3430 ) -> Result<ElNode, String> {
3431 if let Some(owner) = inst.cell_owner.take() {
3432 owner.dispose();
3433 }
3434 let (owner, el) = parent.run(|| crate::element::create_root(|| caught(build)));
3435 inst.cell_owner = Some(owner);
3436 el
3437 }
3438
3439 fn list_component_owner(&self, list: Option<NodeId>) -> crate::element::Owner {
3442 let component = list
3443 .and_then(|list| {
3444 self.components
3445 .virtual_lists
3446 .get(&list)
3447 .map(|s| s.owner)
3448 .or_else(|| self.components.slot_hosts.get(&list).copied())
3449 })
3450 .and_then(|host| self.components.instances.get(&host))
3451 .and_then(|inst| match &inst.inner {
3452 Inner::Component(inner) => inner.owner(),
3453 _ => None,
3454 });
3455 component.unwrap_or_else(crate::element::Owner::detached)
3456 }
3457
3458 fn reconcile_text(
3461 &mut self,
3462 id: NodeId,
3463 host: NodeId,
3464 new: Option<SharedString>,
3465 old: Option<(SharedString, NodeId)>,
3466 ) -> Option<(SharedString, NodeId)> {
3467 match (new, old) {
3468 (Some(content), Some((old, raw))) => {
3469 if content != old {
3470 let _ = self.apply_op(Op::SetText {
3471 id: raw,
3472 text: content.as_str().to_owned(),
3473 });
3474 }
3475 Some((content, raw))
3476 }
3477 (Some(content), None) => {
3478 let raw = self.components.alloc();
3479 let _ = self.apply_op(Op::CreateText {
3480 id: raw,
3481 text: content.as_str().to_owned(),
3482 });
3483 self.components.owners.insert(raw, host);
3484 let _ = self.apply_op(Op::Insert {
3485 parent: id,
3486 child: raw,
3487 before: None,
3488 });
3489 Some((content, raw))
3490 }
3491 (None, Some((_, raw))) => {
3492 self.release_id(raw);
3493 None
3494 }
3495 (None, None) => None,
3496 }
3497 }
3498
3499 fn expand_root(&mut self, host: NodeId, inst: &mut Instance, mut el: ElNode) {
3505 if matches!(el.kind, ElKind::Component(_))
3506 && matches!(inst.inner, Inner::Component(_))
3507 && inst
3508 .root
3509 .as_ref()
3510 .is_none_or(|r| matches!(r.part, Part::Component(_)))
3511 {
3512 return self.expand_rooted(host, inst, el);
3513 }
3514 let node = matches!(el.kind, ElKind::Plain | ElKind::VirtualList(_));
3515 if !node || (el.tag != Tag::View && !self.retag(host, el.tag)) {
3516 if node {
3517 log::error!(target: "js", "a component's root takes its kind only when it is first mounted; it is placed in a view");
3518 }
3519 let inner = std::mem::replace(&mut el, ElNode::new(Tag::View));
3520 el.children.push(inner);
3521 }
3522 if !el.children.is_empty()
3523 && let Some(content) = el.bound_text.take()
3524 {
3525 let mut first = ElNode::new(Tag::Text);
3526 first.text = Some(SharedString::default());
3527 first.bound_text = Some(content);
3528 el.text = None;
3529 el.children.insert(0, first);
3530 }
3531 let applied_layout = if matches!(el.kind, ElKind::VirtualList(_)) {
3534 self.components.list_layouts.remove(&host)
3535 } else {
3536 None
3537 };
3538 let bound = super::views::Bound::take(&mut el).map(|bound| {
3539 self.bind_parts(host, host, bound, &mut el);
3540 });
3541 inst.handlers.clear();
3542 inst.event_handlers.clear();
3543 inst.responders.clear();
3544 let old = inst.root.take();
3545 let first = old.is_none();
3546 let old_place = std::mem::replace(&mut inst.children_at, Placement::None);
3547 let (old_attrs, old_style, old_classes, old_events, old_children, old_text, old_list) =
3549 match old {
3550 Some(e) => (
3551 e.attrs,
3552 e.style,
3553 e.classes,
3554 e.events,
3555 e.children,
3556 e.text,
3557 e.list.map(|l| *l).unwrap_or_default(),
3558 ),
3559 None => (
3560 Attrs::default(),
3561 StyleRefinement::default(),
3562 (None, None),
3563 EventMask::default(),
3564 Vec::new(),
3565 None,
3566 ListConfig::default(),
3567 ),
3568 };
3569 let cx = self.root_context(inst);
3572 let app = if cx.combined {
3573 cx.app.as_ref()
3574 } else {
3575 inst.app_style.as_ref()
3576 };
3577 let attrs = cx.over(el.attrs.clone());
3578 let mut old_over = old_attrs.clone();
3580 old_over.set_insets(inst.root_insets_applied);
3581 let old_over = with_host(old_over, &inst.root_host_applied);
3582 if !self.apply_target_attrs(host, &attrs, &old_over, app) {
3583 self.apply_attrs_over(host, &attrs, &old_over, app);
3584 }
3585 inst.root_insets_applied = attrs.insets();
3586 inst.root_host_applied = cx.host.clone();
3587 let given_changed = std::mem::take(&mut inst.given_changed) || first;
3590 if cx.given
3591 && given_changed
3592 && attrs.inline == old_over.inline
3593 && attrs.animated() == old_over.animated()
3594 {
3595 let _ = self.apply_op(inline_style(
3596 host,
3597 attrs.inline.as_deref(),
3598 attrs.animated(),
3599 app,
3600 ));
3601 }
3602 let user = cx.user.clone();
3603 let top_js = cx.js;
3604 let given_events = cx.given_events;
3605 let classes = self.apply_el_styles(
3606 host,
3607 &el.style,
3608 &old_style,
3609 old_classes,
3610 el.attrs.class.as_ref(),
3611 user,
3612 );
3613 let text = self.reconcile_text(host, host, el.text.take(), old_text);
3614 if bound.is_some() {
3615 Self::keep_bound(
3616 inst,
3617 host,
3618 &el.attrs,
3619 &el.style,
3620 classes.clone(),
3621 text.clone(),
3622 );
3623 }
3624 let js = top_js.unwrap_or(inst.js_events) | given_events;
3627 self.apply_handlers(host, host, &el, old_events | js, js, inst);
3628 let mut events = EventMask::default();
3629 for (kind, _) in &el.handlers {
3630 events.set(*kind, true);
3631 }
3632 events.set(
3633 EventKind::Touch,
3634 events.contains(EventKind::Touch) || el.responder.is_some(),
3635 );
3636 let new_children = std::mem::take(&mut el.children);
3637 let children = self.reconcile_children(host, old_children, new_children, host, inst);
3638 let (list, part) = match std::mem::replace(&mut el.kind, ElKind::Plain) {
3639 ElKind::VirtualList(list) => {
3640 let config = list.config;
3641 let old_list = applied_layout.unwrap_or(old_list);
3642 self.update_virtual_list(self.native_id(host), host, *list, &old_list);
3643 (Some(Box::new(config)), Part::VirtualList)
3644 }
3645 _ => (None, Part::Node),
3646 };
3647 inst.root = Some(Expanded {
3648 id: host,
3649 tag: el.tag,
3650 key: None,
3651 text,
3652 attrs: el.attrs,
3653 style: el.style,
3654 classes,
3655 events,
3656 list,
3657 part,
3658 children,
3659 });
3660 self.children_placed(host, inst, old_place);
3661 }
3662
3663 fn expand_rooted(&mut self, host: NodeId, inst: &mut Instance, el: ElNode) {
3669 let ElKind::Component(c) = &el.kind else {
3670 return;
3671 };
3672 let part = Part::Component(c.name);
3673 inst.handlers.clear();
3674 inst.event_handlers.clear();
3675 inst.responders.clear();
3676 let old_place = std::mem::replace(&mut inst.children_at, Placement::None);
3677 let prev = match inst.root.take() {
3678 Some(old) if old.part == part => old,
3679 old => {
3680 if let Some(old) = old {
3681 self.release_expanded(old);
3682 }
3683 let id = self.components.alloc();
3684 if let Err(e) = self.alias(id, host) {
3685 log::error!(target: "js", "a view's root component is not made: {e:?}");
3686 return;
3687 }
3688 self.components.owners.insert(id, host);
3689 self.create_instance_for(id, c);
3690 if let Some(rooted) = self.components.instances.get_mut(&id) {
3691 rooted.app_style = None;
3693 rooted.above = Some(host);
3694 }
3695 Expanded::js(id, part)
3696 }
3697 };
3698 inst.rooted = Some(prev.id);
3699 let root = self.reconcile_node(Some(prev), el, part, host, inst);
3700 inst.root = Some(root);
3701 self.children_placed(host, inst, old_place);
3702 }
3703
3704 pub(super) fn base_of(&self, id: NodeId) -> NodeId {
3707 let mut at = id;
3708 while let Some(next) = self.components.instances.get(&at).and_then(|i| i.rooted) {
3709 at = next;
3710 }
3711 at
3712 }
3713
3714 pub(super) fn root_context(&mut self, inst: &Instance) -> RootContext {
3719 let mut cx = RootContext {
3720 user: inst.user.clone(),
3721 combined: false,
3722 app: None,
3723 js: None,
3724 given_events: inst.given_events,
3725 inset_padding: None,
3726 inset_margin: None,
3727 host: Vec::new(),
3728 given: false,
3729 };
3730 if inst.above.is_none() && inst.given.is_none() {
3731 cx.host.clone_from(&inst.js_host);
3732 return cx;
3733 }
3734 cx.combined = true;
3735 let mut decls: Vec<crate::StyleDecl> = Vec::new();
3736 let mut take = |cx: &mut RootContext, given: &Attrs| {
3737 cx.given = true;
3738 if let Some(inline) = &given.inline {
3739 decls.extend(inline.decls().iter().cloned());
3740 }
3741 if let Some(r) = &given.rare {
3742 decls.extend(r.animated.iter().map(|(d, _)| d.clone()));
3743 cx.inset_padding = r.inset_padding.or(cx.inset_padding);
3744 cx.inset_margin = r.inset_margin.or(cx.inset_margin);
3745 }
3746 given_host(given, &mut cx.host);
3747 };
3748 if let Some(given) = &inst.given {
3749 take(&mut cx, given);
3750 }
3751 if let Some(class) = inst.given.as_ref().and_then(|g| g.class.clone()) {
3754 let given = self.app_class_list(&class);
3755 cx.user = self.merge_user(cx.user.take(), Some(given));
3756 }
3757 let mut app = inst.app_style.clone();
3758 let mut js_host = None;
3760 let mut at = inst.above;
3761 while let Some(id) = at {
3762 let Some(above) = self.components.instances.get(&id) else {
3763 break;
3764 };
3765 let (outer, given) = (above.user.clone(), above.given.clone());
3766 app = above.app_style.clone();
3767 js_host = Some(above.js_host.clone());
3768 cx.js = Some(above.js_events);
3769 cx.given_events = cx.given_events | above.given_events;
3770 at = above.above;
3771 if let Some(given) = &given {
3772 take(&mut cx, given);
3773 }
3774 cx.user = self.merge_user(cx.user.take(), outer);
3775 if let Some(class) = given.and_then(|g| g.class.clone()) {
3776 let given = self.app_class_list(&class);
3777 cx.user = self.merge_user(cx.user.take(), Some(given));
3778 }
3779 }
3780 for prop in js_host.as_ref().unwrap_or(&inst.js_host) {
3781 give_host(&mut cx.host, prop.clone());
3782 }
3783 if let Some(app) = &app {
3784 decls.extend(app.decls().iter().cloned());
3785 }
3786 if !decls.is_empty() {
3787 let mut style = crate::Style::default();
3788 let mut patch = crate::StylePatch::default();
3789 for decl in decls {
3790 let _ = patch.push(&mut style, decl);
3791 }
3792 cx.app = Some(patch);
3793 }
3794 cx
3795 }
3796
3797 pub(super) fn root_context_of(&mut self, host: NodeId) -> Option<RootContext> {
3799 let inst = self.components.instances.remove(&host)?;
3800 let cx = self.root_context(&inst);
3801 self.components.instances.insert(host, inst);
3802 Some(cx)
3803 }
3804
3805 pub(super) fn set_given(&mut self, host: NodeId, mut attrs: Attrs) {
3808 attrs.set_element_ref(None);
3809 let given = (attrs != Attrs::default()).then(|| Box::new(attrs));
3810 let Some(inst) = self.components.instances.get_mut(&host) else {
3811 return;
3812 };
3813 if inst.given != given {
3814 inst.given = given;
3815 inst.given_changed = true;
3816 self.components.mark(host);
3817 }
3818 }
3819
3820 pub(super) fn merge_user(
3822 &mut self,
3823 inner: Option<std::rc::Rc<ClassList>>,
3824 outer: Option<std::rc::Rc<ClassList>>,
3825 ) -> Option<std::rc::Rc<ClassList>> {
3826 match (inner, outer) {
3827 (Some(a), Some(b)) => {
3828 let key = (
3829 std::rc::Rc::as_ptr(&a) as usize,
3830 std::rc::Rc::as_ptr(&b) as usize,
3831 );
3832 if let Some([_, _, merged]) = self.components.merges.get(&key) {
3833 return Some(merged.clone());
3834 }
3835 if self.components.merges.len() >= STYLE_CACHE {
3836 self.components.merges.clear();
3837 }
3838 let merged = std::rc::Rc::new(a.merged(&b));
3839 self.components.merges.insert(key, [a, b, merged.clone()]);
3840 Some(merged)
3841 }
3842 (a, None) => a,
3843 (None, b) => b,
3844 }
3845 }
3846
3847 pub(super) fn children_placed(
3851 &mut self,
3852 host: NodeId,
3853 inst: &mut Instance,
3854 old_place: Placement,
3855 ) {
3856 if inst.children_at == Placement::None && old_place != Placement::None {
3858 for &child in &inst.js_children {
3859 self.unplace(old_place, child);
3860 }
3861 }
3862 let wanted = inst.children_at != Placement::None;
3865 if inst.children_wanted != wanted && inst.spec.as_ref().is_some_and(|s| s.lazy_children) {
3866 inst.children_wanted = wanted;
3867 match self.components.owners.get(&host).copied() {
3868 Some(_) => {
3876 if let Some(signal) = inst.lazy_wanted {
3877 signal.try_set(wanted);
3878 }
3879 }
3880 None => self.events.push(JsEvent::Children { host, wanted }),
3881 }
3882 }
3883 }
3884
3885 fn children_wanted_signal(&mut self, nested: NodeId) -> crate::element::Signal<bool> {
3889 let Some(inst) = self.components.instances.get_mut(&nested) else {
3890 return crate::element::signal(false);
3891 };
3892 match inst.lazy_wanted {
3896 Some(signal) if signal.is_live() => signal,
3897 _ => {
3898 let signal = crate::element::signal(inst.children_wanted);
3899 inst.lazy_wanted = Some(signal);
3900 signal
3901 }
3902 }
3903 }
3904
3905 fn unplace(&mut self, place: Placement, child: NodeId) {
3908 match place {
3909 Placement::Nested(nested, _) if self.is_host(nested) => {
3910 let _ = self.intercept(Op::Remove {
3911 parent: nested,
3912 child,
3913 });
3914 }
3915 _ => self.detach_id(child),
3916 }
3917 }
3918
3919 pub(super) fn detach_id(&mut self, id: NodeId) {
3920 self.unfold_run(id);
3921 if let Ok(key) = self.key(id)
3922 && self.nodes[key as usize].parent != NO_KEY
3923 {
3924 self.detach(key);
3925 }
3926 }
3927
3928 pub(super) fn apply_attrs(&mut self, id: NodeId, new: &Attrs, old: &Attrs) {
3929 self.apply_attrs_over(id, new, old, None);
3930 }
3931
3932 pub(super) fn apply_attrs_over(
3935 &mut self,
3936 id: NodeId,
3937 new: &Attrs,
3938 old: &Attrs,
3939 app: Option<&crate::StylePatch>,
3940 ) {
3941 let node = self.native_id(id);
3943 let has_rare = new.rare.is_some() || old.rare.is_some();
3944 if has_rare {
3945 let empty = crate::element::builder::RareAttrs::default();
3946 let nr = new.rare.as_deref().unwrap_or(&empty);
3947 let or = old.rare.as_deref().unwrap_or(&empty);
3948 if or.element_ref != nr.element_ref
3949 && let Some(r) = &or.element_ref
3950 {
3951 r.detach(node);
3952 }
3953 if let Some(r) = &nr.element_ref {
3954 r.attach(node);
3955 }
3956 if nr.render != or.render {
3957 self.update_render(node, or.render.as_ref(), nr.render.as_ref());
3958 }
3959 }
3960 let mut props = std::mem::take(&mut self.components.props);
3961 new.changes(old, &mut props);
3962 for prop in props.drain(..) {
3963 let _ = self.apply_op(Op::SetProp { id, prop });
3964 }
3965 self.components.props = props;
3966 let animated_changed = has_rare && new.animated() != old.animated();
3967 if new.inline != old.inline || animated_changed {
3968 let _ = self.apply_op(inline_style(id, new.inline.as_deref(), new.animated(), app));
3969 }
3970 if has_rare {
3971 let empty = crate::element::builder::RareAttrs::default();
3972 let nr = new.rare.as_deref().unwrap_or(&empty);
3973 let or = old.rare.as_deref().unwrap_or(&empty);
3974 if nr.drawing != or.drawing
3975 && let Some(drawing) = &nr.drawing
3976 {
3977 let _ = self.apply_op(Op::Draw {
3978 id,
3979 drawing: Box::new((**drawing).clone()),
3980 });
3981 }
3982 if nr.window != or.window
3983 && let Some(window) = &nr.window
3984 {
3985 let command = if or.window.is_none() {
3988 crate::desktop::DesktopCommand::OpenWindow(Box::new(
3989 crate::desktop::OpenWindow {
3990 options: (**window).clone(),
3991 ..Default::default()
3992 },
3993 ))
3994 } else {
3995 crate::desktop::DesktopCommand::SetAttributes(Box::new(
3996 window.attributes.clone(),
3997 ))
3998 };
3999 let opens = or.window.is_none();
4000 let _ = self.apply_op(Op::Command {
4001 id,
4002 command: crate::Command::Desktop(Box::new(command)),
4003 });
4004 if opens {
4007 for command in &nr.window_commands {
4008 let _ = self.apply_op(Op::Command {
4009 id,
4010 command: crate::Command::Desktop(Box::new(command.clone())),
4011 });
4012 }
4013 }
4014 }
4015 }
4016 }
4017
4018 pub(super) fn apply_styles(
4020 &mut self,
4021 id: NodeId,
4022 style: &StyleRefinement,
4023 old_style: &StyleRefinement,
4024 old: Classes,
4025 user: Option<std::rc::Rc<ClassList>>,
4026 ) -> Classes {
4027 let own = if style == old_style {
4028 old.0.clone()
4029 } else if style.is_empty() {
4030 None
4031 } else {
4032 Some(self.components.lowered(style))
4033 };
4034 if !same(&own, &old.0) || !same(&user, &old.1) {
4035 let list = self.merge_user(own.clone(), user.clone());
4036 if let Ok(key) = self.key(id) {
4037 self.set_class_list(key, list);
4038 }
4039 }
4040 (own, user)
4041 }
4042
4043 pub(super) fn apply_el_styles(
4048 &mut self,
4049 id: NodeId,
4050 style: &StyleRefinement,
4051 old_style: &StyleRefinement,
4052 old: Classes,
4053 class: Option<&SharedString>,
4054 outer: Option<std::rc::Rc<ClassList>>,
4055 ) -> Classes {
4056 let Some(class) = class.filter(|c| !c.trim().is_empty()) else {
4057 if !self.components.app_classes.is_empty() {
4058 self.components.app_classes.remove(&id);
4059 }
4060 return self.apply_styles(id, style, old_style, old, outer);
4061 };
4062 let app = self.app_class_list(class);
4063 let user = self.merge_user(Some(app), outer.clone());
4064 let classes = self.apply_styles(id, style, old_style, old, user);
4065 self.components
4066 .app_classes
4067 .insert(id, (classes.0.clone(), class.clone(), outer));
4068 classes
4069 }
4070
4071 pub(super) fn app_class_list(&mut self, class: &str) -> std::rc::Rc<ClassList> {
4074 let (list, fresh) = self.tailwind.get(class);
4075 if fresh && !list.unknown().is_empty() {
4076 log::warn!(
4077 "unknown classes: {}",
4078 list.unknown()
4079 .iter()
4080 .map(|s| &**s)
4081 .collect::<Vec<_>>()
4082 .join(" ")
4083 );
4084 }
4085 list
4086 }
4087
4088 #[allow(
4091 clippy::too_many_arguments,
4092 reason = "the installed node and its owning view"
4093 )]
4094 fn apply_handlers(
4095 &mut self,
4096 host: NodeId,
4097 id: NodeId,
4098 el: &ElNode,
4099 old: EventMask,
4100 extra: EventMask,
4101 inst: &mut Instance,
4102 ) -> EventMask {
4103 let mut mask = extra;
4104 self.initialize_layout_listeners(host, id, el, old, inst);
4105 if old.bits() != 0 {
4108 inst.handlers.remove(id);
4109 inst.responders.retain(|(n, _)| *n != id);
4110 }
4111 for (kind, handler) in &el.handlers {
4112 mask.set(*kind, true);
4113 inst.handlers.push(id, *kind, handler.clone());
4114 }
4115 if let Some(responder) = &el.responder {
4117 mask.set(EventKind::Touch, true);
4118 inst.responders.push((id, responder.clone()));
4119 }
4120 let own = self.target_events(id, mask);
4123 let mut changed = (mask.bits() ^ old.bits()) & !own.bits();
4124 while changed != 0 {
4125 let kind = EventKind::ALL[changed.trailing_zeros() as usize];
4126 changed &= changed - 1;
4127 let _ = self.apply_op(Op::Listen {
4128 id,
4129 event: kind,
4130 enabled: mask.contains(kind),
4131 });
4132 }
4133 mask
4134 }
4135
4136 pub(super) fn initialize_layout_listeners(
4138 &mut self,
4139 host: NodeId,
4140 id: NodeId,
4141 el: &ElNode,
4142 old: EventMask,
4143 inst: &Instance,
4144 ) {
4145 if old.contains(EventKind::Layout)
4148 && let Ok(key) = self.key(id)
4149 {
4150 let frame = self.nodes[key as usize].frame;
4151 if !frame.origin.x.0.is_nan() {
4152 for (kind, listener) in &el.handlers {
4153 if *kind == EventKind::Layout
4154 && !inst
4155 .handlers
4156 .of(id)
4157 .iter()
4158 .any(|(k, old)| *k == *kind && old.same_owner(listener))
4159 {
4160 self.events.push(JsEvent::LayoutListener {
4161 host,
4162 id,
4163 listener: listener.clone(),
4164 frame,
4165 });
4166 }
4167 }
4168 }
4169 }
4170 }
4171
4172 fn reconcile_children(
4173 &mut self,
4174 parent: NodeId,
4175 old: Vec<Expanded>,
4176 new: Vec<ElNode>,
4177 host: NodeId,
4178 inst: &mut Instance,
4179 ) -> Vec<Expanded> {
4180 if new.is_empty() && old.is_empty() {
4181 return Vec::new();
4182 }
4183 let new = new.into_iter().map(|el| NewChild::Made(None, el)).collect();
4184 let (out, placeholder) = self.match_children(parent, old, new, host, inst);
4185 self.set_region_anchors(&out, inst, Anchor::End);
4187 let nested = parent != host && self.is_host(parent);
4188 if nested {
4189 if let Some(at) = placeholder {
4190 let anchor = self.anchor_after(&out[at + 1..], inst, Anchor::End);
4191 inst.children_at = Placement::Nested(parent, anchor);
4192 }
4193 self.place_filled(&out, inst, Anchor::End, |anchor| {
4194 Placement::Nested(parent, anchor)
4195 });
4196 self.fill_nested(parent, &out, host, inst);
4197 self.join_nested(parent, &out, inst);
4198 return out;
4199 }
4200 if let Some(at) = placeholder {
4201 let anchor = self.anchor_after(&out[at + 1..], inst, Anchor::End);
4202 inst.children_at = Placement::At(parent, anchor);
4203 }
4204 self.place_filled(&out, inst, Anchor::End, |anchor| {
4205 Placement::At(parent, anchor)
4206 });
4207 let wanted_ids: Vec<NodeId> = out
4211 .iter()
4212 .flat_map(|e| match e.part {
4213 Part::Children => inst.js_children.clone(),
4214 Part::Filled(name) => self
4215 .fill_of(inst, name)
4216 .map(|f| self.fill_nodes(f))
4217 .unwrap_or_default(),
4218 Part::Region(region) => self.region_nodes(region),
4219 _ => vec![e.id],
4220 })
4221 .collect();
4222 let wanted = || wanted_ids.iter();
4223 if self.is_list(parent) {
4226 for e in out.iter().filter(|e| e.id != 0) {
4228 let joined = self
4229 .key(e.id)
4230 .is_ok_and(|k| self.nodes[k as usize].parent != NO_KEY);
4231 if !joined {
4232 let _ = self.apply_op(Op::Insert {
4233 parent,
4234 child: e.id,
4235 before: None,
4236 });
4237 }
4238 }
4239 return out;
4240 }
4241 let in_order = self.key(parent).is_ok_and(|k| {
4242 let have = &self.nodes[k as usize].children;
4243 have.len() == wanted().count()
4244 && have
4245 .iter()
4246 .zip(wanted())
4247 .all(|(&c, &id)| self.nodes[c as usize].id == id)
4248 });
4249 if !in_order {
4250 let ids: Vec<NodeId> = wanted().copied().collect();
4256 let empty = self
4259 .key(parent)
4260 .is_ok_and(|k| self.nodes[k as usize].children.is_empty());
4261 if empty {
4262 for &child in &ids {
4263 let _ = self.apply_op(Op::Insert {
4264 parent,
4265 child,
4266 before: None,
4267 });
4268 }
4269 return out;
4270 }
4271 let mut before = None;
4272 for &child in ids.iter().rev() {
4273 if !self.precedes(parent, child, before) {
4274 let _ = self.apply_op(Op::Insert {
4275 parent,
4276 child,
4277 before,
4278 });
4279 }
4280 before = Some(child);
4281 }
4282 }
4283 out
4284 }
4285
4286 pub(super) fn match_children(
4290 &mut self,
4291 parent: NodeId,
4292 old: Vec<Expanded>,
4293 new: Vec<NewChild>,
4294 host: NodeId,
4295 inst: &mut Instance,
4296 ) -> (Vec<Expanded>, Option<usize>) {
4297 let new = if new.iter().any(
4300 |child| matches!(child, NewChild::Made(_, e) if matches!(e.kind, ElKind::EachChild(_))),
4301 ) {
4302 let mut each = Vec::with_capacity(new.len() + inst.js_children.len());
4303 for child in new {
4304 let NewChild::Made(owner, el) = child else {
4305 each.push(child);
4306 continue;
4307 };
4308 let ElKind::EachChild(place) = &el.kind else {
4309 each.push(NewChild::Made(owner, el));
4310 continue;
4311 };
4312 if inst.children_at != Placement::None {
4313 log::error!(target: "js", "a view places its children once");
4314 continue;
4315 }
4316 inst.children_at = Placement::Each;
4317 {
4318 let children = match inst.js_kids {
4319 Some(children) => children,
4320 None => *inst.js_kids.insert(crate::element::signal_with(
4321 inst.js_kids(),
4322 crate::element::SignalEquals::Never,
4323 )),
4324 };
4325 let place = place.clone();
4328 let count = crate::element::computed(move || children.with(Vec::len));
4329 let region = crate::element::each(
4330 children,
4331 |&(child, _): &(NodeId, bool)| child,
4332 move |child, index| {
4333 let at = Position::of(index.node(), count.node());
4334 let (child, text) = child.get_untracked();
4335 place(Child::js(child, text), at)
4336 },
4337 );
4338 each.push(NewChild::Made(owner, region.0));
4339 }
4340 }
4341 each
4342 } else {
4343 new
4344 };
4345 let mut old: Vec<Option<Expanded>> = old.into_iter().map(Some).collect();
4346 let mut out = Vec::with_capacity(new.len());
4347 let mut placeholder = None;
4348 let mut cursor = 0;
4352 let mut after_kept = 0;
4356 let mut keys = OldKeys::default();
4359 for child in new {
4360 let (owner, el) = match child {
4361 NewChild::Made(owner, el) => (owner, el),
4362 NewChild::Kept(key) => {
4365 let is = |o: &Option<Expanded>| {
4366 o.as_ref().is_some_and(|o| o.key.as_ref() == Some(&key))
4367 };
4368 let at = if old.get(after_kept).is_some_and(is) {
4369 Some(after_kept)
4370 } else {
4371 keys.find(&old, &key, |_| true)
4372 };
4373 match at.and_then(|at| {
4374 after_kept = at + 1;
4375 old[at].take()
4376 }) {
4377 Some(e) => out.push(e),
4378 None => log::error!("a kept row is gone"),
4379 }
4380 continue;
4381 }
4382 };
4383 let child = |core: &mut Self| {
4384 core.match_child(
4385 parent,
4386 el,
4387 host,
4388 inst,
4389 &mut old,
4390 &mut out,
4391 &mut placeholder,
4392 &mut cursor,
4393 &mut keys,
4394 );
4395 };
4396 match owner {
4397 Some(owner) => owner.run(|| child(self)),
4398 None => child(self),
4399 }
4400 }
4401 let nested = parent != host && self.is_host(parent);
4405 for o in old.into_iter().flatten() {
4406 self.unplace_filled(&o, inst);
4409 if nested && o.part == Part::Children {
4410 for &child in &inst.js_children {
4412 let _ = self.intercept(Op::Remove { parent, child });
4413 }
4414 } else if nested {
4415 for node in self.placed(&o) {
4416 self.forget_nested(parent, node);
4417 }
4418 }
4419 self.release_expanded(o);
4420 }
4421 (out, placeholder)
4422 }
4423
4424 #[allow(clippy::too_many_arguments, reason = "the matching's state")]
4427 fn match_child(
4428 &mut self,
4429 parent: NodeId,
4430 mut el: ElNode,
4431 host: NodeId,
4432 inst: &mut Instance,
4433 old: &mut [Option<Expanded>],
4434 out: &mut Vec<Expanded>,
4435 placeholder: &mut Option<usize>,
4436 cursor: &mut usize,
4437 keys: &mut OldKeys,
4438 ) {
4439 let mut wrapper = false;
4444 if let ElKind::Slot(name) = el.kind
4445 && inst.fills.iter().any(|f| f.name == name)
4446 {
4447 if is_plain(&el) {
4448 el.kind = ElKind::Filled(name);
4449 } else {
4450 el.kind = ElKind::Plain;
4451 let mut filled = ElNode::new(Tag::View);
4452 filled.kind = ElKind::Filled(name);
4453 el.children = vec![filled];
4454 el.key.get_or_insert_with(|| format!("slot:{name}").into());
4455 wrapper = true;
4456 }
4457 }
4458 match std::mem::replace(&mut el.kind, ElKind::Plain) {
4459 ElKind::Filled(name) => {
4460 if let Some(j) = old
4461 .iter()
4462 .position(|o| o.as_ref().is_some_and(|o| o.part == Part::Filled(name)))
4463 {
4464 old[j] = None;
4465 }
4466 out.push(Expanded::js(0, Part::Filled(name)));
4467 }
4468 ElKind::Fill(name) => {
4469 let prev = old
4472 .iter()
4473 .position(|o| o.as_ref().is_some_and(|o| o.part == Part::Fill(name)))
4474 .and_then(|j| old[j].take());
4475 let old_children = prev.map(|p| p.children).unwrap_or_default();
4476 let new = std::mem::take(&mut el.children)
4477 .into_iter()
4478 .map(|c| NewChild::Made(None, c))
4479 .collect();
4480 let filling = self.components.filling.replace((parent, name));
4481 let (children, _) = self.match_children(parent, old_children, new, host, inst);
4482 self.components.filling = filling;
4483 let mut e = Expanded::js(0, Part::Fill(name));
4484 e.children = children;
4485 out.push(e);
4486 }
4487 ElKind::Slot(name) => {
4488 let Some(&(_, node)) = inst.slots.iter().find(|(s, _)| *s == name) else {
4490 return;
4491 };
4492 let at = old.iter().position(|o| {
4493 o.as_ref()
4494 .is_some_and(|o| o.part == Part::Slot && o.id == node)
4495 });
4496 let prev = at.and_then(|j| old[j].take());
4497 out.push(self.reconcile_slot(prev, node, el, host, inst));
4498 }
4499 ElKind::Children => {
4500 if placeholder.is_some() || inst.children_at != Placement::None {
4501 log::error!(target: "js", "a view places its children once");
4502 return;
4503 }
4504 if let Some(j) = old
4505 .iter()
4506 .position(|o| o.as_ref().is_some_and(|o| o.part == Part::Children))
4507 {
4508 old[j] = None;
4509 }
4510 *placeholder = Some(out.len());
4511 inst.children_owner = Some(crate::element::Owner::current());
4512 out.push(Expanded::js(0, Part::Children));
4513 }
4514 ElKind::JsChild(id) => {
4515 if let Some(j) = old.iter().position(|o| {
4517 o.as_ref()
4518 .is_some_and(|o| o.part == Part::JsChild && o.id == id)
4519 }) {
4520 old[j] = None;
4521 }
4522 if inst.js_children.contains(&id) {
4523 out.push(Expanded::js(id, Part::JsChild));
4524 }
4525 }
4526 ElKind::EachChild(_) => {}
4528 ElKind::Region(region) => {
4530 let id = self.bind_region(host, parent, region);
4531 let mut e = super::views::region_placeholder(id);
4532 e.key = el.key;
4535 out.push(e);
4536 }
4537 ElKind::List(list) => {
4538 let Some(&(_, node)) = inst.slots.iter().find(|(s, _)| *s == list.name) else {
4541 return;
4542 };
4543 let at = old.iter().position(|o| {
4544 o.as_ref()
4545 .is_some_and(|o| o.part == Part::Slot && o.id == node)
4546 });
4547 let prev = at.and_then(|j| old[j].take());
4548 let old_config = self
4549 .components
4550 .list_layouts
4551 .remove(&node)
4552 .or_else(|| prev.as_ref().and_then(|p| p.list.as_deref().copied()))
4553 .unwrap_or_default();
4554 let parts = std::mem::take(&mut el.bound_list);
4556 let config = if parts.is_empty() {
4557 list.config
4558 } else {
4559 self.bind_list_layout(node, list.config, parts)
4560 };
4561 let mut props = std::mem::take(&mut self.components.props);
4562 config.changes(&old_config, &mut props);
4563 for prop in props.drain(..) {
4564 let _ = self.apply_op(Op::SetProp { id: node, prop });
4565 }
4566 self.components.props = props;
4567 let mut e = self.reconcile_slot(prev, node, el, host, inst);
4568 e.list = Some(Box::new(config));
4569 let rows = self.rows_of_list(node);
4570 self.components.lists.insert(node, (list.row.clone(), rows));
4571 if let Some(state) = self.components.virtual_lists.get_mut(&node) {
4574 state.place = Some(list.row.clone());
4575 }
4576 let cells: Vec<NodeId> = match self.key(node) {
4577 Ok(k) => self.nodes[k as usize]
4578 .children
4579 .iter()
4580 .map(|&c| self.nodes[c as usize].id)
4581 .collect(),
4582 Err(_) => Vec::new(),
4583 };
4584 for cell in cells {
4585 self.wrap_row(cell, list.row.clone());
4586 }
4587 out.push(e);
4588 }
4589 kind => {
4590 el.kind = kind;
4591 let part = match &el.kind {
4592 ElKind::Component(c) => Part::Component(c.name),
4593 ElKind::VirtualList(_) => Part::VirtualList,
4594 ElKind::Raw => Part::Raw,
4595 _ => Part::Node,
4596 };
4597 let component = matches!(part, Part::Component(_));
4601 let matches = |o: &Expanded| !component && o.tag == el.tag && o.part == part;
4602 let at = match &el.key {
4603 Some(k) => keys.find(old, k, matches),
4604 None => {
4605 let at = old[(*cursor).min(old.len())..]
4606 .iter()
4607 .position(|o| o.as_ref().is_some_and(|o| o.key.is_none() && matches(o)))
4608 .map(|j| j + *cursor);
4609 if let Some(j) = at {
4610 *cursor = j + 1;
4611 }
4612 at
4613 }
4614 };
4615 let prev = at.and_then(|j| old[j].take());
4616 let e = if wrapper {
4617 self.reconcile_wrapper(prev, el, host, inst)
4618 } else {
4619 self.reconcile_node(prev, el, part, host, inst)
4620 };
4621 out.push(e);
4622 }
4623 }
4624 }
4625
4626 pub(super) fn nested_precedes(
4629 &self,
4630 nested: NodeId,
4631 child: NodeId,
4632 next: Option<NodeId>,
4633 ) -> bool {
4634 let Some(inst) = self.components.instances.get(&nested) else {
4635 return false;
4636 };
4637 let kids = &inst.js_children;
4638 kids.iter()
4639 .position(|&c| c == child)
4640 .is_some_and(|i| kids.get(i + 1).copied() == next)
4641 }
4642
4643 pub(super) fn join_nested_at(&mut self, nested: NodeId, child: NodeId, before: Option<NodeId>) {
4646 if let Ok(Some(op)) = self.intercept(Op::Insert {
4647 parent: nested,
4648 child,
4649 before,
4650 }) {
4651 let _ = self.apply_op(op);
4652 }
4653 }
4654
4655 fn forget_nested(&mut self, nested: NodeId, child: NodeId) {
4660 if self.components.slot_names.remove(&child).is_some() {
4661 self.unslot(child);
4662 return;
4663 }
4664 let Some(inst) = self.components.instances.get_mut(&nested) else {
4665 return;
4666 };
4667 let count = inst.js_children.len();
4668 inst.forget_js_child(child);
4669 if inst.js_children.len() == count {
4670 return;
4671 }
4672 inst.js_children_changed();
4673 let place = inst.children_at;
4674 if inst.js_children.is_empty() || place == Placement::Each {
4675 self.components.mark(nested);
4676 }
4677 if let Placement::Nested(deeper, _) = place
4679 && self.is_host(deeper)
4680 {
4681 self.forget_nested(deeper, child);
4682 }
4683 }
4684
4685 fn join_nested(&mut self, nested: NodeId, out: &[Expanded], inst: &Instance) {
4690 let insert = |core: &mut Self, child: NodeId, before: Option<NodeId>| {
4691 if let Ok(Some(op)) = core.intercept(Op::Insert {
4692 parent: nested,
4693 child,
4694 before,
4695 }) {
4696 let _ = core.apply_op(op);
4697 }
4698 };
4699 let (slots, children): (Vec<NodeId>, Vec<NodeId>) = out
4700 .iter()
4701 .flat_map(|e| match e.part {
4702 Part::Children => inst.js_children.clone(),
4703 Part::Filled(name) => self
4704 .fill_of(inst, name)
4705 .map(|f| self.fill_nodes(f))
4706 .unwrap_or_default(),
4707 Part::Fill(_) | Part::Tooltip => Vec::new(),
4709 _ => self.placed(e),
4710 })
4711 .partition(|id| self.components.slot_names.contains_key(id));
4712 for slot in slots {
4713 if self.components.slot_hosts.get(&slot) != Some(&nested) {
4714 insert(self, slot, None);
4715 }
4716 }
4717 let same = self
4718 .components
4719 .instances
4720 .get(&nested)
4721 .is_some_and(|i| i.js_children == children);
4722 if !same {
4723 let mut before = None;
4724 for &child in children.iter().rev() {
4725 insert(self, child, before);
4726 before = Some(child);
4727 }
4728 }
4729 }
4730
4731 pub(super) fn fill_of<'a>(&self, inst: &'a Instance, name: &'static str) -> Option<&'a Fill> {
4733 inst.fills.iter().find(|f| f.name == name)
4734 }
4735
4736 pub(super) fn fill_nodes(&self, fill: &Fill) -> Vec<NodeId> {
4738 self.fill_nodes_with(fill, None)
4739 }
4740
4741 fn fill_nodes_with(&self, fill: &Fill, out: Option<(NodeId, &Instance)>) -> Vec<NodeId> {
4744 let mut nodes = Vec::with_capacity(fill.parts.len());
4745 for part in &fill.parts {
4746 match *part {
4747 FillPart::Node(id) => nodes.push(id),
4748 FillPart::Region(region) => self.fill_region_nodes(region, out, &mut nodes),
4749 FillPart::Filled(name) => self.passed_nodes(fill.from, name, out, &mut nodes),
4750 }
4751 }
4752 nodes
4753 }
4754
4755 fn fill_region_nodes(
4758 &self,
4759 region: u32,
4760 out: Option<(NodeId, &Instance)>,
4761 nodes: &mut Vec<NodeId>,
4762 ) {
4763 let Some(state) = self.components.regions.get(®ion) else {
4764 return;
4765 };
4766 for e in &state.children {
4767 match e.part {
4768 Part::Filled(name) => self.passed_nodes(state.host, name, out, nodes),
4769 Part::Region(inner) => self.fill_region_nodes(inner, out, nodes),
4770 _ => nodes.extend(self.placed(e)),
4771 }
4772 }
4773 }
4774
4775 fn passed_nodes(
4778 &self,
4779 host: NodeId,
4780 name: &'static str,
4781 out: Option<(NodeId, &Instance)>,
4782 nodes: &mut Vec<NodeId>,
4783 ) {
4784 let inst = match out {
4785 Some((h, inst)) if h == host => Some(inst),
4786 _ => self.components.instances.get(&host).map(|i| &**i),
4787 };
4788 if let Some(fill) = inst.and_then(|i| self.fill_of(i, name)) {
4789 nodes.extend(self.fill_nodes_with(fill, out));
4790 }
4791 }
4792
4793 fn passed_slots(&self, parts: &[FillPart], host: NodeId, names: &mut Vec<&'static str>) {
4796 fn of_region<M: TextEngine>(
4797 core: &Core<M>,
4798 region: u32,
4799 host: NodeId,
4800 names: &mut Vec<&'static str>,
4801 ) {
4802 let Some(state) = core.components.regions.get(®ion) else {
4803 return;
4804 };
4805 for e in &state.children {
4806 match e.part {
4807 Part::Filled(name) if state.host == host => names.push(name),
4808 Part::Region(inner) => of_region(core, inner, host, names),
4809 _ => {}
4810 }
4811 }
4812 }
4813 for part in parts {
4814 match *part {
4815 FillPart::Filled(name) => names.push(name),
4816 FillPart::Region(region) => of_region(self, region, host, names),
4817 FillPart::Node(_) => {}
4818 }
4819 }
4820 }
4821
4822 pub(super) fn note_passed(
4825 &self,
4826 nested: NodeId,
4827 name: &'static str,
4828 host: NodeId,
4829 inst: &mut Instance,
4830 ) {
4831 let mut passed = Vec::new();
4832 if let Some(fill) = self
4833 .components
4834 .instances
4835 .get(&nested)
4836 .and_then(|t| self.fill_of(t, name))
4837 {
4838 self.passed_slots(&fill.parts, host, &mut passed);
4839 }
4840 for fill in &mut inst.fills {
4841 if passed.contains(&fill.name) {
4842 fill.forwarded = Some((nested, name));
4843 } else if fill.forwarded == Some((nested, name)) {
4844 fill.forwarded = None;
4845 }
4846 }
4847 }
4848
4849 pub(super) fn place_filled(
4852 &self,
4853 out: &[Expanded],
4854 inst: &mut Instance,
4855 end: Anchor,
4856 place: impl Fn(Anchor) -> Placement,
4857 ) {
4858 if inst.fills.is_empty() {
4859 return;
4860 }
4861 for (i, e) in out.iter().enumerate() {
4862 let Part::Filled(name) = e.part else {
4863 continue;
4864 };
4865 let at = place(self.anchor_after(&out[i + 1..], inst, end));
4866 if let Some(fill) = inst.fills.iter_mut().find(|f| f.name == name) {
4867 fill.at = at;
4868 }
4869 }
4870 }
4871
4872 pub(super) fn unplace_filled(&mut self, e: &Expanded, inst: &mut Instance) {
4875 if inst.fills.is_empty() {
4876 return;
4877 }
4878 match e.part {
4879 Part::Filled(name) => {
4880 let Some(fill) = inst.fills.iter_mut().find(|f| f.name == name) else {
4881 return;
4882 };
4883 let at = std::mem::replace(&mut fill.at, Placement::None);
4884 if at == Placement::None {
4885 return;
4886 }
4887 let nodes = self.fill_nodes(self.fill_of(inst, name).expect("a fill"));
4888 for node in nodes {
4889 self.unplace(at, node);
4890 }
4891 }
4892 Part::Region(region) => {
4893 let children = self
4894 .components
4895 .regions
4896 .get_mut(®ion)
4897 .map(|s| std::mem::take(&mut s.children))
4898 .unwrap_or_default();
4899 for c in &children {
4900 self.unplace_filled(c, inst);
4901 }
4902 if let Some(state) = self.components.regions.get_mut(®ion) {
4903 state.children = children;
4904 }
4905 }
4906 _ => {
4907 for c in &e.children {
4908 self.unplace_filled(c, inst);
4909 }
4910 }
4911 }
4912 }
4913
4914 fn fill_nested(&mut self, nested: NodeId, out: &[Expanded], host: NodeId, inst: &mut Instance) {
4920 let fills: Vec<(&'static str, Vec<FillPart>)> = out
4921 .iter()
4922 .filter_map(|e| match e.part {
4923 Part::Fill(name) => Some((
4924 name,
4925 e.children
4926 .iter()
4927 .filter_map(|c| match c.part {
4928 Part::Region(region) => Some(FillPart::Region(region)),
4929 Part::Filled(name) => Some(FillPart::Filled(name)),
4930 _ if c.id != 0 => Some(FillPart::Node(c.id)),
4931 _ => None,
4932 })
4933 .collect(),
4934 )),
4935 _ => None,
4936 })
4937 .collect();
4938 for fill in &mut inst.fills {
4940 if fill.forwarded.is_some_and(|(n, _)| n == nested) {
4941 fill.forwarded = None;
4942 }
4943 }
4944 for (name, parts) in &fills {
4945 let mut passed = Vec::new();
4946 self.passed_slots(parts, host, &mut passed);
4947 for fill in inst.fills.iter_mut().filter(|f| passed.contains(&f.name)) {
4948 fill.forwarded = Some((nested, name));
4949 }
4950 }
4951 let Some(target) = self.components.instances.get_mut(&nested) else {
4952 return;
4953 };
4954 if fills.is_empty() && target.fills.is_empty() {
4955 return;
4956 }
4957 let mut changed = target.fills.len() != fills.len();
4958 let old = std::mem::take(&mut target.fills);
4959 let mut joining = Vec::new();
4960 for (name, parts) in fills {
4961 let (at, forwarded, same) = match old.iter().find(|f| f.name == name) {
4962 Some(f) => (f.at, f.forwarded, f.parts == parts),
4963 None => (Placement::None, None, false),
4964 };
4965 changed |= !same;
4966 if !same {
4967 joining.push(name);
4968 }
4969 target.fills.push(Fill {
4970 name,
4971 parts,
4972 from: host,
4973 at,
4974 forwarded,
4975 });
4976 }
4977 if !changed {
4978 return;
4979 }
4980 let out = Some((host, &*inst));
4983 let mut leaving = Vec::new();
4984 for fill in &old {
4985 let at = self.fill_place(nested, fill.name);
4986 let now = self
4987 .components
4988 .instances
4989 .get(&nested)
4990 .and_then(|t| self.fill_of(t, fill.name))
4991 .map(|f| self.fill_nodes_with(f, out))
4992 .unwrap_or_default();
4993 for node in self.fill_nodes_with(fill, out) {
4994 if !now.contains(&node) && self.key(node).is_ok() {
4995 leaving.push((at, node));
4996 }
4997 }
4998 }
4999 for (at, node) in leaving {
5000 self.unplace(at, node);
5001 }
5002 for name in joining {
5003 self.join_fill(nested, name, out);
5004 }
5005 self.components.mark(nested);
5007 let names: Vec<&'static str> = self.components.instances[&nested]
5008 .fills
5009 .iter()
5010 .map(|f| f.name)
5011 .collect();
5012 for name in names {
5013 self.place_fill_with(nested, name, Some((host, &*inst)));
5014 }
5015 }
5016
5017 pub(super) fn join_fill(
5023 &mut self,
5024 nested: NodeId,
5025 name: &'static str,
5026 out: Option<(NodeId, &Instance)>,
5027 ) {
5028 let nodes = self
5029 .components
5030 .instances
5031 .get(&nested)
5032 .and_then(|inst| self.fill_of(inst, name))
5033 .map(|fill| self.fill_nodes_with(fill, out))
5034 .unwrap_or_default();
5035 for node in nodes {
5036 self.join_content(node);
5037 }
5038 }
5039
5040 fn fill_place(&self, nested: NodeId, name: &'static str) -> Placement {
5044 let Some(fill) = self
5045 .components
5046 .instances
5047 .get(&nested)
5048 .and_then(|inst| self.fill_of(inst, name))
5049 else {
5050 return Placement::None;
5051 };
5052 match (fill.at, fill.forwarded) {
5053 (Placement::None, Some((deeper, slot))) => self.fill_place(deeper, slot),
5054 (at, _) => at,
5055 }
5056 }
5057
5058 pub(super) fn place_fill(&mut self, nested: NodeId, name: &'static str) {
5062 self.place_fill_with(nested, name, None);
5063 }
5064
5065 fn place_fill_with(
5068 &mut self,
5069 nested: NodeId,
5070 name: &'static str,
5071 out: Option<(NodeId, &Instance)>,
5072 ) {
5073 let Some(fill) = self
5074 .components
5075 .instances
5076 .get(&nested)
5077 .and_then(|inst| self.fill_of(inst, name))
5078 else {
5079 return;
5080 };
5081 let (nodes, at, forwarded) = (self.fill_nodes_with(fill, out), fill.at, fill.forwarded);
5082 if let Some((deeper, slot)) = forwarded {
5083 self.components.mark(deeper);
5086 self.place_fill_with(deeper, slot, out);
5087 }
5088 match at {
5089 Placement::At(parent, anchor) => {
5090 let parent_key = self.key(parent).ok();
5091 let mut before = self.anchor_node(anchor).filter(|&a| {
5093 self.key(a)
5094 .is_ok_and(|k| Some(self.nodes[k as usize].parent) == parent_key)
5095 });
5096 for &child in nodes.iter().rev() {
5097 if !self.precedes(parent, child, before) {
5098 let _ = self.apply_op(Op::Insert {
5099 parent,
5100 child,
5101 before,
5102 });
5103 }
5104 before = Some(child);
5105 }
5106 if self.components.fill_holders.contains(&parent) {
5108 self.retarget_slot(parent, None);
5109 }
5110 }
5111 Placement::Nested(other, anchor) => {
5112 let mut before = self.anchor_node(anchor);
5113 for &child in nodes.iter().rev() {
5114 if !self.nested_precedes(other, child, before) {
5115 self.join_nested_at(other, child, before);
5116 }
5117 before = Some(child);
5118 }
5119 }
5120 _ => {}
5121 }
5122 }
5123
5124 pub(super) fn precedes(&self, parent: NodeId, child: NodeId, next: Option<NodeId>) -> bool {
5127 self.preceding(parent, child, next, None).is_some()
5128 }
5129
5130 pub(super) fn preceding(
5137 &self,
5138 parent: NodeId,
5139 child: NodeId,
5140 next: Option<NodeId>,
5141 hint: Option<usize>,
5142 ) -> Option<usize> {
5143 let k = self.key(parent).ok()?;
5144 if self.nodes[self.key(child).ok()? as usize].parent != k {
5145 return None;
5146 }
5147 let children = &self.nodes[k as usize].children;
5148 let id = |at: usize| children.get(at).map(|&c| self.nodes[c as usize].id);
5149 let at = match hint {
5150 Some(at) if id(at) == Some(child) => at,
5151 _ => {
5152 let at = children
5153 .iter()
5154 .position(|&c| self.nodes[c as usize].id == child);
5155 self.placing(at.map_or(children.len(), |at| at + 1));
5156 at?
5157 }
5158 };
5159 (id(at + 1) == next).then_some(at)
5160 }
5161
5162 #[cfg(test)]
5165 pub(super) fn placing(&self, n: usize) {
5166 let work = &self.components.placing_work;
5167 work.set(work.get() + n);
5168 }
5169
5170 #[cfg(not(test))]
5171 #[inline(always)]
5172 pub(super) fn placing(&self, _n: usize) {}
5173
5174 #[cfg(test)]
5177 pub(super) fn retagging(&self, n: usize) {
5178 let work = &self.components.retag_work;
5179 work.set(work.get() + n);
5180 }
5181
5182 #[cfg(not(test))]
5183 #[inline(always)]
5184 pub(super) fn retagging(&self, _n: usize) {}
5185
5186 fn reconcile_slot(
5192 &mut self,
5193 prev: Option<Expanded>,
5194 node: NodeId,
5195 mut el: ElNode,
5196 host: NodeId,
5197 inst: &mut Instance,
5198 ) -> Expanded {
5199 let bound = super::views::Bound::take(&mut el);
5200 let applied = inst.bound.remove(&node);
5203 let (old_attrs, old_style, old_classes) = match (prev, applied) {
5204 (Some(_), Some(a)) => (a.attrs, a.style, a.classes),
5205 (Some(p), None) => (p.attrs, p.style, p.classes),
5206 (None, _) => (Attrs::default(), StyleRefinement::default(), (None, None)),
5207 };
5208 let bound = bound.map(|bound| self.bind_parts(host, node, bound, &mut el));
5209 self.apply_slot_attrs(node, host, &el.attrs, &old_attrs, Some(&mut *inst));
5210 let classes = self.apply_el_styles(
5211 node,
5212 &el.style,
5213 &old_style,
5214 old_classes,
5215 el.attrs.class.as_ref(),
5216 None,
5217 );
5218 if bound.is_some() {
5219 Self::keep_bound(inst, node, &el.attrs, &el.style, classes.clone(), None);
5220 }
5221 let events = self.apply_slot_handlers(node, host, &el, inst);
5224 Expanded {
5225 id: node,
5226 tag: Tag::View,
5227 key: None,
5228 text: None,
5229 attrs: el.attrs,
5230 style: el.style,
5231 classes,
5232 events,
5233 list: None,
5234 part: Part::Slot,
5235 children: Vec::new(),
5236 }
5237 }
5238
5239 fn reconcile_wrapper(
5247 &mut self,
5248 mut prev: Option<Expanded>,
5249 mut el: ElNode,
5250 host: NodeId,
5251 inst: &mut Instance,
5252 ) -> Expanded {
5253 let (id, old_children) = match &mut prev {
5254 Some(p) => (p.id, std::mem::take(&mut p.children)),
5255 None => {
5256 let id = self.components.alloc();
5257 let _ = self.apply_op(Op::Create { id, tag: el.tag });
5258 self.components.owners.insert(id, host);
5259 (id, Vec::new())
5260 }
5261 };
5262 self.components.fill_holders.insert(id);
5263 let children = std::mem::take(&mut el.children);
5265 let children = self.reconcile_children(id, old_children, children, host, inst);
5266 let (tag, key) = (el.tag, el.key.clone());
5267 let mut e = self.reconcile_slot(prev, id, el, host, inst);
5268 if let Ok(k) = self.key(id) {
5269 self.lay_out_through(k);
5270 }
5271 e.tag = tag;
5272 e.key = key;
5273 e.part = Part::Node;
5274 e.children = children;
5275 e
5276 }
5277
5278 pub(super) fn reconcile_node(
5279 &mut self,
5280 prev: Option<Expanded>,
5281 mut el: ElNode,
5282 part: Part,
5283 host: NodeId,
5284 inst: &mut Instance,
5285 ) -> Expanded {
5286 if !el.children.is_empty()
5289 && let Some(content) = el.bound_text.take()
5290 {
5291 let mut first = ElNode::new(Tag::Text);
5292 first.text = Some(SharedString::default());
5293 first.bound_text = Some(content);
5294 el.text = None;
5295 el.children.insert(0, first);
5296 }
5297 let nested_style = (matches!(el.kind, ElKind::Component(_)) && el.style.is_bound())
5302 .then(|| el.style.clone());
5303 let nested_attrs = (matches!(el.kind, ElKind::Component(_)) && !el.bound_attrs.is_empty())
5305 .then(|| (el.attrs.clone(), el.bound_attrs.clone()));
5306 let bound = if matches!(el.kind, ElKind::Component(_)) {
5307 el.resolve_once();
5308 None
5309 } else {
5310 super::views::Bound::take(&mut el)
5311 };
5312 if matches!(el.kind, ElKind::Raw) {
5313 return self.reconcile_raw(prev, el, host);
5314 }
5315 if !el.children.is_empty()
5318 && let Some(content) = el.text.take()
5319 && !content.is_empty()
5320 {
5321 let mut raw = ElNode::new(Tag::Text);
5322 raw.text = Some(content);
5323 raw.kind = ElKind::Raw;
5324 el.children.insert(0, raw);
5325 }
5326 let old_list = prev
5327 .as_ref()
5328 .and_then(|p| p.list.as_deref().copied())
5329 .unwrap_or_default();
5330 let kept = prev.is_some();
5331 let (id, old_attrs, old_style, old_classes, old_events, old_children, old_text) = match prev
5332 {
5333 Some(mut p) => {
5334 if let Some(applied) = inst.bound.remove(&p.id) {
5338 p.attrs = applied.attrs;
5339 p.style = applied.style;
5340 p.classes = applied.classes;
5341 p.text = applied.text;
5342 }
5343 (
5344 p.id, p.attrs, p.style, p.classes, p.events, p.children, p.text,
5345 )
5346 }
5347 None => {
5348 let id = self.components.alloc();
5349 let _ = self.apply_op(Op::Create { id, tag: el.tag });
5350 self.components.owners.insert(id, host);
5351 if let ElKind::Component(c) = &el.kind {
5352 self.create_instance_for(id, c);
5353 }
5354 (
5355 id,
5356 Attrs::default(),
5357 StyleRefinement::default(),
5358 (None, None),
5359 EventMask::default(),
5360 Vec::new(),
5361 None,
5362 )
5363 }
5364 };
5365 let old_list = if matches!(el.kind, ElKind::VirtualList(_)) {
5367 self.components.list_layouts.remove(&id).unwrap_or(old_list)
5368 } else {
5369 old_list
5370 };
5371 let bound = bound.map(|bound| self.bind_parts(host, id, bound, &mut el));
5372 let (component, virtual_list) = match std::mem::replace(&mut el.kind, ElKind::Plain) {
5373 ElKind::Component(c) => (Some(c), None),
5374 ElKind::VirtualList(list) => (None, Some(list)),
5375 _ => (None, None),
5376 };
5377 if let Some(c) = component {
5378 self.set_element_props(id, c.props.as_ref());
5381 if self.is_host(id) {
5382 if let Some(style) = nested_style {
5383 el.style = self.bind_nested_style(id, style);
5384 }
5385 let user = (!el.style.is_empty()).then(|| self.components.lowered(&el.style));
5386 self.set_user(id, user);
5387 }
5388 if kept {
5390 inst.event_handlers.retain(|(n, _)| *n != id);
5391 }
5392 if self.is_host(id) {
5394 self.set_given_handlers(id, std::mem::take(&mut el.handlers));
5395 }
5396 inst.event_handlers
5397 .extend(c.on_event.into_iter().map(|listener| (id, listener)));
5398 let element_ref = el.attrs.take_element_ref();
5400 if old_attrs.element_ref() != element_ref.as_ref()
5401 && let Some(r) = old_attrs.element_ref()
5402 {
5403 r.detach(id);
5404 }
5405 if let Some(r) = &element_ref {
5406 r.attach(id);
5407 }
5408 let mut old_children = old_children;
5411 let tooltip =
5412 self.reconcile_given_tooltip(id, &mut old_children, &mut el.children, host, inst);
5413 let tooltip_prop = tooltip
5414 .as_ref()
5415 .and_then(|t| t.children.first())
5416 .filter(|e| e.id != 0)
5417 .map(|e| Prop::Tooltip(crate::overlay::TooltipContent::Node(e.id)));
5418 if self.is_host(id) {
5420 let given = match nested_attrs {
5421 Some((mut base, parts)) => {
5422 if let Some(prop) = &tooltip_prop {
5423 crate::element::host::set_in(&mut base.props, prop.clone());
5424 }
5425 self.bind_nested_attrs(id, base, parts)
5426 }
5427 None => {
5428 let mut given = std::mem::take(&mut el.attrs);
5429 if let Some(prop) = tooltip_prop {
5430 crate::element::host::set_in(&mut given.props, prop);
5431 }
5432 given
5433 }
5434 };
5435 self.set_given(id, given);
5436 }
5437 let mut content = std::mem::take(&mut el.children);
5443 let is_slot = |c: &ElNode| {
5444 matches!(c.kind, ElKind::Fill(_))
5445 || c.attrs
5446 .props
5447 .iter()
5448 .any(|p| matches!(p, Prop::ComponentSlot(_)))
5449 };
5450 let lazy = self
5451 .components
5452 .instances
5453 .get(&id)
5454 .is_some_and(|i| i.spec.as_ref().is_some_and(|s| s.lazy_children));
5455 if lazy {
5456 let (slots, kids): (Vec<ElNode>, Vec<ElNode>) =
5459 content.into_iter().partition(|c| is_slot(c));
5460 content = slots;
5461 if !kids.is_empty() {
5462 let wanted = self.children_wanted_signal(id);
5463 let shown = crate::element::when(wanted, move || {
5464 kids.iter()
5465 .cloned()
5466 .map(crate::element::AnyElement)
5467 .collect::<Vec<_>>()
5468 });
5469 content.push(shown.into_element().0);
5470 }
5471 }
5472 let mut children = self.reconcile_children(id, old_children, content, host, inst);
5473 children.extend(tooltip);
5474 let mut kept_attrs = Attrs::default();
5475 kept_attrs.set_element_ref(element_ref);
5476 return Expanded {
5477 id,
5478 tag: el.tag,
5479 key: el.key,
5480 text: None,
5481 attrs: kept_attrs,
5482 style: el.style,
5483 classes: (None, None),
5484 events: EventMask::default(),
5485 list: None,
5486 part,
5487 children,
5488 };
5489 }
5490 if !self.apply_target_attrs(id, &el.attrs, &old_attrs, None) {
5491 self.apply_attrs(id, &el.attrs, &old_attrs);
5492 }
5493 let classes = self.apply_el_styles(
5494 id,
5495 &el.style,
5496 &old_style,
5497 old_classes,
5498 el.attrs.class.as_ref(),
5499 None,
5500 );
5501 let text = self.reconcile_text(id, host, el.text.take(), old_text);
5502 if bound.is_some() {
5503 Self::keep_bound(
5504 inst,
5505 id,
5506 &el.attrs,
5507 &el.style,
5508 classes.clone(),
5509 text.clone(),
5510 );
5511 }
5512 let events = self.apply_handlers(host, id, &el, old_events, EventMask::default(), inst);
5513 let new_children = std::mem::take(&mut el.children);
5514 let children = self.reconcile_children(id, old_children, new_children, host, inst);
5515 let list = match virtual_list {
5516 Some(list) => {
5517 let config = list.config;
5518 self.update_virtual_list(id, host, *list, &old_list);
5519 Some(Box::new(config))
5520 }
5521 None => None,
5522 };
5523 Expanded {
5524 id,
5525 tag: el.tag,
5526 key: el.key,
5527 text,
5528 attrs: el.attrs,
5529 style: el.style,
5530 classes,
5531 events,
5532 list,
5533 part,
5534 children,
5535 }
5536 }
5537
5538 fn reconcile_given_tooltip(
5544 &mut self,
5545 nested: NodeId,
5546 old: &mut Vec<Expanded>,
5547 content: &mut Vec<ElNode>,
5548 host: NodeId,
5549 inst: &mut Instance,
5550 ) -> Option<Expanded> {
5551 let prev = old
5552 .iter()
5553 .position(|e| e.part == Part::Tooltip)
5554 .map(|at| old.remove(at));
5555 let Some(at) = content
5556 .iter()
5557 .position(|c| matches!(c.kind, ElKind::Tooltip))
5558 else {
5559 if let Some(prev) = prev {
5560 self.release_expanded(prev);
5561 }
5562 return None;
5563 };
5564 let given = content.remove(at);
5565 let new = given
5566 .children
5567 .into_iter()
5568 .map(|c| NewChild::Made(None, c))
5569 .collect();
5570 let old = prev.map(|p| p.children).unwrap_or_default();
5571 let (children, _) = self.match_children(nested, old, new, host, inst);
5572 let mut tooltip = Expanded::js(0, Part::Tooltip);
5573 tooltip.children = children;
5574 Some(tooltip)
5575 }
5576
5577 fn reconcile_raw(&mut self, prev: Option<Expanded>, el: ElNode, host: NodeId) -> Expanded {
5580 let content = el.text.unwrap_or_else(|| "".into());
5581 let id = match prev {
5582 Some(p) => {
5583 if p.text.as_ref().is_none_or(|(old, _)| *old != content) {
5584 let _ = self.apply_op(Op::SetText {
5585 id: p.id,
5586 text: content.as_str().to_owned(),
5587 });
5588 }
5589 p.id
5590 }
5591 None => {
5592 let id = self.components.alloc();
5593 let _ = self.apply_op(Op::CreateText {
5594 id,
5595 text: content.as_str().to_owned(),
5596 });
5597 self.components.owners.insert(id, host);
5598 id
5599 }
5600 };
5601 Expanded {
5602 id,
5603 tag: Tag::Text,
5604 key: None,
5605 text: Some((content, id)),
5606 attrs: Attrs::default(),
5607 style: StyleRefinement::default(),
5608 classes: (None, None),
5609 events: EventMask::default(),
5610 list: None,
5611 part: Part::Raw,
5612 children: Vec::new(),
5613 }
5614 }
5615
5616 fn update_virtual_list(
5626 &mut self,
5627 id: NodeId,
5628 owner: NodeId,
5629 list: VirtualListEl,
5630 old: &ListConfig,
5631 ) {
5632 let mut props = std::mem::take(&mut self.components.props);
5634 list.config.changes(old, &mut props);
5635 for prop in props.drain(..) {
5636 let _ = self.apply_op(Op::SetProp { id, prop });
5637 }
5638 self.components.props = props;
5639 let before = self
5640 .components
5641 .virtual_lists
5642 .get(&id)
5643 .map(|state| (state.count, state.keys.clone()));
5644 let items = self.components.slot_names.contains_key(&id);
5646 let state = self
5647 .components
5648 .virtual_lists
5649 .entry(id)
5650 .or_insert_with(|| VirtualListState {
5651 owner,
5652 scope: Rc::default(),
5653 row: list.row.clone(),
5654 count: 0,
5655 keys: None,
5656 separator: None,
5657 cells: Vec::new(),
5658 rows: CellRows::default(),
5659 moves: None,
5660 items,
5661 place: None,
5662 contents: Vec::new(),
5663 min_view: None,
5664 reported: None,
5665 latest: None,
5666 report: None,
5667 });
5668 if state.scope.get() != list.scope {
5671 state.scope.set(list.scope);
5672 if let Some(scope) = list.scope {
5673 let rows = Rc::downgrade(&state.rows);
5674 let current = Rc::downgrade(&state.scope);
5675 scope.run(|| {
5676 crate::element::cleanup(move || {
5677 if current.upgrade().is_some_and(|c| c.get() == Some(scope)) {
5680 dispose_rows(&rows);
5681 }
5682 })
5683 });
5684 }
5685 }
5686 let cells = state.rows.clone();
5687 let bound = matches!(list.count, Reactive::Bound(_)) || list.keys.is_some();
5688 let (count, keys) = (list.count, list.keys);
5689 let rows = move || (count.get(), keys.as_ref().map(|k| k()));
5690 let mut moves = None;
5691 let (count, keys) = if bound {
5692 let count_signal = self.list_count(id, 0);
5693 let patches = self.components.patches.clone();
5694 let first: Rc<RefCell<Option<Rows>>> = Rc::default();
5695 let slot = first.clone();
5696 let last: RefCell<Option<Rc<[u64]>>> = RefCell::new(None);
5697 let made = std::cell::Cell::new(false);
5698 let memo = crate::element::computed(move || {
5699 let (count, keys) = rows();
5700 let diff = match (&*last.borrow(), &keys) {
5701 (Some(old), Some(new)) => ListDiff::new(old, new),
5702 _ => None,
5703 };
5704 last.replace(keys.clone());
5705 if made.replace(true) {
5706 move_rows(&cells, diff.as_ref(), count);
5707 count_signal.set(count as usize);
5708 patches.borrow_mut().push(super::views::Patch::Rows {
5709 list: id,
5710 binding: crate::element::Owner::current(),
5711 count,
5712 keys,
5713 });
5714 } else {
5715 count_signal.set(count as usize);
5716 *slot.borrow_mut() = Some((count, keys));
5717 }
5718 });
5719 moves = Some(memo.node());
5720 first.take().expect("a memo runs when it is made")
5721 } else {
5722 let (count, keys) = crate::element::untracked(rows);
5723 {
5725 self.list_count(id, count as usize).set(count as usize);
5726 }
5727 (count, keys)
5728 };
5729 self.send_list_rows(id, before.as_ref(), count, keys.as_ref());
5730 if before.is_none()
5731 && let Some(command) = list.initial_scroll
5732 {
5733 let _ = self.apply_op(Op::Command { id, command });
5734 }
5735 let state = self.components.virtual_lists.get_mut(&id).expect("list");
5736 state.row = list.row;
5737 state.count = count;
5738 state.keys = keys;
5739 state.moves = moves;
5740 state.separator = list.separator;
5741 state.min_view = list.min_view_time;
5742 self.sync_virtual_cells(id, true);
5743 }
5744
5745 fn send_list_rows(
5748 &mut self,
5749 id: NodeId,
5750 before: Option<&Rows>,
5751 count: u32,
5752 keys: Option<&Rc<[u64]>>,
5753 ) {
5754 if let (Some((_, Some(old))), Some(new)) = (before, keys)
5755 && let Some(diff) = ListDiff::new(old, new)
5756 {
5757 let _ = self.apply_op(Op::SetProp {
5758 id,
5759 prop: Prop::ListDiff(Rc::new(diff)),
5760 });
5761 }
5762 if before.map(|(count, _)| *count) != Some(count) {
5763 let _ = self.apply_op(Op::SetProp {
5764 id,
5765 prop: Prop::Count(count),
5766 });
5767 }
5768 }
5769
5770 pub(super) fn set_list_rows(&mut self, id: NodeId, count: u32, keys: Option<Rc<[u64]>>) {
5775 let Some(state) = self.components.virtual_lists.get(&id) else {
5776 return;
5777 };
5778 let before = (state.count, state.keys.clone());
5779 self.send_list_rows(id, Some(&before), count, keys.as_ref());
5780 let state = self.components.virtual_lists.get_mut(&id).expect("list");
5781 state.count = count;
5782 state.keys = keys;
5783 self.sync_virtual_cells(id, false);
5784 }
5785
5786 fn sync_virtual_cells(&mut self, id: NodeId, rebuild: bool) {
5787 let key = self.key(id).expect("virtual list node");
5788 let slots = &self.nodes[key as usize].list.as_ref().expect("list").slots;
5789 let state = &self.components.virtual_lists[&id];
5790 for (slot, (&cell, &content)) in state.cells.iter().zip(&state.contents).enumerate() {
5791 for part in [cell, content].into_iter().filter(|&part| part != 0) {
5792 let Some(inst) = self.components.instances.get_mut(&part) else {
5793 continue;
5794 };
5795 let remake = rebuild || !inst.cell_owner.is_some_and(|o| o.is_live());
5796 if let Inner::VirtualRow { index, .. } | Inner::Row { index, .. } = &mut inst.inner
5797 {
5798 if remake {
5799 *index = slots[slot].requested.map_or(usize::MAX, |i| i as usize);
5801 } else if let Some(position) = inst.row_index {
5802 *index = position.get_untracked();
5803 }
5804 }
5805 if remake && !inst.dirty {
5806 inst.dirty = true;
5807 self.components.dirty.push(part);
5808 }
5809 }
5810 }
5811 }
5812
5813 fn list_count(&mut self, list: NodeId, count: usize) -> crate::element::Signal<usize> {
5816 if let Some(&(_, signal)) = self.components.list_counts.get(&list) {
5817 return signal;
5818 }
5819 let made = crate::element::Owner::detached()
5820 .run(|| crate::element::create_root(|| crate::element::signal(count)));
5821 self.components.list_counts.insert(list, made);
5822 made.1
5823 }
5824
5825 fn forget_list_count(&mut self, list: NodeId) {
5827 if let Some((owner, _)) = self.components.list_counts.remove(&list) {
5828 owner.dispose();
5829 }
5830 self.components.list_layouts.remove(&list);
5831 }
5832
5833 pub(super) fn bind_virtual_lists(&mut self) -> bool {
5836 if self.components.virtual_lists.is_empty() {
5837 return false;
5838 }
5839 let _entered = self.components.runtime.enter();
5840 let mut binds = std::mem::take(&mut self.list_binds);
5841 let mut bound = false;
5842 binds.retain(|bind| {
5843 if !self.components.virtual_lists.contains_key(&bind.list) {
5844 return true;
5845 }
5846 for &(slot, index) in &bind.binds {
5847 self.bind_virtual_cell(bind.list, slot as usize, index as usize);
5848 }
5849 bound = true;
5850 false
5851 });
5852 self.list_binds = binds;
5853 bound
5854 }
5855
5856 fn bind_virtual_cell(&mut self, list: NodeId, slot: usize, index: usize) {
5857 let state = &self.components.virtual_lists[&list];
5858 let owner = state.owner;
5859 let cell = match state.cells.get(slot).copied().filter(|&c| c != 0) {
5860 Some(cell) => {
5861 let content = state.contents.get(slot).copied().filter(|&c| c != 0);
5862 for part in [Some(cell), content].into_iter().flatten() {
5863 if let Some(inst) = self.components.instances.get_mut(&part) {
5864 match &mut inst.inner {
5865 Inner::VirtualRow { index: current, .. }
5866 | Inner::Row { index: current, .. } => *current = index,
5867 _ => {}
5868 }
5869 if let Some(row) = inst.row_index
5872 && inst.cell_owner.is_some_and(|o| o.is_live())
5873 {
5874 row.set(index);
5875 continue;
5876 }
5877 }
5878 self.components.mark(part);
5879 }
5880 cell
5881 }
5882 None => {
5883 let (items, place) = (state.items, state.place.clone());
5884 let cell = self.components.alloc();
5885 let _ = self.apply_op(Op::Create {
5886 id: cell,
5887 tag: Tag::Cell,
5888 });
5889 self.components.owners.insert(cell, owner);
5890 let _ = self.apply_op(Op::SetProp {
5891 id: cell,
5892 prop: Prop::Slot(crate::CellSlot::Item(slot as u32)),
5893 });
5894 let _ = self.apply_op(Op::Insert {
5895 parent: list,
5896 child: cell,
5897 before: None,
5898 });
5899 let row = Inner::VirtualRow { list, index };
5900 let content = if items {
5901 let content = self.components.alloc();
5904 let _ = self.apply_op(Op::Create {
5905 id: content,
5906 tag: Tag::View,
5907 });
5908 self.components.owners.insert(content, owner);
5909 let _ = self.apply_op(Op::Insert {
5910 parent: cell,
5911 child: content,
5912 before: None,
5913 });
5914 let instance = Instance::new(row, None, Vec::new(), None);
5915 self.components
5916 .instances
5917 .insert(content, Box::new(instance));
5918 self.components.mark(content);
5919 let place = place.unwrap_or_else(|| Rc::new(|row, _| row.into_element()));
5920 let wrapper =
5922 Instance::new(Inner::Row { place, index }, None, vec![content], None);
5923 self.components.instances.insert(cell, Box::new(wrapper));
5924 content
5925 } else {
5926 let instance = Instance::new(row, None, Vec::new(), None);
5927 self.components.instances.insert(cell, Box::new(instance));
5928 0
5929 };
5930 let state = self.components.virtual_lists.get_mut(&list).expect("list");
5931 if state.cells.len() <= slot {
5932 state.cells.resize(slot + 1, 0);
5933 state.contents.resize(slot + 1, 0);
5934 }
5935 state.cells[slot] = cell;
5936 state.contents[slot] = content;
5937 self.components.mark(cell);
5938 cell
5939 }
5940 };
5941 let _ = self.apply_op(Op::SetProp {
5942 id: cell,
5943 prop: Prop::CellIndex(index as u32),
5944 });
5945 }
5946
5947 fn viewable_changed(&mut self, list: NodeId, payload: &EventPayload) {
5951 let executor = self.components.executor.clone();
5952 let Some(state) = self.components.virtual_lists.get_mut(&list) else {
5953 return;
5954 };
5955 state.latest = virtual_list::viewable_range(payload, "first", "last");
5956 match state.min_view {
5957 Some(delay) => {
5958 state.report = Some(crate::element::task::act_after(
5959 &executor,
5960 state.owner,
5961 delay,
5962 Action::ReportViewable(list),
5963 ));
5964 }
5965 None => self.report_viewable(list),
5966 }
5967 }
5968
5969 fn report_viewable(&mut self, list: NodeId) {
5972 let Some(state) = self.components.virtual_lists.get_mut(&list) else {
5973 return;
5974 };
5975 state.report = None;
5976 if state.latest == state.reported {
5977 return;
5978 }
5979 let payload = virtual_list::viewable_payload(state.latest, state.reported);
5980 state.reported = state.latest;
5981 let owner = state.owner;
5982 self.handle(owner, list, EventKind::ViewableItemsChange, &payload);
5983 }
5984
5985 fn release_id(&mut self, id: NodeId) {
5986 self.components.release_generation = self.components.release_generation.wrapping_add(1);
5987 if let Some(host) = self.components.owners.remove(&id) {
5988 self.components.released_hosts.insert(host);
5992 }
5993 self.forget_node_extras(id);
5994 if self.is_alias(id) {
5996 self.unalias(id);
5997 return;
5998 }
5999 let holder = if self.components.fill_holders.is_empty() {
6001 None
6002 } else {
6003 self.key(id)
6004 .ok()
6005 .map(|k| self.nodes[k as usize].parent)
6006 .filter(|&p| p != NO_KEY)
6007 .map(|p| self.nodes[p as usize].id)
6008 .filter(|p| self.components.fill_holders.contains(p))
6009 };
6010 let _ = self.apply_op(Op::Release { id });
6011 if let Some(holder) = holder {
6012 self.retarget_slot(holder, None);
6013 }
6014 }
6015
6016 pub(super) fn release_expanded(&mut self, e: Expanded) {
6019 self.components.release_generation = self.components.release_generation.wrapping_add(1);
6022 match e.part {
6023 Part::Slot => {
6024 self.drop_slot_target(e.id);
6025 self.detach_id(e.id);
6026 return;
6027 }
6028 Part::Children | Part::Filled(_) => return,
6031 Part::Fill(_) | Part::Tooltip => {
6033 for c in e.children {
6034 self.release_expanded(c);
6035 }
6036 return;
6037 }
6038 Part::JsChild => {
6040 self.detach_id(e.id);
6041 return;
6042 }
6043 Part::Raw => {
6044 self.release_id(e.id);
6045 return;
6046 }
6047 Part::Component(_) => {
6050 let content: Vec<NodeId> = e.children.iter().flat_map(|c| self.placed(c)).collect();
6051 self.release_component(e.id, &content);
6052 }
6053 Part::Region(region) => {
6055 self.release_region(region);
6056 return;
6057 }
6058 Part::VirtualList => self.release_virtual_list(e.id),
6059 Part::Node => {
6061 if !self.components.fill_holders.is_empty()
6062 && self.components.fill_holders.remove(&e.id)
6063 {
6064 self.drop_slot_target(e.id);
6065 }
6066 }
6067 }
6068 if let Some(r) = e.attrs.rare.as_ref().and_then(|r| r.element_ref.as_ref()) {
6069 r.detach(e.id);
6070 }
6071 for c in e.children {
6072 self.release_expanded(c);
6073 }
6074 if let Some((_, raw)) = e.text {
6075 self.release_id(raw);
6076 }
6077 self.release_id(e.id);
6078 }
6079
6080 pub(super) fn release_instance(&mut self, host: NodeId) {
6083 self.release_component(host, &[]);
6084 }
6085
6086 fn release_component(&mut self, host: NodeId, content: &[NodeId]) {
6091 let Some(mut inst) = self.components.instances.remove(&host) else {
6092 return;
6093 };
6094 self.target_released(host);
6096 if self
6097 .components
6098 .parked_methods
6099 .iter()
6100 .any(|(h, ..)| *h == host)
6101 {
6102 let (gone, kept) = std::mem::take(&mut self.components.parked_methods)
6103 .into_iter()
6104 .partition(|(h, ..)| *h == host);
6105 self.components.parked_methods = kept;
6106 for (_, call, method) in gone {
6107 drop_caught(method);
6108 self.settle(
6109 call,
6110 Err(format!("node {host} hosts no Rust component").into()),
6111 );
6112 }
6113 }
6114 self.forget_node_extras(host);
6116 if let Inner::Component(inner) = &mut inst.inner {
6117 if let Err(message) = caught(|| inner.cleanup()) {
6118 log::error!(target: "js", "{} failed in its cleanup: {message}", inner.name());
6119 }
6120 self.apply_actions();
6121 }
6122 self.release_regions(host);
6123 self.components.runtime.forget_host(host);
6124 if let Some(owner) = inst.cell_owner.take() {
6125 owner.dispose();
6126 }
6127 for &child in &inst.js_children {
6128 if !content.contains(&child) {
6129 self.detach_id(child);
6130 }
6131 }
6132 for (_, node) in inst.slots {
6133 self.drop_slot_target(node);
6134 self.components.slot_hosts.remove(&node);
6135 if !content.contains(&node) {
6136 self.detach_id(node);
6137 }
6138 }
6139 if let Some(root) = inst.root {
6140 if matches!(root.part, Part::Component(_)) {
6142 self.release_expanded(root);
6143 return;
6144 }
6145 let node = self.native_id(host);
6146 if let Some(r) = root
6147 .attrs
6148 .rare
6149 .as_ref()
6150 .and_then(|r| r.element_ref.as_ref())
6151 {
6152 r.detach(node);
6153 }
6154 if root.part == Part::VirtualList {
6155 self.release_virtual_list(node);
6156 }
6157 if let Some((_, raw)) = root.text {
6158 self.release_id(raw);
6159 }
6160 for c in root.children {
6161 self.release_expanded(c);
6162 }
6163 }
6164 }
6165
6166 fn release_virtual_list(&mut self, id: NodeId) {
6169 if let Some(state) = self.components.virtual_lists.remove(&id) {
6170 let parts = state.contents.into_iter().chain(state.cells);
6171 for part in parts.filter(|&c| c != 0) {
6172 self.release_instance(part);
6173 self.release_id(part);
6174 }
6175 }
6176 if self.components.slot_names.remove(&id).is_some() {
6178 self.unslot(id);
6179 }
6180 self.components.lists.remove(&id);
6181 self.forget_list_count(id);
6182 }
6183
6184 pub fn component_event(&mut self, id: NodeId, kind: EventKind, payload: &EventPayload) -> bool {
6187 let _entered = self.components.runtime.enter();
6188 let _geometry = (kind == EventKind::TextLayout)
6190 .then(|| self.geometries.remove(&id))
6191 .flatten()
6192 .map(crate::text::GeometryScope::enter);
6193 let handled = self.dispatch_event(id, kind, payload);
6194 self.flush_component_emits();
6195 handled
6196 }
6197
6198 #[doc(hidden)]
6202 pub fn listens(&self, id: NodeId, event: EventKind) -> bool {
6203 self.key(id)
6204 .is_ok_and(|key| self.nodes[key as usize].mounted_events().contains(event))
6205 }
6206
6207 #[doc(hidden)]
6213 pub fn key_interest(&self, id: NodeId) -> bool {
6214 let Ok(mut key) = self.key(id).map(|key| self.key_start(key)) else {
6215 return false;
6216 };
6217 let window = self.key_window(key);
6218 loop {
6219 let node = &self.nodes[key as usize];
6220 let disabled = node
6221 .props
6222 .as_ref()
6223 .is_some_and(|p| p.accessibility.state.disabled);
6224 if !disabled {
6225 let events = node.mounted_events();
6226 if events.contains(EventKind::KeyDown) || events.contains(EventKind::KeyUp) {
6227 return true;
6228 }
6229 if node
6230 .props
6231 .as_ref()
6232 .is_some_and(|p| !p.key_capture.is_none())
6233 {
6234 return true;
6235 }
6236 }
6237 if node.id == window || node.parent == NO_KEY {
6238 return false;
6239 }
6240 key = node.parent;
6241 }
6242 }
6243
6244 #[doc(hidden)]
6251 pub fn key_path(&self, id: NodeId, out: &mut Vec<NodeId>) {
6252 out.clear();
6253 let Ok(mut key) = self.key(id).map(|key| self.key_start(key)) else {
6254 return;
6255 };
6256 let window = self.key_window(key);
6257 loop {
6258 let node = &self.nodes[key as usize];
6259 let disabled = node
6260 .props
6261 .as_ref()
6262 .is_some_and(|p| p.accessibility.state.disabled);
6263 if !disabled {
6264 out.push(node.id);
6265 }
6266 if node.id == window || node.parent == NO_KEY {
6267 return;
6268 }
6269 key = node.parent;
6270 }
6271 }
6272
6273 #[doc(hidden)]
6282 pub fn key_captured(&self, id: NodeId, keystroke: Option<&crate::keymap::Keystroke>) -> bool {
6283 let Ok(mut key) = self.key(id).map(|key| self.key_start(key)) else {
6284 return false;
6285 };
6286 if self.nodes[key as usize].kind == Kind::Input {
6289 return false;
6290 }
6291 let window = self.key_window(key);
6292 loop {
6293 let node = &self.nodes[key as usize];
6294 let disabled = node
6295 .props
6296 .as_ref()
6297 .is_some_and(|p| p.accessibility.state.disabled);
6298 if !disabled
6299 && node
6300 .props
6301 .as_ref()
6302 .is_some_and(|p| p.key_capture.captures_key(keystroke))
6303 {
6304 return true;
6305 }
6306 if node.id == window || node.parent == NO_KEY {
6307 return false;
6308 }
6309 key = node.parent;
6310 }
6311 }
6312
6313 pub(super) fn key_start(&self, key: Key) -> Key {
6321 let node = &self.nodes[key as usize];
6322 if node.id != crate::ROOT_ID
6323 && (node.kind != Kind::Modal || self.key_window(key) != node.id)
6324 {
6325 return key;
6326 }
6327 node.children
6328 .iter()
6329 .copied()
6330 .find(|&child| !matches!(self.nodes[child as usize].kind, Kind::Overlay | Kind::Modal))
6331 .unwrap_or(key)
6332 }
6333
6334 pub(super) fn key_content_changed(&mut self, parent: Key) {
6336 let node = &self.nodes[parent as usize];
6337 if node.id == crate::ROOT_ID
6338 || (node.kind == Kind::Modal && self.key_window(parent) == node.id)
6339 {
6340 self.key_ancestry_dirty = true;
6341 }
6342 }
6343
6344 pub(super) fn key_window(&self, key: Key) -> NodeId {
6346 let node = &self.nodes[key as usize];
6347 if node.kind == Kind::Modal && self.window_ids.values().any(|(root, _)| *root == node.id) {
6348 node.id
6349 } else {
6350 self.window_of(key)
6351 }
6352 }
6353
6354 fn flush_component_emits(&mut self) {
6355 loop {
6358 let emits = self.components.runtime.take_emits();
6359 if emits.is_empty() {
6360 break;
6361 }
6362 for (host, event) in emits {
6363 self.route_emit(host, event);
6364 }
6365 }
6366 }
6367
6368 #[doc(hidden)]
6372 pub fn component_layout(
6373 &mut self,
6374 host: NodeId,
6375 id: NodeId,
6376 listener: &Listener<EventPayload>,
6377 frame: crate::Bounds<Points>,
6378 ) {
6379 let _entered = self.components.runtime.enter();
6380 let installed = self.components.instances.get(&host).is_some_and(|inst| {
6381 inst.handlers
6382 .of(id)
6383 .iter()
6384 .any(|(kind, current)| *kind == EventKind::Layout && current.ptr_eq(listener))
6385 });
6386 if installed {
6387 self.run_listener(host, listener, &EventPayload::Layout(frame));
6388 self.flush_component_emits();
6389 }
6390 }
6391
6392 fn dispatch_event(&mut self, id: NodeId, kind: EventKind, payload: &EventPayload) -> bool {
6393 self.span_state(id, kind);
6396 if self.drop_cancelled_press(id, kind, payload) {
6398 return true;
6399 }
6400 if kind == EventKind::Touch && id == ROOT_ID {
6403 if let EventPayload::Touch(touch) = payload {
6404 self.overlay_touches(touch);
6405 self.touches(payload, touch);
6406 }
6407 return false;
6408 }
6409 if matches!(kind, EventKind::MouseEnter | EventKind::MouseLeave) {
6411 let at = match payload {
6412 EventPayload::Mouse(mouse) => Some(mouse.page_position),
6413 _ => None,
6414 };
6415 self.overlay_hover(id, kind, at);
6416 }
6417 let _target = matches!(kind, EventKind::DownloadPending | EventKind::Download)
6421 .then(|| crate::element::download_target(id, Rc::downgrade(&self.components.executor)));
6422 if self.platform_event(id, kind, payload) {
6423 return true;
6424 }
6425 if self.is_host(id) {
6426 let base = self.base_of(id);
6429 if let Some(slot) = self.adopted_host(base) {
6430 self.handle(slot, base, kind, payload);
6431 }
6432 let own = self.handle(base, base, kind, payload);
6433 if own && kind == EventKind::ContextMenu {
6436 return true;
6437 }
6438 let given = self.handle_given(base, kind, payload);
6439 return (own || given) && !self.js_listens(base, kind);
6441 }
6442 if kind == EventKind::ViewableItemsChange && self.components.virtual_lists.contains_key(&id)
6444 {
6445 self.viewable_changed(id, payload);
6446 return true;
6447 }
6448 let slot_of = self
6453 .components
6454 .slot_hosts
6455 .get(&id)
6456 .copied()
6457 .or_else(|| self.adopted_host(id));
6458 let owner = self.components.owners.get(&id).copied();
6459 if let Some(host) = slot_of {
6460 self.handle(host, id, kind, payload);
6461 }
6462 if let Some(host) = owner
6463 && Some(host) != slot_of
6464 {
6465 self.handle(host, id, kind, payload);
6466 }
6467 (slot_of.is_some() || owner.is_some()) && id % 2 == 1
6470 }
6471
6472 pub(super) fn host_of(&self, id: NodeId) -> Option<NodeId> {
6476 if self.is_host(id) {
6477 Some(self.base_of(id))
6478 } else {
6479 self.components.owners.get(&id).copied()
6480 }
6481 }
6482
6483 fn handle(
6486 &mut self,
6487 host: NodeId,
6488 id: NodeId,
6489 kind: EventKind,
6490 payload: &EventPayload,
6491 ) -> bool {
6492 let id = self.base_of(id);
6493 let mut handled = false;
6494 let mut from = 0;
6495 while let Some((at, listener)) = self.next_handler(host, id, kind, from) {
6496 from = at + 1;
6497 if !self.run_listener(host, &listener, payload) {
6499 break;
6500 }
6501 handled = true;
6502 }
6503 handled
6504 }
6505
6506 pub(super) fn next_handler(
6513 &self,
6514 host: NodeId,
6515 id: NodeId,
6516 kind: EventKind,
6517 from: usize,
6518 ) -> Option<(usize, Listener<EventPayload>)> {
6519 let id = self.base_of(id);
6520 let inst = self.components.instances.get(&host)?;
6521 let handlers = inst.handlers.of(id);
6522 #[cfg(test)]
6523 self.components
6524 .handler_visits
6525 .set(self.components.handler_visits.get() + handlers.len().saturating_sub(from));
6526 handlers
6527 .iter()
6528 .enumerate()
6529 .skip(from)
6530 .find(|(_, (k, _))| *k == kind)
6531 .map(|(at, (_, l))| (at, l.clone()))
6532 }
6533
6534 pub(super) fn responder_el(&self, host: NodeId, id: NodeId) -> Option<Rc<ResponderEl>> {
6536 let id = self.base_of(id);
6537 self.components
6538 .instances
6539 .get(&host)?
6540 .responders
6541 .iter()
6542 .find(|(n, _)| *n == id)
6543 .map(|(_, r)| r.clone())
6544 }
6545
6546 pub(super) fn run_listener<E: ?Sized + 'static>(
6549 &mut self,
6550 host: NodeId,
6551 listener: &Listener<E>,
6552 event: &E,
6553 ) -> bool {
6554 let Some(owner) = self.state_owner(host) else {
6555 return false;
6556 };
6557 if let Err(message) = caught(|| listener.call(event)) {
6558 self.component_failed(owner, message);
6559 }
6560 self.apply_actions();
6561 true
6562 }
6563
6564 pub(super) fn state_owner(&self, host: NodeId) -> Option<NodeId> {
6567 match &self.components.instances.get(&host)?.inner {
6568 Inner::Component(_) => Some(host),
6569 Inner::VirtualRow { list, .. } => {
6570 self.components.virtual_lists.get(list).map(|s| s.owner)
6571 }
6572 Inner::Row { .. } => self
6573 .list_of(host)
6574 .and_then(|l| self.components.slot_hosts.get(&l))
6575 .copied(),
6576 Inner::Missing => None,
6577 }
6578 }
6579
6580 pub(super) fn component_failed(&mut self, host: NodeId, message: String) {
6583 let component = match self.components.instances.get(&host).map(|i| &i.inner) {
6584 Some(Inner::Component(inner)) => inner.name(),
6585 _ => "a list row",
6586 };
6587 let error = ComponentError { component, message };
6588 let owner = self
6590 .components
6591 .instances
6592 .get(&host)
6593 .and_then(|inst| match &inst.inner {
6594 Inner::Component(inner) => Some(inner.failure_owner()),
6595 _ => inst.cell_owner,
6596 });
6597 let _entered = self.components.runtime.enter();
6598 match owner.and_then(crate::element::reactive::boundary_of) {
6599 Some(boundary) => boundary.set(Some(error)),
6600 None => log::error!(target: "js", "{error}"),
6601 }
6602 }
6603
6604 fn list_of(&self, cell: NodeId) -> Option<NodeId> {
6606 let key = self.key(cell).ok()?;
6607 let parent = self.nodes[key as usize].parent;
6608 (parent != NO_KEY).then(|| self.nodes[parent as usize].id)
6609 }
6610
6611 fn login_item_action(
6616 &mut self,
6617 enabled: Option<bool>,
6618 answer: crate::element::AnswerSlot<Result<bool, crate::desktop::LaunchAtLoginError>>,
6619 ) {
6620 use crate::desktop::{LaunchAtLoginError, LoginItemStatus};
6621 if !self.access.allows_application() {
6625 answer.borrow_mut().deliver(match enabled {
6626 None => Ok(false),
6627 Some(_) => Err(LaunchAtLoginError::Denied),
6628 });
6629 return;
6630 }
6631 let Some(items) = self.login_item.as_mut() else {
6632 answer.borrow_mut().deliver(match enabled {
6633 None => Ok(false),
6634 Some(_) => Err(LaunchAtLoginError::Unavailable),
6635 });
6636 return;
6637 };
6638 let result = items.call(enabled);
6639 crate::element::task::spawn_raw(
6640 &self.components.executor,
6641 crate::ROOT_ID,
6642 Box::pin(async move {
6643 let result = match result.await {
6644 Ok(LoginItemStatus::Unavailable) if enabled.is_some() => {
6647 Err(LaunchAtLoginError::Unavailable)
6648 }
6649 Ok(status) => Ok(status == LoginItemStatus::Enabled),
6650 Err(error) => Err(LaunchAtLoginError::System(error)),
6651 };
6652 answer.borrow_mut().deliver(result);
6653 }),
6654 );
6655 }
6656
6657 fn notification_action(&mut self, action: crate::element::NotificationAction) {
6661 use crate::{
6662 element::NotificationAction,
6663 notifications::{NotificationCommand, NotificationPermission},
6664 };
6665 let allowed = self.access.allows_notifications();
6666 let available = allowed && self.components.environment.notifications;
6667 let command = match action {
6668 NotificationAction::Permission { ask, answer } => {
6669 if !available {
6670 answer
6671 .borrow_mut()
6672 .deliver(NotificationPermission::Unavailable);
6673 return;
6674 }
6675 let state = &mut self.components.notifications;
6676 let id = state.next;
6677 state.next = id.wrapping_add(1);
6678 state.permissions.insert(id, answer);
6679 NotificationCommand::Permission { id, ask }
6680 }
6681 NotificationAction::Show {
6682 notification,
6683 answer,
6684 } => {
6685 if !available {
6686 answer.borrow_mut().deliver(false);
6687 return;
6688 }
6689 let state = &mut self.components.notifications;
6690 let id = state.next;
6691 state.next = id.wrapping_add(1);
6692 state.shows.insert(id, answer);
6693 NotificationCommand::Show { id, notification }
6694 }
6695 NotificationAction::Close(id) => {
6696 if !available {
6697 return;
6698 }
6699 NotificationCommand::Close(id)
6700 }
6701 NotificationAction::CloseAll => {
6702 if !available {
6703 return;
6704 }
6705 NotificationCommand::CloseAll
6706 }
6707 NotificationAction::SetBadge(count) => {
6708 if !allowed {
6709 return;
6710 }
6711 NotificationCommand::SetBadge(count)
6712 }
6713 NotificationAction::NextPress(answer) => {
6714 let state = &mut self.components.notifications;
6715 if let Some(pressed) = state.presses.pop_front() {
6716 answer.borrow_mut().deliver(pressed);
6717 return;
6718 }
6719 state.next_press = Some(answer);
6720 if !available || state.listening {
6721 return;
6722 }
6723 state.listening = true;
6724 NotificationCommand::Listen
6725 }
6726 };
6727 let _ = self.apply_op(Op::Command {
6728 id: crate::ROOT_ID,
6729 command: Command::Notification(command),
6730 });
6731 }
6732
6733 #[doc(hidden)]
6736 pub fn app_url_cell(&self) -> crate::url_scheme::AppUrlCell {
6737 self.components.url_schemes.address.clone()
6738 }
6739
6740 fn url_scheme(
6747 &mut self,
6748 url: String,
6749 page: bool,
6750 quiet: bool,
6751 change: Option<crate::url_scheme::AppUrlChangeReason>,
6752 ) {
6753 let links = &mut self.components.url_schemes;
6754 if !page && change.is_none() && crate::file_type::is_file_url(&url) {
6758 if !links
6759 .links
6760 .schemes()
6761 .iter()
6762 .any(|s| s == crate::file_type::FILE_SCHEME)
6763 {
6764 log::warn!("file dropped: the app declares no file types (nsh.json `fileTypes`)");
6765 return;
6766 }
6767 let Some(path) = crate::file_type::file_path(&url) else {
6768 log::warn!("file dropped: {url} is not a local file");
6769 return;
6770 };
6771 let files = &mut self.components.open_files;
6772 if let Some(answer) = files.next.take() {
6773 answer.borrow_mut().deliver(vec![path]);
6774 return;
6775 }
6776 if files.pending.len() == crate::file_type::MAX_PENDING {
6777 log::warn!(
6778 "file dropped: {} came while nothing listened",
6779 crate::file_type::MAX_PENDING
6780 );
6781 files.pending.pop_front();
6782 }
6783 files.pending.push_back(path);
6784 return;
6785 }
6786 let checked = if page {
6787 crate::url_scheme::check_page_url(&url)
6788 } else {
6789 links.links.check(&url)
6790 };
6791 if let Err(dropped) = checked {
6792 log::warn!("link dropped: {dropped}");
6793 return;
6794 }
6795 let links = &mut self.components.url_schemes;
6796 if !quiet && change.is_none() {
6800 let scheme = url.split_once(':').map_or("", |(scheme, _)| scheme);
6801 links
6802 .next_of_scheme
6803 .retain(|(_, answer)| crate::element::task::awaited(answer));
6804 if let Some(at) = links
6805 .next_of_scheme
6806 .iter()
6807 .position(|(waited, _)| waited.eq_ignore_ascii_case(scheme))
6808 {
6809 let (_, answer) = links.next_of_scheme.remove(at);
6810 answer.borrow_mut().deliver(url);
6811 return;
6812 }
6813 }
6814 links.address.set(url.clone());
6815 if quiet {
6816 return;
6817 }
6818 if let Some(reason) = change {
6819 if !links.hears_changes {
6820 return;
6821 }
6822 let change = crate::url_scheme::AppUrlChange { url, reason };
6823 if let Some(answer) = links.next_change.take() {
6824 answer.borrow_mut().deliver(change);
6825 return;
6826 }
6827 if links.changes.len() == crate::url_scheme::MAX_PENDING {
6828 links.changes.pop_front();
6829 }
6830 links.changes.push_back(change);
6831 return;
6832 }
6833 let executor = &self.components.executor;
6834 links.open(url, |task| executor.has_task(task));
6835 }
6836
6837 pub fn set_url_schemes(&mut self, schemes: impl IntoIterator<Item = impl Into<String>>) {
6842 self.components.url_schemes.links.set_schemes(schemes);
6843 }
6844
6845 pub fn set_app_links(&mut self, links: crate::url_scheme::AppLinks) {
6850 self.components.url_schemes.links = links;
6851 }
6852
6853 fn notification_event(&mut self, payload: &EventPayload) {
6855 use crate::notifications::{NotificationEvent as Field, NotificationPermission};
6856 let EventPayload::Map(entries) = payload else {
6857 return;
6858 };
6859 let state = &mut self.components.notifications;
6860 let id = entries.iter().find_map(|(k, v)| match v {
6861 crate::PayloadValue::Number(n) if *k == Field::ID => Some(*n as u32),
6862 _ => None,
6863 });
6864 for (key, value) in entries {
6865 match (*key, value) {
6866 (Field::PERMISSION, crate::PayloadValue::Str(name)) => {
6867 if let Some(answer) = id.and_then(|id| state.permissions.remove(&id)) {
6868 let permission = NotificationPermission::from_name(name)
6869 .unwrap_or(NotificationPermission::Unavailable);
6870 answer.borrow_mut().deliver(permission);
6871 }
6872 }
6873 (Field::SHOWN, crate::PayloadValue::Bool(shown)) => {
6874 if let Some(answer) = id.and_then(|id| state.shows.remove(&id)) {
6875 answer.borrow_mut().deliver(*shown);
6876 }
6877 }
6878 (Field::PRESSED, crate::PayloadValue::Str(pressed)) => {
6879 match state.next_press.take() {
6880 Some(answer) => answer.borrow_mut().deliver(pressed.clone()),
6881 None => state.presses.push_back(pressed.clone()),
6882 }
6883 }
6884 _ => {}
6885 }
6886 }
6887 }
6888
6889 fn audio_action(&mut self, action: crate::element::AudioAction) {
6893 use crate::{
6894 audio::{AudioCommand, AudioError, AudioEvent},
6895 element::AudioAction,
6896 };
6897 let (command, sink) = match action {
6898 AudioAction::Available(answer) => {
6899 let available = match &self.audio {
6900 Some(backend) => backend.available(),
6901 None => self.components.environment.audio,
6902 };
6903 answer.borrow_mut().deliver(available);
6904 return;
6905 }
6906 AudioAction::Open { mut command, sink } => {
6907 debug_assert!(matches!(
6908 command,
6909 AudioCommand::Load { .. }
6910 | AudioCommand::LoadUrl { .. }
6911 | AudioCommand::Open { .. }
6912 ));
6913 let failed = |error, message: &str| AudioEvent::Failed {
6914 error,
6915 message: message.into(),
6916 };
6917 if !self.access.allows_audio() {
6918 sink.send(failed(AudioError::NotAllowed, "sound is not granted"));
6919 sink.close();
6920 self.deny(
6921 "sound is not granted: add `\"audio\": true` to capabilities in nsh.json"
6922 .into(),
6923 );
6924 return;
6925 }
6926 if let AudioCommand::Open { src, .. } | AudioCommand::LoadUrl { url: src, .. } =
6928 &mut command
6929 {
6930 match self.media_source(src) {
6931 Some(granted) => {
6932 if let Some(url) = granted {
6933 *src = url.to_string();
6934 }
6935 }
6936 None => {
6937 let base = self.base_url.as_deref();
6938 let capability = crate::access::media_capability(src, base);
6939 let advice = crate::access::media_grant_advice(src, base);
6940 sink.send(failed(
6943 AudioError::NotAllowed,
6944 &format!("{}{capability}", super::SOURCE_NOT_GRANTED),
6945 ));
6946 sink.close();
6947 self.deny(format!(
6948 "`{src}` is not granted by capabilities.{capability}: {advice}"
6949 ));
6950 return;
6951 }
6952 }
6953 }
6954 if self.audio.is_none() && !self.components.environment.audio {
6955 sink.send(failed(AudioError::Unavailable, "nothing plays sound here"));
6956 sink.close();
6957 return;
6958 }
6959 self.components.audio.insert(command.id(), sink.clone());
6960 (command, sink)
6961 }
6962 AudioAction::Command(command) => {
6963 let id = command.id();
6964 let sink = if command.ends() {
6965 self.components.audio.remove(&id)
6966 } else {
6967 self.components.audio.get(&id).cloned()
6968 };
6969 let Some(sink) = sink else {
6971 return;
6972 };
6973 if command.ends() {
6974 sink.close();
6975 }
6976 (command, sink)
6977 }
6978 };
6979 match self.audio.clone() {
6980 Some(backend) => backend.command(command, &sink),
6981 None => {
6982 let _ = self.apply_op(Op::Command {
6983 id: crate::ROOT_ID,
6984 command: Command::Audio(command),
6985 });
6986 }
6987 }
6988 }
6989
6990 fn apply_action(&mut self, action: Action) {
6991 match action {
6992 Action::Command(id, command) => {
6993 let _ = self.apply_op(Op::Command { id, command });
6994 }
6995 Action::WriteClipboard(command, answer) => {
6998 self.components.clipboard_writes.push_back(answer);
6999 let _ = self.apply_op(Op::Command {
7000 id: crate::ROOT_ID,
7001 command,
7002 });
7003 }
7004 Action::FocusBack { to, from } => self.focus_back = Some((to, from)),
7005 Action::FocusOrigin { to } => self.note_focus_origin(to),
7006 Action::Dialog(mut dialog, answer) => {
7007 dialog.id = self.components.next_dialog;
7008 self.components.next_dialog += 1;
7009 self.components.dialogs.insert(dialog.id, answer);
7010 let _ = self.apply_op(Op::Command {
7011 id: crate::ROOT_ID,
7012 command: Command::Dialog(Box::new(dialog)),
7013 });
7014 }
7015 Action::CloseDialog(answer) => {
7016 let Some(id) = self
7018 .components
7019 .dialogs
7020 .iter()
7021 .find_map(|(id, slot)| Rc::ptr_eq(slot, &answer).then_some(*id))
7022 else {
7023 return;
7024 };
7025 self.components.dialogs.remove(&id);
7026 answer
7027 .borrow_mut()
7028 .deliver(crate::element::DialogReply::dismissed());
7029 let _ = self.apply_op(Op::Command {
7030 id: crate::ROOT_ID,
7031 command: Command::CloseDialog(id),
7032 });
7033 }
7034 Action::Return(call, result) => self.settle(call, result),
7035 Action::Animation(op) => {
7036 let _ = self.apply_op(Op::Animation(op));
7037 }
7038 Action::Animate { op, animation, end } => {
7039 self.components
7040 .animations
7041 .insert(animation, Awaited::End(end));
7042 let _ = self.apply_op(Op::Animation(op));
7043 }
7044 Action::ReadValue { node, value } => {
7045 let request = self.components.executor.next_animation_id();
7046 self.components
7047 .animations
7048 .insert(request, Awaited::Value(value));
7049 let _ = self.apply_op(Op::Animation(crate::animation::AnimationOp::Read {
7050 node,
7051 request,
7052 }));
7053 }
7054 Action::ReportViewable(list) => self.report_viewable(list),
7055 Action::Hint(overlay) => self.hint_due(overlay),
7056 Action::Frame(answer) => self.wait_frame(answer),
7057 Action::Appearance(appearance) => self.set_appearance(appearance),
7058 Action::Tokens(tokens) => self.set_tokens(tokens),
7059 Action::Translations(translations) => self.set_translations(translations),
7060 Action::AddTranslations(map) => self.add_translations(map),
7061 Action::TranslationsChanged(before) => self.translations_changed(&before),
7062 Action::Locale(locale) => self.components.locale_request = Some(locale),
7063 Action::MainThread(task) => self.components.main_thread.push(task),
7064 Action::BuiltInScrollbars(source, theme) => {
7065 self.set_builtin_scrollbars(theme.map(|theme| (source, theme)))
7066 }
7067 Action::Measure(id, answer) => self.components.measures.push((id, answer)),
7068 Action::MeasureScrollPosition(id, answer) => {
7069 self.components.scroll_positions.push((id, answer))
7070 }
7071 Action::Evaluate(node, script, timeout, answer) => {
7072 self.start_web_evaluation(node, script, timeout, answer)
7073 }
7074 Action::WebEvaluationTimeout(request) => self.timeout_web_evaluation(request),
7075 Action::CanvasRenderTimeout(id) => self.timeout_canvas_render(id),
7076 Action::TransitionTime(id, answer) => {
7077 self.components.transition_times.push((id, answer))
7078 }
7079 Action::TextContent(id, answer) => self.components.text_contents.push((id, answer)),
7080 Action::PressAt(id, press, answer) => self.components.presses.push((id, press, answer)),
7081 Action::HoverAt(id, mouse) => self.components.hovers.push((id, mouse)),
7082 Action::ImageInfo(uri, answer) => {
7083 let id = self.components.next_image_info;
7084 self.components.next_image_info += 1;
7085 self.components.image_infos.insert(id, answer);
7086 let _ = self.apply_op(Op::Command {
7087 id: crate::ROOT_ID,
7088 command: Command::ImageInfo { id, uri },
7089 });
7090 }
7091 Action::Fetch(request, answer) => {
7092 let id = self.components.next_fetch;
7093 self.components.next_fetch += 1;
7094 self.components.fetches.insert(
7095 id,
7096 PendingFetch {
7097 response: crate::element::HttpResponse::default(),
7098 answer,
7099 },
7100 );
7101 self.components.fetch_requests.push((id, *request));
7102 }
7103 Action::RegisterFont(data, answer) => {
7104 let family = crate::text::font_family(&data)
7106 .and_then(|family| self.register_font(&data).map(|()| family));
7107 answer.borrow_mut().deliver(family);
7108 }
7109 Action::PickImages(request, answer) => {
7110 if !self.access.allows_picker() {
7111 answer.borrow_mut().deliver(Vec::new());
7112 self.deny(
7113 "the picker is not granted: add `\"picker\": true` to capabilities in nsh.json"
7114 .into(),
7115 );
7116 return;
7117 }
7118 if let Some(picker) = self.picker.clone() {
7119 let picked = picker.pick_images(request);
7120 crate::element::task::spawn_raw(
7121 &self.components.executor,
7122 crate::ROOT_ID,
7123 Box::pin(async move {
7124 let files = crate::picker::finish(&request, picked.await);
7125 answer.borrow_mut().deliver(files);
7126 }),
7127 );
7128 return;
7129 }
7130 let id = self.components.next_pick;
7131 self.components.next_pick += 1;
7132 self.components
7133 .picks
7134 .insert(id, (crate::picker::Pick::Images(request), answer));
7135 let _ = self.apply_op(Op::Command {
7136 id: crate::ROOT_ID,
7137 command: Command::PickImages { id, request },
7138 });
7139 }
7140 Action::PickFiles(request, answer) => {
7141 if !self.access.allows_picker() {
7142 answer.borrow_mut().deliver(Vec::new());
7143 self.deny(
7144 "the picker is not granted: add `\"picker\": true` to capabilities in nsh.json"
7145 .into(),
7146 );
7147 return;
7148 }
7149 if let Some(picker) = self.picker.clone() {
7150 let picked = picker.pick_files(request.clone());
7151 crate::element::task::spawn_raw(
7152 &self.components.executor,
7153 crate::ROOT_ID,
7154 Box::pin(async move {
7155 let files = crate::picker::finish_files(&request, picked.await);
7156 answer.borrow_mut().deliver(files);
7157 }),
7158 );
7159 return;
7160 }
7161 let id = self.components.next_pick;
7162 self.components.next_pick += 1;
7163 self.components
7164 .picks
7165 .insert(id, (crate::picker::Pick::Files(request.clone()), answer));
7166 let _ = self.apply_op(Op::Command {
7167 id: crate::ROOT_ID,
7168 command: Command::PickFiles { id, request },
7169 });
7170 }
7171 Action::ReadClipboard(read) => {
7172 let id = self.components.next_clipboard_read;
7173 self.components.next_clipboard_read += 1;
7174 let command = match &read {
7175 ClipboardRead::Text(_) | ClipboardRead::CheckedText(_) => {
7176 Command::ReadClipboard {
7177 id,
7178 has_only: false,
7179 }
7180 }
7181 ClipboardRead::Has(_) => Command::ReadClipboard { id, has_only: true },
7182 ClipboardRead::Image(_) | ClipboardRead::CheckedImage(_) => {
7183 Command::ReadClipboardImage {
7184 id,
7185 has_only: false,
7186 }
7187 }
7188 ClipboardRead::HasImage(_) => {
7189 Command::ReadClipboardImage { id, has_only: true }
7190 }
7191 ClipboardRead::Files(_) => Command::ReadClipboardFiles { id },
7192 };
7193 self.components.clipboard_reads.insert(id, read);
7194 let _ = self.apply_op(Op::Command {
7195 id: crate::ROOT_ID,
7196 command,
7197 });
7198 }
7199 Action::HostCall { name, args, answer } => {
7202 use crate::host_channel::{HostError, MAX_PENDING_CALLS};
7203 let refused = crate::host_channel::refusal(&self.access, &name).or_else(|| {
7204 (self.components.host_calls.len() >= MAX_PENDING_CALLS)
7205 .then(|| HostError::TooManyCalls { name: name.clone() })
7206 });
7207 if let Some(error) = refused {
7208 if !matches!(error, HostError::TooManyCalls { .. }) {
7209 self.deny(error.to_string());
7210 }
7211 answer.borrow_mut().deliver(Err(error));
7212 return;
7213 }
7214 let id = self.components.next_host_call;
7215 self.components.next_host_call += 1;
7216 self.components.host_calls.insert(id, answer);
7217 self.components
7218 .host_requests
7219 .push(crate::host_channel::HostRequest::Call { id, name, args });
7220 }
7221 Action::HostPost { name, args } => {
7222 if let Some(error) = crate::host_channel::refusal(&self.access, &name) {
7223 self.deny(error.to_string());
7224 return;
7225 }
7226 self.components
7227 .host_requests
7228 .push(crate::host_channel::HostRequest::Post { name, args });
7229 }
7230 Action::ForgetHostCalls => {
7233 self.components
7234 .host_calls
7235 .retain(|_, slot| std::rc::Rc::strong_count(slot) > 1);
7236 }
7237 Action::OpenUrl(url, answer) => {
7238 if let Err(refused) = crate::open_url::check_url(&url) {
7239 log::warn!(target: "js", "{refused}");
7240 answer.borrow_mut().deliver(false);
7241 return;
7242 }
7243 if !self.access.allows_open_url(&url) {
7244 answer.borrow_mut().deliver(false);
7245 self.deny(crate::open_url::not_granted(&url).message().to_owned());
7246 return;
7247 }
7248 let id = self.components.next_url_open;
7249 self.components.next_url_open = id.wrapping_add(1);
7250 self.components.url_opens.insert(id, answer);
7251 self.components.url_requests.push((id, url));
7252 }
7253 Action::OpenAppSettings(answer) => {
7254 use crate::mobile::AppSettingsError;
7255 let refused = if !self.access.allows_application() {
7259 Some(AppSettingsError::Denied)
7260 } else if !self.components.environment.app_settings {
7261 Some(AppSettingsError::Unavailable)
7262 } else {
7263 None
7264 };
7265 if let Some(error) = refused {
7266 answer.borrow_mut().deliver(Err(error));
7267 return;
7268 }
7269 let id = self.components.next_app_settings_open;
7270 self.components.next_app_settings_open = id.wrapping_add(1);
7271 self.components.app_settings_opens.insert(id, answer);
7272 let _ = self.apply_op(Op::Command {
7273 id: crate::ROOT_ID,
7274 command: Command::OpenAppSettings { id },
7275 });
7276 }
7277 Action::AppSettingsAvailable(answer) => {
7278 let available =
7279 self.components.environment.app_settings && self.access.allows_application();
7280 answer.borrow_mut().deliver(available);
7281 }
7282 Action::Audio(action) => self.audio_action(action),
7283 Action::Notification(action) => self.notification_action(action),
7284 Action::LoginItem(enabled, answer) => self.login_item_action(enabled, answer),
7285 Action::SnapToWindowMargin(margin) => self.set_snap_to_window_margin(margin),
7286 Action::ChooseMenuItem(item) => {
7287 let payload =
7290 EventPayload::Map(vec![("id", crate::PayloadValue::Number(f64::from(item)))]);
7291 if !self.dispatch_event(crate::ROOT_ID, EventKind::Menu, &payload) {
7292 self.events.push(crate::element::JsEvent::Event(
7293 crate::ROOT_ID,
7294 EventKind::Menu,
7295 payload,
7296 ));
7297 }
7298 }
7299 Action::NextUrlSchemeOpen(task, answer) => {
7300 let executor = &self.components.executor;
7301 self.components
7302 .url_schemes
7303 .listen(task, answer, |task| executor.has_task(task));
7304 }
7305 Action::NextUrlSchemeOpenFor(scheme, answer) => {
7306 let links = &mut self.components.url_schemes;
7307 let claimed = links.links.schemes().contains(&scheme)
7308 || (scheme == "https" && !links.links.web().is_empty());
7309 if !claimed {
7310 log::warn!(
7311 "next_url_scheme_open_for: the app does not claim `{scheme}` (nsh.json `schemes`), so no link of it comes"
7312 );
7313 }
7314 links
7315 .next_of_scheme
7316 .retain(|(_, answer)| crate::element::task::awaited(answer));
7317 links.next_of_scheme.push((scheme, answer));
7318 }
7319 Action::NextOpenFiles(answer) => {
7320 let files = &mut self.components.open_files;
7321 if files.pending.is_empty() {
7322 files.next = Some(answer);
7323 } else {
7324 answer
7325 .borrow_mut()
7326 .deliver(files.pending.drain(..).collect());
7327 }
7328 }
7329 Action::NextSecondInstance(answer) => {
7330 let launches = &mut self.components.second_instances;
7331 match launches.pending.pop_front() {
7332 Some(launch) => answer.borrow_mut().deliver(launch),
7333 None => launches.next = Some(answer),
7334 }
7335 }
7336 Action::NextAppUrlChange(answer) => {
7337 let links = &mut self.components.url_schemes;
7338 links.hears_changes = true;
7339 match links.changes.pop_front() {
7340 Some(change) => answer.borrow_mut().deliver(change),
7341 None => links.next_change = Some(answer),
7342 }
7343 }
7344 Action::AppUrl(answer) => {
7345 let address = self.components.url_schemes.address.get();
7346 answer.borrow_mut().deliver(address);
7347 }
7348 Action::SetAppUrl(url, history) => {
7349 let address = self.components.url_schemes.address.clone();
7353 if let Some(base) = address.page_base()
7354 && !crate::url_scheme::same_origin(Some(base.as_str()), &url)
7355 {
7356 log::warn!("set_app_url: {url} is not of the page's origin");
7357 return;
7358 }
7359 address.set(url.clone());
7362 let command = match history {
7366 crate::url_scheme::HistoryBehavior::Push => Command::PushAppUrl(url),
7367 _ => Command::SetAppUrl(url),
7368 };
7369 let _ = self.apply_op(Op::Command {
7370 id: crate::ROOT_ID,
7371 command,
7372 });
7373 }
7374 Action::WebInputAvailable(answer) => {
7375 let available =
7376 self.components.environment.web_input && self.access.allows_web_input();
7377 answer.borrow_mut().deliver(available);
7378 }
7379 Action::WebEvaluateAvailable(answer) => {
7380 let available =
7381 self.components.environment.web_evaluate && self.access.allows_webviews();
7382 answer.borrow_mut().deliver(available);
7383 }
7384 Action::WebViewAvailable(answer) => {
7385 let available =
7386 self.components.environment.web_views && self.access.allows_webviews();
7387 answer.borrow_mut().deliver(available);
7388 }
7389 Action::DownloadDecision {
7390 node,
7391 id,
7392 decision,
7393 answer,
7394 } => {
7395 let effects = self
7396 .components
7397 .downloads
7398 .decide(node, &id, decision, answer);
7399 self.apply_download_effects(effects);
7400 }
7401 Action::PickScreenColor(answer) => {
7402 if !self.components.environment.screen_color {
7403 answer.borrow_mut().deliver(None);
7404 return;
7405 }
7406 let id = self.components.next_screen_color;
7407 self.components.next_screen_color = id.wrapping_add(1);
7408 self.components.screen_colors.insert(id, answer);
7409 let _ = self.apply_op(Op::Command {
7410 id: crate::ROOT_ID,
7411 command: Command::PickScreenColor { id },
7412 });
7413 }
7414 Action::RenderCanvas(request, answer) => self.start_canvas_render(*request, answer),
7415 Action::FileRequest(request, answer) => {
7416 use crate::file_dialog::FileRequest;
7417 if !self.components.environment.file_requests {
7418 answer.deliver(
7419 Vec::new(),
7420 Some("this platform has no file dialogs, file manager or trash".into()),
7421 );
7422 return;
7423 }
7424 if let FileRequest::OpenPath(path)
7425 | FileRequest::RevealPath(path)
7426 | FileRequest::MoveToTrash(path) = &request
7427 && !path.is_absolute()
7428 {
7429 let refused = format!("`{}` is not an absolute path", path.display());
7430 log::warn!("{refused}");
7431 answer.deliver(Vec::new(), Some(refused));
7432 return;
7433 }
7434 let id = self.components.next_file_request;
7435 self.components.next_file_request = id.wrapping_add(1);
7436 self.components.file_requests.insert(id, answer);
7437 let _ = self.apply_op(Op::Command {
7438 id: crate::ROOT_ID,
7439 command: Command::FileRequest {
7440 id,
7441 request: Box::new(request),
7442 },
7443 });
7444 }
7445 }
7446 }
7447
7448 fn apply_download_effects(&mut self, effects: Vec<crate::webview::downloads::Effect>) {
7451 use crate::webview::downloads::Effect;
7452 for effect in effects {
7453 match effect {
7454 Effect::Event {
7455 node,
7456 kind,
7457 payload,
7458 } => {
7459 self.events
7460 .push(crate::element::JsEvent::Event(node, kind, payload));
7461 }
7462 Effect::Command {
7463 node,
7464 operation,
7465 track,
7466 } => {
7467 let id = self.alloc_webview_request();
7468 self.components.downloads.track(id, track);
7469 let _ = self.apply_op(Op::Command {
7470 id: node,
7471 command: Command::WebViewRequest(crate::webview::WebViewRequest {
7472 id,
7473 operation,
7474 }),
7475 });
7476 }
7477 Effect::Answer { slot, result } => slot.borrow_mut().deliver(result),
7478 }
7479 }
7480 }
7481
7482 fn alloc_webview_request(&mut self) -> u64 {
7485 loop {
7486 let id = self.components.next_webview_request;
7487 self.components.next_webview_request = id.wrapping_add(1);
7488 if !self.components.downloads.tracks(id) {
7489 break id;
7490 }
7491 }
7492 }
7493
7494 pub(super) fn webview_released(&mut self, id: NodeId) {
7500 let effects = self.components.downloads.teardown(id);
7501 for effect in effects {
7505 match effect {
7506 crate::webview::downloads::Effect::Event {
7507 node,
7508 kind,
7509 payload,
7510 } => self
7511 .events
7512 .push(crate::element::JsEvent::Event(node, kind, payload)),
7513 crate::webview::downloads::Effect::Command {
7514 node,
7515 operation,
7516 track,
7517 } => {
7518 let request = self.alloc_webview_request();
7519 self.components.downloads.track(request, track);
7520 self.mount.push(crate::MountItem::Command {
7521 id: node,
7522 command: Command::WebViewRequest(crate::webview::WebViewRequest {
7523 id: request,
7524 operation,
7525 }),
7526 });
7527 }
7528 crate::webview::downloads::Effect::Answer { slot, result } => {
7529 slot.borrow_mut().deliver(result);
7530 }
7531 }
7532 }
7533 }
7534
7535 fn download_event(&mut self, id: NodeId, kind: EventKind, payload: &EventPayload) -> bool {
7539 match kind {
7540 EventKind::DownloadOffer => {
7541 let EventPayload::Json(value) = payload else {
7542 return true;
7543 };
7544 let Some(offer) = crate::webview::downloads::parse_offer(value) else {
7545 log::debug!(target: "js", "web view: dropped a malformed download offer: {value}");
7546 return true;
7547 };
7548 let events = self
7549 .key(id)
7550 .ok()
7551 .map(|key| self.nodes[key as usize].events)
7552 .unwrap_or_default();
7553 let mode = if events.contains(EventKind::DownloadPending) {
7554 crate::webview::downloads::Mode::Manual
7555 } else if events.contains(EventKind::Download) {
7556 crate::webview::downloads::Mode::Automatic
7557 } else {
7558 crate::webview::downloads::Mode::None
7559 };
7560 let automatic =
7561 crate::webview::downloads::automatic_destination(&offer.id, &offer.filename);
7562 let refused = (!self.access.is_unrestricted()
7569 && !page_content(&offer.url)
7570 && !self.access.allows_webview(&offer.url))
7571 .then(|| super::not_granted("the download", &offer.url, "webview.hosts"));
7572 if let Some(message) = &refused {
7573 self.deny(message.clone());
7574 }
7575 let effects = self
7576 .components
7577 .downloads
7578 .offer(id, offer, mode, automatic, refused);
7579 self.apply_download_effects(effects);
7580 }
7581 EventKind::DownloadProgress => {
7582 }
7585 EventKind::DownloadEnd => {
7586 let EventPayload::Json(value) = payload else {
7587 return true;
7588 };
7589 let Some(end) = crate::webview::downloads::parse_end(value) else {
7590 log::debug!(target: "js", "web view: dropped a malformed download end: {value}");
7591 return true;
7592 };
7593 let effects = self.components.downloads.end(id, end);
7594 self.apply_download_effects(effects);
7595 }
7596 _ => return false,
7597 }
7598 true
7599 }
7600
7601 pub(super) fn poll_downloads(&mut self) {
7603 let effects = self.components.downloads.poll(crate::time::now());
7604 if !effects.is_empty() {
7605 self.apply_download_effects(effects);
7606 }
7607 }
7608
7609 pub(super) fn sync_download_listeners(&mut self) {
7616 let nodes = self.components.downloads.unobserved_nodes(|node| {
7617 self.key(node).is_ok_and(|key| {
7618 let events = self.nodes[key as usize].events;
7619 events.contains(EventKind::Download) || events.contains(EventKind::DownloadPending)
7620 })
7621 });
7622 for node in nodes {
7623 let effects = self.components.downloads.lost_listener(node);
7624 self.apply_download_effects(effects);
7625 }
7626 }
7627
7628 pub fn download_deadline(&self) -> Option<crate::time::Instant> {
7630 self.components.downloads.deadline()
7631 }
7632
7633 pub fn animations_finished(&mut self, finished: &mut Vec<crate::animation::Finished>) {
7636 finished.retain(|f| match self.components.animations.remove(&f.animation) {
7637 Some(Awaited::End(end)) => {
7638 end.borrow_mut().deliver(f.finished);
7639 false
7640 }
7641 Some(Awaited::Value(value)) => {
7642 value.borrow_mut().deliver(f.value.unwrap_or_default());
7643 false
7644 }
7645 None => f.animation % 2 == 0,
7647 });
7648 }
7649
7650 pub(super) fn answer_image_info(&mut self, id: u32, size: Result<ImageSize, String>) {
7652 if let Some(answer) = self.components.image_infos.remove(&id) {
7653 answer.borrow_mut().deliver(size);
7654 }
7655 }
7656
7657 pub fn take_url_opens(&mut self, out: &mut Vec<(u32, String)>) {
7663 out.append(&mut self.components.url_requests);
7664 }
7665
7666 pub(super) fn answer_clipboard_write(&mut self, result: crate::element::ClipboardWrite) {
7668 if let Some(answer) = self.components.clipboard_writes.pop_front() {
7669 answer.borrow_mut().deliver(result);
7670 }
7671 }
7672
7673 pub fn answer_open_url(&mut self, id: u32, opened: bool) {
7675 if let Some(answer) = self.components.url_opens.remove(&id) {
7676 answer.borrow_mut().deliver(opened);
7677 }
7678 }
7679
7680 pub fn open_url_on_platform(&mut self, id: u32, url: String) {
7683 if !self.components.url_opens.contains_key(&id) {
7684 return;
7685 }
7686 let _ = self.apply_op(Op::Command {
7687 id: crate::ROOT_ID,
7688 command: Command::OpenUrl { id, url },
7689 });
7690 }
7691
7692 pub fn take_fetches(
7698 &mut self,
7699 start: &mut Vec<(u32, crate::platform::HttpRequest)>,
7700 abandoned: &mut Vec<u32>,
7701 ) {
7702 start.append(&mut self.components.fetch_requests);
7703 if self.components.fetches.is_empty() {
7704 return;
7705 }
7706 self.components.fetches.retain(|&id, pending| {
7707 let wanted = Rc::strong_count(&pending.answer) > 1;
7709 if !wanted {
7710 abandoned.push(id);
7711 }
7712 wanted
7713 });
7714 start.retain(|(id, _)| !abandoned.contains(id));
7715 }
7716
7717 pub fn fetch_event(&mut self, id: u32, event: crate::platform::FetchEvent) -> bool {
7721 use crate::platform::FetchEvent;
7722 let Some(pending) = self.components.fetches.get_mut(&id) else {
7723 return false;
7724 };
7725 if Rc::strong_count(&pending.answer) == 1 {
7727 self.components.fetches.remove(&id);
7728 return false;
7729 }
7730 match event {
7731 FetchEvent::BodyWanted => {}
7732 FetchEvent::Head(head) => pending.response.head = head,
7733 FetchEvent::Data(data) => pending.response.body.extend_from_slice(&data),
7734 FetchEvent::End => {
7735 if let Some(pending) = self.components.fetches.remove(&id) {
7736 pending.answer.borrow_mut().deliver(Ok(pending.response));
7737 }
7738 return false;
7739 }
7740 FetchEvent::Failed(error) => {
7741 if let Some(pending) = self.components.fetches.remove(&id) {
7742 pending
7743 .answer
7744 .borrow_mut()
7745 .deliver(Err(FetchFailure::Failed(error)));
7746 }
7747 return false;
7748 }
7749 }
7750 true
7751 }
7752
7753 pub fn fetch_refused(&mut self, id: u32, message: String, url: String) {
7761 if let Some(pending) = self.components.fetches.remove(&id) {
7762 let refused = FetchFailure::Refused { message, url };
7763 pending.answer.borrow_mut().deliver(Err(refused));
7764 }
7765 }
7766
7767 pub(super) fn answer_clipboard(&mut self, id: u32, answer: ClipboardAnswer) {
7770 let ClipboardAnswer {
7771 has,
7772 text,
7773 denied,
7774 image,
7775 too_large,
7776 files,
7777 } = answer;
7778 let image = image.filter(|i| !i.url.is_empty());
7779 match self.components.clipboard_reads.remove(&id) {
7780 Some(ClipboardRead::Text(slot)) => slot.borrow_mut().deliver(text.unwrap_or_default()),
7781 Some(ClipboardRead::CheckedText(slot)) => slot
7782 .borrow_mut()
7783 .deliver((!denied).then(|| text.unwrap_or_default())),
7784 Some(ClipboardRead::Has(slot) | ClipboardRead::HasImage(slot)) => {
7785 slot.borrow_mut().deliver(has)
7786 }
7787 Some(ClipboardRead::Image(slot)) => slot.borrow_mut().deliver(image),
7788 Some(ClipboardRead::CheckedImage(slot)) => slot.borrow_mut().deliver(match too_large {
7789 Some(bytes) => Err(bytes),
7790 None => Ok(image),
7791 }),
7792 Some(ClipboardRead::Files(slot)) => slot.borrow_mut().deliver(files),
7793 None => {}
7794 }
7795 }
7796
7797 #[doc(hidden)]
7801 pub fn answer_host(
7802 &mut self,
7803 id: u64,
7804 result: Result<crate::JsonValue, crate::host_channel::HostError>,
7805 ) {
7806 match self.components.host_calls.remove(&id) {
7807 Some(answer) if std::rc::Rc::strong_count(&answer) > 1 => {
7808 answer.borrow_mut().deliver(result);
7809 }
7810 _ => {
7811 log::debug!(target: "js", "nsh/host: dropped the answer to call {id}, which no longer waits")
7812 }
7813 }
7814 }
7815
7816 #[doc(hidden)]
7823 pub fn take_host_requests(&mut self, out: &mut Vec<crate::host_channel::HostRequest>) {
7824 out.append(&mut self.components.host_requests);
7825 }
7826
7827 #[doc(hidden)]
7836 pub fn host_request_on_platform(&mut self, request: crate::host_channel::HostRequest) {
7837 use crate::host_channel::{HostError, HostRequest};
7838 let host = self.components.environment.host;
7839 let command = match request {
7840 HostRequest::Call { id, .. } if !host => {
7841 self.answer_host(id, Err(HostError::Unavailable));
7842 return;
7843 }
7844 HostRequest::Post { .. } if !host => return,
7845 HostRequest::Call { id, name, args } => Command::HostCall { id, name, args },
7846 HostRequest::Post { name, args } => Command::HostPost { name, args },
7847 };
7848 let _ = self.apply_op(Op::Command {
7849 id: crate::ROOT_ID,
7850 command,
7851 });
7852 }
7853
7854 #[doc(hidden)]
7861 pub fn host_event(&mut self, event: &str, data: &crate::JsonValue) {
7862 if !self.components.executor.host_events.borrow().listens(event) {
7863 if let Some((dropped, _)) = self
7866 .components
7867 .host_inbox
7868 .push(event.to_owned(), data.clone())
7869 {
7870 log::debug!(target: "js", "nsh/host: no Rust listener heard \"{dropped}\"; the oldest kept event was dropped");
7871 }
7872 return;
7873 }
7874 self.deliver_kept_host_events(event);
7876 self.dispatch_host_event(event, data);
7877 }
7878
7879 #[doc(hidden)]
7886 pub fn release_host_events(&mut self) -> bool {
7887 let names = {
7888 let mut listeners = self.components.executor.host_events.borrow_mut();
7889 if !std::mem::take(&mut listeners.added) || self.components.host_inbox.is_empty() {
7890 return false;
7891 }
7892 listeners.names()
7893 };
7894 let mut delivered = false;
7895 for name in names {
7896 delivered |= self.deliver_kept_host_events(&name);
7897 }
7898 delivered
7899 }
7900
7901 fn deliver_kept_host_events(&mut self, event: &str) -> bool {
7905 let mut delivered = false;
7906 while self.components.executor.host_events.borrow().listens(event) {
7907 let Some(data) = self.components.host_inbox.pop(event) else {
7908 break;
7909 };
7910 self.dispatch_host_event(event, &data);
7911 delivered = true;
7912 }
7913 delivered
7914 }
7915
7916 fn dispatch_host_event(&mut self, event: &str, data: &crate::JsonValue) {
7919 let listeners = self.components.executor.host_events.borrow().of(event);
7920 let _entered = self.components.runtime.enter();
7921 for listener in listeners {
7922 let result = caught(|| listener(data));
7923 self.apply_actions();
7924 if let Err(message) = result {
7925 log::error!(target: "js", "a listener of the host's \"{event}\" failed: {message}");
7926 }
7927 }
7928 }
7929
7930 fn report_window(&mut self, id: NodeId, event: &crate::desktop::WindowEvent) {
7934 use crate::desktop::WindowEvent;
7935 match event {
7936 WindowEvent::State(state) => {
7937 self.components.window_reports.entry(id).or_default().0 = Some(**state);
7938 }
7939 WindowEvent::TitleBar(area) => {
7940 self.components.window_reports.entry(id).or_default().1 = *area;
7941 }
7942 WindowEvent::Closed { .. } => {
7943 self.components.window_reports.remove(&id);
7944 if let Some((owner, _)) = self.components.js_windows.remove(&id) {
7945 let _entered = self.components.runtime.enter();
7946 owner.dispose();
7947 }
7948 return;
7949 }
7950 _ => return,
7951 }
7952 if let Some((_, this)) = self.components.js_windows.get(&id) {
7953 let _entered = self.components.runtime.enter();
7954 this.report(event);
7955 }
7956 }
7957
7958 fn platform_event(&mut self, id: NodeId, kind: EventKind, payload: &EventPayload) -> bool {
7961 if matches!(
7962 kind,
7963 EventKind::DownloadOffer | EventKind::DownloadProgress | EventKind::DownloadEnd
7964 ) {
7965 return self.download_event(id, kind, payload);
7966 }
7967 let number = |key: &str| match payload {
7968 EventPayload::Map(entries) => entries.iter().find_map(|(k, v)| match v {
7969 crate::PayloadValue::Number(n) if *k == key => Some(*n),
7970 _ => None,
7971 }),
7972 _ => None,
7973 };
7974 match kind {
7975 EventKind::Window => {
7978 if let EventPayload::Window(event) = payload {
7979 if id != ROOT_ID {
7980 self.report_window(id, event);
7981 }
7982 match event.as_ref() {
7983 crate::desktop::WindowEvent::State(state) => {
7984 self.keep_window_placement(id, state);
7985 }
7986 crate::desktop::WindowEvent::ClosePress { reason }
7989 if id == crate::ROOT_ID =>
7990 {
7991 self.components.runtime.main_close_pressed(*reason);
7992 }
7993 crate::desktop::WindowEvent::QuitRequest if id == crate::ROOT_ID => {
7994 self.quit_requested();
7995 return true;
7996 }
7997 _ => {}
7998 }
7999 }
8000 false
8001 }
8002 EventKind::Dialog => {
8003 let Some(dialog) = number("id") else {
8004 return false;
8005 };
8006 let Some(answer) = self.components.dialogs.remove(&(dialog as u32)) else {
8007 return false;
8008 };
8009 let value = match payload {
8010 EventPayload::Map(entries) => entries.iter().find_map(|(k, v)| match v {
8011 crate::PayloadValue::Str(text) if *k == "value" => Some(text.clone()),
8012 _ => None,
8013 }),
8014 _ => None,
8015 };
8016 answer.borrow_mut().deliver(crate::element::DialogReply {
8017 index: number("index").unwrap_or(-1.0) as i32,
8018 value,
8019 });
8020 true
8021 }
8022 EventKind::KeyCommand if id == crate::ROOT_ID => {
8024 let EventPayload::Value(crate::PayloadValue::Number(binding)) = payload else {
8025 return false;
8026 };
8027 let binding = *binding as u32;
8028 if binding < crate::element::keys::FIRST_ID {
8029 return false;
8030 }
8031 if binding == super::overlay::ESCAPE_BINDING {
8032 self.overlay_escape();
8033 return true;
8034 }
8035 let found = self.components.executor.keys.borrow().handler(binding);
8036 if let Some((text, handler)) = found {
8038 let result = caught(|| handler(&text));
8039 self.apply_actions();
8040 if let Err(message) = result {
8041 log::error!(target: "js", "a keyboard shortcut failed: {message}");
8042 }
8043 }
8044 true
8045 }
8046 EventKind::Menu if id == crate::ROOT_ID => {
8049 let menus = self.components.executor.menus.clone();
8050 let closed = matches!(payload, EventPayload::Map(entries)
8051 if entries.iter().any(|(k, v)| *k == "closed" && *v == crate::PayloadValue::Bool(true)));
8052 if closed {
8053 menus.borrow_mut().settle_popup();
8054 return false;
8055 }
8056 let Some(item) = number("id").map(|n| n as u32) else {
8057 return false;
8058 };
8059 if item < crate::element::menus::FIRST_ID {
8060 return false;
8061 }
8062 let registered = match payload {
8064 EventPayload::Map(entries) => entries.iter().find_map(|(k, v)| match v {
8065 crate::PayloadValue::Bool(b) if *k == "registered" => Some(*b),
8066 _ => None,
8067 }),
8068 _ => None,
8069 };
8070 if let Some(registered) = registered {
8071 menus.borrow_mut().registered(item, registered);
8072 self.apply_actions();
8073 return true;
8074 }
8075 let click = menus.borrow().tray_click(item);
8076 if let Some(click) = click {
8077 let bounds = match payload {
8078 EventPayload::Map(entries) => entries.iter().find_map(|(k, v)| match v {
8079 crate::PayloadValue::Bounds(b) if *k == "bounds" => Some(*b),
8080 _ => None,
8081 }),
8082 _ => None,
8083 };
8084 let result = caught(|| click(bounds));
8085 self.apply_actions();
8086 if let Err(message) = result {
8087 log::error!(target: "js", "the tray's click failed: {message}");
8088 }
8089 return true;
8090 }
8091 let handler = menus.borrow().handler(item);
8092 if let Some(handler) = handler {
8094 let result = caught(|| handler());
8095 self.apply_actions();
8096 if let Err(message) = result {
8097 log::error!(target: "js", "a menu item failed: {message}");
8098 }
8099 }
8100 true
8101 }
8102 EventKind::BackPress if id == crate::ROOT_ID => {
8103 if self.overlay_cancel() {
8105 return true;
8106 }
8107 let listeners = self.components.executor.back.borrow().newest_first();
8108 for listener in listeners {
8109 if self.back_pressed(&listener) {
8110 return true;
8111 }
8112 }
8113 if self.components.js_back {
8116 return false;
8117 }
8118 let _ = self.apply_op(Op::Command {
8119 id: crate::ROOT_ID,
8120 command: Command::Back,
8121 });
8122 true
8123 }
8124 EventKind::BackProgress if id == crate::ROOT_ID => {
8125 let Some(event) = crate::BackProgressEvent::from_payload(payload) else {
8126 return true;
8127 };
8128 if event.phase == crate::BackPhase::Start {
8132 self.components.back_gesture = !self.overlay_state.cancel;
8133 }
8134 if !self.components.back_gesture {
8135 return true;
8136 }
8137 if matches!(
8138 event.phase,
8139 crate::BackPhase::End | crate::BackPhase::Cancel
8140 ) {
8141 self.components.back_gesture = false;
8142 }
8143 let listeners = self
8144 .components
8145 .executor
8146 .back_progress
8147 .borrow()
8148 .newest_first();
8149 for listener in listeners {
8150 let result = caught(|| listener(&event));
8151 self.apply_actions();
8152 if let Err(message) = result {
8153 log::error!(target: "js", "a back progress listener failed: {message}");
8154 }
8155 }
8156 !self.components.js_back_progress
8158 }
8159 EventKind::WebEvaluation => {
8160 self.answer_web_evaluation(id, payload);
8161 true
8162 }
8163 EventKind::ImageInfo if id == crate::ROOT_ID => {
8164 let Some(request) = number("id") else {
8165 return false;
8166 };
8167 let error = match payload {
8168 EventPayload::Map(entries) => entries.iter().find_map(|(k, v)| match v {
8169 crate::PayloadValue::Str(e) if *k == "error" => Some(e.clone()),
8170 _ => None,
8171 }),
8172 _ => None,
8173 };
8174 let size = match (number("width"), number("height"), error) {
8175 (Some(width), Some(height), None) => Ok(ImageSize {
8176 width: pixels(width),
8177 height: pixels(height),
8178 }),
8179 (_, _, error) => Err(error.unwrap_or_else(|| "no size".into())),
8180 };
8181 self.answer_image_info(request as u32, size);
8182 true
8183 }
8184 EventKind::Audio if id == crate::ROOT_ID => {
8185 let EventPayload::Audio { id: object, event } = payload else {
8186 return false;
8187 };
8188 if let Some(sink) = self.components.audio.get(object) {
8190 sink.send(event.clone());
8191 }
8192 true
8193 }
8194 EventKind::Pick if id == crate::ROOT_ID => {
8195 let EventPayload::Picked { id: request, files } = payload else {
8196 return false;
8197 };
8198 if let Some((asked, answer)) = self.components.picks.remove(request) {
8199 let files = asked.finish(files.clone());
8200 answer.borrow_mut().deliver(files);
8201 }
8202 true
8203 }
8204 EventKind::Notification if id == crate::ROOT_ID => {
8205 self.notification_event(payload);
8206 true
8207 }
8208 EventKind::SecondInstance if id == crate::ROOT_ID => {
8209 let Some(launch) = crate::single_instance::SecondInstance::from_payload(payload)
8210 else {
8211 return false;
8212 };
8213 let launches = &mut self.components.second_instances;
8214 if let Some(answer) = launches.next.take() {
8215 answer.borrow_mut().deliver(launch);
8216 } else {
8217 if launches.pending.len() == crate::single_instance::MAX_PENDING {
8218 launches.pending.pop_front();
8219 }
8220 launches.pending.push_back(launch);
8221 }
8222 true
8223 }
8224 EventKind::UrlScheme if id == crate::ROOT_ID => {
8225 let EventPayload::Map(entries) = payload else {
8226 return false;
8227 };
8228 let url = entries.iter().find_map(|(k, v)| match v {
8229 crate::PayloadValue::Str(url) if *k == crate::url_scheme::URL => Some(url),
8230 _ => None,
8231 });
8232 let Some(url) = url else {
8233 return false;
8234 };
8235 let flag = |key: &str| {
8236 entries.iter().find_map(|(k, v)| match v {
8237 crate::PayloadValue::Bool(b) if *k == key => Some(*b),
8238 _ => None,
8239 })
8240 };
8241 let page = flag(crate::url_scheme::PAGE).unwrap_or(false);
8242 let quiet = flag(crate::url_scheme::QUIET).unwrap_or(false);
8243 let change = entries.iter().find_map(|(k, v)| match v {
8247 crate::PayloadValue::Str(s) if *k == crate::url_scheme::CHANGE => {
8248 Some(crate::url_scheme::AppUrlChangeReason::parse(s))
8249 }
8250 _ => None,
8251 });
8252 let (quiet, change) = match change {
8253 Some(None) => (true, None),
8254 Some(reason) => (quiet, reason),
8255 None => (quiet, None),
8256 };
8257 if let Some(base) = entries.iter().find_map(|(k, v)| match v {
8260 crate::PayloadValue::Str(s) if *k == crate::url_scheme::BASE => {
8261 url::Url::parse(s).ok()
8262 }
8263 _ => None,
8264 }) {
8265 self.components.url_schemes.address.set_page_base(base);
8266 }
8267 self.url_scheme(url.clone(), page, quiet, change);
8268 true
8269 }
8270 EventKind::ClipboardWrite if id == crate::ROOT_ID => {
8271 let written = match payload {
8272 EventPayload::Map(entries) => entries
8273 .iter()
8274 .any(|(k, v)| *k == "written" && *v == crate::PayloadValue::Bool(true)),
8275 _ => false,
8276 };
8277 self.answer_clipboard_write(if written {
8278 crate::element::ClipboardWrite::Written
8279 } else {
8280 crate::element::ClipboardWrite::Failed
8281 });
8282 true
8283 }
8284 EventKind::OpenUrl if id == crate::ROOT_ID => {
8285 let Some(request) = number("id") else {
8286 return false;
8287 };
8288 let opened = match payload {
8289 EventPayload::Map(entries) => entries
8290 .iter()
8291 .any(|(k, v)| *k == "opened" && *v == crate::PayloadValue::Bool(true)),
8292 _ => false,
8293 };
8294 self.answer_open_url(request as u32, opened);
8295 true
8296 }
8297 EventKind::OpenAppSettings if id == crate::ROOT_ID => {
8298 let Some(request) = number("id") else {
8299 return false;
8300 };
8301 let opened = match payload {
8302 EventPayload::Map(entries) => entries
8303 .iter()
8304 .any(|(k, v)| *k == "opened" && *v == crate::PayloadValue::Bool(true)),
8305 _ => false,
8306 };
8307 if let Some(answer) = self.components.app_settings_opens.remove(&(request as u32)) {
8308 answer.borrow_mut().deliver(Ok(opened));
8309 }
8310 true
8311 }
8312 EventKind::ScreenColor if id == crate::ROOT_ID => {
8313 let Some(request) = number("id") else {
8314 return false;
8315 };
8316 let color = number("color").map(|packed| crate::Color(packed as u32).into());
8317 if let Some(answer) = self.components.screen_colors.remove(&(request as u32)) {
8318 answer.borrow_mut().deliver(color);
8319 }
8320 true
8321 }
8322 EventKind::CanvasImage if id == crate::ROOT_ID => self.answer_canvas_render(payload),
8323 EventKind::FileRequest if id == crate::ROOT_ID => {
8324 let EventPayload::FileRequest {
8325 id: request,
8326 paths,
8327 error,
8328 } = payload
8329 else {
8330 return false;
8331 };
8332 if let Some(answer) = self.components.file_requests.remove(request) {
8333 answer.deliver(paths.clone(), error.clone());
8334 }
8335 true
8336 }
8337 EventKind::WebViewReply => {
8342 let EventPayload::Json(reply) = payload else {
8343 return false;
8344 };
8345 let request = reply.get("id").and_then(|id| {
8348 id.as_u64().or_else(|| {
8349 id.as_f64()
8350 .filter(|n| n.is_finite() && n.fract() == 0.0 && *n >= 0.0)
8351 .map(|n| n as u64)
8352 })
8353 });
8354 let Some(request) = request else {
8355 log::debug!(target: "js", "web view: dropped a reply without a request's id: {reply}");
8356 return true;
8357 };
8358 if !self.components.downloads.tracks(request) {
8359 log::debug!(target: "js", "web view: dropped a reply to unknown request {request}: {reply}");
8360 return true;
8361 }
8362 let result = match reply.get("ok").and_then(crate::JsonValue::as_bool) {
8363 Some(true) => Ok(()),
8364 _ => Err(reply
8365 .get("error")
8366 .and_then(crate::JsonValue::as_str)
8367 .unwrap_or("the web view did not answer")
8368 .to_owned()),
8369 };
8370 let effects = self.components.downloads.reply(id, request, result);
8371 self.apply_download_effects(effects);
8372 true
8373 }
8374 EventKind::Clipboard if id == crate::ROOT_ID => {
8375 let Some(request) = number("id") else {
8376 return false;
8377 };
8378 let answer = ClipboardAnswer::from_payload(payload);
8379 self.answer_clipboard(request as u32, answer);
8380 true
8381 }
8382 EventKind::Host if id == crate::ROOT_ID => {
8385 let EventPayload::Json(reply) = payload else {
8386 return false;
8387 };
8388 match reply.get("type").and_then(crate::JsonValue::as_str) {
8389 Some("reply") => {}
8390 Some("event") => {
8391 if let Some(event) = reply.get("event").and_then(crate::JsonValue::as_str) {
8392 let data = reply.get("payload").cloned().unwrap_or_default();
8393 self.host_event(event, &data);
8394 }
8395 return false;
8396 }
8397 _ => return false,
8398 }
8399 let call = reply.get("id").and_then(|id| {
8402 id.as_u64().or_else(|| {
8403 id.as_f64()
8404 .filter(|n| {
8405 n.fract() == 0.0 && (1.0..=9_007_199_254_740_991.0).contains(n)
8406 })
8407 .map(|n| n as u64)
8408 })
8409 });
8410 let Some(call) = call else {
8411 log::debug!(target: "js", "nsh/host: dropped a reply without a call's id: {reply}");
8412 return true;
8413 };
8414 let result = if reply.get("ok").and_then(crate::JsonValue::as_bool) == Some(true) {
8415 Ok(reply.get("value").cloned().unwrap_or_default())
8416 } else {
8417 Err(crate::host_channel::HostError::Failed(
8418 reply
8419 .get("error")
8420 .and_then(crate::JsonValue::as_str)
8421 .unwrap_or("nsh/host: the call failed")
8422 .to_owned(),
8423 ))
8424 };
8425 self.answer_host(call, result);
8426 true
8427 }
8428 EventKind::Insets => {
8429 let insets = EdgeInsets {
8430 top: Points(number("top").unwrap_or(0.0) as f32),
8431 right: Points(number("right").unwrap_or(0.0) as f32),
8432 bottom: Points(number("bottom").unwrap_or(0.0) as f32),
8433 left: Points(number("left").unwrap_or(0.0) as f32),
8434 };
8435 self.components.insets.insert(id, insets);
8437 false
8439 }
8440 _ => false,
8441 }
8442 }
8443
8444 fn back_pressed(&mut self, listener: &crate::element::BackListener) -> bool {
8446 let result = caught(|| listener());
8447 self.apply_actions();
8448 result.unwrap_or_else(|message| {
8449 log::error!(target: "js", "a back press listener failed: {message}");
8450 false
8451 })
8452 }
8453
8454 pub(super) fn sync_back(&mut self) {
8457 let rust = {
8458 let mut back = self.components.executor.back.borrow_mut();
8459 if !std::mem::take(&mut back.changed) {
8460 return;
8461 }
8462 !back.list.is_empty()
8463 };
8464 let _ = self.apply_op(Op::Listen {
8465 id: crate::ROOT_ID,
8466 event: EventKind::BackPress,
8467 enabled: rust || self.components.js_back || self.overlay_state.cancel,
8468 });
8469 }
8470
8471 pub(super) fn sync_back_progress(&mut self) {
8474 let rust = {
8475 let mut progress = self.components.executor.back_progress.borrow_mut();
8476 if !std::mem::take(&mut progress.changed) {
8477 return;
8478 }
8479 !progress.list.is_empty()
8480 };
8481 let _ = self.apply_op(Op::Listen {
8482 id: crate::ROOT_ID,
8483 event: EventKind::BackProgress,
8484 enabled: rust || self.components.js_back_progress,
8485 });
8486 }
8487
8488 pub(super) fn sync_keys(&mut self) {
8491 let escape_to_focus = self.focus_takes_escape();
8492 if escape_to_focus != self.overlay_state.escape_to_focus {
8493 self.overlay_state.escape_to_focus = escape_to_focus;
8494 self.components.executor.keys.borrow_mut().changed = true;
8495 }
8496 let rust = {
8497 let _entered = self.components.runtime.enter();
8499 let mut keys = self.components.executor.keys.borrow_mut();
8500 if !std::mem::take(&mut keys.changed) && !keys.unplaced {
8503 return;
8504 }
8505 !keys.list.is_empty()
8506 };
8507 let keymap = self.keymap();
8508 let _ = self.apply_op(Op::SetProp {
8509 id: crate::ROOT_ID,
8510 prop: Prop::Keymap(keymap),
8511 });
8512 let _ = self.apply_op(Op::Listen {
8513 id: crate::ROOT_ID,
8514 event: EventKind::KeyCommand,
8515 enabled: rust
8516 || self.components.js_keys
8517 || self.overlay_state.cancel
8518 || self.overlay_state.hint_escape,
8519 });
8520 }
8521
8522 fn keymap(&self) -> Arc<crate::keymap::Keymap> {
8525 let mut keys = self.components.executor.keys.borrow_mut();
8526 let overlay = self.overlay_key_binding();
8527 if keys.list.is_empty() && overlay.is_none() {
8528 keys.unplaced = false;
8529 return self.components.js_keymap.clone();
8530 }
8531 let views = {
8532 let _entered = self.components.runtime.enter();
8533 let mut known: Vec<(crate::element::Owner, NodeId)> = Vec::new();
8536 keys.bindings(|owner| {
8537 if let Some(&(_, window)) = known.iter().find(|(o, _)| *o == owner) {
8538 return window;
8539 }
8540 let window = self.window_of_owner(owner);
8541 known.push((owner, window));
8542 window
8543 })
8544 };
8545 drop(keys);
8546 let js = self.components.js_keymap.bindings();
8551 let bindings = js
8552 .iter()
8553 .filter(|b| !b.comes_after_views())
8554 .chain(views.iter().filter(|b| !b.comes_after_views()))
8555 .chain(js.iter().filter(|b| b.comes_after_views()))
8556 .chain(views.iter().filter(|b| b.comes_after_views()))
8557 .copied()
8558 .chain(overlay)
8559 .collect();
8560 Arc::new(crate::keymap::Keymap::new(bindings))
8561 }
8562
8563 pub(super) fn insets_of(&self, host: NodeId) -> EdgeInsets {
8566 let safe = self.components.environment.safe_area;
8567 let mut key = self.key(host).ok();
8568 while let Some(k) = key {
8569 let node = &self.nodes[k as usize];
8570 if let Some(insets) = self.components.insets.get(&node.id) {
8571 return *insets;
8572 }
8573 match node.kind {
8574 Kind::Screen => {
8576 return EdgeInsets {
8577 top: Points::ZERO,
8578 ..safe
8579 };
8580 }
8581 Kind::Modal => return safe,
8582 _ => {}
8583 }
8584 key = (node.parent != NO_KEY).then_some(node.parent);
8585 }
8586 safe
8587 }
8588
8589 fn clears_keyboard(&self, key: super::Key) -> bool {
8593 let mut key = key;
8594 loop {
8595 let node = &self.nodes[key as usize];
8596 if node.clears_keyboard {
8597 return true;
8598 }
8599 if node.parent == NO_KEY {
8600 return false;
8601 }
8602 key = node.parent;
8603 }
8604 }
8605
8606 pub(super) fn env_insets(
8611 &self,
8612 key: super::Key,
8613 env: &crate::style::EnvEdges,
8614 ) -> [EdgeInsets; 2] {
8615 use crate::style::EnvVar;
8616 let mut root = None;
8617 let mut value = |var: Option<EnvVar>| {
8618 let Some(var) = var else {
8619 return Points::ZERO;
8620 };
8621 if var == EnvVar::KeyboardInsetHeight {
8622 if self.clears_keyboard(key) {
8623 return Points::ZERO;
8624 }
8625 return self
8626 .components
8627 .environment
8628 .keyboard_height
8629 .max(Points::ZERO);
8630 }
8631 let insets = *root.get_or_insert_with(|| self.insets_of(self.nodes[key as usize].id));
8632 match var {
8633 EnvVar::SafeAreaInsetTop => insets.top,
8634 EnvVar::SafeAreaInsetRight => insets.right,
8635 EnvVar::SafeAreaInsetBottom => insets.bottom,
8636 _ => insets.left,
8637 }
8638 };
8639 let mut edges = |vars: &[Option<EnvVar>; 4]| EdgeInsets {
8640 top: value(vars[0]),
8641 right: value(vars[1]),
8642 bottom: value(vars[2]),
8643 left: value(vars[3]),
8644 };
8645 [edges(&env.padding), edges(&env.margin)]
8646 }
8647
8648 pub(super) fn sync_env(&mut self) {
8656 let mut keyboard_moved = std::mem::take(&mut self.keyboard_moved);
8657 if !self.env_styled.is_empty() {
8658 keyboard_moved |= self.restyle_env();
8659 }
8660 let duration = self.components.environment.keyboard_duration;
8661 if keyboard_moved && duration > 0.0 && self.layout_animation.is_none() {
8662 use crate::props::{LayoutAnimation, LayoutCurve, LayoutProperty, LayoutTransition};
8663 self.layout_animation = Some(LayoutAnimation {
8664 create: None,
8665 update: Some(LayoutTransition {
8666 curve: LayoutCurve::Keyboard,
8667 property: LayoutProperty::Opacity,
8668 duration_ms: duration,
8669 delay_ms: 0.0,
8670 }),
8671 delete: None,
8672 });
8673 }
8674 }
8675
8676 fn restyle_env(&mut self) -> bool {
8679 let mut ids = std::mem::take(&mut self.env_scratch);
8680 ids.extend(self.env_styled.iter().copied());
8681 let mut keyboard_moved = false;
8682 for &id in &ids {
8683 let node = self.key(id).ok().and_then(|key| {
8684 let env = self.nodes[key as usize].env.as_deref().copied()?;
8685 Some((key, env))
8686 });
8687 let Some((key, (env, applied))) = node else {
8688 self.env_styled.remove(&id);
8689 continue;
8690 };
8691 let now = self.env_insets(key, &env);
8692 if now == applied {
8693 continue;
8694 }
8695 let keyboard = |vars: &[Option<crate::style::EnvVar>; 4],
8697 was: &EdgeInsets,
8698 now: &EdgeInsets| {
8699 let (was, now) = (
8700 [was.top, was.right, was.bottom, was.left],
8701 [now.top, now.right, now.bottom, now.left],
8702 );
8703 (0..4).any(|i| {
8704 vars[i] == Some(crate::style::EnvVar::KeyboardInsetHeight) && was[i] != now[i]
8705 })
8706 };
8707 keyboard_moved |= keyboard(&env.padding, &applied[0], &now[0])
8708 || keyboard(&env.margin, &applied[1], &now[1]);
8709 self.restyle(key);
8710 }
8711 ids.clear();
8712 self.env_scratch = ids;
8713 keyboard_moved
8714 }
8715
8716 pub(super) fn apply_actions(&mut self) {
8719 for action in self.components.executor.take_actions() {
8720 self.apply_action(action);
8721 }
8722 }
8723
8724 pub(super) fn route_emit(
8728 &mut self,
8729 host: NodeId,
8730 event: Box<dyn crate::element::builder::AnyEvent>,
8731 ) {
8732 match self.components.owners.get(&host).copied() {
8733 Some(parent) => {
8734 let Some(owner) = self.state_owner(parent) else {
8735 return;
8736 };
8737 let mut from = 0;
8739 while let Some((at, listener)) =
8740 self.components.instances.get(&parent).and_then(|inst| {
8741 inst.event_handlers
8742 .iter()
8743 .enumerate()
8744 .skip(from)
8745 .find(|(_, (n, _))| *n == host)
8746 .map(|(at, (_, l))| (at, l.clone()))
8747 })
8748 {
8749 from = at + 1;
8750 if let Err(message) = caught(|| listener.call(event.as_any())) {
8751 self.component_failed(owner, message);
8752 }
8753 self.apply_actions();
8754 }
8755 }
8756 None => self.events.push(JsEvent::Component { host, event }),
8757 }
8758 }
8759}
8760
8761fn drop_caught<T>(value: T) {
8765 if let Err(message) = caught(move || drop(value)) {
8766 log::error!(target: "js", "a value of a call into Rust panicked as it dropped: {message}");
8767 }
8768}
8769
8770fn dispose_rows(rows: &std::rc::Weak<RefCell<CellRowMap>>) {
8772 let Some(rows) = rows.upgrade() else {
8773 return;
8774 };
8775 let owners: Vec<_> = rows.borrow_mut().drain().map(|(_, (_, o))| o).collect();
8776 for owner in owners {
8777 owner.dispose();
8778 }
8779}
8780
8781fn move_rows(cells: &CellRows, diff: Option<&ListDiff>, count: u32) {
8789 let parts: Vec<_> = cells
8790 .borrow()
8791 .iter()
8792 .map(|(&id, &(index, owner))| (id, index, owner))
8793 .collect();
8794 let mut gone = Vec::new();
8795 let moves: Vec<_> = parts
8797 .iter()
8798 .map(|&(id, index, owner)| {
8799 let i = index.get_untracked();
8800 let to = match diff {
8801 Some(d) => d.new_index(i as u32).map(|(to, _)| to as usize),
8802 None => Some(i),
8803 };
8804 (id, index, owner, i, to)
8805 })
8806 .collect();
8807 let mut taken: Vec<usize> = moves
8808 .iter()
8809 .filter(|m| m.2.is_live())
8810 .filter_map(|m| m.4)
8811 .collect();
8812 taken.sort_unstable();
8813 for (id, index, owner, i, to) in moves {
8814 if !owner.is_live() {
8815 gone.push(id);
8816 continue;
8817 }
8818 let to = match to {
8819 Some(to) => Some(to),
8820 None => Some(i).filter(|i| taken.binary_search(i).is_err()),
8823 };
8824 match to {
8825 Some(to) if to < count as usize => index.set(to),
8826 _ => {
8827 owner.dispose();
8828 gone.push(id);
8829 }
8830 }
8831 }
8832 let mut cells = cells.borrow_mut();
8833 for id in gone {
8834 cells.remove(&id);
8835 }
8836}
8837
8838fn row_position(
8843 index: usize,
8844 count: usize,
8845 count_signal: Option<crate::element::Signal<usize>>,
8846 moves: Option<crate::element::reactive::Node>,
8847 made: &std::cell::Cell<Option<crate::element::Signal<usize>>>,
8848) -> Position {
8849 match count_signal {
8850 Some(count) => {
8851 let index = crate::element::signal(index);
8852 made.set(Some(index));
8853 Position::of_row(index.node(), count.node(), moves)
8854 }
8855 None => Position::fixed(index, count),
8856 }
8857}
8858
8859fn pixels(n: f64) -> crate::geometry::DevicePixels {
8862 crate::geometry::DevicePixels(n.round() as i32)
8863}
8864
8865fn page_content(url: &str) -> bool {
8868 let scheme = url.split(':').next().unwrap_or_default();
8869 url.contains(':')
8870 && (scheme.eq_ignore_ascii_case("data") || scheme.eq_ignore_ascii_case("blob"))
8871}