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.dirty_overlay_listeners();
1864 self.localize_platform();
1865 }
1866 if let Some(state) = environment.window_state {
1868 self.keep_window_placement(crate::ROOT_ID, &state);
1869 }
1870 }
1871
1872 pub(super) fn components_viewport(&mut self, size: crate::Size<crate::Points>) {
1874 let environment = Environment {
1875 window: size,
1876 ..self.components.environment
1877 };
1878 self.apply_environment(environment);
1879 }
1880
1881 pub fn discard_ops(&mut self, ops: impl IntoIterator<Item = Op>) {
1886 for op in ops {
1887 if let Op::Rust(RustOp { call, run }) = op {
1888 drop_caught(run);
1891 self.settle(call, Err("the script stopped before the call ran".into()));
1892 }
1893 }
1894 }
1895
1896 pub fn set_posts(&mut self, posts: Posts) {
1899 self.components.posts = posts;
1900 }
1901
1902 pub fn set_task_notify(&mut self, notify: Arc<dyn Fn() + Send + Sync>) {
1905 self.components.executor.set_notify(notify.clone());
1906 self.components.downloads.set_notify(notify);
1907 }
1908
1909 #[doc(hidden)]
1913 pub fn set_download_cleanup(&mut self, cleanup: crate::webview::downloads::DownloadCleanup) {
1914 self.components.downloads.set_cleanup(cleanup);
1915 }
1916
1917 pub fn set_task_runtime(&mut self, runtime: tokio::runtime::Handle) {
1920 self.components.executor.set_runtime(runtime);
1921 }
1922
1923 pub fn next_task_timer(&self) -> Option<crate::time::Instant> {
1926 self.components.executor.next_timer()
1927 }
1928
1929 pub fn run_component_tasks(&mut self) {
1932 let _entered = self.components.runtime.enter();
1933 let executor = self.components.executor.clone();
1934 executor.fire_timers(crate::time::now());
1935 for _ in 0..MAX_TASK_ROUNDS {
1937 let polled = executor.poll_ready();
1938 let actions = executor.take_actions();
1939 if !polled && actions.is_empty() {
1940 return;
1941 }
1942 for action in actions {
1943 self.apply_action(action);
1944 }
1945 for (host, message) in executor.take_failures() {
1946 self.component_failed(host, message);
1947 }
1948 }
1949 }
1950
1951 pub fn has_quit_listeners(&self) -> bool {
1954 !self.components.executor.quit.borrow().is_empty()
1955 }
1956
1957 pub fn start_quit(&mut self) -> bool {
1963 let _entered = self.components.runtime.enter();
1964 let executor = self.components.executor.clone();
1965 let listeners = executor.quit.borrow().all();
1966 for listener in listeners {
1967 match caught(|| listener()) {
1968 Ok(future) => {
1969 let pending = crate::element::quit::Pending::new(&executor.quitting);
1970 drop(crate::element::task::spawn_future(&executor, async move {
1972 future.await;
1973 drop(pending);
1974 }));
1975 }
1976 Err(message) => log::error!(target: "js", "a quit listener failed: {message}"),
1977 }
1978 }
1979 self.apply_actions();
1980 self.quit_pending()
1981 }
1982
1983 fn quit_requested(&mut self) {
1986 let _entered = self.components.runtime.enter();
1987 let listeners = self.components.executor.quit_requests.borrow().all();
1988 for listener in listeners {
1989 if let Err(message) = caught(|| listener()) {
1990 log::error!(target: "js", "a quit request listener failed: {message}");
1991 }
1992 }
1993 self.apply_actions();
1994 }
1995
1996 #[doc(hidden)]
1999 pub fn reopened(&mut self) {
2000 let _entered = self.components.runtime.enter();
2001 let listeners = self.components.executor.reopens.borrow().all();
2002 for listener in listeners {
2003 if let Err(message) = caught(|| listener()) {
2004 log::error!(target: "js", "a reopen listener failed: {message}");
2005 }
2006 }
2007 self.apply_actions();
2008 }
2009
2010 pub(crate) fn last_window_closed(&mut self) {
2012 let _entered = self.components.runtime.enter();
2013 let listeners = self.components.executor.last_window_closed.borrow().all();
2014 for listener in listeners {
2015 if let Err(message) = caught(|| listener()) {
2016 log::error!(target: "js", "a last window closed listener failed: {message}");
2017 }
2018 }
2019 self.apply_actions();
2020 }
2021
2022 pub(super) fn sync_quit_requests(&mut self) -> bool {
2026 let asks = !self.components.executor.quit_requests.borrow().is_empty();
2027 if asks == self.components.asks_quit {
2028 return false;
2029 }
2030 self.components.asks_quit = asks;
2031 let _ = self.apply_op(crate::Op::Command {
2032 id: crate::ROOT_ID,
2033 command: crate::Command::Desktop(Box::new(
2034 crate::desktop::DesktopCommand::SetQuitOnRequest(!asks),
2035 )),
2036 });
2037 true
2038 }
2039
2040 pub fn quit_pending(&self) -> bool {
2042 self.components.executor.quitting.get() > 0
2043 }
2044
2045 pub fn async_calls_pending(&self) -> bool {
2049 self.components.executor.calls.get() > 0
2050 }
2051
2052 pub(super) fn run_answers(&mut self) {
2056 let _entered = self.components.runtime.enter();
2057 for answer in self.components.executor.take_due_answers() {
2058 let crate::element::AfterAnswer { owner, f } = answer;
2059 let result = if owner == crate::element::Owner::detached() {
2060 caught(f)
2061 } else if owner.is_live() {
2062 caught(|| owner.scope(f))
2063 } else {
2064 drop_caught(f);
2065 continue;
2066 };
2067 if let Err(message) = result {
2068 match self.host_of_owner(owner) {
2069 Some(host) => self.component_failed(host, message),
2070 None => {
2071 log::error!(target: "js", "a closure after the app's answer failed: {message}")
2072 }
2073 }
2074 }
2075 self.apply_actions();
2076 }
2077 }
2078
2079 pub(super) fn is_host(&self, id: NodeId) -> bool {
2081 self.components.instances.contains_key(&id)
2082 }
2083
2084 pub(super) fn intercept(&mut self, op: Op) -> Result<Option<Op>, ApplyError> {
2087 if !self.components.adopted.is_empty()
2092 && let Op::SetProp { id, .. } | Op::Listen { id, .. } | Op::Release { id } = &op
2093 && self.components.adopted.contains_key(id)
2094 && !self.is_host(*id)
2095 {
2096 return Ok(self.js_slot_op(op));
2097 }
2098 match op {
2099 Op::SetStyle { id, patch, .. } if self.is_host(id) => {
2101 let inst = self.components.instances.get_mut(&id).expect("host");
2102 inst.app_style = (!patch.is_empty()).then_some(patch);
2103 let base = self.base_of(id);
2106 let cx = self.root_context_of(base).expect("a host");
2107 let app = if cx.combined {
2108 cx.app
2109 } else {
2110 self.components.instances[&base].app_style.clone()
2111 };
2112 let (inline, animated) = match &self.components.instances[&base].root {
2113 Some(root) => (root.attrs.inline.clone(), root.attrs.animated().to_vec()),
2114 None => (None, Vec::new()),
2115 };
2116 Ok(Some(inline_style(
2117 id,
2118 inline.as_deref(),
2119 &animated,
2120 app.as_ref(),
2121 )))
2122 }
2123 Op::Insert { parent, child, .. }
2125 if self.is_host(parent) && self.is_render_holder(child) =>
2126 {
2127 self.insert_render_holder(parent, child);
2128 Ok(None)
2129 }
2130 Op::Remove { parent, child }
2131 if self.is_host(parent) && self.is_render_holder(child) =>
2132 {
2133 self.remove_render_holder(child, false);
2134 Ok(None)
2135 }
2136 Op::Release { id } if self.is_render_holder(id) => {
2137 self.remove_render_holder(id, true);
2138 Ok(Some(Op::Release { id }))
2139 }
2140 Op::Insert { parent, child, .. }
2142 if self.is_host(parent) && self.components.slot_names.contains_key(&child) =>
2143 {
2144 let name = self.components.slot_names[&child].clone();
2145 let inst = self.components.instances.get_mut(&parent).expect("host");
2146 let Some(slot) = inst.spec.as_ref().and_then(|s| s.holder(&name)) else {
2147 log::warn!(target: "js", "the component has no slot `{name}`");
2148 self.detach_id(child);
2149 return Ok(None);
2150 };
2151 inst.slots.retain(|(_, n)| *n != child);
2152 inst.slots.push((slot, child));
2153 self.components.slot_hosts.insert(child, parent);
2154 self.components.mark(parent);
2155 Ok(None)
2156 }
2157 Op::Remove { parent, child }
2158 if self.is_host(parent) && self.components.slot_names.contains_key(&child) =>
2159 {
2160 self.unslot(child);
2161 self.detach_id(child);
2162 Ok(None)
2163 }
2164 Op::Insert { parent, child, .. }
2166 if self.components.slot_hosts.contains_key(&parent) && self.is_list(parent) =>
2167 {
2168 self.apply_op(op)?;
2169 if let Some((place, _)) = self.components.lists.get(&parent).cloned() {
2170 self.wrap_row(child, place);
2171 }
2172 Ok(None)
2173 }
2174 Op::Remove { parent, .. }
2175 if self.components.slot_hosts.contains_key(&parent) && self.is_list(parent) =>
2176 {
2177 Ok(Some(op))
2178 }
2179 Op::Insert { parent, .. } | Op::Remove { parent, .. }
2182 if self.components.slot_hosts.contains_key(&parent) =>
2183 {
2184 let empty = |core: &Self| {
2185 core.key(parent)
2186 .map_or(true, |k| core.nodes[k as usize].children.is_empty())
2187 };
2188 let before = empty(self);
2189 self.apply_op(op)?;
2190 if empty(self) != before {
2191 let host = self.components.slot_hosts[&parent];
2192 self.components.mark(host);
2193 }
2194 self.retarget_slot(parent, None);
2196 Ok(None)
2197 }
2198 Op::Release { id } if self.components.slot_names.contains_key(&id) => {
2199 self.unslot(id);
2200 self.components.slot_names.remove(&id);
2201 self.components.lists.remove(&id);
2202 self.forget_list_count(id);
2203 Ok(Some(Op::Release { id }))
2204 }
2205 Op::SetProp {
2209 id,
2210 prop: Prop::Count(count),
2211 } if self.components.lists.contains_key(&id) => {
2212 let key = self.key(id)?;
2213 self.apply_op(Op::SetProp {
2214 id,
2215 prop: Prop::Count(count),
2216 })?;
2217 let seen = &mut self.components.lists.get_mut(&id).expect("list").1;
2219 if std::mem::replace(seen, count) != count {
2220 if let Some(&(_, signal)) = self.components.list_counts.get(&id) {
2222 signal.set(count as usize);
2223 }
2224 let cells: Vec<NodeId> = self.nodes[key as usize]
2225 .children
2226 .iter()
2227 .map(|&c| self.nodes[c as usize].id)
2228 .collect();
2229 for cell in cells {
2230 let binds = self.components.instances.get(&cell).is_some_and(|inst| {
2231 inst.row_index.is_some() && inst.cell_owner.is_some_and(|o| o.is_live())
2232 });
2233 if !binds {
2234 self.components.mark(cell);
2235 }
2236 }
2237 }
2238 Ok(None)
2239 }
2240 Op::SetProp {
2243 id,
2244 prop: Prop::CellIndex(index),
2245 } if self.is_host(id) => {
2246 let inst = self.components.instances.get_mut(&id).expect("host");
2247 if let Inner::Row { index: current, .. } = &mut inst.inner
2248 && *current != index as usize
2249 {
2250 *current = index as usize;
2251 match inst.row_index {
2252 Some(row) if inst.cell_owner.is_some_and(|o| o.is_live()) => {
2254 row.set(index as usize);
2255 }
2256 _ => self.components.mark(id),
2257 }
2258 }
2259 Ok(Some(op))
2260 }
2261 Op::Insert {
2262 parent,
2263 child,
2264 before,
2265 } if self.is_host(parent) => {
2266 let run = self.runs.contains_key(&child);
2269 self.materialize_run(child)?;
2270 let key = self.key(child)?;
2271 let is_text = matches!(self.nodes[key as usize].kind, Kind::Text | Kind::RawText);
2272 let inst = self.components.instances.get_mut(&parent).expect("host");
2273 let was_empty = inst.js_children.is_empty();
2274 let moved = inst.js_children.contains(&child);
2275 inst.forget_js_child(child);
2276 let at = before.and_then(|b| inst.js_children.iter().position(|&c| c == b));
2277 inst.js_children
2278 .insert(at.unwrap_or(inst.js_children.len()), child);
2279 if is_text {
2280 inst.js_texts.insert(child);
2281 }
2282 let place = inst.children_at;
2283 inst.js_children_changed();
2284 if was_empty || place == Placement::Each {
2285 self.components.mark(parent);
2286 }
2287 self.join_content(child);
2288 match place {
2289 Placement::At(p, anchor) => {
2292 let anchor = self.anchor_node(anchor);
2293 self.apply_op(Op::Insert {
2294 parent: p,
2295 child,
2296 before: at.and(before).or(anchor),
2297 })?;
2298 if run
2299 && self
2300 .key(p)
2301 .is_ok_and(|k| self.nodes[k as usize].kind != Kind::Text)
2302 {
2303 let text = self.key(child).map_or("", |k| &self.nodes[k as usize].text);
2304 log::warn!(
2305 target: "js",
2306 "text in a component's children is not shown: text shows in a <Text> (`<Text>{text}</Text>`)"
2307 );
2308 }
2309 }
2310 Placement::Nested(nested, anchor) => {
2311 let anchor = self.anchor_node(anchor);
2312 self.join_nested_at(nested, child, at.and(before).or(anchor));
2313 }
2314 Placement::Each if moved => {}
2318 Placement::Each => self.detach_id(child),
2319 Placement::None => self.detach_id(child),
2320 }
2321 Ok(None)
2322 }
2323 Op::Remove { parent, child } if self.is_host(parent) => {
2324 let inst = self.components.instances.get_mut(&parent).expect("host");
2325 inst.forget_js_child(child);
2326 inst.js_children_changed();
2327 let place = inst.children_at;
2328 if inst.js_children.is_empty() || place == Placement::Each {
2329 self.components.mark(parent);
2330 }
2331 self.unplace(place, child);
2332 Ok(None)
2333 }
2334 Op::SetProp { id, prop }
2336 if js_host_attribute(&prop)
2337 && self
2338 .components
2339 .instances
2340 .get(&id)
2341 .is_some_and(|i| matches!(i.inner, Inner::Component(_))) =>
2342 {
2343 let inst = self.components.instances.get_mut(&id).expect("host");
2344 let before = inst.js_host.len();
2345 if crate::element::host::reset(&prop).as_ref() == Some(&prop) {
2348 inst.js_host
2349 .retain(|p| !crate::element::host::same_kind(p, &prop));
2350 if inst.js_host.len() == before {
2351 return Ok(None);
2352 }
2353 } else if inst.js_host.contains(&prop) {
2354 return Ok(None);
2355 } else {
2356 crate::element::host::set_in(&mut inst.js_host, prop);
2357 }
2358 if inst.root.is_some() {
2360 inst.given_changed = true;
2361 self.components.mark(id);
2362 }
2363 Ok(None)
2364 }
2365 Op::SetProp {
2366 id,
2367 prop: Prop::Class(class),
2368 } if self.is_host(id) => {
2369 let inst = self.components.instances.get_mut(&id).expect("host");
2370 inst.class = class;
2371 self.update_user_class(id);
2372 Ok(None)
2373 }
2374 Op::SetProp {
2375 id,
2376 prop: Prop::ClassList(list),
2377 } if self.is_host(id) => {
2378 let inst = self.components.instances.get_mut(&id).expect("host");
2379 inst.class_list = list;
2380 self.update_user_class(id);
2381 Ok(None)
2382 }
2383 Op::Listen {
2386 id: crate::ROOT_ID,
2387 event: EventKind::BackPress,
2388 enabled,
2389 } => {
2390 self.components.js_back = enabled;
2391 let rust = !self.components.executor.back.borrow().list.is_empty();
2392 Ok(Some(Op::Listen {
2393 id: crate::ROOT_ID,
2394 event: EventKind::BackPress,
2395 enabled: enabled || rust,
2396 }))
2397 }
2398 Op::Listen {
2401 id: crate::ROOT_ID,
2402 event: EventKind::BackProgress,
2403 enabled,
2404 } => {
2405 self.components.js_back_progress = enabled;
2406 let rust = !self
2407 .components
2408 .executor
2409 .back_progress
2410 .borrow()
2411 .list
2412 .is_empty();
2413 Ok(Some(Op::Listen {
2414 id: crate::ROOT_ID,
2415 event: EventKind::BackProgress,
2416 enabled: enabled || rust,
2417 }))
2418 }
2419 Op::SetProp {
2421 id: crate::ROOT_ID,
2422 prop: Prop::Keymap(keymap),
2423 } => {
2424 self.components.js_keymap = keymap;
2425 Ok(Some(Op::SetProp {
2426 id: crate::ROOT_ID,
2427 prop: Prop::Keymap(self.keymap()),
2428 }))
2429 }
2430 Op::Listen {
2431 id: crate::ROOT_ID,
2432 event: EventKind::KeyCommand,
2433 enabled,
2434 } => {
2435 self.components.js_keys = enabled;
2436 let rust = !self.components.executor.keys.borrow().list.is_empty();
2437 Ok(Some(Op::Listen {
2438 id: crate::ROOT_ID,
2439 event: EventKind::KeyCommand,
2440 enabled: enabled || rust,
2441 }))
2442 }
2443 Op::Listen {
2445 id,
2446 event: EventKind::NativeEvent,
2447 ..
2448 } if self.is_host(id) => Ok(None),
2449 Op::Listen { id, event, enabled } if self.is_host(id) => {
2450 let inst = self.components.instances.get_mut(&id).expect("host");
2451 inst.js_events.set(event, enabled);
2452 Ok(Some(self.host_listen(id, event)))
2453 }
2454 Op::Rust(op) => {
2455 self.run_rust(op);
2456 Ok(None)
2457 }
2458 Op::Release { id } if self.is_host(id) => {
2459 self.release_instance(id);
2460 Ok(Some(Op::Release { id }))
2461 }
2462 op => Ok(Some(op)),
2463 }
2464 }
2465
2466 fn outside_listens(&self, id: NodeId, event: EventKind) -> bool {
2470 let mut at = Some(self.base_of(id));
2471 while let Some(host) = at {
2472 let Some(inst) = self.components.instances.get(&host) else {
2473 break;
2474 };
2475 if inst.js_events.contains(event) || inst.given_events.contains(event) {
2476 return true;
2477 }
2478 at = inst.above;
2479 }
2480 false
2481 }
2482
2483 fn host_listen(&mut self, id: NodeId, event: EventKind) -> Op {
2486 let outside = self.outside_listens(id, event);
2487 let base = self.base_of(id);
2488 let own = self.components.instances[&base]
2489 .root
2490 .as_ref()
2491 .is_some_and(|r| r.events.contains(event));
2492 let slot = self.target_listens(base, event, outside || own);
2493 Op::Listen {
2494 id,
2495 event,
2496 enabled: outside || own || slot,
2497 }
2498 }
2499
2500 pub(super) fn set_given_handlers(
2504 &mut self,
2505 id: NodeId,
2506 handlers: Vec<(EventKind, Listener<EventPayload>)>,
2507 ) {
2508 let mut events = EventMask::default();
2509 for (kind, _) in &handlers {
2510 events.set(*kind, true);
2511 }
2512 let Some(inst) = self.components.instances.get_mut(&id) else {
2513 return;
2514 };
2515 let old = std::mem::replace(&mut inst.given_events, events);
2516 inst.given_handlers = handlers;
2517 let mut changed = old.bits() ^ events.bits();
2518 while changed != 0 {
2519 let kind = EventKind::ALL[changed.trailing_zeros() as usize];
2520 changed &= changed - 1;
2521 let op = self.host_listen(id, kind);
2522 let _ = self.apply_op(op);
2523 }
2524 }
2525
2526 fn handle_given(&mut self, base: NodeId, kind: EventKind, payload: &EventPayload) -> bool {
2530 let mut listeners = Vec::new();
2531 let mut at = Some(base);
2532 while let Some(host) = at {
2533 let Some(inst) = self.components.instances.get(&host) else {
2534 break;
2535 };
2536 if inst.given_events.contains(kind)
2537 && let Some(&owner) = self.components.owners.get(&host)
2538 {
2539 listeners.extend(
2540 inst.given_handlers
2541 .iter()
2542 .filter(|(k, _)| *k == kind)
2543 .map(|(_, l)| (owner, l.clone())),
2544 );
2545 }
2546 at = inst.above;
2547 }
2548 let mut handled = false;
2549 for (owner, listener) in listeners {
2550 handled |= self.run_listener(owner, &listener, payload);
2551 }
2552 handled
2553 }
2554
2555 fn js_listens(&self, base: NodeId, kind: EventKind) -> bool {
2558 let mut at = Some(base);
2559 while let Some(host) = at {
2560 let Some(inst) = self.components.instances.get(&host) else {
2561 break;
2562 };
2563 if inst.js_events.contains(kind) {
2564 return true;
2565 }
2566 at = inst.above;
2567 }
2568 false
2569 }
2570
2571 fn rows_of_cell(&self, cell: NodeId) -> usize {
2573 let Ok(key) = self.key(cell) else { return 0 };
2574 self.nodes
2575 .get(self.nodes[key as usize].parent as usize)
2576 .and_then(|list| list.list.as_ref())
2577 .map_or(0, |list| list.count as usize)
2578 }
2579
2580 fn rows_of_list(&self, list: NodeId) -> u32 {
2582 self.key(list)
2583 .ok()
2584 .and_then(|k| self.nodes[k as usize].list.as_ref())
2585 .map_or(0, |l| l.count)
2586 }
2587
2588 fn is_list(&self, id: NodeId) -> bool {
2590 self.key(id)
2591 .is_ok_and(|k| self.nodes[k as usize].list.is_some())
2592 }
2593
2594 fn wrap_row(&mut self, cell: NodeId, place: PlaceFn) {
2597 let Ok(key) = self.key(cell) else { return };
2598 let node = &self.nodes[key as usize];
2599 if !matches!(node.slot, Some(crate::CellSlot::Item(_))) {
2600 return;
2601 }
2602 if let Some(inst) = self.components.instances.get_mut(&cell) {
2603 if let Inner::Row { place: current, .. } = &mut inst.inner {
2604 *current = place;
2605 }
2606 self.components.mark(cell);
2607 return;
2608 }
2609 let js_children = node
2612 .children
2613 .iter()
2614 .map(|&c| self.nodes[c as usize].id)
2615 .collect();
2616 let instance = Instance::new(Inner::Row { place, index: 0 }, None, js_children, None);
2617 self.components.instances.insert(cell, Box::new(instance));
2618 self.components.mark(cell);
2619 }
2620
2621 pub(super) fn run_rust(&mut self, op: RustOp) {
2624 let posts = self.components.posts.clone();
2625 posts.in_op(|| self.run_rust_op(op));
2626 }
2627
2628 fn run_rust_op(&mut self, op: RustOp) {
2629 let RustOp { call, run } = op;
2630 match run {
2631 RustCall::Op(run) => {
2632 let mut cx = ModuleCx::default();
2633 let ran = {
2638 let _entered = self.components.runtime.enter();
2639 caught(|| run(&mut cx))
2640 };
2641 let result = match ran {
2642 Ok(result) => {
2643 for action in std::mem::take(&mut cx.actions) {
2644 self.apply_action(action);
2645 }
2646 result
2647 }
2648 Err(message) => Err(message.into()),
2649 };
2650 self.apply_actions();
2651 self.settle(call, result);
2652 }
2653 RustCall::Task(start) => match caught(start) {
2654 Ok(future) => {
2655 let executor = Rc::downgrade(&self.components.executor);
2656 let pending =
2657 crate::element::quit::Pending::new(&self.components.executor.calls);
2658 crate::element::task::spawn_raw(
2660 &self.components.executor,
2661 ROOT_ID,
2662 Box::pin(async move {
2663 let result = crate::element::module::catching(future).await;
2664 drop(pending);
2665 match executor.upgrade() {
2666 Some(executor) if call != 0 => {
2667 executor.act(Action::Return(call, result));
2668 }
2669 _ => {
2670 if let Err(e) = &result {
2671 log::warn!(target: "js", "an async call into Rust failed: {e}");
2672 }
2673 }
2674 }
2675 }),
2676 );
2677 }
2678 Err(message) => self.settle(call, Err(message.into())),
2679 },
2680 RustCall::Method(host, method) if self.view_pending(host) => {
2681 self.components.parked_methods.push((host, call, method));
2684 }
2685 RustCall::Method(host, method) => {
2686 let mut failed = None;
2687 let result = match self
2688 .components
2689 .instances
2690 .get_mut(&host)
2691 .map(|i| &mut i.inner)
2692 {
2693 Some(Inner::Component(inner)) => match caught(|| inner.call(method)) {
2694 Ok(Some(result)) => result,
2695 Ok(None) => {
2696 Err(format!("{} has no ref of this method's type", inner.name()).into())
2697 }
2698 Err(message) => {
2699 failed = Some(message.clone());
2700 Err(message.into())
2701 }
2702 },
2703 _ => {
2704 drop_caught(method);
2705 Err(format!("node {host} hosts no Rust component").into())
2706 }
2707 };
2708 self.apply_actions();
2709 if let Some(message) = failed {
2710 self.component_failed(host, message);
2711 }
2712 self.settle(call, result);
2713 }
2714 RustCall::Post(place) => drop(place),
2716 }
2717 }
2718
2719 pub(super) fn settle(&mut self, call: u32, result: JsResult) {
2722 if call == 0 {
2723 if let Err(e) = &result {
2724 log::warn!(target: "js", "a call into Rust failed: {e}");
2725 }
2726 drop_caught(result);
2727 return;
2728 }
2729 self.events.push(JsEvent::Reply { call, result });
2730 }
2731
2732 pub(super) fn update_user_class(&mut self, host: NodeId) {
2734 let inst = &self.components.instances[&host];
2735 let mut combined = String::with_capacity(inst.class.len() + 16 * inst.class_list.len());
2736 combined.push_str(&inst.class);
2737 for name in &inst.class_list {
2738 combined.push(' ');
2739 combined.push_str(name);
2740 }
2741 let user = (!combined.trim().is_empty()).then(|| self.tailwind.get(&combined).0);
2742 self.set_user(host, user);
2743 }
2744
2745 pub(super) fn set_user(&mut self, host: NodeId, user: Option<std::rc::Rc<ClassList>>) {
2747 let inst = self.components.instances.get_mut(&host).expect("host");
2748 if !same(&inst.user, &user) {
2749 inst.user = user;
2750 self.components.mark(host);
2751 }
2752 }
2753
2754 fn unslot(&mut self, id: NodeId) {
2756 self.drop_slot_target(id);
2757 if let Some(host) = self.components.slot_hosts.remove(&id) {
2758 if let Some(inst) = self.components.instances.get_mut(&host) {
2759 inst.slots.retain(|(_, n)| *n != id);
2760 }
2761 self.components.mark(host);
2762 }
2763 }
2764
2765 pub(super) fn set_slot_name(&mut self, id: NodeId, name: Arc<str>) {
2767 self.components.slot_names.insert(id, name);
2768 }
2769
2770 pub(super) fn create_instance(&mut self, host: NodeId, name: Arc<str>) {
2772 if self.is_host(host) {
2773 return;
2774 }
2775 let (spec, inner) = match self.components.registry.make(&name) {
2776 Some((spec, inner)) => (Some(spec), Inner::Component(inner)),
2777 None => {
2778 self.deny(format!(
2779 "no component is registered as `{name}`: it renders nothing"
2780 ));
2781 (None, Inner::Missing)
2782 }
2783 };
2784 self.insert_instance(host, spec, inner);
2785 }
2786
2787 pub(super) fn create_instance_of(
2790 &mut self,
2791 host: NodeId,
2792 name: &'static str,
2793 make: fn() -> Box<dyn AnyInstance>,
2794 spec: fn() -> ComponentSpec,
2795 ) {
2796 if self.is_host(host) {
2797 return;
2798 }
2799 let spec = self
2800 .components
2801 .specs
2802 .entry(name)
2803 .or_insert_with(|| Arc::new(spec()))
2804 .clone();
2805 self.insert_instance(host, Some(spec), Inner::Component(make()));
2806 }
2807
2808 fn insert_instance(
2809 &mut self,
2810 host: NodeId,
2811 spec: Option<Arc<ComponentSpec>>,
2812 mut inner: Inner,
2813 ) {
2814 let app_style = self
2816 .key(host)
2817 .ok()
2818 .map(|k| self.nodes[k as usize].inline_style.clone())
2819 .filter(|p| !p.is_empty());
2820 if let Inner::Component(c) = &mut inner {
2823 c.place(host, crate::element::Owner::current());
2824 }
2825 let instance = Instance::new(inner, spec, Vec::new(), app_style);
2826 self.components.instances.insert(host, Box::new(instance));
2827 self.components.mark(host);
2828 if let Ok(k) = self.key(host) {
2833 self.lay_out_through(k);
2834 }
2835 }
2836
2837 pub(super) fn set_component_prop(
2839 &mut self,
2840 host: NodeId,
2841 name: &str,
2842 value: Option<AnyValue>,
2843 ) -> bool {
2844 let Some(inst) = self.components.instances.get_mut(&host) else {
2845 return false;
2846 };
2847 let Inner::Component(inner) = &mut inst.inner else {
2848 return true;
2849 };
2850 match inner.set_prop(name, value) {
2851 Ok(true) => self.components.mark(host),
2852 Ok(false) => {}
2853 Err(e) => {
2854 let component = inst.spec.as_ref().map_or("", |s| s.name);
2855 log::warn!(target: "js", "{component}: {e}");
2856 }
2857 }
2858 true
2859 }
2860
2861 pub(super) fn render_components(&mut self) {
2864 let _entered = self.components.runtime.enter();
2865 loop {
2868 let changed = self.drain_views();
2869 let rendered = self.render_dirty();
2870 let failed = self.report_failures();
2871 let woke = self.wake_waiting();
2872 let called = self.run_parked_methods();
2873 if !changed && !rendered && !failed && !woke && !called && !self.run_after_render() {
2874 break;
2875 }
2876 }
2877 self.flush_renders();
2878 self.end_retags();
2879 }
2880
2881 fn run_after_render(&mut self) -> bool {
2885 let rendered = self.components.executor.take_rendered();
2886 if rendered.is_empty() {
2887 return false;
2888 }
2889 for crate::element::AfterAnswer { f, .. } in rendered {
2890 if let Err(message) = caught(f) {
2891 log::error!(target: "js", "a closure after the views rendered failed: {message}");
2892 }
2893 }
2894 true
2895 }
2896
2897 fn forget_node_extras(&mut self, id: NodeId) {
2900 if !self.components.renders.is_empty() {
2901 self.forget_render_place(id);
2902 }
2903 if !self.components.app_classes.is_empty() {
2904 self.components.app_classes.remove(&id);
2905 }
2906 }
2907
2908 fn report_failures(&mut self) -> bool {
2912 let failures = self.components.runtime.take_failures();
2913 let any = !failures.is_empty();
2914 for (owner, message) in failures {
2915 let host = self.host_of_owner(owner);
2916 let component = host
2917 .and_then(|h| match &self.components.instances.get(&h)?.inner {
2918 Inner::Component(inner) => Some(inner.name()),
2919 _ => None,
2920 })
2921 .unwrap_or("a binding");
2922 if let Some(boundary) = crate::element::reactive::boundary_of(owner) {
2923 boundary.set(Some(ComponentError { component, message }));
2924 continue;
2925 }
2926 match host {
2927 Some(host) => self.component_failed(host, message),
2928 None => log::error!(target: "js", "a binding failed: {message}"),
2929 }
2930 }
2931 any
2932 }
2933
2934 fn render_dirty(&mut self) -> bool {
2938 for action in self.components.executor.take_actions() {
2940 self.apply_action(action);
2941 }
2942 if self.components.dirty.is_empty() {
2943 return false;
2944 }
2945 while let Some(host) = self.components.dirty.pop() {
2946 if self.waits_for_tree(host) {
2949 if let Some(inst) = self.components.instances.get_mut(&host) {
2950 inst.dirty = false;
2951 }
2952 if !self.components.waiting.contains(&host) {
2953 self.components.waiting.push(host);
2954 }
2955 continue;
2956 }
2957 let Some(mut inst) = self.components.instances.remove(&host) else {
2958 continue;
2959 };
2960 inst.dirty = false;
2961 let rooted = inst.rooted;
2962 let failed = self.render(host, &mut inst);
2963 let rerooted = inst.rooted != rooted;
2964 self.components.instances.insert(host, inst);
2965 if rerooted {
2966 self.follow_base(host, rooted);
2967 }
2968 if let Some(message) = failed {
2969 self.component_failed(host, message);
2970 }
2971 }
2972 true
2973 }
2974
2975 fn restyle_view(&mut self, host: NodeId, inst: &mut Instance) {
2978 if let Some(rooted) = inst.rooted {
2980 if std::mem::take(&mut inst.given_changed)
2981 && let Some(rooted) = self.components.instances.get_mut(&rooted)
2982 {
2983 rooted.given_changed = true;
2984 }
2985 self.components.mark(rooted);
2986 return;
2987 }
2988 let cx = self.root_context(inst);
2989 let given_changed = std::mem::take(&mut inst.given_changed);
2990 let attrs = if let Some(node) = inst.bound.get_mut(&host) {
2991 let (style, classes) = (node.style.clone(), node.classes.clone());
2992 let class = node.attrs.class.clone();
2993 let classes = self.apply_el_styles(
2994 host,
2995 &style,
2996 &style,
2997 classes,
2998 class.as_ref(),
2999 cx.user.clone(),
3000 );
3001 if let Some(node) = inst.bound.get_mut(&host) {
3002 node.classes = classes;
3003 given_changed.then(|| node.attrs.clone())
3004 } else {
3005 None
3006 }
3007 } else if let Some(root) = inst.root.as_mut() {
3008 let (style, classes) = (root.style.clone(), root.classes.clone());
3009 let class = root.attrs.class.clone();
3010 root.classes = self.apply_el_styles(
3011 host,
3012 &style,
3013 &style,
3014 classes,
3015 class.as_ref(),
3016 cx.user.clone(),
3017 );
3018 given_changed.then(|| root.attrs.clone())
3019 } else {
3020 None
3021 };
3022 if let Some(attrs) = attrs {
3025 let app = if cx.combined {
3026 cx.app.as_ref()
3027 } else {
3028 inst.app_style.as_ref()
3029 };
3030 let _ = self.apply_op(inline_style(
3031 host,
3032 attrs.inline.as_deref(),
3033 attrs.animated(),
3034 app,
3035 ));
3036 let applied = inst.root_insets_applied;
3037 let own_insets = attrs.insets();
3038 let insets = (
3039 cx.inset_padding.or(own_insets.0),
3040 cx.inset_margin.or(own_insets.1),
3041 );
3042 if insets.0 != applied.0 {
3043 let _ = self.apply_op(Op::SetProp {
3044 id: host,
3045 prop: Prop::InsetPadding(insets.0.unwrap_or_default()),
3046 });
3047 }
3048 if insets.1 != applied.1 {
3049 let _ = self.apply_op(Op::SetProp {
3050 id: host,
3051 prop: Prop::InsetMargin(insets.1.unwrap_or_default()),
3052 });
3053 }
3054 inst.root_insets_applied = insets;
3055 if cx.host != inst.root_host_applied {
3056 let mut attrs = attrs;
3059 attrs.set_insets(insets);
3060 let old = with_host(attrs.clone(), &inst.root_host_applied);
3061 let new = with_host(attrs, &cx.host);
3062 if !self.apply_target_attrs(host, &new, &old, app) {
3063 self.apply_attrs_over(host, &new, &old, app);
3064 }
3065 inst.root_host_applied = cx.host;
3066 }
3067 }
3068 }
3069
3070 fn join_content(&mut self, id: NodeId) {
3077 let mut stack = vec![id];
3078 while let Some(id) = stack.pop() {
3079 if let Some(inst) = self.components.instances.get_mut(&id) {
3080 inst.joined = true;
3081 continue;
3082 }
3083 if let Ok(k) = self.key(id) {
3084 stack.extend(
3085 self.nodes[k as usize]
3086 .children
3087 .iter()
3088 .map(|&c| self.nodes[c as usize].id),
3089 );
3090 }
3091 }
3092 }
3093
3094 fn waits_for_tree(&self, host: NodeId) -> bool {
3099 let Some(inst) = self.components.instances.get(&host) else {
3100 return false;
3101 };
3102 let Inner::Component(inner) = &inst.inner else {
3103 return false;
3104 };
3105 inst.root.is_none()
3106 && (inst.joined || !inner.failure_owner().is_live())
3107 && !self.id_in_tree(host)
3108 }
3109
3110 fn id_in_tree(&self, id: NodeId) -> bool {
3112 self.key(id).is_ok_and(|k| self.in_tree(k))
3113 }
3114
3115 fn wake_waiting(&mut self) -> bool {
3118 let waiting = std::mem::take(&mut self.components.waiting);
3119 let mut woke = false;
3120 for host in waiting {
3121 if !self.components.instances.contains_key(&host) {
3122 continue;
3123 }
3124 if self.id_in_tree(host) {
3125 self.components.mark(host);
3126 woke = true;
3127 } else {
3128 self.components.waiting.push(host);
3129 }
3130 }
3131 woke
3132 }
3133
3134 fn run_parked_methods(&mut self) -> bool {
3137 if self.components.parked_methods.is_empty() {
3138 return false;
3139 }
3140 let parked = std::mem::take(&mut self.components.parked_methods);
3141 let mut ran = false;
3142 for (host, call, method) in parked {
3143 if self.view_pending(host) {
3144 self.components.parked_methods.push((host, call, method));
3145 } else {
3146 ran = true;
3147 self.run_rust(RustOp {
3148 call,
3149 run: RustCall::Method(host, method),
3150 });
3151 }
3152 }
3153 ran
3154 }
3155
3156 fn view_pending(&self, host: NodeId) -> bool {
3158 self.components
3159 .instances
3160 .get(&host)
3161 .is_some_and(|i| matches!(&i.inner, Inner::Component(inner) if inner.owner().is_none()))
3162 }
3163
3164 fn owner_above(&self, host: NodeId) -> (crate::element::Owner, crate::element::Owner) {
3169 let mut key = self.key(host).ok();
3170 while let Some(k) = key {
3171 let parent = self.nodes[k as usize].parent;
3172 if parent == NO_KEY {
3173 break;
3174 }
3175 key = Some(parent);
3176 let id = self.base_of(self.nodes[parent as usize].id);
3179 let owners = self
3182 .components
3183 .instances
3184 .get(&id)
3185 .and_then(|inst| match &inst.inner {
3186 Inner::Component(inner) => {
3187 let view = inner.owner().filter(|o| o.is_live());
3188 inst.children_owner
3189 .filter(|o| o.is_live())
3190 .or(view)
3191 .map(|owner| (owner, view.unwrap_or(owner)))
3192 }
3193 _ => inst
3196 .cell_owner
3197 .map(|owner| (owner, crate::element::Owner::detached())),
3198 });
3199 if let Some(owners) = owners {
3200 return owners;
3201 }
3202 }
3203 let detached = crate::element::Owner::detached();
3204 (detached, detached)
3205 }
3206
3207 fn js_window_owner(&mut self, host: NodeId) -> Option<crate::element::Owner> {
3212 let key = self.key(host).ok()?;
3213 let window = self.key_window(key);
3214 if window == ROOT_ID {
3215 return None;
3216 }
3217 if let Some((owner, _)) = self.components.js_windows.get(&window)
3218 && owner.is_live()
3219 {
3220 return Some(*owner);
3221 }
3222 let id = self
3223 .window_ids
3224 .iter()
3225 .find_map(|(id, (node, _))| (*node == window).then(|| id.clone()))?;
3226 let reported = self
3227 .components
3228 .window_reports
3229 .get(&window)
3230 .copied()
3231 .unwrap_or_default();
3232 let (owner, this) =
3233 crate::element::desktop::js_window(&id, window, &self.components.executor, reported);
3234 self.components.js_windows.insert(window, (owner, this));
3235 Some(owner)
3236 }
3237
3238 fn host_of_owner(&self, owner: crate::element::Owner) -> Option<NodeId> {
3241 let mut at = Some(owner);
3242 while let Some(owner) = at {
3243 let host =
3244 self.components
3245 .instances
3246 .iter()
3247 .find_map(|(&host, inst)| match &inst.inner {
3248 Inner::Component(inner) if inner.owner() == Some(owner) => Some(host),
3249 _ => None,
3250 });
3251 if host.is_some() {
3252 return host;
3253 }
3254 at = owner.parent();
3255 }
3256 None
3257 }
3258
3259 fn window_of_owner(&self, owner: crate::element::Owner) -> NodeId {
3262 if self.window_ids.is_empty() {
3263 return crate::ROOT_ID;
3264 }
3265 self.host_of_owner(owner)
3266 .and_then(|host| self.key(host).ok())
3267 .map_or(crate::ROOT_ID, |key| self.key_window(key))
3268 }
3269
3270 fn render(&mut self, host: NodeId, inst: &mut Instance) -> Option<String> {
3274 let mut failure = None;
3275 let el = match &mut inst.inner {
3276 Inner::Component(inner) => {
3277 if let Some(spec) = &inst.spec {
3279 for name in spec.slots() {
3280 let filled = inst.slots.iter().any(|(s, node)| {
3281 *s == name
3282 && self
3283 .key(*node)
3284 .is_ok_and(|k| !self.nodes[k as usize].children.is_empty())
3285 }) || inst
3286 .fills
3287 .iter()
3288 .any(|f| f.name == name && !self.fill_nodes(f).is_empty());
3289 inner.set_slot(name, filled);
3290 }
3291 }
3292 inner.set_children(!inst.js_children.is_empty());
3293 if inst.root.is_some() && !std::mem::take(&mut inst.remake) {
3296 self.restyle_view(host, inst);
3297 return None;
3298 }
3299 let (owner, keeper) = self.owner_above(host);
3300 let (owner, keeper) = if owner.is_live() {
3301 (owner, keeper)
3302 } else {
3303 let window = self.js_window_owner(host).unwrap_or(owner);
3304 (window, window)
3305 };
3306 inner.adopt(owner, keeper);
3307 caught(|| inner.view()).unwrap_or_else(|message| {
3309 failure = Some(message);
3310 ElNode::empty_view()
3311 })
3312 }
3313 Inner::Row { place, index } => {
3315 let (place, index) = (place.clone(), *index);
3316 let count = self.rows_of_cell(host);
3317 let list = self.list_of(host);
3318 let count_signal = list.map(|list| self.list_count(list, count));
3320 let moves = list
3321 .and_then(|list| self.components.virtual_lists.get(&list))
3322 .and_then(|state| state.moves);
3323 let made = std::cell::Cell::new(None);
3324 let build = || {
3325 let at = row_position(index, count, count_signal, moves, &made);
3326 view().child(place(Child::row(), at)).into_element().0
3327 };
3328 let parent = self.list_component_owner(list);
3330 let el = self.build_cell(parent, inst, build);
3331 inst.row_index = made.take();
3332 if let (Some(list), Some(index), Some(owner)) =
3333 (list, inst.row_index, inst.cell_owner)
3334 && let Some(state) = self.components.virtual_lists.get(&list)
3335 {
3336 state.rows.borrow_mut().insert(host, (index, owner));
3337 }
3338 match el {
3339 Ok(el) => el,
3340 Err(message) => {
3341 failure = Some(message);
3342 ElNode::empty_view()
3343 }
3344 }
3345 }
3346 Inner::VirtualRow { list, index } => {
3347 let (list, index) = (*list, *index);
3348 let inverted = self
3349 .key(list)
3350 .ok()
3351 .and_then(|k| self.nodes[k as usize].list.as_ref())
3352 .is_some_and(|l| l.inverted);
3353 let state = self.components.virtual_lists.get(&list).map(|state| {
3354 let scope = state.scope.get();
3357 let gone = scope.is_some_and(|s| !s.is_live());
3358 (
3359 if gone { 0 } else { state.count as usize },
3360 state.row.clone(),
3361 state.separator.clone(),
3362 state.rows.clone(),
3363 scope,
3364 state.moves,
3365 )
3366 });
3367 match state {
3368 Some((count, ..)) if index >= count => {
3373 if let Some(owner) = inst.cell_owner.take() {
3374 owner.dispose();
3375 }
3376 inst.row_index = None;
3377 ElNode::empty_view()
3378 }
3379 Some((count, row, separator, rows, scope, moves)) => {
3380 let count_signal = Some(self.list_count(list, count));
3381 let made = std::cell::Cell::new(None);
3382 let build = || {
3383 let at = row_position(index, count, count_signal, moves, &made);
3384 let row = row(at);
3385 let separator = separator.map(|s| {
3388 crate::element::when(move || !at.is_last(), move || s())
3389 .into_element()
3390 });
3391 match separator {
3392 Some(s) if inverted => view().child(s).child(row),
3393 Some(s) => view().child(row).child(s),
3394 None => view().child(row),
3395 }
3396 .into_element()
3397 .0
3398 };
3399 let parent = scope.unwrap_or_else(|| self.list_component_owner(Some(list)));
3404 let el = self.build_cell(parent, inst, build);
3405 inst.row_index = made.take();
3406 if let (Some(index), Some(owner)) = (inst.row_index, inst.cell_owner) {
3407 rows.borrow_mut().insert(host, (index, owner));
3408 }
3409 match el {
3410 Ok(el) => el,
3411 Err(message) => {
3412 failure = Some(message);
3413 ElNode::empty_view()
3414 }
3415 }
3416 }
3417 None => ElNode::empty_view(),
3418 }
3419 }
3420 Inner::Missing => ElNode::empty_view(),
3421 };
3422 let owner = match &inst.inner {
3424 Inner::Component(inner) => inner.owner(),
3425 _ => inst.cell_owner,
3426 };
3427 match owner {
3428 Some(owner) => owner.run(|| self.expand_root(host, inst, el)),
3429 None => self.expand_root(host, inst, el),
3430 }
3431 failure
3432 }
3433
3434 fn build_cell(
3438 &mut self,
3439 parent: crate::element::Owner,
3440 inst: &mut Instance,
3441 build: impl FnOnce() -> ElNode,
3442 ) -> Result<ElNode, String> {
3443 if let Some(owner) = inst.cell_owner.take() {
3444 owner.dispose();
3445 }
3446 let (owner, el) = parent.run(|| crate::element::create_root(|| caught(build)));
3447 inst.cell_owner = Some(owner);
3448 el
3449 }
3450
3451 fn list_component_owner(&self, list: Option<NodeId>) -> crate::element::Owner {
3454 let component = list
3455 .and_then(|list| {
3456 self.components
3457 .virtual_lists
3458 .get(&list)
3459 .map(|s| s.owner)
3460 .or_else(|| self.components.slot_hosts.get(&list).copied())
3461 })
3462 .and_then(|host| self.components.instances.get(&host))
3463 .and_then(|inst| match &inst.inner {
3464 Inner::Component(inner) => inner.owner(),
3465 _ => None,
3466 });
3467 component.unwrap_or_else(crate::element::Owner::detached)
3468 }
3469
3470 fn reconcile_text(
3473 &mut self,
3474 id: NodeId,
3475 host: NodeId,
3476 new: Option<SharedString>,
3477 old: Option<(SharedString, NodeId)>,
3478 ) -> Option<(SharedString, NodeId)> {
3479 match (new, old) {
3480 (Some(content), Some((old, raw))) => {
3481 if content != old {
3482 let _ = self.apply_op(Op::SetText {
3483 id: raw,
3484 text: content.as_str().to_owned(),
3485 });
3486 }
3487 Some((content, raw))
3488 }
3489 (Some(content), None) => {
3490 let raw = self.components.alloc();
3491 let _ = self.apply_op(Op::CreateText {
3492 id: raw,
3493 text: content.as_str().to_owned(),
3494 });
3495 self.components.owners.insert(raw, host);
3496 let _ = self.apply_op(Op::Insert {
3497 parent: id,
3498 child: raw,
3499 before: None,
3500 });
3501 Some((content, raw))
3502 }
3503 (None, Some((_, raw))) => {
3504 self.release_id(raw);
3505 None
3506 }
3507 (None, None) => None,
3508 }
3509 }
3510
3511 fn expand_root(&mut self, host: NodeId, inst: &mut Instance, mut el: ElNode) {
3517 if matches!(el.kind, ElKind::Component(_))
3518 && matches!(inst.inner, Inner::Component(_))
3519 && inst
3520 .root
3521 .as_ref()
3522 .is_none_or(|r| matches!(r.part, Part::Component(_)))
3523 {
3524 return self.expand_rooted(host, inst, el);
3525 }
3526 let node = matches!(el.kind, ElKind::Plain | ElKind::VirtualList(_));
3527 if !node || (el.tag != Tag::View && !self.retag(host, el.tag)) {
3528 if node {
3529 log::error!(target: "js", "a component's root takes its kind only when it is first mounted; it is placed in a view");
3530 }
3531 let inner = std::mem::replace(&mut el, ElNode::new(Tag::View));
3532 el.children.push(inner);
3533 }
3534 if !el.children.is_empty()
3535 && let Some(content) = el.bound_text.take()
3536 {
3537 let mut first = ElNode::new(Tag::Text);
3538 first.text = Some(SharedString::default());
3539 first.bound_text = Some(content);
3540 el.text = None;
3541 el.children.insert(0, first);
3542 }
3543 let applied_layout = if matches!(el.kind, ElKind::VirtualList(_)) {
3546 self.components.list_layouts.remove(&host)
3547 } else {
3548 None
3549 };
3550 let bound = super::views::Bound::take(&mut el).map(|bound| {
3551 self.bind_parts(host, host, bound, &mut el);
3552 });
3553 inst.handlers.clear();
3554 inst.event_handlers.clear();
3555 inst.responders.clear();
3556 let old = inst.root.take();
3557 let first = old.is_none();
3558 let old_place = std::mem::replace(&mut inst.children_at, Placement::None);
3559 let (old_attrs, old_style, old_classes, old_events, old_children, old_text, old_list) =
3561 match old {
3562 Some(e) => (
3563 e.attrs,
3564 e.style,
3565 e.classes,
3566 e.events,
3567 e.children,
3568 e.text,
3569 e.list.map(|l| *l).unwrap_or_default(),
3570 ),
3571 None => (
3572 Attrs::default(),
3573 StyleRefinement::default(),
3574 (None, None),
3575 EventMask::default(),
3576 Vec::new(),
3577 None,
3578 ListConfig::default(),
3579 ),
3580 };
3581 let cx = self.root_context(inst);
3584 let app = if cx.combined {
3585 cx.app.as_ref()
3586 } else {
3587 inst.app_style.as_ref()
3588 };
3589 let attrs = cx.over(el.attrs.clone());
3590 let mut old_over = old_attrs.clone();
3592 old_over.set_insets(inst.root_insets_applied);
3593 let old_over = with_host(old_over, &inst.root_host_applied);
3594 if !self.apply_target_attrs(host, &attrs, &old_over, app) {
3595 self.apply_attrs_over(host, &attrs, &old_over, app);
3596 }
3597 inst.root_insets_applied = attrs.insets();
3598 inst.root_host_applied = cx.host.clone();
3599 let given_changed = std::mem::take(&mut inst.given_changed) || first;
3602 if cx.given
3603 && given_changed
3604 && attrs.inline == old_over.inline
3605 && attrs.animated() == old_over.animated()
3606 {
3607 let _ = self.apply_op(inline_style(
3608 host,
3609 attrs.inline.as_deref(),
3610 attrs.animated(),
3611 app,
3612 ));
3613 }
3614 let user = cx.user.clone();
3615 let top_js = cx.js;
3616 let given_events = cx.given_events;
3617 let classes = self.apply_el_styles(
3618 host,
3619 &el.style,
3620 &old_style,
3621 old_classes,
3622 el.attrs.class.as_ref(),
3623 user,
3624 );
3625 let text = self.reconcile_text(host, host, el.text.take(), old_text);
3626 if bound.is_some() {
3627 Self::keep_bound(
3628 inst,
3629 host,
3630 &el.attrs,
3631 &el.style,
3632 classes.clone(),
3633 text.clone(),
3634 );
3635 }
3636 let js = top_js.unwrap_or(inst.js_events) | given_events;
3639 self.apply_handlers(host, host, &el, old_events | js, js, inst);
3640 let mut events = EventMask::default();
3641 for (kind, _) in &el.handlers {
3642 events.set(*kind, true);
3643 }
3644 events.set(
3645 EventKind::Touch,
3646 events.contains(EventKind::Touch) || el.responder.is_some(),
3647 );
3648 let new_children = std::mem::take(&mut el.children);
3649 let children = self.reconcile_children(host, old_children, new_children, host, inst);
3650 let (list, part) = match std::mem::replace(&mut el.kind, ElKind::Plain) {
3651 ElKind::VirtualList(list) => {
3652 let config = list.config;
3653 let old_list = applied_layout.unwrap_or(old_list);
3654 self.update_virtual_list(self.native_id(host), host, *list, &old_list);
3655 (Some(Box::new(config)), Part::VirtualList)
3656 }
3657 _ => (None, Part::Node),
3658 };
3659 inst.root = Some(Expanded {
3660 id: host,
3661 tag: el.tag,
3662 key: None,
3663 text,
3664 attrs: el.attrs,
3665 style: el.style,
3666 classes,
3667 events,
3668 list,
3669 part,
3670 children,
3671 });
3672 self.children_placed(host, inst, old_place);
3673 }
3674
3675 fn expand_rooted(&mut self, host: NodeId, inst: &mut Instance, el: ElNode) {
3681 let ElKind::Component(c) = &el.kind else {
3682 return;
3683 };
3684 let part = Part::Component(c.name);
3685 inst.handlers.clear();
3686 inst.event_handlers.clear();
3687 inst.responders.clear();
3688 let old_place = std::mem::replace(&mut inst.children_at, Placement::None);
3689 let prev = match inst.root.take() {
3690 Some(old) if old.part == part => old,
3691 old => {
3692 if let Some(old) = old {
3693 self.release_expanded(old);
3694 }
3695 let id = self.components.alloc();
3696 if let Err(e) = self.alias(id, host) {
3697 log::error!(target: "js", "a view's root component is not made: {e:?}");
3698 return;
3699 }
3700 self.components.owners.insert(id, host);
3701 self.create_instance_for(id, c);
3702 if let Some(rooted) = self.components.instances.get_mut(&id) {
3703 rooted.app_style = None;
3705 rooted.above = Some(host);
3706 }
3707 Expanded::js(id, part)
3708 }
3709 };
3710 inst.rooted = Some(prev.id);
3711 let root = self.reconcile_node(Some(prev), el, part, host, inst);
3712 inst.root = Some(root);
3713 self.children_placed(host, inst, old_place);
3714 }
3715
3716 pub(super) fn base_of(&self, id: NodeId) -> NodeId {
3719 let mut at = id;
3720 while let Some(next) = self.components.instances.get(&at).and_then(|i| i.rooted) {
3721 at = next;
3722 }
3723 at
3724 }
3725
3726 pub(super) fn root_context(&mut self, inst: &Instance) -> RootContext {
3731 let mut cx = RootContext {
3732 user: inst.user.clone(),
3733 combined: false,
3734 app: None,
3735 js: None,
3736 given_events: inst.given_events,
3737 inset_padding: None,
3738 inset_margin: None,
3739 host: Vec::new(),
3740 given: false,
3741 };
3742 if inst.above.is_none() && inst.given.is_none() {
3743 cx.host.clone_from(&inst.js_host);
3744 return cx;
3745 }
3746 cx.combined = true;
3747 let mut decls: Vec<crate::StyleDecl> = Vec::new();
3748 let mut take = |cx: &mut RootContext, given: &Attrs| {
3749 cx.given = true;
3750 if let Some(inline) = &given.inline {
3751 decls.extend(inline.decls().iter().cloned());
3752 }
3753 if let Some(r) = &given.rare {
3754 decls.extend(r.animated.iter().map(|(d, _)| d.clone()));
3755 cx.inset_padding = r.inset_padding.or(cx.inset_padding);
3756 cx.inset_margin = r.inset_margin.or(cx.inset_margin);
3757 }
3758 given_host(given, &mut cx.host);
3759 };
3760 if let Some(given) = &inst.given {
3761 take(&mut cx, given);
3762 }
3763 if let Some(class) = inst.given.as_ref().and_then(|g| g.class.clone()) {
3766 let given = self.app_class_list(&class);
3767 cx.user = self.merge_user(cx.user.take(), Some(given));
3768 }
3769 let mut app = inst.app_style.clone();
3770 let mut js_host = None;
3772 let mut at = inst.above;
3773 while let Some(id) = at {
3774 let Some(above) = self.components.instances.get(&id) else {
3775 break;
3776 };
3777 let (outer, given) = (above.user.clone(), above.given.clone());
3778 app = above.app_style.clone();
3779 js_host = Some(above.js_host.clone());
3780 cx.js = Some(above.js_events);
3781 cx.given_events = cx.given_events | above.given_events;
3782 at = above.above;
3783 if let Some(given) = &given {
3784 take(&mut cx, given);
3785 }
3786 cx.user = self.merge_user(cx.user.take(), outer);
3787 if let Some(class) = given.and_then(|g| g.class.clone()) {
3788 let given = self.app_class_list(&class);
3789 cx.user = self.merge_user(cx.user.take(), Some(given));
3790 }
3791 }
3792 for prop in js_host.as_ref().unwrap_or(&inst.js_host) {
3793 give_host(&mut cx.host, prop.clone());
3794 }
3795 if let Some(app) = &app {
3796 decls.extend(app.decls().iter().cloned());
3797 }
3798 if !decls.is_empty() {
3799 let mut style = crate::Style::default();
3800 let mut patch = crate::StylePatch::default();
3801 for decl in decls {
3802 let _ = patch.push(&mut style, decl);
3803 }
3804 cx.app = Some(patch);
3805 }
3806 cx
3807 }
3808
3809 pub(super) fn root_context_of(&mut self, host: NodeId) -> Option<RootContext> {
3811 let inst = self.components.instances.remove(&host)?;
3812 let cx = self.root_context(&inst);
3813 self.components.instances.insert(host, inst);
3814 Some(cx)
3815 }
3816
3817 pub(super) fn set_given(&mut self, host: NodeId, mut attrs: Attrs) {
3820 attrs.set_element_ref(None);
3821 let given = (attrs != Attrs::default()).then(|| Box::new(attrs));
3822 let Some(inst) = self.components.instances.get_mut(&host) else {
3823 return;
3824 };
3825 if inst.given != given {
3826 inst.given = given;
3827 inst.given_changed = true;
3828 self.components.mark(host);
3829 }
3830 }
3831
3832 pub(super) fn merge_user(
3834 &mut self,
3835 inner: Option<std::rc::Rc<ClassList>>,
3836 outer: Option<std::rc::Rc<ClassList>>,
3837 ) -> Option<std::rc::Rc<ClassList>> {
3838 match (inner, outer) {
3839 (Some(a), Some(b)) => {
3840 let key = (
3841 std::rc::Rc::as_ptr(&a) as usize,
3842 std::rc::Rc::as_ptr(&b) as usize,
3843 );
3844 if let Some([_, _, merged]) = self.components.merges.get(&key) {
3845 return Some(merged.clone());
3846 }
3847 if self.components.merges.len() >= STYLE_CACHE {
3848 self.components.merges.clear();
3849 }
3850 let merged = std::rc::Rc::new(a.merged(&b));
3851 self.components.merges.insert(key, [a, b, merged.clone()]);
3852 Some(merged)
3853 }
3854 (a, None) => a,
3855 (None, b) => b,
3856 }
3857 }
3858
3859 pub(super) fn children_placed(
3863 &mut self,
3864 host: NodeId,
3865 inst: &mut Instance,
3866 old_place: Placement,
3867 ) {
3868 if inst.children_at == Placement::None && old_place != Placement::None {
3870 for &child in &inst.js_children {
3871 self.unplace(old_place, child);
3872 }
3873 }
3874 let wanted = inst.children_at != Placement::None;
3877 if inst.children_wanted != wanted && inst.spec.as_ref().is_some_and(|s| s.lazy_children) {
3878 inst.children_wanted = wanted;
3879 match self.components.owners.get(&host).copied() {
3880 Some(_) => {
3888 if let Some(signal) = inst.lazy_wanted {
3889 signal.try_set(wanted);
3890 }
3891 }
3892 None => self.events.push(JsEvent::Children { host, wanted }),
3893 }
3894 }
3895 }
3896
3897 fn children_wanted_signal(&mut self, nested: NodeId) -> crate::element::Signal<bool> {
3901 let Some(inst) = self.components.instances.get_mut(&nested) else {
3902 return crate::element::signal(false);
3903 };
3904 match inst.lazy_wanted {
3908 Some(signal) if signal.is_live() => signal,
3909 _ => {
3910 let signal = crate::element::signal(inst.children_wanted);
3911 inst.lazy_wanted = Some(signal);
3912 signal
3913 }
3914 }
3915 }
3916
3917 fn unplace(&mut self, place: Placement, child: NodeId) {
3920 match place {
3921 Placement::Nested(nested, _) if self.is_host(nested) => {
3922 let _ = self.intercept(Op::Remove {
3923 parent: nested,
3924 child,
3925 });
3926 }
3927 _ => self.detach_id(child),
3928 }
3929 }
3930
3931 pub(super) fn detach_id(&mut self, id: NodeId) {
3932 self.unfold_run(id);
3933 if let Ok(key) = self.key(id)
3934 && self.nodes[key as usize].parent != NO_KEY
3935 {
3936 self.detach(key);
3937 }
3938 }
3939
3940 pub(super) fn apply_attrs(&mut self, id: NodeId, new: &Attrs, old: &Attrs) {
3941 self.apply_attrs_over(id, new, old, None);
3942 }
3943
3944 pub(super) fn apply_attrs_over(
3947 &mut self,
3948 id: NodeId,
3949 new: &Attrs,
3950 old: &Attrs,
3951 app: Option<&crate::StylePatch>,
3952 ) {
3953 let node = self.native_id(id);
3955 let has_rare = new.rare.is_some() || old.rare.is_some();
3956 if has_rare {
3957 let empty = crate::element::builder::RareAttrs::default();
3958 let nr = new.rare.as_deref().unwrap_or(&empty);
3959 let or = old.rare.as_deref().unwrap_or(&empty);
3960 if or.element_ref != nr.element_ref
3961 && let Some(r) = &or.element_ref
3962 {
3963 r.detach(node);
3964 }
3965 if let Some(r) = &nr.element_ref {
3966 r.attach(node);
3967 }
3968 if nr.render != or.render {
3969 self.update_render(node, or.render.as_ref(), nr.render.as_ref());
3970 }
3971 }
3972 let mut props = std::mem::take(&mut self.components.props);
3973 new.changes(old, &mut props);
3974 for prop in props.drain(..) {
3975 let _ = self.apply_op(Op::SetProp { id, prop });
3976 }
3977 self.components.props = props;
3978 let animated_changed = has_rare && new.animated() != old.animated();
3979 if new.inline != old.inline || animated_changed {
3980 let _ = self.apply_op(inline_style(id, new.inline.as_deref(), new.animated(), app));
3981 }
3982 if has_rare {
3983 let empty = crate::element::builder::RareAttrs::default();
3984 let nr = new.rare.as_deref().unwrap_or(&empty);
3985 let or = old.rare.as_deref().unwrap_or(&empty);
3986 if nr.drawing != or.drawing
3987 && let Some(drawing) = &nr.drawing
3988 {
3989 let _ = self.apply_op(Op::Draw {
3990 id,
3991 drawing: Box::new((**drawing).clone()),
3992 });
3993 }
3994 if nr.window != or.window
3995 && let Some(window) = &nr.window
3996 {
3997 let command = if or.window.is_none() {
4000 crate::desktop::DesktopCommand::OpenWindow(Box::new(
4001 crate::desktop::OpenWindow {
4002 options: (**window).clone(),
4003 ..Default::default()
4004 },
4005 ))
4006 } else {
4007 crate::desktop::DesktopCommand::SetAttributes(Box::new(
4008 window.attributes.clone(),
4009 ))
4010 };
4011 let opens = or.window.is_none();
4012 let _ = self.apply_op(Op::Command {
4013 id,
4014 command: crate::Command::Desktop(Box::new(command)),
4015 });
4016 if opens {
4019 for command in &nr.window_commands {
4020 let _ = self.apply_op(Op::Command {
4021 id,
4022 command: crate::Command::Desktop(Box::new(command.clone())),
4023 });
4024 }
4025 }
4026 }
4027 }
4028 }
4029
4030 pub(super) fn apply_styles(
4032 &mut self,
4033 id: NodeId,
4034 style: &StyleRefinement,
4035 old_style: &StyleRefinement,
4036 old: Classes,
4037 user: Option<std::rc::Rc<ClassList>>,
4038 ) -> Classes {
4039 let own = if style == old_style {
4040 old.0.clone()
4041 } else if style.is_empty() {
4042 None
4043 } else {
4044 Some(self.components.lowered(style))
4045 };
4046 if !same(&own, &old.0) || !same(&user, &old.1) {
4047 let list = self.merge_user(own.clone(), user.clone());
4048 if let Ok(key) = self.key(id) {
4049 self.set_class_list(key, list);
4050 }
4051 }
4052 (own, user)
4053 }
4054
4055 pub(super) fn apply_el_styles(
4060 &mut self,
4061 id: NodeId,
4062 style: &StyleRefinement,
4063 old_style: &StyleRefinement,
4064 old: Classes,
4065 class: Option<&SharedString>,
4066 outer: Option<std::rc::Rc<ClassList>>,
4067 ) -> Classes {
4068 let Some(class) = class.filter(|c| !c.trim().is_empty()) else {
4069 if !self.components.app_classes.is_empty() {
4070 self.components.app_classes.remove(&id);
4071 }
4072 return self.apply_styles(id, style, old_style, old, outer);
4073 };
4074 let app = self.app_class_list(class);
4075 let user = self.merge_user(Some(app), outer.clone());
4076 let classes = self.apply_styles(id, style, old_style, old, user);
4077 self.components
4078 .app_classes
4079 .insert(id, (classes.0.clone(), class.clone(), outer));
4080 classes
4081 }
4082
4083 pub(super) fn app_class_list(&mut self, class: &str) -> std::rc::Rc<ClassList> {
4086 let (list, fresh) = self.tailwind.get(class);
4087 if fresh && !list.unknown().is_empty() {
4088 log::warn!(
4089 "unknown classes: {}",
4090 list.unknown()
4091 .iter()
4092 .map(|s| &**s)
4093 .collect::<Vec<_>>()
4094 .join(" ")
4095 );
4096 }
4097 list
4098 }
4099
4100 #[allow(
4103 clippy::too_many_arguments,
4104 reason = "the installed node and its owning view"
4105 )]
4106 fn apply_handlers(
4107 &mut self,
4108 host: NodeId,
4109 id: NodeId,
4110 el: &ElNode,
4111 old: EventMask,
4112 extra: EventMask,
4113 inst: &mut Instance,
4114 ) -> EventMask {
4115 let mut mask = extra;
4116 self.initialize_layout_listeners(host, id, el, old, inst);
4117 if old.bits() != 0 {
4120 inst.handlers.remove(id);
4121 inst.responders.retain(|(n, _)| *n != id);
4122 }
4123 for (kind, handler) in &el.handlers {
4124 mask.set(*kind, true);
4125 inst.handlers.push(id, *kind, handler.clone());
4126 }
4127 if let Some(responder) = &el.responder {
4129 mask.set(EventKind::Touch, true);
4130 inst.responders.push((id, responder.clone()));
4131 }
4132 let own = self.target_events(id, mask);
4135 let mut changed = (mask.bits() ^ old.bits()) & !own.bits();
4136 while changed != 0 {
4137 let kind = EventKind::ALL[changed.trailing_zeros() as usize];
4138 changed &= changed - 1;
4139 let _ = self.apply_op(Op::Listen {
4140 id,
4141 event: kind,
4142 enabled: mask.contains(kind),
4143 });
4144 }
4145 mask
4146 }
4147
4148 pub(super) fn initialize_layout_listeners(
4150 &mut self,
4151 host: NodeId,
4152 id: NodeId,
4153 el: &ElNode,
4154 old: EventMask,
4155 inst: &Instance,
4156 ) {
4157 if old.contains(EventKind::Layout)
4160 && let Ok(key) = self.key(id)
4161 {
4162 let frame = self.nodes[key as usize].frame;
4163 if !frame.origin.x.0.is_nan() {
4164 for (kind, listener) in &el.handlers {
4165 if *kind == EventKind::Layout
4166 && !inst
4167 .handlers
4168 .of(id)
4169 .iter()
4170 .any(|(k, old)| *k == *kind && old.same_owner(listener))
4171 {
4172 self.events.push(JsEvent::LayoutListener {
4173 host,
4174 id,
4175 listener: listener.clone(),
4176 frame,
4177 });
4178 }
4179 }
4180 }
4181 }
4182 }
4183
4184 fn reconcile_children(
4185 &mut self,
4186 parent: NodeId,
4187 old: Vec<Expanded>,
4188 new: Vec<ElNode>,
4189 host: NodeId,
4190 inst: &mut Instance,
4191 ) -> Vec<Expanded> {
4192 if new.is_empty() && old.is_empty() {
4193 return Vec::new();
4194 }
4195 let new = new.into_iter().map(|el| NewChild::Made(None, el)).collect();
4196 let (out, placeholder) = self.match_children(parent, old, new, host, inst);
4197 self.set_region_anchors(&out, inst, Anchor::End);
4199 let nested = parent != host && self.is_host(parent);
4200 if nested {
4201 if let Some(at) = placeholder {
4202 let anchor = self.anchor_after(&out[at + 1..], inst, Anchor::End);
4203 inst.children_at = Placement::Nested(parent, anchor);
4204 }
4205 self.place_filled(&out, inst, Anchor::End, |anchor| {
4206 Placement::Nested(parent, anchor)
4207 });
4208 self.fill_nested(parent, &out, host, inst);
4209 self.join_nested(parent, &out, inst);
4210 return out;
4211 }
4212 if let Some(at) = placeholder {
4213 let anchor = self.anchor_after(&out[at + 1..], inst, Anchor::End);
4214 inst.children_at = Placement::At(parent, anchor);
4215 }
4216 self.place_filled(&out, inst, Anchor::End, |anchor| {
4217 Placement::At(parent, anchor)
4218 });
4219 let wanted_ids: Vec<NodeId> = out
4223 .iter()
4224 .flat_map(|e| match e.part {
4225 Part::Children => inst.js_children.clone(),
4226 Part::Filled(name) => self
4227 .fill_of(inst, name)
4228 .map(|f| self.fill_nodes(f))
4229 .unwrap_or_default(),
4230 Part::Region(region) => self.region_nodes(region),
4231 _ => vec![e.id],
4232 })
4233 .collect();
4234 let wanted = || wanted_ids.iter();
4235 if self.is_list(parent) {
4238 for e in out.iter().filter(|e| e.id != 0) {
4240 let joined = self
4241 .key(e.id)
4242 .is_ok_and(|k| self.nodes[k as usize].parent != NO_KEY);
4243 if !joined {
4244 let _ = self.apply_op(Op::Insert {
4245 parent,
4246 child: e.id,
4247 before: None,
4248 });
4249 }
4250 }
4251 return out;
4252 }
4253 let in_order = self.key(parent).is_ok_and(|k| {
4254 let have = &self.nodes[k as usize].children;
4255 have.len() == wanted().count()
4256 && have
4257 .iter()
4258 .zip(wanted())
4259 .all(|(&c, &id)| self.nodes[c as usize].id == id)
4260 });
4261 if !in_order {
4262 let ids: Vec<NodeId> = wanted().copied().collect();
4268 let empty = self
4271 .key(parent)
4272 .is_ok_and(|k| self.nodes[k as usize].children.is_empty());
4273 if empty {
4274 for &child in &ids {
4275 let _ = self.apply_op(Op::Insert {
4276 parent,
4277 child,
4278 before: None,
4279 });
4280 }
4281 return out;
4282 }
4283 let mut before = None;
4284 for &child in ids.iter().rev() {
4285 if !self.precedes(parent, child, before) {
4286 let _ = self.apply_op(Op::Insert {
4287 parent,
4288 child,
4289 before,
4290 });
4291 }
4292 before = Some(child);
4293 }
4294 }
4295 out
4296 }
4297
4298 pub(super) fn match_children(
4302 &mut self,
4303 parent: NodeId,
4304 old: Vec<Expanded>,
4305 new: Vec<NewChild>,
4306 host: NodeId,
4307 inst: &mut Instance,
4308 ) -> (Vec<Expanded>, Option<usize>) {
4309 let new = if new.iter().any(
4312 |child| matches!(child, NewChild::Made(_, e) if matches!(e.kind, ElKind::EachChild(_))),
4313 ) {
4314 let mut each = Vec::with_capacity(new.len() + inst.js_children.len());
4315 for child in new {
4316 let NewChild::Made(owner, el) = child else {
4317 each.push(child);
4318 continue;
4319 };
4320 let ElKind::EachChild(place) = &el.kind else {
4321 each.push(NewChild::Made(owner, el));
4322 continue;
4323 };
4324 if inst.children_at != Placement::None {
4325 log::error!(target: "js", "a view places its children once");
4326 continue;
4327 }
4328 inst.children_at = Placement::Each;
4329 {
4330 let children = match inst.js_kids {
4331 Some(children) => children,
4332 None => *inst.js_kids.insert(crate::element::signal_with(
4333 inst.js_kids(),
4334 crate::element::SignalEquals::Never,
4335 )),
4336 };
4337 let place = place.clone();
4340 let count = crate::element::computed(move || children.with(Vec::len));
4341 let region = crate::element::each(
4342 children,
4343 |&(child, _): &(NodeId, bool)| child,
4344 move |child, index| {
4345 let at = Position::of(index.node(), count.node());
4346 let (child, text) = child.get_untracked();
4347 place(Child::js(child, text), at)
4348 },
4349 );
4350 each.push(NewChild::Made(owner, region.0));
4351 }
4352 }
4353 each
4354 } else {
4355 new
4356 };
4357 let mut old: Vec<Option<Expanded>> = old.into_iter().map(Some).collect();
4358 let mut out = Vec::with_capacity(new.len());
4359 let mut placeholder = None;
4360 let mut cursor = 0;
4364 let mut after_kept = 0;
4368 let mut keys = OldKeys::default();
4371 for child in new {
4372 let (owner, el) = match child {
4373 NewChild::Made(owner, el) => (owner, el),
4374 NewChild::Kept(key) => {
4377 let is = |o: &Option<Expanded>| {
4378 o.as_ref().is_some_and(|o| o.key.as_ref() == Some(&key))
4379 };
4380 let at = if old.get(after_kept).is_some_and(is) {
4381 Some(after_kept)
4382 } else {
4383 keys.find(&old, &key, |_| true)
4384 };
4385 match at.and_then(|at| {
4386 after_kept = at + 1;
4387 old[at].take()
4388 }) {
4389 Some(e) => out.push(e),
4390 None => log::error!("a kept row is gone"),
4391 }
4392 continue;
4393 }
4394 };
4395 let child = |core: &mut Self| {
4396 core.match_child(
4397 parent,
4398 el,
4399 host,
4400 inst,
4401 &mut old,
4402 &mut out,
4403 &mut placeholder,
4404 &mut cursor,
4405 &mut keys,
4406 );
4407 };
4408 match owner {
4409 Some(owner) => owner.run(|| child(self)),
4410 None => child(self),
4411 }
4412 }
4413 let nested = parent != host && self.is_host(parent);
4417 for o in old.into_iter().flatten() {
4418 self.unplace_filled(&o, inst);
4421 if nested && o.part == Part::Children {
4422 for &child in &inst.js_children {
4424 let _ = self.intercept(Op::Remove { parent, child });
4425 }
4426 } else if nested {
4427 for node in self.placed(&o) {
4428 self.forget_nested(parent, node);
4429 }
4430 }
4431 self.release_expanded(o);
4432 }
4433 (out, placeholder)
4434 }
4435
4436 #[allow(clippy::too_many_arguments, reason = "the matching's state")]
4439 fn match_child(
4440 &mut self,
4441 parent: NodeId,
4442 mut el: ElNode,
4443 host: NodeId,
4444 inst: &mut Instance,
4445 old: &mut [Option<Expanded>],
4446 out: &mut Vec<Expanded>,
4447 placeholder: &mut Option<usize>,
4448 cursor: &mut usize,
4449 keys: &mut OldKeys,
4450 ) {
4451 let mut wrapper = false;
4456 if let ElKind::Slot(name) = el.kind
4457 && inst.fills.iter().any(|f| f.name == name)
4458 {
4459 if is_plain(&el) {
4460 el.kind = ElKind::Filled(name);
4461 } else {
4462 el.kind = ElKind::Plain;
4463 let mut filled = ElNode::new(Tag::View);
4464 filled.kind = ElKind::Filled(name);
4465 el.children = vec![filled];
4466 el.key.get_or_insert_with(|| format!("slot:{name}").into());
4467 wrapper = true;
4468 }
4469 }
4470 match std::mem::replace(&mut el.kind, ElKind::Plain) {
4471 ElKind::Filled(name) => {
4472 if let Some(j) = old
4473 .iter()
4474 .position(|o| o.as_ref().is_some_and(|o| o.part == Part::Filled(name)))
4475 {
4476 old[j] = None;
4477 }
4478 out.push(Expanded::js(0, Part::Filled(name)));
4479 }
4480 ElKind::Fill(name) => {
4481 let prev = old
4484 .iter()
4485 .position(|o| o.as_ref().is_some_and(|o| o.part == Part::Fill(name)))
4486 .and_then(|j| old[j].take());
4487 let old_children = prev.map(|p| p.children).unwrap_or_default();
4488 let new = std::mem::take(&mut el.children)
4489 .into_iter()
4490 .map(|c| NewChild::Made(None, c))
4491 .collect();
4492 let filling = self.components.filling.replace((parent, name));
4493 let (children, _) = self.match_children(parent, old_children, new, host, inst);
4494 self.components.filling = filling;
4495 let mut e = Expanded::js(0, Part::Fill(name));
4496 e.children = children;
4497 out.push(e);
4498 }
4499 ElKind::Slot(name) => {
4500 let Some(&(_, node)) = inst.slots.iter().find(|(s, _)| *s == name) else {
4502 return;
4503 };
4504 let at = old.iter().position(|o| {
4505 o.as_ref()
4506 .is_some_and(|o| o.part == Part::Slot && o.id == node)
4507 });
4508 let prev = at.and_then(|j| old[j].take());
4509 out.push(self.reconcile_slot(prev, node, el, host, inst));
4510 }
4511 ElKind::Children => {
4512 if placeholder.is_some() || inst.children_at != Placement::None {
4513 log::error!(target: "js", "a view places its children once");
4514 return;
4515 }
4516 if let Some(j) = old
4517 .iter()
4518 .position(|o| o.as_ref().is_some_and(|o| o.part == Part::Children))
4519 {
4520 old[j] = None;
4521 }
4522 *placeholder = Some(out.len());
4523 inst.children_owner = Some(crate::element::Owner::current());
4524 out.push(Expanded::js(0, Part::Children));
4525 }
4526 ElKind::JsChild(id) => {
4527 if let Some(j) = old.iter().position(|o| {
4529 o.as_ref()
4530 .is_some_and(|o| o.part == Part::JsChild && o.id == id)
4531 }) {
4532 old[j] = None;
4533 }
4534 if inst.js_children.contains(&id) {
4535 let mut e = Expanded::js(id, Part::JsChild);
4536 e.key = el.key;
4539 out.push(e);
4540 }
4541 }
4542 ElKind::EachChild(_) => {}
4544 ElKind::Region(region) => {
4546 let id = self.bind_region(host, parent, region);
4547 let mut e = super::views::region_placeholder(id);
4548 e.key = el.key;
4551 out.push(e);
4552 }
4553 ElKind::List(list) => {
4554 let Some(&(_, node)) = inst.slots.iter().find(|(s, _)| *s == list.name) else {
4557 return;
4558 };
4559 let at = old.iter().position(|o| {
4560 o.as_ref()
4561 .is_some_and(|o| o.part == Part::Slot && o.id == node)
4562 });
4563 let prev = at.and_then(|j| old[j].take());
4564 let old_config = self
4565 .components
4566 .list_layouts
4567 .remove(&node)
4568 .or_else(|| prev.as_ref().and_then(|p| p.list.as_deref().copied()))
4569 .unwrap_or_default();
4570 let parts = std::mem::take(&mut el.bound_list);
4572 let config = if parts.is_empty() {
4573 list.config
4574 } else {
4575 self.bind_list_layout(node, list.config, parts)
4576 };
4577 let mut props = std::mem::take(&mut self.components.props);
4578 config.changes(&old_config, &mut props);
4579 for prop in props.drain(..) {
4580 let _ = self.apply_op(Op::SetProp { id: node, prop });
4581 }
4582 self.components.props = props;
4583 let mut e = self.reconcile_slot(prev, node, el, host, inst);
4584 e.list = Some(Box::new(config));
4585 let rows = self.rows_of_list(node);
4586 self.components.lists.insert(node, (list.row.clone(), rows));
4587 if let Some(state) = self.components.virtual_lists.get_mut(&node) {
4590 state.place = Some(list.row.clone());
4591 }
4592 let cells: Vec<NodeId> = match self.key(node) {
4593 Ok(k) => self.nodes[k as usize]
4594 .children
4595 .iter()
4596 .map(|&c| self.nodes[c as usize].id)
4597 .collect(),
4598 Err(_) => Vec::new(),
4599 };
4600 for cell in cells {
4601 self.wrap_row(cell, list.row.clone());
4602 }
4603 out.push(e);
4604 }
4605 kind => {
4606 el.kind = kind;
4607 let part = match &el.kind {
4608 ElKind::Component(c) => Part::Component(c.name),
4609 ElKind::VirtualList(_) => Part::VirtualList,
4610 ElKind::Raw => Part::Raw,
4611 _ => Part::Node,
4612 };
4613 let component = matches!(part, Part::Component(_));
4617 let matches = |o: &Expanded| !component && o.tag == el.tag && o.part == part;
4618 let at = match &el.key {
4619 Some(k) => keys.find(old, k, matches),
4620 None => {
4621 let at = old[(*cursor).min(old.len())..]
4622 .iter()
4623 .position(|o| o.as_ref().is_some_and(|o| o.key.is_none() && matches(o)))
4624 .map(|j| j + *cursor);
4625 if let Some(j) = at {
4626 *cursor = j + 1;
4627 }
4628 at
4629 }
4630 };
4631 let prev = at.and_then(|j| old[j].take());
4632 let e = if wrapper {
4633 self.reconcile_wrapper(prev, el, host, inst)
4634 } else {
4635 self.reconcile_node(prev, el, part, host, inst)
4636 };
4637 out.push(e);
4638 }
4639 }
4640 }
4641
4642 pub(super) fn nested_precedes(
4645 &self,
4646 nested: NodeId,
4647 child: NodeId,
4648 next: Option<NodeId>,
4649 ) -> bool {
4650 let Some(inst) = self.components.instances.get(&nested) else {
4651 return false;
4652 };
4653 let kids = &inst.js_children;
4654 kids.iter()
4655 .position(|&c| c == child)
4656 .is_some_and(|i| kids.get(i + 1).copied() == next)
4657 }
4658
4659 pub(super) fn join_nested_at(&mut self, nested: NodeId, child: NodeId, before: Option<NodeId>) {
4662 if let Ok(Some(op)) = self.intercept(Op::Insert {
4663 parent: nested,
4664 child,
4665 before,
4666 }) {
4667 let _ = self.apply_op(op);
4668 }
4669 }
4670
4671 fn forget_nested(&mut self, nested: NodeId, child: NodeId) {
4676 if self.components.slot_names.remove(&child).is_some() {
4677 self.unslot(child);
4678 return;
4679 }
4680 let Some(inst) = self.components.instances.get_mut(&nested) else {
4681 return;
4682 };
4683 let count = inst.js_children.len();
4684 inst.forget_js_child(child);
4685 if inst.js_children.len() == count {
4686 return;
4687 }
4688 inst.js_children_changed();
4689 let place = inst.children_at;
4690 if inst.js_children.is_empty() || place == Placement::Each {
4691 self.components.mark(nested);
4692 }
4693 if let Placement::Nested(deeper, _) = place
4695 && self.is_host(deeper)
4696 {
4697 self.forget_nested(deeper, child);
4698 }
4699 }
4700
4701 fn join_nested(&mut self, nested: NodeId, out: &[Expanded], inst: &Instance) {
4706 let insert = |core: &mut Self, child: NodeId, before: Option<NodeId>| {
4707 if let Ok(Some(op)) = core.intercept(Op::Insert {
4708 parent: nested,
4709 child,
4710 before,
4711 }) {
4712 let _ = core.apply_op(op);
4713 }
4714 };
4715 let (slots, children): (Vec<NodeId>, Vec<NodeId>) = out
4716 .iter()
4717 .flat_map(|e| match e.part {
4718 Part::Children => inst.js_children.clone(),
4719 Part::Filled(name) => self
4720 .fill_of(inst, name)
4721 .map(|f| self.fill_nodes(f))
4722 .unwrap_or_default(),
4723 Part::Fill(_) | Part::Tooltip => Vec::new(),
4725 _ => self.placed(e),
4726 })
4727 .partition(|id| self.components.slot_names.contains_key(id));
4728 for slot in slots {
4729 if self.components.slot_hosts.get(&slot) != Some(&nested) {
4730 insert(self, slot, None);
4731 }
4732 }
4733 let same = self
4734 .components
4735 .instances
4736 .get(&nested)
4737 .is_some_and(|i| i.js_children == children);
4738 if !same {
4739 let mut before = None;
4740 for &child in children.iter().rev() {
4741 insert(self, child, before);
4742 before = Some(child);
4743 }
4744 }
4745 }
4746
4747 pub(super) fn fill_of<'a>(&self, inst: &'a Instance, name: &'static str) -> Option<&'a Fill> {
4749 inst.fills.iter().find(|f| f.name == name)
4750 }
4751
4752 pub(super) fn fill_nodes(&self, fill: &Fill) -> Vec<NodeId> {
4754 self.fill_nodes_with(fill, None)
4755 }
4756
4757 fn fill_nodes_with(&self, fill: &Fill, out: Option<(NodeId, &Instance)>) -> Vec<NodeId> {
4760 let mut nodes = Vec::with_capacity(fill.parts.len());
4761 for part in &fill.parts {
4762 match *part {
4763 FillPart::Node(id) => nodes.push(id),
4764 FillPart::Region(region) => self.fill_region_nodes(region, out, &mut nodes),
4765 FillPart::Filled(name) => self.passed_nodes(fill.from, name, out, &mut nodes),
4766 }
4767 }
4768 nodes
4769 }
4770
4771 fn fill_region_nodes(
4774 &self,
4775 region: u32,
4776 out: Option<(NodeId, &Instance)>,
4777 nodes: &mut Vec<NodeId>,
4778 ) {
4779 let Some(state) = self.components.regions.get(®ion) else {
4780 return;
4781 };
4782 for e in &state.children {
4783 match e.part {
4784 Part::Filled(name) => self.passed_nodes(state.host, name, out, nodes),
4785 Part::Region(inner) => self.fill_region_nodes(inner, out, nodes),
4786 _ => nodes.extend(self.placed(e)),
4787 }
4788 }
4789 }
4790
4791 fn passed_nodes(
4794 &self,
4795 host: NodeId,
4796 name: &'static str,
4797 out: Option<(NodeId, &Instance)>,
4798 nodes: &mut Vec<NodeId>,
4799 ) {
4800 let inst = match out {
4801 Some((h, inst)) if h == host => Some(inst),
4802 _ => self.components.instances.get(&host).map(|i| &**i),
4803 };
4804 if let Some(fill) = inst.and_then(|i| self.fill_of(i, name)) {
4805 nodes.extend(self.fill_nodes_with(fill, out));
4806 }
4807 }
4808
4809 fn passed_slots(&self, parts: &[FillPart], host: NodeId, names: &mut Vec<&'static str>) {
4812 fn of_region<M: TextEngine>(
4813 core: &Core<M>,
4814 region: u32,
4815 host: NodeId,
4816 names: &mut Vec<&'static str>,
4817 ) {
4818 let Some(state) = core.components.regions.get(®ion) else {
4819 return;
4820 };
4821 for e in &state.children {
4822 match e.part {
4823 Part::Filled(name) if state.host == host => names.push(name),
4824 Part::Region(inner) => of_region(core, inner, host, names),
4825 _ => {}
4826 }
4827 }
4828 }
4829 for part in parts {
4830 match *part {
4831 FillPart::Filled(name) => names.push(name),
4832 FillPart::Region(region) => of_region(self, region, host, names),
4833 FillPart::Node(_) => {}
4834 }
4835 }
4836 }
4837
4838 pub(super) fn note_passed(
4841 &self,
4842 nested: NodeId,
4843 name: &'static str,
4844 host: NodeId,
4845 inst: &mut Instance,
4846 ) {
4847 let mut passed = Vec::new();
4848 if let Some(fill) = self
4849 .components
4850 .instances
4851 .get(&nested)
4852 .and_then(|t| self.fill_of(t, name))
4853 {
4854 self.passed_slots(&fill.parts, host, &mut passed);
4855 }
4856 for fill in &mut inst.fills {
4857 if passed.contains(&fill.name) {
4858 fill.forwarded = Some((nested, name));
4859 } else if fill.forwarded == Some((nested, name)) {
4860 fill.forwarded = None;
4861 }
4862 }
4863 }
4864
4865 pub(super) fn place_filled(
4868 &self,
4869 out: &[Expanded],
4870 inst: &mut Instance,
4871 end: Anchor,
4872 place: impl Fn(Anchor) -> Placement,
4873 ) {
4874 if inst.fills.is_empty() {
4875 return;
4876 }
4877 for (i, e) in out.iter().enumerate() {
4878 let Part::Filled(name) = e.part else {
4879 continue;
4880 };
4881 let at = place(self.anchor_after(&out[i + 1..], inst, end));
4882 if let Some(fill) = inst.fills.iter_mut().find(|f| f.name == name) {
4883 fill.at = at;
4884 }
4885 }
4886 }
4887
4888 pub(super) fn unplace_filled(&mut self, e: &Expanded, inst: &mut Instance) {
4891 if inst.fills.is_empty() {
4892 return;
4893 }
4894 match e.part {
4895 Part::Filled(name) => {
4896 let Some(fill) = inst.fills.iter_mut().find(|f| f.name == name) else {
4897 return;
4898 };
4899 let at = std::mem::replace(&mut fill.at, Placement::None);
4900 if at == Placement::None {
4901 return;
4902 }
4903 let nodes = self.fill_nodes(self.fill_of(inst, name).expect("a fill"));
4904 for node in nodes {
4905 self.unplace(at, node);
4906 }
4907 }
4908 Part::Region(region) => {
4909 let children = self
4910 .components
4911 .regions
4912 .get_mut(®ion)
4913 .map(|s| std::mem::take(&mut s.children))
4914 .unwrap_or_default();
4915 for c in &children {
4916 self.unplace_filled(c, inst);
4917 }
4918 if let Some(state) = self.components.regions.get_mut(®ion) {
4919 state.children = children;
4920 }
4921 }
4922 _ => {
4923 for c in &e.children {
4924 self.unplace_filled(c, inst);
4925 }
4926 }
4927 }
4928 }
4929
4930 fn fill_nested(&mut self, nested: NodeId, out: &[Expanded], host: NodeId, inst: &mut Instance) {
4936 let fills: Vec<(&'static str, Vec<FillPart>)> = out
4937 .iter()
4938 .filter_map(|e| match e.part {
4939 Part::Fill(name) => Some((
4940 name,
4941 e.children
4942 .iter()
4943 .filter_map(|c| match c.part {
4944 Part::Region(region) => Some(FillPart::Region(region)),
4945 Part::Filled(name) => Some(FillPart::Filled(name)),
4946 _ if c.id != 0 => Some(FillPart::Node(c.id)),
4947 _ => None,
4948 })
4949 .collect(),
4950 )),
4951 _ => None,
4952 })
4953 .collect();
4954 for fill in &mut inst.fills {
4956 if fill.forwarded.is_some_and(|(n, _)| n == nested) {
4957 fill.forwarded = None;
4958 }
4959 }
4960 for (name, parts) in &fills {
4961 let mut passed = Vec::new();
4962 self.passed_slots(parts, host, &mut passed);
4963 for fill in inst.fills.iter_mut().filter(|f| passed.contains(&f.name)) {
4964 fill.forwarded = Some((nested, name));
4965 }
4966 }
4967 let Some(target) = self.components.instances.get_mut(&nested) else {
4968 return;
4969 };
4970 if fills.is_empty() && target.fills.is_empty() {
4971 return;
4972 }
4973 let mut changed = target.fills.len() != fills.len();
4974 let old = std::mem::take(&mut target.fills);
4975 let mut joining = Vec::new();
4976 for (name, parts) in fills {
4977 let (at, forwarded, same) = match old.iter().find(|f| f.name == name) {
4978 Some(f) => (f.at, f.forwarded, f.parts == parts),
4979 None => (Placement::None, None, false),
4980 };
4981 changed |= !same;
4982 if !same {
4983 joining.push(name);
4984 }
4985 target.fills.push(Fill {
4986 name,
4987 parts,
4988 from: host,
4989 at,
4990 forwarded,
4991 });
4992 }
4993 if !changed {
4994 return;
4995 }
4996 let out = Some((host, &*inst));
4999 let mut leaving = Vec::new();
5000 for fill in &old {
5001 let at = self.fill_place(nested, fill.name);
5002 let now = self
5003 .components
5004 .instances
5005 .get(&nested)
5006 .and_then(|t| self.fill_of(t, fill.name))
5007 .map(|f| self.fill_nodes_with(f, out))
5008 .unwrap_or_default();
5009 for node in self.fill_nodes_with(fill, out) {
5010 if !now.contains(&node) && self.key(node).is_ok() {
5011 leaving.push((at, node));
5012 }
5013 }
5014 }
5015 for (at, node) in leaving {
5016 self.unplace(at, node);
5017 }
5018 for name in joining {
5019 self.join_fill(nested, name, out);
5020 }
5021 self.components.mark(nested);
5023 let names: Vec<&'static str> = self.components.instances[&nested]
5024 .fills
5025 .iter()
5026 .map(|f| f.name)
5027 .collect();
5028 for name in names {
5029 self.place_fill_with(nested, name, Some((host, &*inst)));
5030 }
5031 }
5032
5033 pub(super) fn join_fill(
5039 &mut self,
5040 nested: NodeId,
5041 name: &'static str,
5042 out: Option<(NodeId, &Instance)>,
5043 ) {
5044 let nodes = self
5045 .components
5046 .instances
5047 .get(&nested)
5048 .and_then(|inst| self.fill_of(inst, name))
5049 .map(|fill| self.fill_nodes_with(fill, out))
5050 .unwrap_or_default();
5051 for node in nodes {
5052 self.join_content(node);
5053 }
5054 }
5055
5056 fn fill_place(&self, nested: NodeId, name: &'static str) -> Placement {
5060 let Some(fill) = self
5061 .components
5062 .instances
5063 .get(&nested)
5064 .and_then(|inst| self.fill_of(inst, name))
5065 else {
5066 return Placement::None;
5067 };
5068 match (fill.at, fill.forwarded) {
5069 (Placement::None, Some((deeper, slot))) => self.fill_place(deeper, slot),
5070 (at, _) => at,
5071 }
5072 }
5073
5074 pub(super) fn place_fill(&mut self, nested: NodeId, name: &'static str) {
5078 self.place_fill_with(nested, name, None);
5079 }
5080
5081 fn place_fill_with(
5084 &mut self,
5085 nested: NodeId,
5086 name: &'static str,
5087 out: Option<(NodeId, &Instance)>,
5088 ) {
5089 let Some(fill) = self
5090 .components
5091 .instances
5092 .get(&nested)
5093 .and_then(|inst| self.fill_of(inst, name))
5094 else {
5095 return;
5096 };
5097 let (nodes, at, forwarded) = (self.fill_nodes_with(fill, out), fill.at, fill.forwarded);
5098 if let Some((deeper, slot)) = forwarded {
5099 self.components.mark(deeper);
5102 self.place_fill_with(deeper, slot, out);
5103 }
5104 match at {
5105 Placement::At(parent, anchor) => {
5106 let parent_key = self.key(parent).ok();
5107 let mut before = self.anchor_node(anchor).filter(|&a| {
5109 self.key(a)
5110 .is_ok_and(|k| Some(self.nodes[k as usize].parent) == parent_key)
5111 });
5112 for &child in nodes.iter().rev() {
5113 if !self.precedes(parent, child, before) {
5114 let _ = self.apply_op(Op::Insert {
5115 parent,
5116 child,
5117 before,
5118 });
5119 }
5120 before = Some(child);
5121 }
5122 if self.components.fill_holders.contains(&parent) {
5124 self.retarget_slot(parent, None);
5125 }
5126 }
5127 Placement::Nested(other, anchor) => {
5128 let mut before = self.anchor_node(anchor);
5129 for &child in nodes.iter().rev() {
5130 if !self.nested_precedes(other, child, before) {
5131 self.join_nested_at(other, child, before);
5132 }
5133 before = Some(child);
5134 }
5135 }
5136 _ => {}
5137 }
5138 }
5139
5140 pub(super) fn precedes(&self, parent: NodeId, child: NodeId, next: Option<NodeId>) -> bool {
5143 self.preceding(parent, child, next, None).is_some()
5144 }
5145
5146 pub(super) fn preceding(
5153 &self,
5154 parent: NodeId,
5155 child: NodeId,
5156 next: Option<NodeId>,
5157 hint: Option<usize>,
5158 ) -> Option<usize> {
5159 let k = self.key(parent).ok()?;
5160 if self.nodes[self.key(child).ok()? as usize].parent != k {
5161 return None;
5162 }
5163 let children = &self.nodes[k as usize].children;
5164 let id = |at: usize| children.get(at).map(|&c| self.nodes[c as usize].id);
5165 let at = match hint {
5166 Some(at) if id(at) == Some(child) => at,
5167 _ => {
5168 let at = children
5169 .iter()
5170 .position(|&c| self.nodes[c as usize].id == child);
5171 self.placing(at.map_or(children.len(), |at| at + 1));
5172 at?
5173 }
5174 };
5175 (id(at + 1) == next).then_some(at)
5176 }
5177
5178 #[cfg(test)]
5181 pub(super) fn placing(&self, n: usize) {
5182 let work = &self.components.placing_work;
5183 work.set(work.get() + n);
5184 }
5185
5186 #[cfg(not(test))]
5187 #[inline(always)]
5188 pub(super) fn placing(&self, _n: usize) {}
5189
5190 #[cfg(test)]
5193 pub(super) fn retagging(&self, n: usize) {
5194 let work = &self.components.retag_work;
5195 work.set(work.get() + n);
5196 }
5197
5198 #[cfg(not(test))]
5199 #[inline(always)]
5200 pub(super) fn retagging(&self, _n: usize) {}
5201
5202 fn reconcile_slot(
5208 &mut self,
5209 prev: Option<Expanded>,
5210 node: NodeId,
5211 mut el: ElNode,
5212 host: NodeId,
5213 inst: &mut Instance,
5214 ) -> Expanded {
5215 let bound = super::views::Bound::take(&mut el);
5216 let applied = inst.bound.remove(&node);
5219 let (old_attrs, old_style, old_classes) = match (prev, applied) {
5220 (Some(_), Some(a)) => (a.attrs, a.style, a.classes),
5221 (Some(p), None) => (p.attrs, p.style, p.classes),
5222 (None, _) => (Attrs::default(), StyleRefinement::default(), (None, None)),
5223 };
5224 let bound = bound.map(|bound| self.bind_parts(host, node, bound, &mut el));
5225 self.apply_slot_attrs(node, host, &el.attrs, &old_attrs, Some(&mut *inst));
5226 let classes = self.apply_el_styles(
5227 node,
5228 &el.style,
5229 &old_style,
5230 old_classes,
5231 el.attrs.class.as_ref(),
5232 None,
5233 );
5234 if bound.is_some() {
5235 Self::keep_bound(inst, node, &el.attrs, &el.style, classes.clone(), None);
5236 }
5237 let events = self.apply_slot_handlers(node, host, &el, inst);
5240 Expanded {
5241 id: node,
5242 tag: Tag::View,
5243 key: None,
5244 text: None,
5245 attrs: el.attrs,
5246 style: el.style,
5247 classes,
5248 events,
5249 list: None,
5250 part: Part::Slot,
5251 children: Vec::new(),
5252 }
5253 }
5254
5255 fn reconcile_wrapper(
5263 &mut self,
5264 mut prev: Option<Expanded>,
5265 mut el: ElNode,
5266 host: NodeId,
5267 inst: &mut Instance,
5268 ) -> Expanded {
5269 let (id, old_children) = match &mut prev {
5270 Some(p) => (p.id, std::mem::take(&mut p.children)),
5271 None => {
5272 let id = self.components.alloc();
5273 let _ = self.apply_op(Op::Create { id, tag: el.tag });
5274 self.components.owners.insert(id, host);
5275 (id, Vec::new())
5276 }
5277 };
5278 self.components.fill_holders.insert(id);
5279 let children = std::mem::take(&mut el.children);
5281 let children = self.reconcile_children(id, old_children, children, host, inst);
5282 let (tag, key) = (el.tag, el.key.clone());
5283 let mut e = self.reconcile_slot(prev, id, el, host, inst);
5284 if let Ok(k) = self.key(id) {
5285 self.lay_out_through(k);
5286 }
5287 e.tag = tag;
5288 e.key = key;
5289 e.part = Part::Node;
5290 e.children = children;
5291 e
5292 }
5293
5294 pub(super) fn reconcile_node(
5295 &mut self,
5296 prev: Option<Expanded>,
5297 mut el: ElNode,
5298 part: Part,
5299 host: NodeId,
5300 inst: &mut Instance,
5301 ) -> Expanded {
5302 if !el.children.is_empty()
5305 && let Some(content) = el.bound_text.take()
5306 {
5307 let mut first = ElNode::new(Tag::Text);
5308 first.text = Some(SharedString::default());
5309 first.bound_text = Some(content);
5310 el.text = None;
5311 el.children.insert(0, first);
5312 }
5313 let nested_style = (matches!(el.kind, ElKind::Component(_)) && el.style.is_bound())
5318 .then(|| el.style.clone());
5319 let nested_attrs = (matches!(el.kind, ElKind::Component(_)) && !el.bound_attrs.is_empty())
5321 .then(|| (el.attrs.clone(), el.bound_attrs.clone()));
5322 let bound = if matches!(el.kind, ElKind::Component(_)) {
5323 el.resolve_once();
5324 None
5325 } else {
5326 super::views::Bound::take(&mut el)
5327 };
5328 if matches!(el.kind, ElKind::Raw) {
5329 return self.reconcile_raw(prev, el, host);
5330 }
5331 if !el.children.is_empty()
5334 && let Some(content) = el.text.take()
5335 && !content.is_empty()
5336 {
5337 let mut raw = ElNode::new(Tag::Text);
5338 raw.text = Some(content);
5339 raw.kind = ElKind::Raw;
5340 el.children.insert(0, raw);
5341 }
5342 let old_list = prev
5343 .as_ref()
5344 .and_then(|p| p.list.as_deref().copied())
5345 .unwrap_or_default();
5346 let kept = prev.is_some();
5347 let (id, old_attrs, old_style, old_classes, old_events, old_children, old_text) = match prev
5348 {
5349 Some(mut p) => {
5350 if let Some(applied) = inst.bound.remove(&p.id) {
5354 p.attrs = applied.attrs;
5355 p.style = applied.style;
5356 p.classes = applied.classes;
5357 p.text = applied.text;
5358 }
5359 (
5360 p.id, p.attrs, p.style, p.classes, p.events, p.children, p.text,
5361 )
5362 }
5363 None => {
5364 let id = self.components.alloc();
5365 let _ = self.apply_op(Op::Create { id, tag: el.tag });
5366 self.components.owners.insert(id, host);
5367 if let ElKind::Component(c) = &el.kind {
5368 self.create_instance_for(id, c);
5369 }
5370 (
5371 id,
5372 Attrs::default(),
5373 StyleRefinement::default(),
5374 (None, None),
5375 EventMask::default(),
5376 Vec::new(),
5377 None,
5378 )
5379 }
5380 };
5381 let old_list = if matches!(el.kind, ElKind::VirtualList(_)) {
5383 self.components.list_layouts.remove(&id).unwrap_or(old_list)
5384 } else {
5385 old_list
5386 };
5387 let bound = bound.map(|bound| self.bind_parts(host, id, bound, &mut el));
5388 let (component, virtual_list) = match std::mem::replace(&mut el.kind, ElKind::Plain) {
5389 ElKind::Component(c) => (Some(c), None),
5390 ElKind::VirtualList(list) => (None, Some(list)),
5391 _ => (None, None),
5392 };
5393 if let Some(c) = component {
5394 self.set_element_props(id, c.props.as_ref());
5397 if self.is_host(id) {
5398 if let Some(style) = nested_style {
5399 el.style = self.bind_nested_style(id, style);
5400 }
5401 let user = (!el.style.is_empty()).then(|| self.components.lowered(&el.style));
5402 self.set_user(id, user);
5403 }
5404 if kept {
5406 inst.event_handlers.retain(|(n, _)| *n != id);
5407 }
5408 if self.is_host(id) {
5410 self.set_given_handlers(id, std::mem::take(&mut el.handlers));
5411 }
5412 inst.event_handlers
5413 .extend(c.on_event.into_iter().map(|listener| (id, listener)));
5414 let element_ref = el.attrs.take_element_ref();
5416 if old_attrs.element_ref() != element_ref.as_ref()
5417 && let Some(r) = old_attrs.element_ref()
5418 {
5419 r.detach(id);
5420 }
5421 if let Some(r) = &element_ref {
5422 r.attach(id);
5423 }
5424 let mut old_children = old_children;
5427 let tooltip =
5428 self.reconcile_given_tooltip(id, &mut old_children, &mut el.children, host, inst);
5429 let tooltip_prop = tooltip
5430 .as_ref()
5431 .and_then(|t| t.children.first())
5432 .filter(|e| e.id != 0)
5433 .map(|e| Prop::Tooltip(crate::overlay::TooltipContent::Node(e.id)));
5434 if self.is_host(id) {
5436 let given = match nested_attrs {
5437 Some((mut base, parts)) => {
5438 if let Some(prop) = &tooltip_prop {
5439 crate::element::host::set_in(&mut base.props, prop.clone());
5440 }
5441 self.bind_nested_attrs(id, base, parts)
5442 }
5443 None => {
5444 let mut given = std::mem::take(&mut el.attrs);
5445 if let Some(prop) = tooltip_prop {
5446 crate::element::host::set_in(&mut given.props, prop);
5447 }
5448 given
5449 }
5450 };
5451 self.set_given(id, given);
5452 }
5453 let mut content = std::mem::take(&mut el.children);
5459 let is_slot = |c: &ElNode| {
5460 matches!(c.kind, ElKind::Fill(_))
5461 || c.attrs
5462 .props
5463 .iter()
5464 .any(|p| matches!(p, Prop::ComponentSlot(_)))
5465 };
5466 let lazy = self
5467 .components
5468 .instances
5469 .get(&id)
5470 .is_some_and(|i| i.spec.as_ref().is_some_and(|s| s.lazy_children));
5471 if lazy {
5472 let (slots, kids): (Vec<ElNode>, Vec<ElNode>) =
5475 content.into_iter().partition(|c| is_slot(c));
5476 content = slots;
5477 if !kids.is_empty() {
5478 let wanted = self.children_wanted_signal(id);
5479 let shown = crate::element::when(wanted, move || {
5480 kids.iter()
5481 .cloned()
5482 .map(crate::element::AnyElement)
5483 .collect::<Vec<_>>()
5484 });
5485 content.push(shown.into_element().0);
5486 }
5487 }
5488 let mut children = self.reconcile_children(id, old_children, content, host, inst);
5489 children.extend(tooltip);
5490 let mut kept_attrs = Attrs::default();
5491 kept_attrs.set_element_ref(element_ref);
5492 return Expanded {
5493 id,
5494 tag: el.tag,
5495 key: el.key,
5496 text: None,
5497 attrs: kept_attrs,
5498 style: el.style,
5499 classes: (None, None),
5500 events: EventMask::default(),
5501 list: None,
5502 part,
5503 children,
5504 };
5505 }
5506 if !self.apply_target_attrs(id, &el.attrs, &old_attrs, None) {
5507 self.apply_attrs(id, &el.attrs, &old_attrs);
5508 }
5509 let classes = self.apply_el_styles(
5510 id,
5511 &el.style,
5512 &old_style,
5513 old_classes,
5514 el.attrs.class.as_ref(),
5515 None,
5516 );
5517 let text = self.reconcile_text(id, host, el.text.take(), old_text);
5518 if bound.is_some() {
5519 Self::keep_bound(
5520 inst,
5521 id,
5522 &el.attrs,
5523 &el.style,
5524 classes.clone(),
5525 text.clone(),
5526 );
5527 }
5528 let events = self.apply_handlers(host, id, &el, old_events, EventMask::default(), inst);
5529 let new_children = std::mem::take(&mut el.children);
5530 let children = self.reconcile_children(id, old_children, new_children, host, inst);
5531 let list = match virtual_list {
5532 Some(list) => {
5533 let config = list.config;
5534 self.update_virtual_list(id, host, *list, &old_list);
5535 Some(Box::new(config))
5536 }
5537 None => None,
5538 };
5539 Expanded {
5540 id,
5541 tag: el.tag,
5542 key: el.key,
5543 text,
5544 attrs: el.attrs,
5545 style: el.style,
5546 classes,
5547 events,
5548 list,
5549 part,
5550 children,
5551 }
5552 }
5553
5554 fn reconcile_given_tooltip(
5560 &mut self,
5561 nested: NodeId,
5562 old: &mut Vec<Expanded>,
5563 content: &mut Vec<ElNode>,
5564 host: NodeId,
5565 inst: &mut Instance,
5566 ) -> Option<Expanded> {
5567 let prev = old
5568 .iter()
5569 .position(|e| e.part == Part::Tooltip)
5570 .map(|at| old.remove(at));
5571 let Some(at) = content
5572 .iter()
5573 .position(|c| matches!(c.kind, ElKind::Tooltip))
5574 else {
5575 if let Some(prev) = prev {
5576 self.release_expanded(prev);
5577 }
5578 return None;
5579 };
5580 let given = content.remove(at);
5581 let new = given
5582 .children
5583 .into_iter()
5584 .map(|c| NewChild::Made(None, c))
5585 .collect();
5586 let old = prev.map(|p| p.children).unwrap_or_default();
5587 let (children, _) = self.match_children(nested, old, new, host, inst);
5588 let mut tooltip = Expanded::js(0, Part::Tooltip);
5589 tooltip.children = children;
5590 Some(tooltip)
5591 }
5592
5593 fn reconcile_raw(&mut self, prev: Option<Expanded>, el: ElNode, host: NodeId) -> Expanded {
5596 let content = el.text.unwrap_or_else(|| "".into());
5597 let id = match prev {
5598 Some(p) => {
5599 if p.text.as_ref().is_none_or(|(old, _)| *old != content) {
5600 let _ = self.apply_op(Op::SetText {
5601 id: p.id,
5602 text: content.as_str().to_owned(),
5603 });
5604 }
5605 p.id
5606 }
5607 None => {
5608 let id = self.components.alloc();
5609 let _ = self.apply_op(Op::CreateText {
5610 id,
5611 text: content.as_str().to_owned(),
5612 });
5613 self.components.owners.insert(id, host);
5614 id
5615 }
5616 };
5617 Expanded {
5618 id,
5619 tag: Tag::Text,
5620 key: None,
5621 text: Some((content, id)),
5622 attrs: Attrs::default(),
5623 style: StyleRefinement::default(),
5624 classes: (None, None),
5625 events: EventMask::default(),
5626 list: None,
5627 part: Part::Raw,
5628 children: Vec::new(),
5629 }
5630 }
5631
5632 fn update_virtual_list(
5642 &mut self,
5643 id: NodeId,
5644 owner: NodeId,
5645 list: VirtualListEl,
5646 old: &ListConfig,
5647 ) {
5648 let mut props = std::mem::take(&mut self.components.props);
5650 list.config.changes(old, &mut props);
5651 for prop in props.drain(..) {
5652 let _ = self.apply_op(Op::SetProp { id, prop });
5653 }
5654 self.components.props = props;
5655 let before = self
5656 .components
5657 .virtual_lists
5658 .get(&id)
5659 .map(|state| (state.count, state.keys.clone()));
5660 let items = self.components.slot_names.contains_key(&id);
5662 let state = self
5663 .components
5664 .virtual_lists
5665 .entry(id)
5666 .or_insert_with(|| VirtualListState {
5667 owner,
5668 scope: Rc::default(),
5669 row: list.row.clone(),
5670 count: 0,
5671 keys: None,
5672 separator: None,
5673 cells: Vec::new(),
5674 rows: CellRows::default(),
5675 moves: None,
5676 items,
5677 place: None,
5678 contents: Vec::new(),
5679 min_view: None,
5680 reported: None,
5681 latest: None,
5682 report: None,
5683 });
5684 if state.scope.get() != list.scope {
5687 state.scope.set(list.scope);
5688 if let Some(scope) = list.scope {
5689 let rows = Rc::downgrade(&state.rows);
5690 let current = Rc::downgrade(&state.scope);
5691 scope.run(|| {
5692 crate::element::cleanup(move || {
5693 if current.upgrade().is_some_and(|c| c.get() == Some(scope)) {
5696 dispose_rows(&rows);
5697 }
5698 })
5699 });
5700 }
5701 }
5702 let cells = state.rows.clone();
5703 let bound = matches!(list.count, Reactive::Bound(_)) || list.keys.is_some();
5704 let (count, keys) = (list.count, list.keys);
5705 let rows = move || (count.get(), keys.as_ref().map(|k| k()));
5706 let mut moves = None;
5707 let (count, keys) = if bound {
5708 let count_signal = self.list_count(id, 0);
5709 let patches = self.components.patches.clone();
5710 let first: Rc<RefCell<Option<Rows>>> = Rc::default();
5711 let slot = first.clone();
5712 let last: RefCell<Option<Rc<[u64]>>> = RefCell::new(None);
5713 let made = std::cell::Cell::new(false);
5714 let memo = crate::element::computed(move || {
5715 let (count, keys) = rows();
5716 let diff = match (&*last.borrow(), &keys) {
5717 (Some(old), Some(new)) => ListDiff::new(old, new),
5718 _ => None,
5719 };
5720 last.replace(keys.clone());
5721 if made.replace(true) {
5722 move_rows(&cells, diff.as_ref(), count);
5723 count_signal.set(count as usize);
5724 patches.borrow_mut().push(super::views::Patch::Rows {
5725 list: id,
5726 binding: crate::element::Owner::current(),
5727 count,
5728 keys,
5729 });
5730 } else {
5731 count_signal.set(count as usize);
5732 *slot.borrow_mut() = Some((count, keys));
5733 }
5734 });
5735 moves = Some(memo.node());
5736 first.take().expect("a memo runs when it is made")
5737 } else {
5738 let (count, keys) = crate::element::untracked(rows);
5739 {
5741 self.list_count(id, count as usize).set(count as usize);
5742 }
5743 (count, keys)
5744 };
5745 self.send_list_rows(id, before.as_ref(), count, keys.as_ref());
5746 if before.is_none()
5747 && let Some(command) = list.initial_scroll
5748 {
5749 let _ = self.apply_op(Op::Command { id, command });
5750 }
5751 let state = self.components.virtual_lists.get_mut(&id).expect("list");
5752 state.row = list.row;
5753 state.count = count;
5754 state.keys = keys;
5755 state.moves = moves;
5756 state.separator = list.separator;
5757 state.min_view = list.min_view_time;
5758 self.sync_virtual_cells(id, true);
5759 }
5760
5761 fn send_list_rows(
5764 &mut self,
5765 id: NodeId,
5766 before: Option<&Rows>,
5767 count: u32,
5768 keys: Option<&Rc<[u64]>>,
5769 ) {
5770 if let (Some((_, Some(old))), Some(new)) = (before, keys)
5771 && let Some(diff) = ListDiff::new(old, new)
5772 {
5773 let _ = self.apply_op(Op::SetProp {
5774 id,
5775 prop: Prop::ListDiff(Rc::new(diff)),
5776 });
5777 }
5778 if before.map(|(count, _)| *count) != Some(count) {
5779 let _ = self.apply_op(Op::SetProp {
5780 id,
5781 prop: Prop::Count(count),
5782 });
5783 }
5784 }
5785
5786 pub(super) fn set_list_rows(&mut self, id: NodeId, count: u32, keys: Option<Rc<[u64]>>) {
5791 let Some(state) = self.components.virtual_lists.get(&id) else {
5792 return;
5793 };
5794 let before = (state.count, state.keys.clone());
5795 self.send_list_rows(id, Some(&before), count, keys.as_ref());
5796 let state = self.components.virtual_lists.get_mut(&id).expect("list");
5797 state.count = count;
5798 state.keys = keys;
5799 self.sync_virtual_cells(id, false);
5800 }
5801
5802 fn sync_virtual_cells(&mut self, id: NodeId, rebuild: bool) {
5803 let key = self.key(id).expect("virtual list node");
5804 let slots = &self.nodes[key as usize].list.as_ref().expect("list").slots;
5805 let state = &self.components.virtual_lists[&id];
5806 for (slot, (&cell, &content)) in state.cells.iter().zip(&state.contents).enumerate() {
5807 for part in [cell, content].into_iter().filter(|&part| part != 0) {
5808 let Some(inst) = self.components.instances.get_mut(&part) else {
5809 continue;
5810 };
5811 let remake = rebuild || !inst.cell_owner.is_some_and(|o| o.is_live());
5812 if let Inner::VirtualRow { index, .. } | Inner::Row { index, .. } = &mut inst.inner
5813 {
5814 if remake {
5815 *index = slots[slot].requested.map_or(usize::MAX, |i| i as usize);
5817 } else if let Some(position) = inst.row_index {
5818 *index = position.get_untracked();
5819 }
5820 }
5821 if remake && !inst.dirty {
5822 inst.dirty = true;
5823 self.components.dirty.push(part);
5824 }
5825 }
5826 }
5827 }
5828
5829 fn list_count(&mut self, list: NodeId, count: usize) -> crate::element::Signal<usize> {
5832 if let Some(&(_, signal)) = self.components.list_counts.get(&list) {
5833 return signal;
5834 }
5835 let made = crate::element::Owner::detached()
5836 .run(|| crate::element::create_root(|| crate::element::signal(count)));
5837 self.components.list_counts.insert(list, made);
5838 made.1
5839 }
5840
5841 fn forget_list_count(&mut self, list: NodeId) {
5843 if let Some((owner, _)) = self.components.list_counts.remove(&list) {
5844 owner.dispose();
5845 }
5846 self.components.list_layouts.remove(&list);
5847 }
5848
5849 pub(super) fn bind_virtual_lists(&mut self) -> bool {
5852 if self.components.virtual_lists.is_empty() {
5853 return false;
5854 }
5855 let _entered = self.components.runtime.enter();
5856 let mut binds = std::mem::take(&mut self.list_binds);
5857 let mut bound = false;
5858 binds.retain(|bind| {
5859 if !self.components.virtual_lists.contains_key(&bind.list) {
5860 return true;
5861 }
5862 for &(slot, index) in &bind.binds {
5863 self.bind_virtual_cell(bind.list, slot as usize, index as usize);
5864 }
5865 bound = true;
5866 false
5867 });
5868 self.list_binds = binds;
5869 bound
5870 }
5871
5872 fn bind_virtual_cell(&mut self, list: NodeId, slot: usize, index: usize) {
5873 let state = &self.components.virtual_lists[&list];
5874 let owner = state.owner;
5875 let cell = match state.cells.get(slot).copied().filter(|&c| c != 0) {
5876 Some(cell) => {
5877 let content = state.contents.get(slot).copied().filter(|&c| c != 0);
5878 for part in [Some(cell), content].into_iter().flatten() {
5879 if let Some(inst) = self.components.instances.get_mut(&part) {
5880 match &mut inst.inner {
5881 Inner::VirtualRow { index: current, .. }
5882 | Inner::Row { index: current, .. } => *current = index,
5883 _ => {}
5884 }
5885 if let Some(row) = inst.row_index
5888 && inst.cell_owner.is_some_and(|o| o.is_live())
5889 {
5890 row.set(index);
5891 continue;
5892 }
5893 }
5894 self.components.mark(part);
5895 }
5896 cell
5897 }
5898 None => {
5899 let (items, place) = (state.items, state.place.clone());
5900 let cell = self.components.alloc();
5901 let _ = self.apply_op(Op::Create {
5902 id: cell,
5903 tag: Tag::Cell,
5904 });
5905 self.components.owners.insert(cell, owner);
5906 let _ = self.apply_op(Op::SetProp {
5907 id: cell,
5908 prop: Prop::Slot(crate::CellSlot::Item(slot as u32)),
5909 });
5910 let _ = self.apply_op(Op::Insert {
5911 parent: list,
5912 child: cell,
5913 before: None,
5914 });
5915 let row = Inner::VirtualRow { list, index };
5916 let content = if items {
5917 let content = self.components.alloc();
5920 let _ = self.apply_op(Op::Create {
5921 id: content,
5922 tag: Tag::View,
5923 });
5924 self.components.owners.insert(content, owner);
5925 let _ = self.apply_op(Op::Insert {
5926 parent: cell,
5927 child: content,
5928 before: None,
5929 });
5930 let instance = Instance::new(row, None, Vec::new(), None);
5931 self.components
5932 .instances
5933 .insert(content, Box::new(instance));
5934 self.components.mark(content);
5935 let place = place.unwrap_or_else(|| Rc::new(|row, _| row.into_element()));
5936 let wrapper =
5938 Instance::new(Inner::Row { place, index }, None, vec![content], None);
5939 self.components.instances.insert(cell, Box::new(wrapper));
5940 content
5941 } else {
5942 let instance = Instance::new(row, None, Vec::new(), None);
5943 self.components.instances.insert(cell, Box::new(instance));
5944 0
5945 };
5946 let state = self.components.virtual_lists.get_mut(&list).expect("list");
5947 if state.cells.len() <= slot {
5948 state.cells.resize(slot + 1, 0);
5949 state.contents.resize(slot + 1, 0);
5950 }
5951 state.cells[slot] = cell;
5952 state.contents[slot] = content;
5953 self.components.mark(cell);
5954 cell
5955 }
5956 };
5957 let _ = self.apply_op(Op::SetProp {
5958 id: cell,
5959 prop: Prop::CellIndex(index as u32),
5960 });
5961 }
5962
5963 fn viewable_changed(&mut self, list: NodeId, payload: &EventPayload) {
5967 let executor = self.components.executor.clone();
5968 let Some(state) = self.components.virtual_lists.get_mut(&list) else {
5969 return;
5970 };
5971 state.latest = virtual_list::viewable_range(payload, "first", "last");
5972 match state.min_view {
5973 Some(delay) => {
5974 state.report = Some(crate::element::task::act_after(
5975 &executor,
5976 state.owner,
5977 delay,
5978 Action::ReportViewable(list),
5979 ));
5980 }
5981 None => self.report_viewable(list),
5982 }
5983 }
5984
5985 fn report_viewable(&mut self, list: NodeId) {
5988 let Some(state) = self.components.virtual_lists.get_mut(&list) else {
5989 return;
5990 };
5991 state.report = None;
5992 if state.latest == state.reported {
5993 return;
5994 }
5995 let payload = virtual_list::viewable_payload(state.latest, state.reported);
5996 state.reported = state.latest;
5997 let owner = state.owner;
5998 self.handle(owner, list, EventKind::ViewableItemsChange, &payload);
5999 }
6000
6001 fn release_id(&mut self, id: NodeId) {
6002 self.components.release_generation = self.components.release_generation.wrapping_add(1);
6003 if let Some(host) = self.components.owners.remove(&id) {
6004 self.components.released_hosts.insert(host);
6008 }
6009 self.forget_node_extras(id);
6010 if self.is_alias(id) {
6012 self.unalias(id);
6013 return;
6014 }
6015 let holder = if self.components.fill_holders.is_empty() {
6017 None
6018 } else {
6019 self.key(id)
6020 .ok()
6021 .map(|k| self.nodes[k as usize].parent)
6022 .filter(|&p| p != NO_KEY)
6023 .map(|p| self.nodes[p as usize].id)
6024 .filter(|p| self.components.fill_holders.contains(p))
6025 };
6026 let _ = self.apply_op(Op::Release { id });
6027 if let Some(holder) = holder {
6028 self.retarget_slot(holder, None);
6029 }
6030 }
6031
6032 pub(super) fn release_expanded(&mut self, e: Expanded) {
6035 self.components.release_generation = self.components.release_generation.wrapping_add(1);
6038 match e.part {
6039 Part::Slot => {
6040 self.drop_slot_target(e.id);
6041 self.detach_id(e.id);
6042 return;
6043 }
6044 Part::Children | Part::Filled(_) => return,
6047 Part::Fill(_) | Part::Tooltip => {
6049 for c in e.children {
6050 self.release_expanded(c);
6051 }
6052 return;
6053 }
6054 Part::JsChild => {
6056 self.detach_id(e.id);
6057 return;
6058 }
6059 Part::Raw => {
6060 self.release_id(e.id);
6061 return;
6062 }
6063 Part::Component(_) => {
6066 let content: Vec<NodeId> = e.children.iter().flat_map(|c| self.placed(c)).collect();
6067 self.release_component(e.id, &content);
6068 }
6069 Part::Region(region) => {
6071 self.release_region(region);
6072 return;
6073 }
6074 Part::VirtualList => self.release_virtual_list(e.id),
6075 Part::Node => {
6077 if !self.components.fill_holders.is_empty()
6078 && self.components.fill_holders.remove(&e.id)
6079 {
6080 self.drop_slot_target(e.id);
6081 }
6082 }
6083 }
6084 if let Some(r) = e.attrs.rare.as_ref().and_then(|r| r.element_ref.as_ref()) {
6085 r.detach(e.id);
6086 }
6087 for c in e.children {
6088 self.release_expanded(c);
6089 }
6090 if let Some((_, raw)) = e.text {
6091 self.release_id(raw);
6092 }
6093 self.release_id(e.id);
6094 }
6095
6096 pub(super) fn release_instance(&mut self, host: NodeId) {
6099 self.release_component(host, &[]);
6100 }
6101
6102 fn release_component(&mut self, host: NodeId, content: &[NodeId]) {
6107 let Some(mut inst) = self.components.instances.remove(&host) else {
6108 return;
6109 };
6110 self.target_released(host);
6112 if self
6113 .components
6114 .parked_methods
6115 .iter()
6116 .any(|(h, ..)| *h == host)
6117 {
6118 let (gone, kept) = std::mem::take(&mut self.components.parked_methods)
6119 .into_iter()
6120 .partition(|(h, ..)| *h == host);
6121 self.components.parked_methods = kept;
6122 for (_, call, method) in gone {
6123 drop_caught(method);
6124 self.settle(
6125 call,
6126 Err(format!("node {host} hosts no Rust component").into()),
6127 );
6128 }
6129 }
6130 self.forget_node_extras(host);
6132 if let Inner::Component(inner) = &mut inst.inner {
6133 if let Err(message) = caught(|| inner.cleanup()) {
6134 log::error!(target: "js", "{} failed in its cleanup: {message}", inner.name());
6135 }
6136 self.apply_actions();
6137 }
6138 self.release_regions(host);
6139 self.components.runtime.forget_host(host);
6140 if let Some(owner) = inst.cell_owner.take() {
6141 owner.dispose();
6142 }
6143 for &child in &inst.js_children {
6144 if !content.contains(&child) {
6145 self.detach_id(child);
6146 }
6147 }
6148 for (_, node) in inst.slots {
6149 self.drop_slot_target(node);
6150 self.components.slot_hosts.remove(&node);
6151 if !content.contains(&node) {
6152 self.detach_id(node);
6153 }
6154 }
6155 if let Some(root) = inst.root {
6156 if matches!(root.part, Part::Component(_)) {
6158 self.release_expanded(root);
6159 return;
6160 }
6161 let node = self.native_id(host);
6162 if let Some(r) = root
6163 .attrs
6164 .rare
6165 .as_ref()
6166 .and_then(|r| r.element_ref.as_ref())
6167 {
6168 r.detach(node);
6169 }
6170 if root.part == Part::VirtualList {
6171 self.release_virtual_list(node);
6172 }
6173 if let Some((_, raw)) = root.text {
6174 self.release_id(raw);
6175 }
6176 for c in root.children {
6177 self.release_expanded(c);
6178 }
6179 }
6180 }
6181
6182 fn release_virtual_list(&mut self, id: NodeId) {
6185 if let Some(state) = self.components.virtual_lists.remove(&id) {
6186 let parts = state.contents.into_iter().chain(state.cells);
6187 for part in parts.filter(|&c| c != 0) {
6188 self.release_instance(part);
6189 self.release_id(part);
6190 }
6191 }
6192 if self.components.slot_names.remove(&id).is_some() {
6194 self.unslot(id);
6195 }
6196 self.components.lists.remove(&id);
6197 self.forget_list_count(id);
6198 }
6199
6200 pub fn component_event(&mut self, id: NodeId, kind: EventKind, payload: &EventPayload) -> bool {
6203 let _entered = self.components.runtime.enter();
6204 let _geometry = (kind == EventKind::TextLayout)
6206 .then(|| self.geometries.remove(&id))
6207 .flatten()
6208 .map(crate::text::GeometryScope::enter);
6209 let handled = self.dispatch_event(id, kind, payload);
6210 self.flush_component_emits();
6211 handled
6212 }
6213
6214 #[doc(hidden)]
6218 pub fn listens(&self, id: NodeId, event: EventKind) -> bool {
6219 self.key(id)
6220 .is_ok_and(|key| self.nodes[key as usize].mounted_events().contains(event))
6221 }
6222
6223 #[doc(hidden)]
6229 pub fn key_interest(&self, id: NodeId) -> bool {
6230 let Ok(mut key) = self.key(id).map(|key| self.key_start(key)) else {
6231 return false;
6232 };
6233 let window = self.key_window(key);
6234 loop {
6235 let node = &self.nodes[key as usize];
6236 let disabled = node
6237 .props
6238 .as_ref()
6239 .is_some_and(|p| p.accessibility.state.disabled);
6240 if !disabled {
6241 let events = node.mounted_events();
6242 if events.contains(EventKind::KeyDown) || events.contains(EventKind::KeyUp) {
6243 return true;
6244 }
6245 if node
6246 .props
6247 .as_ref()
6248 .is_some_and(|p| !p.key_capture.is_none())
6249 {
6250 return true;
6251 }
6252 }
6253 if node.id == window || node.parent == NO_KEY {
6254 return false;
6255 }
6256 key = node.parent;
6257 }
6258 }
6259
6260 #[doc(hidden)]
6267 pub fn key_path(&self, id: NodeId, out: &mut Vec<NodeId>) {
6268 out.clear();
6269 let Ok(mut key) = self.key(id).map(|key| self.key_start(key)) else {
6270 return;
6271 };
6272 let window = self.key_window(key);
6273 loop {
6274 let node = &self.nodes[key as usize];
6275 let disabled = node
6276 .props
6277 .as_ref()
6278 .is_some_and(|p| p.accessibility.state.disabled);
6279 if !disabled {
6280 out.push(node.id);
6281 }
6282 if node.id == window || node.parent == NO_KEY {
6283 return;
6284 }
6285 key = node.parent;
6286 }
6287 }
6288
6289 #[doc(hidden)]
6298 pub fn key_captured(&self, id: NodeId, keystroke: Option<&crate::keymap::Keystroke>) -> bool {
6299 let Ok(mut key) = self.key(id).map(|key| self.key_start(key)) else {
6300 return false;
6301 };
6302 if self.nodes[key as usize].kind == Kind::Input {
6305 return false;
6306 }
6307 let window = self.key_window(key);
6308 loop {
6309 let node = &self.nodes[key as usize];
6310 let disabled = node
6311 .props
6312 .as_ref()
6313 .is_some_and(|p| p.accessibility.state.disabled);
6314 if !disabled
6315 && node
6316 .props
6317 .as_ref()
6318 .is_some_and(|p| p.key_capture.captures_key(keystroke))
6319 {
6320 return true;
6321 }
6322 if node.id == window || node.parent == NO_KEY {
6323 return false;
6324 }
6325 key = node.parent;
6326 }
6327 }
6328
6329 pub(super) fn key_start(&self, key: Key) -> Key {
6337 let node = &self.nodes[key as usize];
6338 if node.id != crate::ROOT_ID
6339 && (node.kind != Kind::Modal || self.key_window(key) != node.id)
6340 {
6341 return key;
6342 }
6343 node.children
6344 .iter()
6345 .copied()
6346 .find(|&child| !matches!(self.nodes[child as usize].kind, Kind::Overlay | Kind::Modal))
6347 .unwrap_or(key)
6348 }
6349
6350 pub(super) fn key_content_changed(&mut self, parent: Key) {
6352 let node = &self.nodes[parent as usize];
6353 if node.id == crate::ROOT_ID
6354 || (node.kind == Kind::Modal && self.key_window(parent) == node.id)
6355 {
6356 self.key_ancestry_dirty = true;
6357 }
6358 }
6359
6360 pub(super) fn key_window(&self, key: Key) -> NodeId {
6362 let node = &self.nodes[key as usize];
6363 if node.kind == Kind::Modal && self.window_ids.values().any(|(root, _)| *root == node.id) {
6364 node.id
6365 } else {
6366 self.window_of(key)
6367 }
6368 }
6369
6370 fn flush_component_emits(&mut self) {
6371 loop {
6374 let emits = self.components.runtime.take_emits();
6375 if emits.is_empty() {
6376 break;
6377 }
6378 for (host, event) in emits {
6379 self.route_emit(host, event);
6380 }
6381 }
6382 }
6383
6384 #[doc(hidden)]
6388 pub fn component_layout(
6389 &mut self,
6390 host: NodeId,
6391 id: NodeId,
6392 listener: &Listener<EventPayload>,
6393 frame: crate::Bounds<Points>,
6394 ) {
6395 let _entered = self.components.runtime.enter();
6396 let installed = self.components.instances.get(&host).is_some_and(|inst| {
6397 inst.handlers
6398 .of(id)
6399 .iter()
6400 .any(|(kind, current)| *kind == EventKind::Layout && current.ptr_eq(listener))
6401 });
6402 if installed {
6403 self.run_listener(host, listener, &EventPayload::Layout(frame));
6404 self.flush_component_emits();
6405 }
6406 }
6407
6408 fn dispatch_event(&mut self, id: NodeId, kind: EventKind, payload: &EventPayload) -> bool {
6409 self.span_state(id, kind);
6412 if self.drop_cancelled_press(id, kind, payload) {
6414 return true;
6415 }
6416 if kind == EventKind::Touch && id == ROOT_ID {
6419 if let EventPayload::Touch(touch) = payload {
6420 self.overlay_touches(touch);
6421 self.touches(payload, touch);
6422 }
6423 return false;
6424 }
6425 if matches!(kind, EventKind::MouseEnter | EventKind::MouseLeave) {
6427 let at = match payload {
6428 EventPayload::Mouse(mouse) => Some(mouse.page_position),
6429 _ => None,
6430 };
6431 self.overlay_hover(id, kind, at);
6432 }
6433 let _target = matches!(kind, EventKind::DownloadPending | EventKind::Download)
6437 .then(|| crate::element::download_target(id, Rc::downgrade(&self.components.executor)));
6438 if self.platform_event(id, kind, payload) {
6439 return true;
6440 }
6441 if self.is_host(id) {
6442 let base = self.base_of(id);
6445 if let Some(slot) = self.adopted_host(base) {
6446 self.handle(slot, base, kind, payload);
6447 }
6448 let own = self.handle(base, base, kind, payload);
6449 if own && kind == EventKind::ContextMenu {
6452 return true;
6453 }
6454 let given = self.handle_given(base, kind, payload);
6455 return (own || given) && !self.js_listens(base, kind);
6457 }
6458 if kind == EventKind::ViewableItemsChange && self.components.virtual_lists.contains_key(&id)
6460 {
6461 self.viewable_changed(id, payload);
6462 return true;
6463 }
6464 let slot_of = self
6469 .components
6470 .slot_hosts
6471 .get(&id)
6472 .copied()
6473 .or_else(|| self.adopted_host(id));
6474 let owner = self.components.owners.get(&id).copied();
6475 if let Some(host) = slot_of {
6476 self.handle(host, id, kind, payload);
6477 }
6478 if let Some(host) = owner
6479 && Some(host) != slot_of
6480 {
6481 self.handle(host, id, kind, payload);
6482 }
6483 (slot_of.is_some() || owner.is_some()) && id % 2 == 1
6486 }
6487
6488 pub(super) fn host_of(&self, id: NodeId) -> Option<NodeId> {
6492 if self.is_host(id) {
6493 Some(self.base_of(id))
6494 } else {
6495 self.components.owners.get(&id).copied()
6496 }
6497 }
6498
6499 fn handle(
6502 &mut self,
6503 host: NodeId,
6504 id: NodeId,
6505 kind: EventKind,
6506 payload: &EventPayload,
6507 ) -> bool {
6508 let id = self.base_of(id);
6509 let mut handled = false;
6510 let mut from = 0;
6511 while let Some((at, listener)) = self.next_handler(host, id, kind, from) {
6512 from = at + 1;
6513 if !self.run_listener(host, &listener, payload) {
6515 break;
6516 }
6517 handled = true;
6518 }
6519 handled
6520 }
6521
6522 pub(super) fn next_handler(
6529 &self,
6530 host: NodeId,
6531 id: NodeId,
6532 kind: EventKind,
6533 from: usize,
6534 ) -> Option<(usize, Listener<EventPayload>)> {
6535 let id = self.base_of(id);
6536 let inst = self.components.instances.get(&host)?;
6537 let handlers = inst.handlers.of(id);
6538 #[cfg(test)]
6539 self.components
6540 .handler_visits
6541 .set(self.components.handler_visits.get() + handlers.len().saturating_sub(from));
6542 handlers
6543 .iter()
6544 .enumerate()
6545 .skip(from)
6546 .find(|(_, (k, _))| *k == kind)
6547 .map(|(at, (_, l))| (at, l.clone()))
6548 }
6549
6550 pub(super) fn responder_el(&self, host: NodeId, id: NodeId) -> Option<Rc<ResponderEl>> {
6552 let id = self.base_of(id);
6553 self.components
6554 .instances
6555 .get(&host)?
6556 .responders
6557 .iter()
6558 .find(|(n, _)| *n == id)
6559 .map(|(_, r)| r.clone())
6560 }
6561
6562 pub(super) fn run_listener<E: ?Sized + 'static>(
6565 &mut self,
6566 host: NodeId,
6567 listener: &Listener<E>,
6568 event: &E,
6569 ) -> bool {
6570 let Some(owner) = self.state_owner(host) else {
6571 return false;
6572 };
6573 if let Err(message) = caught(|| listener.call(event)) {
6574 self.component_failed(owner, message);
6575 }
6576 self.apply_actions();
6577 true
6578 }
6579
6580 pub(super) fn state_owner(&self, host: NodeId) -> Option<NodeId> {
6583 match &self.components.instances.get(&host)?.inner {
6584 Inner::Component(_) => Some(host),
6585 Inner::VirtualRow { list, .. } => {
6586 self.components.virtual_lists.get(list).map(|s| s.owner)
6587 }
6588 Inner::Row { .. } => self
6589 .list_of(host)
6590 .and_then(|l| self.components.slot_hosts.get(&l))
6591 .copied(),
6592 Inner::Missing => None,
6593 }
6594 }
6595
6596 pub(super) fn component_failed(&mut self, host: NodeId, message: String) {
6599 let component = match self.components.instances.get(&host).map(|i| &i.inner) {
6600 Some(Inner::Component(inner)) => inner.name(),
6601 _ => "a list row",
6602 };
6603 let error = ComponentError { component, message };
6604 let owner = self
6606 .components
6607 .instances
6608 .get(&host)
6609 .and_then(|inst| match &inst.inner {
6610 Inner::Component(inner) => Some(inner.failure_owner()),
6611 _ => inst.cell_owner,
6612 });
6613 let _entered = self.components.runtime.enter();
6614 match owner.and_then(crate::element::reactive::boundary_of) {
6615 Some(boundary) => boundary.set(Some(error)),
6616 None => log::error!(target: "js", "{error}"),
6617 }
6618 }
6619
6620 fn list_of(&self, cell: NodeId) -> Option<NodeId> {
6622 let key = self.key(cell).ok()?;
6623 let parent = self.nodes[key as usize].parent;
6624 (parent != NO_KEY).then(|| self.nodes[parent as usize].id)
6625 }
6626
6627 fn login_item_action(
6632 &mut self,
6633 enabled: Option<bool>,
6634 answer: crate::element::AnswerSlot<Result<bool, crate::desktop::LaunchAtLoginError>>,
6635 ) {
6636 use crate::desktop::{LaunchAtLoginError, LoginItemStatus};
6637 if !self.access.allows_application() {
6641 answer.borrow_mut().deliver(match enabled {
6642 None => Ok(false),
6643 Some(_) => Err(LaunchAtLoginError::Denied),
6644 });
6645 return;
6646 }
6647 let Some(items) = self.login_item.as_mut() else {
6648 answer.borrow_mut().deliver(match enabled {
6649 None => Ok(false),
6650 Some(_) => Err(LaunchAtLoginError::Unavailable),
6651 });
6652 return;
6653 };
6654 let result = items.call(enabled);
6655 crate::element::task::spawn_raw(
6656 &self.components.executor,
6657 crate::ROOT_ID,
6658 Box::pin(async move {
6659 let result = match result.await {
6660 Ok(LoginItemStatus::Unavailable) if enabled.is_some() => {
6663 Err(LaunchAtLoginError::Unavailable)
6664 }
6665 Ok(status) => Ok(status == LoginItemStatus::Enabled),
6666 Err(error) => Err(LaunchAtLoginError::System(error)),
6667 };
6668 answer.borrow_mut().deliver(result);
6669 }),
6670 );
6671 }
6672
6673 fn notification_action(&mut self, action: crate::element::NotificationAction) {
6677 use crate::{
6678 element::NotificationAction,
6679 notifications::{NotificationCommand, NotificationPermission},
6680 };
6681 let allowed = self.access.allows_notifications();
6682 let available = allowed && self.components.environment.notifications;
6683 let command = match action {
6684 NotificationAction::Permission { ask, answer } => {
6685 if !available {
6686 answer
6687 .borrow_mut()
6688 .deliver(NotificationPermission::Unavailable);
6689 return;
6690 }
6691 let state = &mut self.components.notifications;
6692 let id = state.next;
6693 state.next = id.wrapping_add(1);
6694 state.permissions.insert(id, answer);
6695 NotificationCommand::Permission { id, ask }
6696 }
6697 NotificationAction::Show {
6698 notification,
6699 answer,
6700 } => {
6701 if !available {
6702 answer.borrow_mut().deliver(false);
6703 return;
6704 }
6705 let state = &mut self.components.notifications;
6706 let id = state.next;
6707 state.next = id.wrapping_add(1);
6708 state.shows.insert(id, answer);
6709 NotificationCommand::Show { id, notification }
6710 }
6711 NotificationAction::Close(id) => {
6712 if !available {
6713 return;
6714 }
6715 NotificationCommand::Close(id)
6716 }
6717 NotificationAction::CloseAll => {
6718 if !available {
6719 return;
6720 }
6721 NotificationCommand::CloseAll
6722 }
6723 NotificationAction::SetBadge(count) => {
6724 if !allowed {
6725 return;
6726 }
6727 NotificationCommand::SetBadge(count)
6728 }
6729 NotificationAction::NextPress(answer) => {
6730 let state = &mut self.components.notifications;
6731 if let Some(pressed) = state.presses.pop_front() {
6732 answer.borrow_mut().deliver(pressed);
6733 return;
6734 }
6735 state.next_press = Some(answer);
6736 if !available || state.listening {
6737 return;
6738 }
6739 state.listening = true;
6740 NotificationCommand::Listen
6741 }
6742 };
6743 let _ = self.apply_op(Op::Command {
6744 id: crate::ROOT_ID,
6745 command: Command::Notification(command),
6746 });
6747 }
6748
6749 #[doc(hidden)]
6752 pub fn app_url_cell(&self) -> crate::url_scheme::AppUrlCell {
6753 self.components.url_schemes.address.clone()
6754 }
6755
6756 fn url_scheme(
6763 &mut self,
6764 url: String,
6765 page: bool,
6766 quiet: bool,
6767 change: Option<crate::url_scheme::AppUrlChangeReason>,
6768 ) {
6769 let links = &mut self.components.url_schemes;
6770 if !page && change.is_none() && crate::file_type::is_file_url(&url) {
6774 if !links
6775 .links
6776 .schemes()
6777 .iter()
6778 .any(|s| s == crate::file_type::FILE_SCHEME)
6779 {
6780 log::warn!("file dropped: the app declares no file types (nsh.json `fileTypes`)");
6781 return;
6782 }
6783 let Some(path) = crate::file_type::file_path(&url) else {
6784 log::warn!("file dropped: {url} is not a local file");
6785 return;
6786 };
6787 let files = &mut self.components.open_files;
6788 if let Some(answer) = files.next.take() {
6789 answer.borrow_mut().deliver(vec![path]);
6790 return;
6791 }
6792 if files.pending.len() == crate::file_type::MAX_PENDING {
6793 log::warn!(
6794 "file dropped: {} came while nothing listened",
6795 crate::file_type::MAX_PENDING
6796 );
6797 files.pending.pop_front();
6798 }
6799 files.pending.push_back(path);
6800 return;
6801 }
6802 let checked = if page {
6803 crate::url_scheme::check_page_url(&url)
6804 } else {
6805 links.links.check(&url)
6806 };
6807 if let Err(dropped) = checked {
6808 log::warn!("link dropped: {dropped}");
6809 return;
6810 }
6811 let links = &mut self.components.url_schemes;
6812 if !quiet && change.is_none() {
6816 let scheme = url.split_once(':').map_or("", |(scheme, _)| scheme);
6817 links
6818 .next_of_scheme
6819 .retain(|(_, answer)| crate::element::task::awaited(answer));
6820 if let Some(at) = links
6821 .next_of_scheme
6822 .iter()
6823 .position(|(waited, _)| waited.eq_ignore_ascii_case(scheme))
6824 {
6825 let (_, answer) = links.next_of_scheme.remove(at);
6826 answer.borrow_mut().deliver(url);
6827 return;
6828 }
6829 }
6830 links.address.set(url.clone());
6831 if quiet {
6832 return;
6833 }
6834 if let Some(reason) = change {
6835 if !links.hears_changes {
6836 return;
6837 }
6838 let change = crate::url_scheme::AppUrlChange { url, reason };
6839 if let Some(answer) = links.next_change.take() {
6840 answer.borrow_mut().deliver(change);
6841 return;
6842 }
6843 if links.changes.len() == crate::url_scheme::MAX_PENDING {
6844 links.changes.pop_front();
6845 }
6846 links.changes.push_back(change);
6847 return;
6848 }
6849 let executor = &self.components.executor;
6850 links.open(url, |task| executor.has_task(task));
6851 }
6852
6853 pub fn set_url_schemes(&mut self, schemes: impl IntoIterator<Item = impl Into<String>>) {
6858 self.components.url_schemes.links.set_schemes(schemes);
6859 }
6860
6861 pub fn set_app_links(&mut self, links: crate::url_scheme::AppLinks) {
6866 self.components.url_schemes.links = links;
6867 }
6868
6869 fn notification_event(&mut self, payload: &EventPayload) {
6871 use crate::notifications::{NotificationEvent as Field, NotificationPermission};
6872 let EventPayload::Map(entries) = payload else {
6873 return;
6874 };
6875 let state = &mut self.components.notifications;
6876 let id = entries.iter().find_map(|(k, v)| match v {
6877 crate::PayloadValue::Number(n) if *k == Field::ID => Some(*n as u32),
6878 _ => None,
6879 });
6880 for (key, value) in entries {
6881 match (*key, value) {
6882 (Field::PERMISSION, crate::PayloadValue::Str(name)) => {
6883 if let Some(answer) = id.and_then(|id| state.permissions.remove(&id)) {
6884 let permission = NotificationPermission::from_name(name)
6885 .unwrap_or(NotificationPermission::Unavailable);
6886 answer.borrow_mut().deliver(permission);
6887 }
6888 }
6889 (Field::SHOWN, crate::PayloadValue::Bool(shown)) => {
6890 if let Some(answer) = id.and_then(|id| state.shows.remove(&id)) {
6891 answer.borrow_mut().deliver(*shown);
6892 }
6893 }
6894 (Field::PRESSED, crate::PayloadValue::Str(pressed)) => {
6895 match state.next_press.take() {
6896 Some(answer) => answer.borrow_mut().deliver(pressed.clone()),
6897 None => state.presses.push_back(pressed.clone()),
6898 }
6899 }
6900 _ => {}
6901 }
6902 }
6903 }
6904
6905 fn audio_action(&mut self, action: crate::element::AudioAction) {
6909 use crate::{
6910 audio::{AudioCommand, AudioError, AudioEvent},
6911 element::AudioAction,
6912 };
6913 let (command, sink) = match action {
6914 AudioAction::Available(answer) => {
6915 let available = match &self.audio {
6916 Some(backend) => backend.available(),
6917 None => self.components.environment.audio,
6918 };
6919 answer.borrow_mut().deliver(available);
6920 return;
6921 }
6922 AudioAction::Open { mut command, sink } => {
6923 debug_assert!(matches!(
6924 command,
6925 AudioCommand::Load { .. }
6926 | AudioCommand::LoadUrl { .. }
6927 | AudioCommand::Open { .. }
6928 ));
6929 let failed = |error, message: &str| AudioEvent::Failed {
6930 error,
6931 message: message.into(),
6932 };
6933 if !self.access.allows_audio() {
6934 sink.send(failed(AudioError::NotAllowed, "sound is not granted"));
6935 sink.close();
6936 self.deny(
6937 "sound is not granted: add `\"audio\": true` to capabilities in nsh.json"
6938 .into(),
6939 );
6940 return;
6941 }
6942 if let AudioCommand::Open { src, .. } | AudioCommand::LoadUrl { url: src, .. } =
6944 &mut command
6945 {
6946 match self.media_source(src) {
6947 Some(granted) => {
6948 if let Some(url) = granted {
6949 *src = url.to_string();
6950 }
6951 }
6952 None => {
6953 let base = self.base_url.as_deref();
6954 let capability = crate::access::media_capability(src, base);
6955 let advice = crate::access::media_grant_advice(src, base);
6956 sink.send(failed(
6959 AudioError::NotAllowed,
6960 &format!("{}{capability}", super::SOURCE_NOT_GRANTED),
6961 ));
6962 sink.close();
6963 self.deny(format!(
6964 "`{src}` is not granted by capabilities.{capability}: {advice}"
6965 ));
6966 return;
6967 }
6968 }
6969 }
6970 if self.audio.is_none() && !self.components.environment.audio {
6971 sink.send(failed(AudioError::Unavailable, "nothing plays sound here"));
6972 sink.close();
6973 return;
6974 }
6975 self.components.audio.insert(command.id(), sink.clone());
6976 (command, sink)
6977 }
6978 AudioAction::Command(command) => {
6979 let id = command.id();
6980 let sink = if command.ends() {
6981 self.components.audio.remove(&id)
6982 } else {
6983 self.components.audio.get(&id).cloned()
6984 };
6985 let Some(sink) = sink else {
6987 return;
6988 };
6989 if command.ends() {
6990 sink.close();
6991 }
6992 (command, sink)
6993 }
6994 };
6995 match self.audio.clone() {
6996 Some(backend) => backend.command(command, &sink),
6997 None => {
6998 let _ = self.apply_op(Op::Command {
6999 id: crate::ROOT_ID,
7000 command: Command::Audio(command),
7001 });
7002 }
7003 }
7004 }
7005
7006 fn apply_action(&mut self, action: Action) {
7007 match action {
7008 Action::Command(id, command) => {
7009 let _ = self.apply_op(Op::Command { id, command });
7010 }
7011 Action::WriteClipboard(command, answer) => {
7014 self.components.clipboard_writes.push_back(answer);
7015 let _ = self.apply_op(Op::Command {
7016 id: crate::ROOT_ID,
7017 command,
7018 });
7019 }
7020 Action::FocusBack { to, from, past } => self.focus_back = Some((to, from, past)),
7021 Action::FocusOrigin { to } => self.note_focus_origin(to),
7022 Action::Dialog(mut dialog, answer) => {
7023 dialog.id = self.components.next_dialog;
7024 self.components.next_dialog += 1;
7025 self.components.dialogs.insert(dialog.id, answer);
7026 let _ = self.apply_op(Op::Command {
7027 id: crate::ROOT_ID,
7028 command: Command::Dialog(Box::new(dialog)),
7029 });
7030 }
7031 Action::CloseDialog(answer) => {
7032 let Some(id) = self
7034 .components
7035 .dialogs
7036 .iter()
7037 .find_map(|(id, slot)| Rc::ptr_eq(slot, &answer).then_some(*id))
7038 else {
7039 return;
7040 };
7041 self.components.dialogs.remove(&id);
7042 answer
7043 .borrow_mut()
7044 .deliver(crate::element::DialogReply::dismissed());
7045 let _ = self.apply_op(Op::Command {
7046 id: crate::ROOT_ID,
7047 command: Command::CloseDialog(id),
7048 });
7049 }
7050 Action::Return(call, result) => self.settle(call, result),
7051 Action::Animation(op) => {
7052 let _ = self.apply_op(Op::Animation(op));
7053 }
7054 Action::Animate { op, animation, end } => {
7055 self.components
7056 .animations
7057 .insert(animation, Awaited::End(end));
7058 let _ = self.apply_op(Op::Animation(op));
7059 }
7060 Action::ReadValue { node, value } => {
7061 let request = self.components.executor.next_animation_id();
7062 self.components
7063 .animations
7064 .insert(request, Awaited::Value(value));
7065 let _ = self.apply_op(Op::Animation(crate::animation::AnimationOp::Read {
7066 node,
7067 request,
7068 }));
7069 }
7070 Action::ReportViewable(list) => self.report_viewable(list),
7071 Action::Hint(overlay) => self.hint_due(overlay),
7072 Action::Frame(answer) => self.wait_frame(answer),
7073 Action::Appearance(appearance) => self.set_appearance(appearance),
7074 Action::Tokens(tokens) => self.set_tokens(tokens),
7075 Action::Translations(translations) => self.set_translations(translations),
7076 Action::AddTranslations(map) => self.add_translations(map),
7077 Action::TranslationsChanged(before) => self.translations_changed(&before),
7078 Action::Locale(locale) => self.components.locale_request = Some(locale),
7079 Action::MainThread(task) => self.components.main_thread.push(task),
7080 Action::BuiltInScrollbars(source, theme) => {
7081 self.set_builtin_scrollbars(theme.map(|theme| (source, theme)))
7082 }
7083 Action::Measure(id, answer) => self.components.measures.push((id, answer)),
7084 Action::MeasureScrollPosition(id, answer) => {
7085 self.components.scroll_positions.push((id, answer))
7086 }
7087 Action::Evaluate(node, script, timeout, answer) => {
7088 self.start_web_evaluation(node, script, timeout, answer)
7089 }
7090 Action::WebEvaluationTimeout(request) => self.timeout_web_evaluation(request),
7091 Action::CanvasRenderTimeout(id) => self.timeout_canvas_render(id),
7092 Action::TransitionTime(id, answer) => {
7093 self.components.transition_times.push((id, answer))
7094 }
7095 Action::TextContent(id, answer) => self.components.text_contents.push((id, answer)),
7096 Action::PressAt(id, press, answer) => self.components.presses.push((id, press, answer)),
7097 Action::HoverAt(id, mouse) => self.components.hovers.push((id, mouse)),
7098 Action::ImageInfo(uri, answer) => {
7099 let id = self.components.next_image_info;
7100 self.components.next_image_info += 1;
7101 self.components.image_infos.insert(id, answer);
7102 let _ = self.apply_op(Op::Command {
7103 id: crate::ROOT_ID,
7104 command: Command::ImageInfo { id, uri },
7105 });
7106 }
7107 Action::Fetch(request, answer) => {
7108 let id = self.components.next_fetch;
7109 self.components.next_fetch += 1;
7110 self.components.fetches.insert(
7111 id,
7112 PendingFetch {
7113 response: crate::element::HttpResponse::default(),
7114 answer,
7115 },
7116 );
7117 self.components.fetch_requests.push((id, *request));
7118 }
7119 Action::RegisterFont(data, answer) => {
7120 let family = crate::text::font_family(&data)
7122 .and_then(|family| self.register_font(&data).map(|()| family));
7123 answer.borrow_mut().deliver(family);
7124 }
7125 Action::PickImages(request, answer) => {
7126 if !self.access.allows_picker() {
7127 answer.borrow_mut().deliver(Vec::new());
7128 self.deny(
7129 "the picker is not granted: add `\"picker\": true` to capabilities in nsh.json"
7130 .into(),
7131 );
7132 return;
7133 }
7134 if let Some(picker) = self.picker.clone() {
7135 let picked = picker.pick_images(request);
7136 crate::element::task::spawn_raw(
7137 &self.components.executor,
7138 crate::ROOT_ID,
7139 Box::pin(async move {
7140 let files = crate::picker::finish(&request, picked.await);
7141 answer.borrow_mut().deliver(files);
7142 }),
7143 );
7144 return;
7145 }
7146 let id = self.components.next_pick;
7147 self.components.next_pick += 1;
7148 self.components
7149 .picks
7150 .insert(id, (crate::picker::Pick::Images(request), answer));
7151 let _ = self.apply_op(Op::Command {
7152 id: crate::ROOT_ID,
7153 command: Command::PickImages { id, request },
7154 });
7155 }
7156 Action::PickFiles(request, answer) => {
7157 if !self.access.allows_picker() {
7158 answer.borrow_mut().deliver(Vec::new());
7159 self.deny(
7160 "the picker is not granted: add `\"picker\": true` to capabilities in nsh.json"
7161 .into(),
7162 );
7163 return;
7164 }
7165 if let Some(picker) = self.picker.clone() {
7166 let picked = picker.pick_files(request.clone());
7167 crate::element::task::spawn_raw(
7168 &self.components.executor,
7169 crate::ROOT_ID,
7170 Box::pin(async move {
7171 let files = crate::picker::finish_files(&request, picked.await);
7172 answer.borrow_mut().deliver(files);
7173 }),
7174 );
7175 return;
7176 }
7177 let id = self.components.next_pick;
7178 self.components.next_pick += 1;
7179 self.components
7180 .picks
7181 .insert(id, (crate::picker::Pick::Files(request.clone()), answer));
7182 let _ = self.apply_op(Op::Command {
7183 id: crate::ROOT_ID,
7184 command: Command::PickFiles { id, request },
7185 });
7186 }
7187 Action::ReadClipboard(read) => {
7188 let id = self.components.next_clipboard_read;
7189 self.components.next_clipboard_read += 1;
7190 let command = match &read {
7191 ClipboardRead::Text(_) | ClipboardRead::CheckedText(_) => {
7192 Command::ReadClipboard {
7193 id,
7194 has_only: false,
7195 }
7196 }
7197 ClipboardRead::Has(_) => Command::ReadClipboard { id, has_only: true },
7198 ClipboardRead::Image(_) | ClipboardRead::CheckedImage(_) => {
7199 Command::ReadClipboardImage {
7200 id,
7201 has_only: false,
7202 }
7203 }
7204 ClipboardRead::HasImage(_) => {
7205 Command::ReadClipboardImage { id, has_only: true }
7206 }
7207 ClipboardRead::Files(_) => Command::ReadClipboardFiles { id },
7208 };
7209 self.components.clipboard_reads.insert(id, read);
7210 let _ = self.apply_op(Op::Command {
7211 id: crate::ROOT_ID,
7212 command,
7213 });
7214 }
7215 Action::HostCall { name, args, answer } => {
7218 use crate::host_channel::{HostError, MAX_PENDING_CALLS};
7219 let refused = crate::host_channel::refusal(&self.access, &name).or_else(|| {
7220 (self.components.host_calls.len() >= MAX_PENDING_CALLS)
7221 .then(|| HostError::TooManyCalls { name: name.clone() })
7222 });
7223 if let Some(error) = refused {
7224 if !matches!(error, HostError::TooManyCalls { .. }) {
7225 self.deny(error.to_string());
7226 }
7227 answer.borrow_mut().deliver(Err(error));
7228 return;
7229 }
7230 let id = self.components.next_host_call;
7231 self.components.next_host_call += 1;
7232 self.components.host_calls.insert(id, answer);
7233 self.components
7234 .host_requests
7235 .push(crate::host_channel::HostRequest::Call { id, name, args });
7236 }
7237 Action::HostPost { name, args } => {
7238 if let Some(error) = crate::host_channel::refusal(&self.access, &name) {
7239 self.deny(error.to_string());
7240 return;
7241 }
7242 self.components
7243 .host_requests
7244 .push(crate::host_channel::HostRequest::Post { name, args });
7245 }
7246 Action::ForgetHostCalls => {
7249 self.components
7250 .host_calls
7251 .retain(|_, slot| std::rc::Rc::strong_count(slot) > 1);
7252 }
7253 Action::OpenUrl(url, answer) => {
7254 if let Err(refused) = crate::open_url::check_url(&url) {
7255 log::warn!(target: "js", "{refused}");
7256 answer.borrow_mut().deliver(false);
7257 return;
7258 }
7259 if !self.access.allows_open_url(&url) {
7260 answer.borrow_mut().deliver(false);
7261 self.deny(crate::open_url::not_granted(&url).message().to_owned());
7262 return;
7263 }
7264 let id = self.components.next_url_open;
7265 self.components.next_url_open = id.wrapping_add(1);
7266 self.components.url_opens.insert(id, answer);
7267 self.components.url_requests.push((id, url));
7268 }
7269 Action::OpenAppSettings(answer) => {
7270 use crate::mobile::AppSettingsError;
7271 let refused = if !self.access.allows_application() {
7275 Some(AppSettingsError::Denied)
7276 } else if !self.components.environment.app_settings {
7277 Some(AppSettingsError::Unavailable)
7278 } else {
7279 None
7280 };
7281 if let Some(error) = refused {
7282 answer.borrow_mut().deliver(Err(error));
7283 return;
7284 }
7285 let id = self.components.next_app_settings_open;
7286 self.components.next_app_settings_open = id.wrapping_add(1);
7287 self.components.app_settings_opens.insert(id, answer);
7288 let _ = self.apply_op(Op::Command {
7289 id: crate::ROOT_ID,
7290 command: Command::OpenAppSettings { id },
7291 });
7292 }
7293 Action::AppSettingsAvailable(answer) => {
7294 let available =
7295 self.components.environment.app_settings && self.access.allows_application();
7296 answer.borrow_mut().deliver(available);
7297 }
7298 Action::Audio(action) => self.audio_action(action),
7299 Action::Notification(action) => self.notification_action(action),
7300 Action::LoginItem(enabled, answer) => self.login_item_action(enabled, answer),
7301 Action::SnapToWindowMargin(margin) => self.set_snap_to_window_margin(margin),
7302 Action::ChooseMenuItem(item) => {
7303 let payload =
7306 EventPayload::Map(vec![("id", crate::PayloadValue::Number(f64::from(item)))]);
7307 if !self.dispatch_event(crate::ROOT_ID, EventKind::Menu, &payload) {
7308 self.events.push(crate::element::JsEvent::Event(
7309 crate::ROOT_ID,
7310 EventKind::Menu,
7311 payload,
7312 ));
7313 }
7314 }
7315 Action::NextUrlSchemeOpen(task, answer) => {
7316 let executor = &self.components.executor;
7317 self.components
7318 .url_schemes
7319 .listen(task, answer, |task| executor.has_task(task));
7320 }
7321 Action::NextUrlSchemeOpenFor(scheme, answer) => {
7322 let links = &mut self.components.url_schemes;
7323 let claimed = links.links.schemes().contains(&scheme)
7324 || (scheme == "https" && !links.links.web().is_empty());
7325 if !claimed {
7326 log::warn!(
7327 "next_url_scheme_open_for: the app does not claim `{scheme}` (nsh.json `schemes`), so no link of it comes"
7328 );
7329 }
7330 links
7331 .next_of_scheme
7332 .retain(|(_, answer)| crate::element::task::awaited(answer));
7333 links.next_of_scheme.push((scheme, answer));
7334 }
7335 Action::NextOpenFiles(answer) => {
7336 let files = &mut self.components.open_files;
7337 if files.pending.is_empty() {
7338 files.next = Some(answer);
7339 } else {
7340 answer
7341 .borrow_mut()
7342 .deliver(files.pending.drain(..).collect());
7343 }
7344 }
7345 Action::NextSecondInstance(answer) => {
7346 let launches = &mut self.components.second_instances;
7347 match launches.pending.pop_front() {
7348 Some(launch) => answer.borrow_mut().deliver(launch),
7349 None => launches.next = Some(answer),
7350 }
7351 }
7352 Action::NextAppUrlChange(answer) => {
7353 let links = &mut self.components.url_schemes;
7354 links.hears_changes = true;
7355 match links.changes.pop_front() {
7356 Some(change) => answer.borrow_mut().deliver(change),
7357 None => links.next_change = Some(answer),
7358 }
7359 }
7360 Action::AppUrl(answer) => {
7361 let address = self.components.url_schemes.address.get();
7362 answer.borrow_mut().deliver(address);
7363 }
7364 Action::SetAppUrl(url, history) => {
7365 let address = self.components.url_schemes.address.clone();
7369 if let Some(base) = address.page_base()
7370 && !crate::url_scheme::same_origin(Some(base.as_str()), &url)
7371 {
7372 log::warn!("set_app_url: {url} is not of the page's origin");
7373 return;
7374 }
7375 address.set(url.clone());
7378 let command = match history {
7382 crate::url_scheme::HistoryBehavior::Push => Command::PushAppUrl(url),
7383 _ => Command::SetAppUrl(url),
7384 };
7385 let _ = self.apply_op(Op::Command {
7386 id: crate::ROOT_ID,
7387 command,
7388 });
7389 }
7390 Action::WebInputAvailable(answer) => {
7391 let available =
7392 self.components.environment.web_input && self.access.allows_web_input();
7393 answer.borrow_mut().deliver(available);
7394 }
7395 Action::WebEvaluateAvailable(answer) => {
7396 let available =
7397 self.components.environment.web_evaluate && self.access.allows_webviews();
7398 answer.borrow_mut().deliver(available);
7399 }
7400 Action::WebViewAvailable(answer) => {
7401 let available =
7402 self.components.environment.web_views && self.access.allows_webviews();
7403 answer.borrow_mut().deliver(available);
7404 }
7405 Action::DownloadDecision {
7406 node,
7407 id,
7408 decision,
7409 answer,
7410 } => {
7411 let effects = self
7412 .components
7413 .downloads
7414 .decide(node, &id, decision, answer);
7415 self.apply_download_effects(effects);
7416 }
7417 Action::PickScreenColor(answer) => {
7418 if !self.components.environment.screen_color {
7419 answer.borrow_mut().deliver(None);
7420 return;
7421 }
7422 let id = self.components.next_screen_color;
7423 self.components.next_screen_color = id.wrapping_add(1);
7424 self.components.screen_colors.insert(id, answer);
7425 let _ = self.apply_op(Op::Command {
7426 id: crate::ROOT_ID,
7427 command: Command::PickScreenColor { id },
7428 });
7429 }
7430 Action::RenderCanvas(request, answer) => self.start_canvas_render(*request, answer),
7431 Action::FileRequest(request, answer) => {
7432 use crate::file_dialog::FileRequest;
7433 if !self.components.environment.file_requests {
7434 answer.deliver(
7435 Vec::new(),
7436 Some("this platform has no file dialogs, file manager or trash".into()),
7437 );
7438 return;
7439 }
7440 if let FileRequest::OpenPath(path)
7441 | FileRequest::RevealPath(path)
7442 | FileRequest::MoveToTrash(path) = &request
7443 && !path.is_absolute()
7444 {
7445 let refused = format!("`{}` is not an absolute path", path.display());
7446 log::warn!("{refused}");
7447 answer.deliver(Vec::new(), Some(refused));
7448 return;
7449 }
7450 let id = self.components.next_file_request;
7451 self.components.next_file_request = id.wrapping_add(1);
7452 self.components.file_requests.insert(id, answer);
7453 let _ = self.apply_op(Op::Command {
7454 id: crate::ROOT_ID,
7455 command: Command::FileRequest {
7456 id,
7457 request: Box::new(request),
7458 },
7459 });
7460 }
7461 }
7462 }
7463
7464 fn apply_download_effects(&mut self, effects: Vec<crate::webview::downloads::Effect>) {
7467 use crate::webview::downloads::Effect;
7468 for effect in effects {
7469 match effect {
7470 Effect::Event {
7471 node,
7472 kind,
7473 payload,
7474 } => {
7475 self.events
7476 .push(crate::element::JsEvent::Event(node, kind, payload));
7477 }
7478 Effect::Command {
7479 node,
7480 operation,
7481 track,
7482 } => {
7483 let id = self.alloc_webview_request();
7484 self.components.downloads.track(id, track);
7485 let _ = self.apply_op(Op::Command {
7486 id: node,
7487 command: Command::WebViewRequest(crate::webview::WebViewRequest {
7488 id,
7489 operation,
7490 }),
7491 });
7492 }
7493 Effect::Answer { slot, result } => slot.borrow_mut().deliver(result),
7494 }
7495 }
7496 }
7497
7498 fn alloc_webview_request(&mut self) -> u64 {
7501 loop {
7502 let id = self.components.next_webview_request;
7503 self.components.next_webview_request = id.wrapping_add(1);
7504 if !self.components.downloads.tracks(id) {
7505 break id;
7506 }
7507 }
7508 }
7509
7510 pub(super) fn webview_released(&mut self, id: NodeId) {
7516 let effects = self.components.downloads.teardown(id);
7517 for effect in effects {
7521 match effect {
7522 crate::webview::downloads::Effect::Event {
7523 node,
7524 kind,
7525 payload,
7526 } => self
7527 .events
7528 .push(crate::element::JsEvent::Event(node, kind, payload)),
7529 crate::webview::downloads::Effect::Command {
7530 node,
7531 operation,
7532 track,
7533 } => {
7534 let request = self.alloc_webview_request();
7535 self.components.downloads.track(request, track);
7536 self.mount.push(crate::MountItem::Command {
7537 id: node,
7538 command: Command::WebViewRequest(crate::webview::WebViewRequest {
7539 id: request,
7540 operation,
7541 }),
7542 });
7543 }
7544 crate::webview::downloads::Effect::Answer { slot, result } => {
7545 slot.borrow_mut().deliver(result);
7546 }
7547 }
7548 }
7549 }
7550
7551 fn download_event(&mut self, id: NodeId, kind: EventKind, payload: &EventPayload) -> bool {
7555 match kind {
7556 EventKind::DownloadOffer => {
7557 let EventPayload::Json(value) = payload else {
7558 return true;
7559 };
7560 let Some(offer) = crate::webview::downloads::parse_offer(value) else {
7561 log::debug!(target: "js", "web view: dropped a malformed download offer: {value}");
7562 return true;
7563 };
7564 let events = self
7565 .key(id)
7566 .ok()
7567 .map(|key| self.nodes[key as usize].events)
7568 .unwrap_or_default();
7569 let mode = if events.contains(EventKind::DownloadPending) {
7570 crate::webview::downloads::Mode::Manual
7571 } else if events.contains(EventKind::Download) {
7572 crate::webview::downloads::Mode::Automatic
7573 } else {
7574 crate::webview::downloads::Mode::None
7575 };
7576 let automatic =
7577 crate::webview::downloads::automatic_destination(&offer.id, &offer.filename);
7578 let refused = (!self.access.is_unrestricted()
7585 && !page_content(&offer.url)
7586 && !self.access.allows_webview(&offer.url))
7587 .then(|| super::not_granted("the download", &offer.url, "webview.hosts"));
7588 if let Some(message) = &refused {
7589 self.deny(message.clone());
7590 }
7591 let effects = self
7592 .components
7593 .downloads
7594 .offer(id, offer, mode, automatic, refused);
7595 self.apply_download_effects(effects);
7596 }
7597 EventKind::DownloadProgress => {
7598 }
7601 EventKind::DownloadEnd => {
7602 let EventPayload::Json(value) = payload else {
7603 return true;
7604 };
7605 let Some(end) = crate::webview::downloads::parse_end(value) else {
7606 log::debug!(target: "js", "web view: dropped a malformed download end: {value}");
7607 return true;
7608 };
7609 let effects = self.components.downloads.end(id, end);
7610 self.apply_download_effects(effects);
7611 }
7612 _ => return false,
7613 }
7614 true
7615 }
7616
7617 pub(super) fn poll_downloads(&mut self) {
7619 let effects = self.components.downloads.poll(crate::time::now());
7620 if !effects.is_empty() {
7621 self.apply_download_effects(effects);
7622 }
7623 }
7624
7625 pub(super) fn sync_download_listeners(&mut self) {
7632 let nodes = self.components.downloads.unobserved_nodes(|node| {
7633 self.key(node).is_ok_and(|key| {
7634 let events = self.nodes[key as usize].events;
7635 events.contains(EventKind::Download) || events.contains(EventKind::DownloadPending)
7636 })
7637 });
7638 for node in nodes {
7639 let effects = self.components.downloads.lost_listener(node);
7640 self.apply_download_effects(effects);
7641 }
7642 }
7643
7644 pub fn download_deadline(&self) -> Option<crate::time::Instant> {
7646 self.components.downloads.deadline()
7647 }
7648
7649 pub fn animations_finished(&mut self, finished: &mut Vec<crate::animation::Finished>) {
7652 finished.retain(|f| match self.components.animations.remove(&f.animation) {
7653 Some(Awaited::End(end)) => {
7654 end.borrow_mut().deliver(f.finished);
7655 false
7656 }
7657 Some(Awaited::Value(value)) => {
7658 value.borrow_mut().deliver(f.value.unwrap_or_default());
7659 false
7660 }
7661 None => f.animation % 2 == 0,
7663 });
7664 }
7665
7666 pub(super) fn answer_image_info(&mut self, id: u32, size: Result<ImageSize, String>) {
7668 if let Some(answer) = self.components.image_infos.remove(&id) {
7669 answer.borrow_mut().deliver(size);
7670 }
7671 }
7672
7673 pub fn take_url_opens(&mut self, out: &mut Vec<(u32, String)>) {
7679 out.append(&mut self.components.url_requests);
7680 }
7681
7682 pub(super) fn answer_clipboard_write(&mut self, result: crate::element::ClipboardWrite) {
7684 if let Some(answer) = self.components.clipboard_writes.pop_front() {
7685 answer.borrow_mut().deliver(result);
7686 }
7687 }
7688
7689 pub fn answer_open_url(&mut self, id: u32, opened: bool) {
7691 if let Some(answer) = self.components.url_opens.remove(&id) {
7692 answer.borrow_mut().deliver(opened);
7693 }
7694 }
7695
7696 pub fn open_url_on_platform(&mut self, id: u32, url: String) {
7699 if !self.components.url_opens.contains_key(&id) {
7700 return;
7701 }
7702 let _ = self.apply_op(Op::Command {
7703 id: crate::ROOT_ID,
7704 command: Command::OpenUrl { id, url },
7705 });
7706 }
7707
7708 pub fn take_fetches(
7714 &mut self,
7715 start: &mut Vec<(u32, crate::platform::HttpRequest)>,
7716 abandoned: &mut Vec<u32>,
7717 ) {
7718 start.append(&mut self.components.fetch_requests);
7719 if self.components.fetches.is_empty() {
7720 return;
7721 }
7722 self.components.fetches.retain(|&id, pending| {
7723 let wanted = Rc::strong_count(&pending.answer) > 1;
7725 if !wanted {
7726 abandoned.push(id);
7727 }
7728 wanted
7729 });
7730 start.retain(|(id, _)| !abandoned.contains(id));
7731 }
7732
7733 pub fn fetch_event(&mut self, id: u32, event: crate::platform::FetchEvent) -> bool {
7737 use crate::platform::FetchEvent;
7738 let Some(pending) = self.components.fetches.get_mut(&id) else {
7739 return false;
7740 };
7741 if Rc::strong_count(&pending.answer) == 1 {
7743 self.components.fetches.remove(&id);
7744 return false;
7745 }
7746 match event {
7747 FetchEvent::BodyWanted => {}
7748 FetchEvent::Head(head) => pending.response.head = head,
7749 FetchEvent::Data(data) => pending.response.body.extend_from_slice(&data),
7750 FetchEvent::End => {
7751 if let Some(pending) = self.components.fetches.remove(&id) {
7752 pending.answer.borrow_mut().deliver(Ok(pending.response));
7753 }
7754 return false;
7755 }
7756 FetchEvent::Failed(error) => {
7757 if let Some(pending) = self.components.fetches.remove(&id) {
7758 pending
7759 .answer
7760 .borrow_mut()
7761 .deliver(Err(FetchFailure::Failed(error)));
7762 }
7763 return false;
7764 }
7765 }
7766 true
7767 }
7768
7769 pub fn fetch_refused(&mut self, id: u32, message: String, url: String) {
7777 if let Some(pending) = self.components.fetches.remove(&id) {
7778 let refused = FetchFailure::Refused { message, url };
7779 pending.answer.borrow_mut().deliver(Err(refused));
7780 }
7781 }
7782
7783 pub(super) fn answer_clipboard(&mut self, id: u32, answer: ClipboardAnswer) {
7786 let ClipboardAnswer {
7787 has,
7788 text,
7789 denied,
7790 image,
7791 too_large,
7792 files,
7793 } = answer;
7794 let image = image.filter(|i| !i.url.is_empty());
7795 match self.components.clipboard_reads.remove(&id) {
7796 Some(ClipboardRead::Text(slot)) => slot.borrow_mut().deliver(text.unwrap_or_default()),
7797 Some(ClipboardRead::CheckedText(slot)) => slot
7798 .borrow_mut()
7799 .deliver((!denied).then(|| text.unwrap_or_default())),
7800 Some(ClipboardRead::Has(slot) | ClipboardRead::HasImage(slot)) => {
7801 slot.borrow_mut().deliver(has)
7802 }
7803 Some(ClipboardRead::Image(slot)) => slot.borrow_mut().deliver(image),
7804 Some(ClipboardRead::CheckedImage(slot)) => slot.borrow_mut().deliver(match too_large {
7805 Some(bytes) => Err(bytes),
7806 None => Ok(image),
7807 }),
7808 Some(ClipboardRead::Files(slot)) => slot.borrow_mut().deliver(files),
7809 None => {}
7810 }
7811 }
7812
7813 #[doc(hidden)]
7817 pub fn answer_host(
7818 &mut self,
7819 id: u64,
7820 result: Result<crate::JsonValue, crate::host_channel::HostError>,
7821 ) {
7822 match self.components.host_calls.remove(&id) {
7823 Some(answer) if std::rc::Rc::strong_count(&answer) > 1 => {
7824 answer.borrow_mut().deliver(result);
7825 }
7826 _ => {
7827 log::debug!(target: "js", "nsh/host: dropped the answer to call {id}, which no longer waits")
7828 }
7829 }
7830 }
7831
7832 #[doc(hidden)]
7839 pub fn take_host_requests(&mut self, out: &mut Vec<crate::host_channel::HostRequest>) {
7840 out.append(&mut self.components.host_requests);
7841 }
7842
7843 #[doc(hidden)]
7852 pub fn host_request_on_platform(&mut self, request: crate::host_channel::HostRequest) {
7853 use crate::host_channel::{HostError, HostRequest};
7854 let host = self.components.environment.host;
7855 let command = match request {
7856 HostRequest::Call { id, .. } if !host => {
7857 self.answer_host(id, Err(HostError::Unavailable));
7858 return;
7859 }
7860 HostRequest::Post { .. } if !host => return,
7861 HostRequest::Call { id, name, args } => Command::HostCall { id, name, args },
7862 HostRequest::Post { name, args } => Command::HostPost { name, args },
7863 };
7864 let _ = self.apply_op(Op::Command {
7865 id: crate::ROOT_ID,
7866 command,
7867 });
7868 }
7869
7870 #[doc(hidden)]
7877 pub fn host_event(&mut self, event: &str, data: &crate::JsonValue) {
7878 if !self.components.executor.host_events.borrow().listens(event) {
7879 if let Some((dropped, _)) = self
7882 .components
7883 .host_inbox
7884 .push(event.to_owned(), data.clone())
7885 {
7886 log::debug!(target: "js", "nsh/host: no Rust listener heard \"{dropped}\"; the oldest kept event was dropped");
7887 }
7888 return;
7889 }
7890 self.deliver_kept_host_events(event);
7892 self.dispatch_host_event(event, data);
7893 }
7894
7895 #[doc(hidden)]
7902 pub fn release_host_events(&mut self) -> bool {
7903 let names = {
7904 let mut listeners = self.components.executor.host_events.borrow_mut();
7905 if !std::mem::take(&mut listeners.added) || self.components.host_inbox.is_empty() {
7906 return false;
7907 }
7908 listeners.names()
7909 };
7910 let mut delivered = false;
7911 for name in names {
7912 delivered |= self.deliver_kept_host_events(&name);
7913 }
7914 delivered
7915 }
7916
7917 fn deliver_kept_host_events(&mut self, event: &str) -> bool {
7921 let mut delivered = false;
7922 while self.components.executor.host_events.borrow().listens(event) {
7923 let Some(data) = self.components.host_inbox.pop(event) else {
7924 break;
7925 };
7926 self.dispatch_host_event(event, &data);
7927 delivered = true;
7928 }
7929 delivered
7930 }
7931
7932 fn dispatch_host_event(&mut self, event: &str, data: &crate::JsonValue) {
7935 let listeners = self.components.executor.host_events.borrow().of(event);
7936 let _entered = self.components.runtime.enter();
7937 for listener in listeners {
7938 let result = caught(|| listener(data));
7939 self.apply_actions();
7940 if let Err(message) = result {
7941 log::error!(target: "js", "a listener of the host's \"{event}\" failed: {message}");
7942 }
7943 }
7944 }
7945
7946 fn report_window(&mut self, id: NodeId, event: &crate::desktop::WindowEvent) {
7950 use crate::desktop::WindowEvent;
7951 match event {
7952 WindowEvent::State(state) => {
7953 self.components.window_reports.entry(id).or_default().0 = Some(**state);
7954 }
7955 WindowEvent::TitleBar(area) => {
7956 self.components.window_reports.entry(id).or_default().1 = *area;
7957 }
7958 WindowEvent::Closed { .. } => {
7959 self.components.window_reports.remove(&id);
7960 if let Some((owner, _)) = self.components.js_windows.remove(&id) {
7961 let _entered = self.components.runtime.enter();
7962 owner.dispose();
7963 }
7964 return;
7965 }
7966 _ => return,
7967 }
7968 if let Some((_, this)) = self.components.js_windows.get(&id) {
7969 let _entered = self.components.runtime.enter();
7970 this.report(event);
7971 }
7972 }
7973
7974 fn platform_event(&mut self, id: NodeId, kind: EventKind, payload: &EventPayload) -> bool {
7977 if matches!(
7978 kind,
7979 EventKind::DownloadOffer | EventKind::DownloadProgress | EventKind::DownloadEnd
7980 ) {
7981 return self.download_event(id, kind, payload);
7982 }
7983 let number = |key: &str| match payload {
7984 EventPayload::Map(entries) => entries.iter().find_map(|(k, v)| match v {
7985 crate::PayloadValue::Number(n) if *k == key => Some(*n),
7986 _ => None,
7987 }),
7988 _ => None,
7989 };
7990 match kind {
7991 EventKind::Window => {
7994 if let EventPayload::Window(event) = payload {
7995 if id != ROOT_ID {
7996 self.report_window(id, event);
7997 }
7998 match event.as_ref() {
7999 crate::desktop::WindowEvent::State(state) => {
8000 self.keep_window_placement(id, state);
8001 }
8002 crate::desktop::WindowEvent::ClosePress { reason }
8005 if id == crate::ROOT_ID =>
8006 {
8007 self.components.runtime.main_close_pressed(*reason);
8008 }
8009 crate::desktop::WindowEvent::QuitRequest if id == crate::ROOT_ID => {
8010 self.quit_requested();
8011 return true;
8012 }
8013 _ => {}
8014 }
8015 }
8016 false
8017 }
8018 EventKind::Dialog => {
8019 let Some(dialog) = number("id") else {
8020 return false;
8021 };
8022 let Some(answer) = self.components.dialogs.remove(&(dialog as u32)) else {
8023 return false;
8024 };
8025 let value = match payload {
8026 EventPayload::Map(entries) => entries.iter().find_map(|(k, v)| match v {
8027 crate::PayloadValue::Str(text) if *k == "value" => Some(text.clone()),
8028 _ => None,
8029 }),
8030 _ => None,
8031 };
8032 answer.borrow_mut().deliver(crate::element::DialogReply {
8033 index: number("index").unwrap_or(-1.0) as i32,
8034 value,
8035 });
8036 true
8037 }
8038 EventKind::KeyCommand if id == crate::ROOT_ID => {
8040 let EventPayload::Value(crate::PayloadValue::Number(binding)) = payload else {
8041 return false;
8042 };
8043 let binding = *binding as u32;
8044 if binding < crate::element::keys::FIRST_ID {
8045 return false;
8046 }
8047 if binding == super::overlay::ESCAPE_BINDING {
8048 self.overlay_escape();
8049 return true;
8050 }
8051 let found = self.components.executor.keys.borrow().handler(binding);
8052 if let Some((text, handler)) = found {
8054 let result = caught(|| handler(&text));
8055 self.apply_actions();
8056 if let Err(message) = result {
8057 log::error!(target: "js", "a keyboard shortcut failed: {message}");
8058 }
8059 }
8060 true
8061 }
8062 EventKind::Menu if id == crate::ROOT_ID => {
8065 let menus = self.components.executor.menus.clone();
8066 let closed = matches!(payload, EventPayload::Map(entries)
8067 if entries.iter().any(|(k, v)| *k == "closed" && *v == crate::PayloadValue::Bool(true)));
8068 if closed {
8069 menus.borrow_mut().settle_popup();
8070 return false;
8071 }
8072 let Some(item) = number("id").map(|n| n as u32) else {
8073 return false;
8074 };
8075 if item < crate::element::menus::FIRST_ID {
8076 return false;
8077 }
8078 let registered = match payload {
8080 EventPayload::Map(entries) => entries.iter().find_map(|(k, v)| match v {
8081 crate::PayloadValue::Bool(b) if *k == "registered" => Some(*b),
8082 _ => None,
8083 }),
8084 _ => None,
8085 };
8086 if let Some(registered) = registered {
8087 menus.borrow_mut().registered(item, registered);
8088 self.apply_actions();
8089 return true;
8090 }
8091 let click = menus.borrow().tray_click(item);
8092 if let Some(click) = click {
8093 let bounds = match payload {
8094 EventPayload::Map(entries) => entries.iter().find_map(|(k, v)| match v {
8095 crate::PayloadValue::Bounds(b) if *k == "bounds" => Some(*b),
8096 _ => None,
8097 }),
8098 _ => None,
8099 };
8100 let result = caught(|| click(bounds));
8101 self.apply_actions();
8102 if let Err(message) = result {
8103 log::error!(target: "js", "the tray's click failed: {message}");
8104 }
8105 return true;
8106 }
8107 let handler = menus.borrow().handler(item);
8108 if let Some(handler) = handler {
8110 let result = caught(|| handler());
8111 self.apply_actions();
8112 if let Err(message) = result {
8113 log::error!(target: "js", "a menu item failed: {message}");
8114 }
8115 }
8116 true
8117 }
8118 EventKind::BackPress if id == crate::ROOT_ID => {
8119 if self.overlay_cancel() {
8121 return true;
8122 }
8123 let listeners = self.components.executor.back.borrow().newest_first();
8124 for listener in listeners {
8125 if self.back_pressed(&listener) {
8126 return true;
8127 }
8128 }
8129 if self.components.js_back {
8132 return false;
8133 }
8134 let _ = self.apply_op(Op::Command {
8135 id: crate::ROOT_ID,
8136 command: Command::Back,
8137 });
8138 true
8139 }
8140 EventKind::BackProgress if id == crate::ROOT_ID => {
8141 let Some(event) = crate::BackProgressEvent::from_payload(payload) else {
8142 return true;
8143 };
8144 if event.phase == crate::BackPhase::Start {
8148 self.components.back_gesture = !self.overlay_state.cancel;
8149 }
8150 if !self.components.back_gesture {
8151 return true;
8152 }
8153 if matches!(
8154 event.phase,
8155 crate::BackPhase::End | crate::BackPhase::Cancel
8156 ) {
8157 self.components.back_gesture = false;
8158 }
8159 let listeners = self
8160 .components
8161 .executor
8162 .back_progress
8163 .borrow()
8164 .newest_first();
8165 for listener in listeners {
8166 let result = caught(|| listener(&event));
8167 self.apply_actions();
8168 if let Err(message) = result {
8169 log::error!(target: "js", "a back progress listener failed: {message}");
8170 }
8171 }
8172 !self.components.js_back_progress
8174 }
8175 EventKind::WebEvaluation => {
8176 self.answer_web_evaluation(id, payload);
8177 true
8178 }
8179 EventKind::ImageInfo if id == crate::ROOT_ID => {
8180 let Some(request) = number("id") else {
8181 return false;
8182 };
8183 let error = match payload {
8184 EventPayload::Map(entries) => entries.iter().find_map(|(k, v)| match v {
8185 crate::PayloadValue::Str(e) if *k == "error" => Some(e.clone()),
8186 _ => None,
8187 }),
8188 _ => None,
8189 };
8190 let size = match (number("width"), number("height"), error) {
8191 (Some(width), Some(height), None) => Ok(ImageSize {
8192 width: pixels(width),
8193 height: pixels(height),
8194 }),
8195 (_, _, error) => Err(error.unwrap_or_else(|| "no size".into())),
8196 };
8197 self.answer_image_info(request as u32, size);
8198 true
8199 }
8200 EventKind::Audio if id == crate::ROOT_ID => {
8201 let EventPayload::Audio { id: object, event } = payload else {
8202 return false;
8203 };
8204 if let Some(sink) = self.components.audio.get(object) {
8206 sink.send(event.clone());
8207 }
8208 true
8209 }
8210 EventKind::Pick if id == crate::ROOT_ID => {
8211 let EventPayload::Picked { id: request, files } = payload else {
8212 return false;
8213 };
8214 if let Some((asked, answer)) = self.components.picks.remove(request) {
8215 let files = asked.finish(files.clone());
8216 answer.borrow_mut().deliver(files);
8217 }
8218 true
8219 }
8220 EventKind::Notification if id == crate::ROOT_ID => {
8221 self.notification_event(payload);
8222 true
8223 }
8224 EventKind::SecondInstance if id == crate::ROOT_ID => {
8225 let Some(launch) = crate::single_instance::SecondInstance::from_payload(payload)
8226 else {
8227 return false;
8228 };
8229 let launches = &mut self.components.second_instances;
8230 if let Some(answer) = launches.next.take() {
8231 answer.borrow_mut().deliver(launch);
8232 } else {
8233 if launches.pending.len() == crate::single_instance::MAX_PENDING {
8234 launches.pending.pop_front();
8235 }
8236 launches.pending.push_back(launch);
8237 }
8238 true
8239 }
8240 EventKind::UrlScheme if id == crate::ROOT_ID => {
8241 let EventPayload::Map(entries) = payload else {
8242 return false;
8243 };
8244 let url = entries.iter().find_map(|(k, v)| match v {
8245 crate::PayloadValue::Str(url) if *k == crate::url_scheme::URL => Some(url),
8246 _ => None,
8247 });
8248 let Some(url) = url else {
8249 return false;
8250 };
8251 let flag = |key: &str| {
8252 entries.iter().find_map(|(k, v)| match v {
8253 crate::PayloadValue::Bool(b) if *k == key => Some(*b),
8254 _ => None,
8255 })
8256 };
8257 let page = flag(crate::url_scheme::PAGE).unwrap_or(false);
8258 let quiet = flag(crate::url_scheme::QUIET).unwrap_or(false);
8259 let change = entries.iter().find_map(|(k, v)| match v {
8263 crate::PayloadValue::Str(s) if *k == crate::url_scheme::CHANGE => {
8264 Some(crate::url_scheme::AppUrlChangeReason::parse(s))
8265 }
8266 _ => None,
8267 });
8268 let (quiet, change) = match change {
8269 Some(None) => (true, None),
8270 Some(reason) => (quiet, reason),
8271 None => (quiet, None),
8272 };
8273 if let Some(base) = entries.iter().find_map(|(k, v)| match v {
8276 crate::PayloadValue::Str(s) if *k == crate::url_scheme::BASE => {
8277 url::Url::parse(s).ok()
8278 }
8279 _ => None,
8280 }) {
8281 self.components.url_schemes.address.set_page_base(base);
8282 }
8283 self.url_scheme(url.clone(), page, quiet, change);
8284 true
8285 }
8286 EventKind::ClipboardWrite if id == crate::ROOT_ID => {
8287 let written = match payload {
8288 EventPayload::Map(entries) => entries
8289 .iter()
8290 .any(|(k, v)| *k == "written" && *v == crate::PayloadValue::Bool(true)),
8291 _ => false,
8292 };
8293 self.answer_clipboard_write(if written {
8294 crate::element::ClipboardWrite::Written
8295 } else {
8296 crate::element::ClipboardWrite::Failed
8297 });
8298 true
8299 }
8300 EventKind::OpenUrl if id == crate::ROOT_ID => {
8301 let Some(request) = number("id") else {
8302 return false;
8303 };
8304 let opened = match payload {
8305 EventPayload::Map(entries) => entries
8306 .iter()
8307 .any(|(k, v)| *k == "opened" && *v == crate::PayloadValue::Bool(true)),
8308 _ => false,
8309 };
8310 self.answer_open_url(request as u32, opened);
8311 true
8312 }
8313 EventKind::OpenAppSettings if id == crate::ROOT_ID => {
8314 let Some(request) = number("id") else {
8315 return false;
8316 };
8317 let opened = match payload {
8318 EventPayload::Map(entries) => entries
8319 .iter()
8320 .any(|(k, v)| *k == "opened" && *v == crate::PayloadValue::Bool(true)),
8321 _ => false,
8322 };
8323 if let Some(answer) = self.components.app_settings_opens.remove(&(request as u32)) {
8324 answer.borrow_mut().deliver(Ok(opened));
8325 }
8326 true
8327 }
8328 EventKind::ScreenColor if id == crate::ROOT_ID => {
8329 let Some(request) = number("id") else {
8330 return false;
8331 };
8332 let color = number("color").map(|packed| crate::Color(packed as u32).into());
8333 if let Some(answer) = self.components.screen_colors.remove(&(request as u32)) {
8334 answer.borrow_mut().deliver(color);
8335 }
8336 true
8337 }
8338 EventKind::CanvasImage if id == crate::ROOT_ID => self.answer_canvas_render(payload),
8339 EventKind::FileRequest if id == crate::ROOT_ID => {
8340 let EventPayload::FileRequest {
8341 id: request,
8342 paths,
8343 error,
8344 } = payload
8345 else {
8346 return false;
8347 };
8348 if let Some(answer) = self.components.file_requests.remove(request) {
8349 answer.deliver(paths.clone(), error.clone());
8350 }
8351 true
8352 }
8353 EventKind::WebViewReply => {
8358 let EventPayload::Json(reply) = payload else {
8359 return false;
8360 };
8361 let request = reply.get("id").and_then(|id| {
8364 id.as_u64().or_else(|| {
8365 id.as_f64()
8366 .filter(|n| n.is_finite() && n.fract() == 0.0 && *n >= 0.0)
8367 .map(|n| n as u64)
8368 })
8369 });
8370 let Some(request) = request else {
8371 log::debug!(target: "js", "web view: dropped a reply without a request's id: {reply}");
8372 return true;
8373 };
8374 if !self.components.downloads.tracks(request) {
8375 log::debug!(target: "js", "web view: dropped a reply to unknown request {request}: {reply}");
8376 return true;
8377 }
8378 let result = match reply.get("ok").and_then(crate::JsonValue::as_bool) {
8379 Some(true) => Ok(()),
8380 _ => Err(reply
8381 .get("error")
8382 .and_then(crate::JsonValue::as_str)
8383 .unwrap_or("the web view did not answer")
8384 .to_owned()),
8385 };
8386 let effects = self.components.downloads.reply(id, request, result);
8387 self.apply_download_effects(effects);
8388 true
8389 }
8390 EventKind::Clipboard if id == crate::ROOT_ID => {
8391 let Some(request) = number("id") else {
8392 return false;
8393 };
8394 let answer = ClipboardAnswer::from_payload(payload);
8395 self.answer_clipboard(request as u32, answer);
8396 true
8397 }
8398 EventKind::Host if id == crate::ROOT_ID => {
8401 let EventPayload::Json(reply) = payload else {
8402 return false;
8403 };
8404 match reply.get("type").and_then(crate::JsonValue::as_str) {
8405 Some("reply") => {}
8406 Some("event") => {
8407 if let Some(event) = reply.get("event").and_then(crate::JsonValue::as_str) {
8408 let data = reply.get("payload").cloned().unwrap_or_default();
8409 self.host_event(event, &data);
8410 }
8411 return false;
8412 }
8413 _ => return false,
8414 }
8415 let call = reply.get("id").and_then(|id| {
8418 id.as_u64().or_else(|| {
8419 id.as_f64()
8420 .filter(|n| {
8421 n.fract() == 0.0 && (1.0..=9_007_199_254_740_991.0).contains(n)
8422 })
8423 .map(|n| n as u64)
8424 })
8425 });
8426 let Some(call) = call else {
8427 log::debug!(target: "js", "nsh/host: dropped a reply without a call's id: {reply}");
8428 return true;
8429 };
8430 let result = if reply.get("ok").and_then(crate::JsonValue::as_bool) == Some(true) {
8431 Ok(reply.get("value").cloned().unwrap_or_default())
8432 } else {
8433 Err(crate::host_channel::HostError::Failed(
8434 reply
8435 .get("error")
8436 .and_then(crate::JsonValue::as_str)
8437 .unwrap_or("nsh/host: the call failed")
8438 .to_owned(),
8439 ))
8440 };
8441 self.answer_host(call, result);
8442 true
8443 }
8444 EventKind::Insets => {
8445 let insets = EdgeInsets {
8446 top: Points(number("top").unwrap_or(0.0) as f32),
8447 right: Points(number("right").unwrap_or(0.0) as f32),
8448 bottom: Points(number("bottom").unwrap_or(0.0) as f32),
8449 left: Points(number("left").unwrap_or(0.0) as f32),
8450 };
8451 self.components.insets.insert(id, insets);
8453 false
8455 }
8456 _ => false,
8457 }
8458 }
8459
8460 fn back_pressed(&mut self, listener: &crate::element::BackListener) -> bool {
8462 let result = caught(|| listener());
8463 self.apply_actions();
8464 result.unwrap_or_else(|message| {
8465 log::error!(target: "js", "a back press listener failed: {message}");
8466 false
8467 })
8468 }
8469
8470 pub(super) fn sync_back(&mut self) {
8473 let rust = {
8474 let mut back = self.components.executor.back.borrow_mut();
8475 if !std::mem::take(&mut back.changed) {
8476 return;
8477 }
8478 !back.list.is_empty()
8479 };
8480 let _ = self.apply_op(Op::Listen {
8481 id: crate::ROOT_ID,
8482 event: EventKind::BackPress,
8483 enabled: rust || self.components.js_back || self.overlay_state.cancel,
8484 });
8485 }
8486
8487 pub(super) fn sync_back_progress(&mut self) {
8490 let rust = {
8491 let mut progress = self.components.executor.back_progress.borrow_mut();
8492 if !std::mem::take(&mut progress.changed) {
8493 return;
8494 }
8495 !progress.list.is_empty()
8496 };
8497 let _ = self.apply_op(Op::Listen {
8498 id: crate::ROOT_ID,
8499 event: EventKind::BackProgress,
8500 enabled: rust || self.components.js_back_progress,
8501 });
8502 }
8503
8504 pub(super) fn sync_keys(&mut self) {
8507 let escape_to_focus = self.focus_takes_escape();
8508 if escape_to_focus != self.overlay_state.escape_to_focus {
8509 self.overlay_state.escape_to_focus = escape_to_focus;
8510 self.components.executor.keys.borrow_mut().changed = true;
8511 }
8512 let rust = {
8513 let _entered = self.components.runtime.enter();
8515 let mut keys = self.components.executor.keys.borrow_mut();
8516 if !std::mem::take(&mut keys.changed) && !keys.unplaced {
8519 return;
8520 }
8521 !keys.list.is_empty()
8522 };
8523 let keymap = self.keymap();
8524 let _ = self.apply_op(Op::SetProp {
8525 id: crate::ROOT_ID,
8526 prop: Prop::Keymap(keymap),
8527 });
8528 let _ = self.apply_op(Op::Listen {
8529 id: crate::ROOT_ID,
8530 event: EventKind::KeyCommand,
8531 enabled: rust
8532 || self.components.js_keys
8533 || self.overlay_state.cancel
8534 || self.overlay_state.hint_escape,
8535 });
8536 }
8537
8538 fn keymap(&self) -> Arc<crate::keymap::Keymap> {
8541 let mut keys = self.components.executor.keys.borrow_mut();
8542 let overlay = self.overlay_key_binding();
8543 if keys.list.is_empty() && overlay.is_none() {
8544 keys.unplaced = false;
8545 return self.components.js_keymap.clone();
8546 }
8547 let views = {
8548 let _entered = self.components.runtime.enter();
8549 let mut known: Vec<(crate::element::Owner, NodeId)> = Vec::new();
8552 keys.bindings(|owner| {
8553 if let Some(&(_, window)) = known.iter().find(|(o, _)| *o == owner) {
8554 return window;
8555 }
8556 let window = self.window_of_owner(owner);
8557 known.push((owner, window));
8558 window
8559 })
8560 };
8561 drop(keys);
8562 let js = self.components.js_keymap.bindings();
8567 let bindings = js
8568 .iter()
8569 .filter(|b| !b.comes_after_views())
8570 .chain(views.iter().filter(|b| !b.comes_after_views()))
8571 .chain(js.iter().filter(|b| b.comes_after_views()))
8572 .chain(views.iter().filter(|b| b.comes_after_views()))
8573 .copied()
8574 .chain(overlay)
8575 .collect();
8576 Arc::new(crate::keymap::Keymap::new(bindings))
8577 }
8578
8579 pub(super) fn insets_of(&self, host: NodeId) -> EdgeInsets {
8582 let safe = self.components.environment.safe_area;
8583 let mut key = self.key(host).ok();
8584 while let Some(k) = key {
8585 let node = &self.nodes[k as usize];
8586 if let Some(insets) = self.components.insets.get(&node.id) {
8587 return *insets;
8588 }
8589 match node.kind {
8590 Kind::Screen => {
8592 return EdgeInsets {
8593 top: Points::ZERO,
8594 ..safe
8595 };
8596 }
8597 Kind::Modal => return safe,
8598 _ => {}
8599 }
8600 key = (node.parent != NO_KEY).then_some(node.parent);
8601 }
8602 safe
8603 }
8604
8605 fn clears_keyboard(&self, key: super::Key) -> bool {
8609 let mut key = key;
8610 loop {
8611 let node = &self.nodes[key as usize];
8612 if node.clears_keyboard {
8613 return true;
8614 }
8615 if node.parent == NO_KEY {
8616 return false;
8617 }
8618 key = node.parent;
8619 }
8620 }
8621
8622 pub(super) fn env_insets(
8627 &self,
8628 key: super::Key,
8629 env: &crate::style::EnvEdges,
8630 ) -> [EdgeInsets; 2] {
8631 use crate::style::EnvVar;
8632 let mut root = None;
8633 let mut value = |var: Option<EnvVar>| {
8634 let Some(var) = var else {
8635 return Points::ZERO;
8636 };
8637 if var == EnvVar::KeyboardInsetHeight {
8638 if self.clears_keyboard(key) {
8639 return Points::ZERO;
8640 }
8641 return self
8642 .components
8643 .environment
8644 .keyboard_height
8645 .max(Points::ZERO);
8646 }
8647 let insets = *root.get_or_insert_with(|| self.insets_of(self.nodes[key as usize].id));
8648 match var {
8649 EnvVar::SafeAreaInsetTop => insets.top,
8650 EnvVar::SafeAreaInsetRight => insets.right,
8651 EnvVar::SafeAreaInsetBottom => insets.bottom,
8652 _ => insets.left,
8653 }
8654 };
8655 let mut edges = |vars: &[Option<EnvVar>; 4]| EdgeInsets {
8656 top: value(vars[0]),
8657 right: value(vars[1]),
8658 bottom: value(vars[2]),
8659 left: value(vars[3]),
8660 };
8661 [edges(&env.padding), edges(&env.margin)]
8662 }
8663
8664 pub(super) fn sync_env(&mut self) {
8672 let mut keyboard_moved = std::mem::take(&mut self.keyboard_moved);
8673 if !self.env_styled.is_empty() {
8674 keyboard_moved |= self.restyle_env();
8675 }
8676 let duration = self.components.environment.keyboard_duration;
8677 if keyboard_moved && duration > 0.0 && self.layout_animation.is_none() {
8678 use crate::props::{LayoutAnimation, LayoutCurve, LayoutProperty, LayoutTransition};
8679 self.layout_animation = Some(LayoutAnimation {
8680 create: None,
8681 update: Some(LayoutTransition {
8682 curve: LayoutCurve::Keyboard,
8683 property: LayoutProperty::Opacity,
8684 duration_ms: duration,
8685 delay_ms: 0.0,
8686 }),
8687 delete: None,
8688 });
8689 }
8690 }
8691
8692 fn restyle_env(&mut self) -> bool {
8695 let mut ids = std::mem::take(&mut self.env_scratch);
8696 ids.extend(self.env_styled.iter().copied());
8697 let mut keyboard_moved = false;
8698 for &id in &ids {
8699 let node = self.key(id).ok().and_then(|key| {
8700 let env = self.nodes[key as usize].env.as_deref().copied()?;
8701 Some((key, env))
8702 });
8703 let Some((key, (env, applied))) = node else {
8704 self.env_styled.remove(&id);
8705 continue;
8706 };
8707 let now = self.env_insets(key, &env);
8708 if now == applied {
8709 continue;
8710 }
8711 let keyboard = |vars: &[Option<crate::style::EnvVar>; 4],
8713 was: &EdgeInsets,
8714 now: &EdgeInsets| {
8715 let (was, now) = (
8716 [was.top, was.right, was.bottom, was.left],
8717 [now.top, now.right, now.bottom, now.left],
8718 );
8719 (0..4).any(|i| {
8720 vars[i] == Some(crate::style::EnvVar::KeyboardInsetHeight) && was[i] != now[i]
8721 })
8722 };
8723 keyboard_moved |= keyboard(&env.padding, &applied[0], &now[0])
8724 || keyboard(&env.margin, &applied[1], &now[1]);
8725 self.restyle(key);
8726 }
8727 ids.clear();
8728 self.env_scratch = ids;
8729 keyboard_moved
8730 }
8731
8732 pub(super) fn apply_actions(&mut self) {
8735 for action in self.components.executor.take_actions() {
8736 self.apply_action(action);
8737 }
8738 }
8739
8740 pub(super) fn route_emit(
8744 &mut self,
8745 host: NodeId,
8746 event: Box<dyn crate::element::builder::AnyEvent>,
8747 ) {
8748 match self.components.owners.get(&host).copied() {
8749 Some(parent) => {
8750 let Some(owner) = self.state_owner(parent) else {
8751 return;
8752 };
8753 let mut from = 0;
8755 while let Some((at, listener)) =
8756 self.components.instances.get(&parent).and_then(|inst| {
8757 inst.event_handlers
8758 .iter()
8759 .enumerate()
8760 .skip(from)
8761 .find(|(_, (n, _))| *n == host)
8762 .map(|(at, (_, l))| (at, l.clone()))
8763 })
8764 {
8765 from = at + 1;
8766 if let Err(message) = caught(|| listener.call(event.as_any())) {
8767 self.component_failed(owner, message);
8768 }
8769 self.apply_actions();
8770 }
8771 }
8772 None => self.events.push(JsEvent::Component { host, event }),
8773 }
8774 }
8775}
8776
8777fn drop_caught<T>(value: T) {
8781 if let Err(message) = caught(move || drop(value)) {
8782 log::error!(target: "js", "a value of a call into Rust panicked as it dropped: {message}");
8783 }
8784}
8785
8786fn dispose_rows(rows: &std::rc::Weak<RefCell<CellRowMap>>) {
8788 let Some(rows) = rows.upgrade() else {
8789 return;
8790 };
8791 let owners: Vec<_> = rows.borrow_mut().drain().map(|(_, (_, o))| o).collect();
8792 for owner in owners {
8793 owner.dispose();
8794 }
8795}
8796
8797fn move_rows(cells: &CellRows, diff: Option<&ListDiff>, count: u32) {
8805 let parts: Vec<_> = cells
8806 .borrow()
8807 .iter()
8808 .map(|(&id, &(index, owner))| (id, index, owner))
8809 .collect();
8810 let mut gone = Vec::new();
8811 let moves: Vec<_> = parts
8813 .iter()
8814 .map(|&(id, index, owner)| {
8815 let i = index.get_untracked();
8816 let to = match diff {
8817 Some(d) => d.new_index(i as u32).map(|(to, _)| to as usize),
8818 None => Some(i),
8819 };
8820 (id, index, owner, i, to)
8821 })
8822 .collect();
8823 let mut taken: Vec<usize> = moves
8824 .iter()
8825 .filter(|m| m.2.is_live())
8826 .filter_map(|m| m.4)
8827 .collect();
8828 taken.sort_unstable();
8829 for (id, index, owner, i, to) in moves {
8830 if !owner.is_live() {
8831 gone.push(id);
8832 continue;
8833 }
8834 let to = match to {
8835 Some(to) => Some(to),
8836 None => Some(i).filter(|i| taken.binary_search(i).is_err()),
8839 };
8840 match to {
8841 Some(to) if to < count as usize => index.set(to),
8842 _ => {
8843 owner.dispose();
8844 gone.push(id);
8845 }
8846 }
8847 }
8848 let mut cells = cells.borrow_mut();
8849 for id in gone {
8850 cells.remove(&id);
8851 }
8852}
8853
8854fn row_position(
8859 index: usize,
8860 count: usize,
8861 count_signal: Option<crate::element::Signal<usize>>,
8862 moves: Option<crate::element::reactive::Node>,
8863 made: &std::cell::Cell<Option<crate::element::Signal<usize>>>,
8864) -> Position {
8865 match count_signal {
8866 Some(count) => {
8867 let index = crate::element::signal(index);
8868 made.set(Some(index));
8869 Position::of_row(index.node(), count.node(), moves)
8870 }
8871 None => Position::fixed(index, count),
8872 }
8873}
8874
8875fn pixels(n: f64) -> crate::geometry::DevicePixels {
8878 crate::geometry::DevicePixels(n.round() as i32)
8879}
8880
8881fn page_content(url: &str) -> bool {
8884 let scheme = url.split(':').next().unwrap_or_default();
8885 url.contains(':')
8886 && (scheme.eq_ignore_ascii_case("data") || scheme.eq_ignore_ascii_case("blob"))
8887}