1#![forbid(unsafe_code)]
26#![warn(missing_docs)]
27
28use noonoo_dom::NodeId;
29use noonoo_engine::Engine;
30use noonoo_events::{Event, EventListener, dispatch};
31use noonoo_geometry::{Point, Rect, Size};
32use noonoo_layout::{LayoutTree, Shaper};
33use noonoo_paint::{CommandList, Glyphs, TextRuns};
34use noonoo_style::{Cursor, Interaction, Styles};
35
36#[derive(Clone, PartialEq, Eq, Debug)]
42pub enum Origin {
43 Chrome,
45 Content,
47 Custom(String),
49}
50
51impl Origin {
52 pub fn is_trusted(&self) -> bool {
54 !matches!(self, Origin::Content)
55 }
56}
57
58pub fn navigation_allowed(origin: &Origin, target_scheme: &str) -> bool {
60 match target_scheme {
61 "shell" | "noonoo" | "exo" => origin.is_trusted(),
62 _ => true,
63 }
64}
65
66#[derive(Clone, Copy, PartialEq, Eq, Debug)]
68pub enum LayerKind {
69 Chrome,
71 Content,
73}
74
75#[derive(Clone, Copy, PartialEq, Eq, Debug)]
77pub struct Anchor {
78 pub parent: usize,
80 pub host: NodeId,
82}
83
84pub struct Layer {
86 pub origin: Origin,
88 pub kind: LayerKind,
90 pub rect: Rect,
93 anchor: Option<Anchor>,
94 engine: Engine,
95 styles: Styles,
96 layout: LayoutTree,
97 commands: CommandList,
98 scroll: Point,
99}
100
101impl Layer {
102 pub fn engine(&self) -> &Engine {
104 &self.engine
105 }
106
107 pub fn engine_mut(&mut self) -> &mut Engine {
110 &mut self.engine
111 }
112
113 pub fn styles(&self) -> &Styles {
115 &self.styles
116 }
117
118 pub fn layout(&self) -> &LayoutTree {
120 &self.layout
121 }
122
123 pub fn commands(&self) -> &CommandList {
125 &self.commands
126 }
127
128 pub fn anchor(&self) -> Option<Anchor> {
130 self.anchor
131 }
132
133 pub fn scroll(&self) -> Point {
135 self.scroll
136 }
137
138 pub fn set_scroll_y(&mut self, y: f32) {
140 let max = self.max_scroll_y();
141 self.scroll.y = y.clamp(0.0, max);
142 }
143
144 pub fn max_scroll_y(&self) -> f32 {
147 (self.layout.content_height() - self.rect.height).max(0.0)
148 }
149
150 #[cfg(feature = "a11y")]
153 pub fn a11y(&self, focus: Option<NodeId>) -> noonoo_a11y::A11yTree {
154 noonoo_a11y::build_in(self.engine.dom(), self.styles(), Some(self.layout()), focus)
155 }
156}
157
158pub struct Host {
160 pub viewport: Size,
162 layers: Vec<Layer>,
163 focus: Option<(usize, NodeId)>,
164 hovered: Option<(usize, NodeId)>,
165 active: Option<(usize, NodeId)>,
166 glyphs: Box<dyn Glyphs + Send + Sync>,
169}
170
171impl Host {
172 pub fn new(viewport: Size) -> Self {
174 Self {
175 viewport,
176 layers: Vec::new(),
177 focus: None,
178 hovered: None,
179 active: None,
180 glyphs: Box::new(TextRuns),
181 }
182 }
183
184 pub fn set_glyphs(&mut self, glyphs: Box<dyn Glyphs + Send + Sync>) {
188 self.glyphs = glyphs;
189 }
190
191 pub fn add_chrome(&mut self, engine: Engine, rect: Rect) -> usize {
193 self.push(LayerKind::Chrome, Origin::Chrome, engine, rect)
194 }
195
196 pub fn add_content(&mut self, engine: Engine, rect: Rect) -> usize {
198 self.push(LayerKind::Content, Origin::Content, engine, rect)
199 }
200
201 fn push(&mut self, kind: LayerKind, origin: Origin, engine: Engine, rect: Rect) -> usize {
202 let index = self.layers.len();
203 self.layers.push(Layer {
204 origin,
205 kind,
206 rect,
207 anchor: None,
208 engine,
209 styles: Styles::default(),
210 layout: LayoutTree::default(),
211 commands: CommandList::default(),
212 scroll: Point::ZERO,
213 });
214 index
215 }
216
217 pub fn add_sub_document(&mut self, parent: usize, host: NodeId, engine: Engine) -> usize {
224 let index = self.layers.len();
225 self.layers.push(Layer {
226 origin: Origin::Content,
227 kind: LayerKind::Content,
228 rect: Rect::default(),
229 anchor: Some(Anchor { parent, host }),
230 engine,
231 styles: Styles::default(),
232 layout: LayoutTree::default(),
233 commands: CommandList::default(),
234 scroll: Point::ZERO,
235 });
236 index
237 }
238
239 pub fn layers(&self) -> &[Layer] {
241 &self.layers
242 }
243
244 pub fn layers_mut(&mut self) -> &mut [Layer] {
246 &mut self.layers
247 }
248
249 pub fn layer(&self, index: usize) -> Option<&Layer> {
251 self.layers.get(index)
252 }
253
254 pub fn layout(&mut self, shaper: &dyn Shaper) {
260 for index in 0..self.layers.len() {
261 if let Some(anchor) = self.layers[index].anchor {
262 let rect = {
263 let parent = &self.layers[anchor.parent];
264 let content = parent
265 .layout
266 .get(anchor.host)
267 .map(|box_| box_.content_box())
268 .unwrap_or_default();
269 Rect::new(
270 parent.rect.x + content.x,
271 parent.rect.y + content.y,
272 content.width,
273 content.height,
274 )
275 };
276 self.layers[index].rect = rect;
277 }
278
279 let interaction = self.interaction_for(index);
280 let layer = &mut self.layers[index];
281 let styles = layer
282 .engine
283 .compute_styles_in(layer.rect.size(), interaction);
284 let mut layout = noonoo_layout::layout_with_images(
285 layer.engine.dom(),
286 &styles,
287 layer.rect.size(),
288 shaper,
289 layer.engine.images(),
290 );
291 layout.inherit_scroll(&layer.layout);
293 let commands = noonoo_paint::paint_with(&styles, &layout, self.glyphs.as_ref());
294 layer.styles = styles;
295 layer.layout = layout;
296 layer.commands = commands;
297 let max_y = layer.max_scroll_y();
298 layer.scroll.y = layer.scroll.y.clamp(0.0, max_y);
299 }
300 }
301
302 pub fn poll_resources(&mut self) -> bool {
306 let mut changed = false;
307 for layer in &mut self.layers {
308 changed |= layer.engine.poll_resources();
309 }
310 changed
311 }
312
313 pub fn route(&self, point: Point) -> Option<usize> {
315 self.layers
316 .iter()
317 .rposition(|layer| layer.rect.contains(point))
318 }
319
320 pub fn hit(&self, point: Point) -> Option<(usize, NodeId)> {
322 let index = self.route(point)?;
323 let layer = &self.layers[index];
324 let local = local_point(layer.rect, layer.scroll, point);
325 let node = layer.layout.hit_test(local)?;
326 Some((index, node))
327 }
328
329 pub fn element_hit(&self, point: Point) -> Option<(usize, NodeId)> {
333 let (index, mut node) = self.hit(point)?;
334 let dom = self.layers[index].engine().dom();
335 while dom.element(node).is_none() {
336 node = dom.tree().parent(node)?;
337 }
338 Some((index, node))
339 }
340
341 pub fn focus(&self) -> Option<(usize, NodeId)> {
343 self.focus
344 }
345
346 pub fn set_focus(&mut self, layer: usize, node: NodeId) {
348 self.focus = Some((layer, node));
349 }
350
351 pub fn hover(&mut self, point: Point) -> bool {
356 let hit = self.element_hit(point);
357 if hit != self.hovered {
358 self.hovered = hit;
359 true
360 } else {
361 false
362 }
363 }
364
365 pub fn hovered(&self) -> Option<(usize, NodeId)> {
367 self.hovered
368 }
369
370 pub fn press(&mut self, point: Point) {
372 self.active = self.element_hit(point);
373 }
374
375 pub fn release(&mut self) {
377 self.active = None;
378 }
379
380 pub fn active(&self) -> Option<(usize, NodeId)> {
382 self.active
383 }
384
385 pub fn cursor_at(&self, point: Point) -> Cursor {
388 match self.element_hit(point) {
389 Some((index, node)) => self.layers[index]
390 .styles
391 .get(node)
392 .map(|style| style.cursor.clone())
393 .unwrap_or(Cursor::Auto),
394 None => Cursor::Auto,
395 }
396 }
397
398 fn interaction_for(&self, index: usize) -> Interaction {
400 let on_layer = |state: Option<(usize, NodeId)>| {
401 state
402 .filter(|(layer, _)| *layer == index)
403 .map(|(_, node)| node)
404 };
405 Interaction {
406 hovered: on_layer(self.hovered),
407 focused: on_layer(self.focus),
408 active: on_layer(self.active),
409 }
410 }
411
412 pub fn dispatch_pointer(
416 &mut self,
417 point: Point,
418 event: &Event,
419 listener: &impl EventListener,
420 ) -> Option<(usize, NodeId)> {
421 let (index, node) = self.element_hit(point)?;
422 self.focus = Some((index, node));
423 dispatch(
424 self.layers[index].engine().dom().tree(),
425 node,
426 event,
427 listener,
428 );
429 Some((index, node))
430 }
431
432 pub fn dispatch_key(&mut self, event: &Event, listener: &impl EventListener) -> bool {
434 let Some((index, node)) = self.focus else {
435 return false;
436 };
437 let layer = &self.layers[index];
438 dispatch(layer.engine().dom().tree(), node, event, listener);
439 true
440 }
441
442 fn repaint(&mut self, index: usize) {
444 let layer = &mut self.layers[index];
445 layer.commands =
446 noonoo_paint::paint_with(&layer.styles, &layer.layout, self.glyphs.as_ref());
447 }
448
449 pub fn wheel(&mut self, point: Point, delta_y: f32) -> Vec<(usize, f32)> {
459 let mut chain = Vec::new();
460 let Some(mut index) = self.route(point) else {
461 return chain;
462 };
463 let mut leftover = delta_y;
464 loop {
465 let local = local_point(self.layers[index].rect, self.layers[index].scroll, point);
467 let (boxes, remaining) = self.layers[index].layout.scroll_at(local, leftover);
468 if !boxes.is_empty() {
469 self.repaint(index);
470 leftover = remaining;
471 }
472
473 let layer = &mut self.layers[index];
475 let max = layer.max_scroll_y();
476 let before = layer.scroll.y;
477 let after = (before + leftover).clamp(0.0, max);
478 let consumed = after - before;
479 layer.scroll.y = after;
480 if consumed != 0.0 {
481 chain.push((index, consumed));
482 }
483 leftover -= consumed;
484 if leftover.abs() < 1e-4 {
485 break;
486 }
487 match layer.anchor {
488 Some(anchor) => index = anchor.parent,
489 None => break,
490 }
491 }
492 chain
493 }
494
495 #[cfg(feature = "a11y")]
501 pub fn a11y(&self) -> noonoo_a11y::A11yTree {
502 let mut trees = Vec::with_capacity(self.layers.len());
503 for (index, layer) in self.layers.iter().enumerate() {
504 let focused = match self.focus {
505 Some((layer_index, node)) if layer_index == index => Some(node),
506 _ => None,
507 };
508 let tree = layer.a11y(focused);
509 let offset = Point::new(layer.rect.x - layer.scroll.x, layer.rect.y - layer.scroll.y);
510 trees.push((tree, offset));
511 }
512 let layers: Vec<(&noonoo_a11y::A11yTree, Point)> =
513 trees.iter().map(|(tree, offset)| (tree, *offset)).collect();
514 noonoo_a11y::compose("", &layers)
515 }
516}
517
518fn local_point(rect: Rect, scroll: Point, point: Point) -> Point {
519 Point::new(point.x - rect.x + scroll.x, point.y - rect.y + scroll.y)
520}
521
522pub const VERSION: &str = env!("CARGO_PKG_VERSION");
524
525#[cfg(test)]
526mod tests {
527 use super::*;
528 use noonoo_layout::MetricShaper;
529 use noonoo_paint::Color;
530 use std::cell::RefCell;
531 use std::rc::Rc;
532
533 fn engine(html: &str, css: &str) -> Engine {
534 Engine::from_html(&format!("<style>body {{ margin: 0 }} {css}</style>{html}"))
536 }
537
538 fn host() -> Host {
539 let mut host = Host::new(Size::new(400.0, 300.0));
540 host.add_chrome(
541 engine(
542 r#"<div id="bar">chrome</div>"#,
543 "#bar { height: 24px; background-color: #222222 }",
544 ),
545 Rect::new(0.0, 0.0, 400.0, 24.0),
546 );
547 host.add_content(
548 engine(
549 r#"<div id="page">content</div>"#,
550 "#page { height: 100px; background-color: #ffffff }",
551 ),
552 Rect::new(0.0, 24.0, 400.0, 276.0),
553 );
554 host.layout(&MetricShaper);
555 host
556 }
557
558 #[test]
561 fn layers_draw_the_images_their_engines_loaded() {
562 let dir = std::env::temp_dir().join("noonoo-shell-images");
563 std::fs::create_dir_all(&dir).unwrap();
564 let mut png = b"\x89PNG\r\n\x1a\n".to_vec();
565 png.extend(13u32.to_be_bytes());
566 png.extend(b"IHDR");
567 png.extend(40u32.to_be_bytes());
568 png.extend(30u32.to_be_bytes());
569 png.extend([8, 6, 0, 0, 0]);
570 std::fs::write(dir.join("a.png"), png).unwrap();
571 let mut host = host();
572 assert!(!host.poll_resources());
573 let mut page = engine(r#"<img src="a.png">"#, "");
574 page.set_base_url(format!("{}/index.html", dir.display()));
575 page.set_loader(noonoo_net::FileLoader);
576 page.load_resources();
577 let layer = host.add_content(page, Rect::new(0.0, 24.0, 400.0, 276.0));
578 assert!(host.poll_resources());
579 assert!(!host.poll_resources());
580 host.layout(&MetricShaper);
581 let drawn = host.layers()[layer]
582 .commands()
583 .commands()
584 .iter()
585 .filter(|c| matches!(c, noonoo_paint::Command::DrawImage { .. }))
586 .count();
587 assert_eq!(drawn, 1);
588 }
589
590 #[test]
593 fn a_layers_document_can_be_changed_in_place() {
594 let mut host = host();
595 let engine = host.layers_mut()[0].engine_mut();
596 let bar = engine.dom().get_element_by_id("bar").unwrap();
597 let text = engine.dom().tree().children(bar)[0];
598 engine.dom_mut().mutate().set_text(text, "patched").unwrap();
599 host.layout(&MetricShaper);
600 let painted = host.layers()[0].commands().commands().iter().any(|command| {
601 matches!(command, noonoo_paint::Command::DrawText { text, .. } if text == "patched")
602 });
603 assert!(painted);
604 }
605
606 #[test]
607 fn routes_by_region() {
608 let host = host();
609 assert_eq!(host.route(Point::new(10.0, 10.0)), Some(0));
610 assert_eq!(host.route(Point::new(10.0, 50.0)), Some(1));
611 assert_eq!(host.route(Point::new(10.0, 999.0)), None);
612 }
613
614 #[test]
615 fn hit_tests_to_the_right_document_and_node() {
616 let host = host();
617 let (layer, node) = host.hit(Point::new(10.0, 50.0)).unwrap();
618 assert_eq!(layer, 1);
619 assert_eq!(
620 host.layer(1)
621 .unwrap()
622 .engine()
623 .dom()
624 .element(node)
625 .unwrap()
626 .name,
627 "div"
628 );
629 }
630
631 #[test]
632 fn pointer_sets_focus_and_dispatches() {
633 let mut host = host();
634 let seen: Rc<RefCell<Vec<NodeId>>> = Rc::new(RefCell::new(Vec::new()));
635 let listener = {
636 let seen = seen.clone();
637 noonoo_events::FnListener(
638 move |node: NodeId, _e: &Event, _p: noonoo_events::EventPhase| {
639 seen.borrow_mut().push(node);
640 noonoo_events::Propagation::Continue
641 },
642 )
643 };
644 let routed = host.dispatch_pointer(
645 Point::new(10.0, 50.0),
646 &Event::Click(noonoo_events::PointerEvent {
647 x: 10.0,
648 y: 50.0,
649 button: noonoo_events::MouseButton::Primary,
650 state: noonoo_events::ElementState::Released,
651 modifiers: noonoo_events::Modifiers::default(),
652 }),
653 &listener,
654 );
655 let (layer, _node) = routed.unwrap();
656 assert_eq!(layer, 1);
657 assert_eq!(host.focus().unwrap().0, 1);
658 assert!(!seen.borrow().is_empty());
659
660 assert!(host.dispatch_key(&Event::Input { value: "a".into() }, &listener));
662 }
663
664 #[test]
665 fn composes_one_command_stream_per_layer() {
666 let host = host();
667 assert_eq!(host.layers().len(), 2);
668 assert!(!host.layer(0).unwrap().commands().is_empty());
669 assert!(!host.layer(1).unwrap().commands().is_empty());
670 }
671
672 #[test]
673 fn sub_document_is_sized_by_its_host_node() {
674 let mut host = Host::new(Size::new(400.0, 300.0));
675 let parent = host.add_chrome(
676 engine(
677 r#"<div id="slot"></div>"#,
678 "#slot { width: 200px; height: 100px }",
679 ),
680 Rect::new(0.0, 0.0, 400.0, 300.0),
681 );
682 let slot = host
683 .layer(parent)
684 .unwrap()
685 .engine()
686 .dom()
687 .get_element_by_id("slot")
688 .unwrap();
689 let sub = engine(
690 r#"<p id="emb">embedded</p>"#,
691 "p { margin: 0; height: 40px; background-color: #eeeeee }",
692 );
693 let sub_index = host.add_sub_document(parent, slot, sub);
694 host.layout(&MetricShaper);
695
696 assert_eq!(
698 host.layer(sub_index).unwrap().rect,
699 Rect::new(0.0, 0.0, 200.0, 100.0)
700 );
701 assert_eq!(host.route(Point::new(10.0, 10.0)), Some(sub_index));
703 let (layer, node) = host.hit(Point::new(10.0, 10.0)).unwrap();
704 assert_eq!(layer, sub_index);
705 assert_eq!(
707 host.layer(sub_index)
708 .unwrap()
709 .engine()
710 .dom()
711 .node(node)
712 .and_then(|data| data.as_text()),
713 Some("embedded")
714 );
715 assert!(!host.layer(sub_index).unwrap().commands().is_empty());
717 }
718
719 #[test]
720 fn pointing_at_text_hovers_and_presses_its_element() {
721 let mut host = Host::new(Size::new(400.0, 300.0));
722 host.add_content(
723 engine(
724 "<p>hello</p>",
725 "body { margin: 0 } p { margin: 0; cursor: pointer }
726 p:hover { background: red }",
727 ),
728 Rect::new(0.0, 0.0, 400.0, 300.0),
729 );
730 host.layout(&MetricShaper);
731 let point = Point::new(2.0, 2.0);
733 let (_, deepest) = host.hit(point).unwrap();
734 let dom = host.layer(0).unwrap().engine().dom();
735 assert!(dom.element(deepest).is_none(), "the hit is the text node");
736
737 assert_eq!(host.cursor_at(point), Cursor::Pointer);
738 host.hover(point);
739 host.press(point);
740 let p = host.hovered().unwrap().1;
741 let dom = host.layer(0).unwrap().engine().dom();
742 assert_eq!(dom.element(p).unwrap().name, "p");
743 assert_eq!(host.active().unwrap().1, p);
744 host.layout(&MetricShaper);
745 assert_eq!(
746 host.layer(0)
747 .unwrap()
748 .styles()
749 .get(p)
750 .unwrap()
751 .background_color,
752 Color::rgb(255, 0, 0)
753 );
754 }
755
756 #[test]
757 fn hover_and_active_restyle_on_the_next_layout() {
758 let mut host = Host::new(Size::new(400.0, 300.0));
759 host.add_content(
760 engine(
761 r#"<button id="b">hi</button>"#,
762 "button { cursor: pointer; background: white }
763 button:hover { background: red }
764 button:active { background: green }
765 button:focus { outline: 1px }",
766 ),
767 Rect::new(0.0, 0.0, 400.0, 300.0),
768 );
769 host.layout(&MetricShaper);
770 let point = Point::new(10.0, 10.0);
771
772 assert!(host.hovered().is_none());
774 assert_eq!(host.cursor_at(point), Cursor::Pointer);
775
776 assert!(host.hover(point), "the first hover is a change");
778 host.layout(&MetricShaper);
779 let b = host.hovered().unwrap().1;
780 assert_eq!(
781 host.layer(0)
782 .unwrap()
783 .styles()
784 .get(b)
785 .unwrap()
786 .background_color,
787 Color::rgb(255, 0, 0)
788 );
789 assert_eq!(host.cursor_at(point), Cursor::Pointer);
790 assert!(!host.hover(point));
792
793 host.press(point);
795 host.layout(&MetricShaper);
796 assert_eq!(
797 host.layer(0)
798 .unwrap()
799 .styles()
800 .get(b)
801 .unwrap()
802 .background_color,
803 Color::rgb(0, 128, 0)
804 );
805 host.release();
806 host.layout(&MetricShaper);
807 assert_eq!(
808 host.layer(0)
809 .unwrap()
810 .styles()
811 .get(b)
812 .unwrap()
813 .background_color,
814 Color::rgb(255, 0, 0)
815 );
816 }
817
818 #[test]
819 fn hover_does_not_leak_across_layers() {
820 let mut host = Host::new(Size::new(400.0, 300.0));
821 host.add_chrome(
822 engine("<div id=\"c\">x</div>", "div:hover { color: red }"),
823 Rect::new(0.0, 0.0, 400.0, 50.0),
824 );
825 host.add_content(
826 engine("<div id=\"d\">y</div>", "div { color: black }"),
827 Rect::new(0.0, 50.0, 400.0, 250.0),
828 );
829 host.layout(&MetricShaper);
830
831 assert!(host.hover(Point::new(10.0, 60.0)));
833 host.layout(&MetricShaper);
834 let c = host
835 .layer(0)
836 .unwrap()
837 .engine()
838 .dom()
839 .get_element_by_id("c")
840 .unwrap();
841 assert_eq!(
842 host.layer(0).unwrap().styles().get(c).unwrap().color,
843 Color::BLACK
844 );
845 }
846
847 #[test]
848 fn wheel_chains_from_a_sub_document_to_its_parent() {
849 let mut host = Host::new(Size::new(400.0, 200.0));
850 let parent = host.add_chrome(
851 engine(
852 r#"<div id="slot"></div><div id="tail"></div>"#,
853 "#slot { width: 200px; height: 100px } #tail { height: 400px }",
854 ),
855 Rect::new(0.0, 0.0, 400.0, 200.0),
856 );
857 let slot = host
858 .layer(parent)
859 .unwrap()
860 .engine()
861 .dom()
862 .get_element_by_id("slot")
863 .unwrap();
864 let sub = engine(r#"<div id="long"></div>"#, "#long { height: 300px }");
865 let sub_index = host.add_sub_document(parent, slot, sub);
866 host.layout(&MetricShaper);
867
868 assert_eq!(host.layer(sub_index).unwrap().max_scroll_y(), 200.0);
870 assert_eq!(host.layer(parent).unwrap().max_scroll_y(), 300.0);
871
872 let chain = host.wheel(Point::new(10.0, 10.0), 250.0);
874 assert_eq!(chain, vec![(sub_index, 200.0), (parent, 50.0)]);
875 assert_eq!(host.layer(sub_index).unwrap().scroll().y, 200.0);
876 assert_eq!(host.layer(parent).unwrap().scroll().y, 50.0);
877 }
878
879 #[test]
882 fn set_scroll_y_clamps_to_the_scrollable_range() {
883 let mut host = Host::new(Size::new(400.0, 200.0));
884 let page = host.add_content(
885 engine(r#"<div id="long"></div>"#, "#long { height: 500px }"),
886 Rect::new(0.0, 0.0, 400.0, 200.0),
887 );
888 host.layout(&MetricShaper);
889 let layer = &mut host.layers_mut()[page];
890 assert_eq!(layer.max_scroll_y(), 300.0);
891 layer.set_scroll_y(120.0);
892 assert_eq!(layer.scroll().y, 120.0);
893 layer.set_scroll_y(1_000.0);
894 assert_eq!(layer.scroll().y, 300.0);
895 layer.set_scroll_y(-5.0);
896 assert_eq!(layer.scroll().y, 0.0);
897 }
898
899 #[test]
902 fn hit_accounts_for_the_layers_scroll() {
903 let mut host = Host::new(Size::new(400.0, 200.0));
904 let page = host.add_content(
905 engine(
906 r#"<div id="top"></div><div id="bottom"></div>"#,
907 "#top { height: 300px } #bottom { height: 300px }",
908 ),
909 Rect::new(0.0, 0.0, 400.0, 200.0),
910 );
911 host.layout(&MetricShaper);
912 let dom = host.layer(page).unwrap().engine().dom();
913 let top = dom.get_element_by_id("top").unwrap();
914 let bottom = dom.get_element_by_id("bottom").unwrap();
915 let point = Point::new(10.0, 50.0);
916 assert_eq!(host.hit(point), Some((page, top)));
917 host.layers_mut()[page].set_scroll_y(300.0);
918 assert_eq!(host.hit(point), Some((page, bottom)));
919 }
920
921 #[test]
922 fn wheel_does_not_chain_while_the_sub_document_can_scroll() {
923 let mut host = Host::new(Size::new(400.0, 200.0));
924 let parent = host.add_chrome(
925 engine(
926 r#"<div id="slot"></div>"#,
927 "#slot { width: 200px; height: 100px }",
928 ),
929 Rect::new(0.0, 0.0, 400.0, 200.0),
930 );
931 let slot = host
932 .layer(parent)
933 .unwrap()
934 .engine()
935 .dom()
936 .get_element_by_id("slot")
937 .unwrap();
938 let sub = engine(r#"<div id="long"></div>"#, "#long { height: 300px }");
939 let sub_index = host.add_sub_document(parent, slot, sub);
940 host.layout(&MetricShaper);
941
942 let chain = host.wheel(Point::new(10.0, 10.0), 50.0);
943 assert_eq!(chain, vec![(sub_index, 50.0)]);
944 assert_eq!(host.layer(parent).unwrap().scroll().y, 0.0);
945 }
946
947 struct MarkGlyphs;
950
951 impl noonoo_paint::Glyphs for MarkGlyphs {
952 fn draw(
953 &self,
954 _text: &str,
955 (x, y): (f32, f32),
956 _font_size: f32,
957 _color: Color,
958 _request: noonoo_paint::FontRequest,
959 out: &mut noonoo_paint::CommandList,
960 ) {
961 out.0.push(noonoo_paint::Command::FillRect {
962 rect: Rect::new(x, y, 1.0, 1.0),
963 color: Color::rgb(0, 255, 0),
964 radius: (0.0, 0.0, 0.0, 0.0),
965 });
966 }
967 }
968
969 fn marks(host: &Host, index: usize) -> (usize, usize) {
970 let commands = host.layer(index).unwrap().commands().commands();
971 let marks = commands
972 .iter()
973 .filter(|c| {
974 matches!(c, noonoo_paint::Command::FillRect { color, .. } if *color == Color::rgb(0, 255, 0))
975 })
976 .count();
977 let runs = commands
978 .iter()
979 .filter(|c| matches!(c, noonoo_paint::Command::DrawText { .. }))
980 .count();
981 (marks, runs)
982 }
983
984 #[test]
988 fn text_paints_through_the_hosts_glyphs() {
989 let mut host = Host::new(Size::new(400.0, 300.0));
990 host.set_glyphs(Box::new(MarkGlyphs));
991 let index = host.add_content(
992 engine(
993 r#"<div id="list"><p>one</p><div id="tall"></div></div>"#,
994 "#list { height: 50px; overflow-y: auto } #tall { height: 200px }",
995 ),
996 Rect::new(0.0, 0.0, 400.0, 300.0),
997 );
998 host.layout(&MetricShaper);
999 assert_eq!(marks(&host, index), (1, 0));
1000
1001 host.wheel(Point::new(10.0, 10.0), 100.0);
1002 assert_eq!(
1003 marks(&host, index),
1004 (1, 0),
1005 "the scroll repaint keeps the glyphs"
1006 );
1007 }
1008
1009 #[test]
1010 fn wheel_scrolls_an_inner_container_before_the_layer() {
1011 let mut host = Host::new(Size::new(400.0, 300.0));
1012 let index = host.add_content(
1013 engine(
1014 r#"<div id="list"><div id="tall"></div></div><div id="tail"></div>"#,
1015 "#list { width: 200px; height: 50px; overflow-y: auto } \
1016 #tall { height: 200px } #tail { height: 600px }",
1017 ),
1018 Rect::new(0.0, 0.0, 400.0, 300.0),
1019 );
1020 host.layout(&MetricShaper);
1021 let list = host
1022 .layer(index)
1023 .unwrap()
1024 .engine()
1025 .dom()
1026 .get_element_by_id("list")
1027 .unwrap();
1028 assert_eq!(host.layer(index).unwrap().layout().scroll_max(list), 150.0);
1029
1030 host.wheel(Point::new(10.0, 10.0), 100.0);
1032 assert_eq!(
1033 host.layer(index).unwrap().layout().scroll_offset(list),
1034 100.0
1035 );
1036 assert_eq!(host.layer(index).unwrap().scroll().y, 0.0);
1037 }
1038
1039 #[test]
1040 fn wheel_chains_from_a_container_to_the_layer() {
1041 let mut host = Host::new(Size::new(400.0, 300.0));
1042 let index = host.add_content(
1043 engine(
1044 r#"<div id="list"><div id="tall"></div></div><div id="tail"></div>"#,
1045 "#list { width: 200px; height: 50px; overflow-y: auto } \
1046 #tall { height: 200px } #tail { height: 600px }",
1047 ),
1048 Rect::new(0.0, 0.0, 400.0, 300.0),
1049 );
1050 host.layout(&MetricShaper);
1051 let list = host
1052 .layer(index)
1053 .unwrap()
1054 .engine()
1055 .dom()
1056 .get_element_by_id("list")
1057 .unwrap();
1058
1059 let chain = host.wheel(Point::new(10.0, 10.0), 200.0);
1061 assert_eq!(
1062 host.layer(index).unwrap().layout().scroll_offset(list),
1063 150.0
1064 );
1065 assert_eq!(host.layer(index).unwrap().scroll().y, 50.0);
1066 assert_eq!(chain, vec![(index, 50.0)]);
1067 }
1068
1069 #[cfg(feature = "a11y")]
1070 #[test]
1071 fn a11y_composes_layers_with_bounds_and_focus() {
1072 let mut host = host();
1073 let node = host
1074 .layer(1)
1075 .unwrap()
1076 .engine()
1077 .dom()
1078 .get_element_by_id("page")
1079 .unwrap();
1080 host.set_focus(1, node);
1081
1082 let tree = host.a11y();
1083 assert_eq!(tree.root.role, noonoo_a11y::Role::Window);
1084 assert_eq!(tree.root.children.len(), 2);
1085
1086 let focused = tree.focus.unwrap();
1087 let node = tree.find_by_id(focused).unwrap();
1088 assert_eq!(
1089 node.node,
1090 Some(
1091 host.layer(1)
1092 .unwrap()
1093 .engine()
1094 .dom()
1095 .get_element_by_id("page")
1096 .unwrap()
1097 )
1098 );
1099 assert_eq!(node.layer, Some(1));
1100 assert_eq!(node.role, noonoo_a11y::Role::Generic);
1101 assert!(node.bounds.unwrap().y >= 24.0);
1102 }
1103
1104 #[test]
1105 fn origin_gates_internal_schemes() {
1106 assert!(navigation_allowed(&Origin::Chrome, "shell"));
1107 assert!(!navigation_allowed(&Origin::Content, "shell"));
1108 assert!(navigation_allowed(&Origin::Content, "https"));
1109 assert!(navigation_allowed(&Origin::Custom("app".into()), "exo"));
1110 }
1111}