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_canvas(
294 &styles,
295 &layout,
296 self.glyphs.as_ref(),
297 layer.engine.canvas(&styles),
298 );
299 layer.styles = styles;
300 layer.layout = layout;
301 layer.commands = commands;
302 let max_y = layer.max_scroll_y();
303 layer.scroll.y = layer.scroll.y.clamp(0.0, max_y);
304 }
305 }
306
307 pub fn poll_resources(&mut self) -> bool {
311 let mut changed = false;
312 for layer in &mut self.layers {
313 changed |= layer.engine.poll_resources();
314 }
315 changed
316 }
317
318 pub fn route(&self, point: Point) -> Option<usize> {
320 self.layers
321 .iter()
322 .rposition(|layer| layer.rect.contains(point))
323 }
324
325 pub fn hit(&self, point: Point) -> Option<(usize, NodeId)> {
327 let index = self.route(point)?;
328 let layer = &self.layers[index];
329 let local = local_point(layer.rect, layer.scroll, point);
330 let node = layer.layout.hit_test(local)?;
331 Some((index, node))
332 }
333
334 pub fn element_hit(&self, point: Point) -> Option<(usize, NodeId)> {
338 let (index, mut node) = self.hit(point)?;
339 let dom = self.layers[index].engine().dom();
340 while dom.element(node).is_none() {
341 node = dom.tree().parent(node)?;
342 }
343 Some((index, node))
344 }
345
346 pub fn focus(&self) -> Option<(usize, NodeId)> {
348 self.focus
349 }
350
351 pub fn set_focus(&mut self, layer: usize, node: NodeId) {
353 self.focus = Some((layer, node));
354 }
355
356 pub fn hover(&mut self, point: Point) -> bool {
361 let hit = self.element_hit(point);
362 if hit != self.hovered {
363 self.hovered = hit;
364 true
365 } else {
366 false
367 }
368 }
369
370 pub fn hovered(&self) -> Option<(usize, NodeId)> {
372 self.hovered
373 }
374
375 pub fn press(&mut self, point: Point) {
377 self.active = self.element_hit(point);
378 }
379
380 pub fn release(&mut self) {
382 self.active = None;
383 }
384
385 pub fn active(&self) -> Option<(usize, NodeId)> {
387 self.active
388 }
389
390 pub fn cursor_at(&self, point: Point) -> Cursor {
393 match self.element_hit(point) {
394 Some((index, node)) => self.layers[index]
395 .styles
396 .get(node)
397 .map(|style| style.cursor.clone())
398 .unwrap_or(Cursor::Auto),
399 None => Cursor::Auto,
400 }
401 }
402
403 fn interaction_for(&self, index: usize) -> Interaction {
405 let on_layer = |state: Option<(usize, NodeId)>| {
406 state
407 .filter(|(layer, _)| *layer == index)
408 .map(|(_, node)| node)
409 };
410 Interaction {
411 hovered: on_layer(self.hovered),
412 focused: on_layer(self.focus),
413 active: on_layer(self.active),
414 }
415 }
416
417 pub fn dispatch_pointer(
421 &mut self,
422 point: Point,
423 event: &Event,
424 listener: &impl EventListener,
425 ) -> Option<(usize, NodeId)> {
426 let (index, node) = self.element_hit(point)?;
427 self.focus = Some((index, node));
428 dispatch(
429 self.layers[index].engine().dom().tree(),
430 node,
431 event,
432 listener,
433 );
434 Some((index, node))
435 }
436
437 pub fn dispatch_key(&mut self, event: &Event, listener: &impl EventListener) -> bool {
439 let Some((index, node)) = self.focus else {
440 return false;
441 };
442 let layer = &self.layers[index];
443 dispatch(layer.engine().dom().tree(), node, event, listener);
444 true
445 }
446
447 fn repaint(&mut self, index: usize) {
449 let layer = &mut self.layers[index];
450 layer.commands = noonoo_paint::paint_canvas(
451 &layer.styles,
452 &layer.layout,
453 self.glyphs.as_ref(),
454 layer.engine.canvas(&layer.styles),
455 );
456 }
457
458 pub fn wheel(&mut self, point: Point, delta_y: f32) -> Vec<(usize, f32)> {
468 let mut chain = Vec::new();
469 let Some(mut index) = self.route(point) else {
470 return chain;
471 };
472 let mut leftover = delta_y;
473 loop {
474 let local = local_point(self.layers[index].rect, self.layers[index].scroll, point);
476 let (boxes, remaining) = self.layers[index].layout.scroll_at(local, leftover);
477 if !boxes.is_empty() {
478 self.repaint(index);
479 leftover = remaining;
480 }
481
482 let layer = &mut self.layers[index];
484 let max = layer.max_scroll_y();
485 let before = layer.scroll.y;
486 let after = (before + leftover).clamp(0.0, max);
487 let consumed = after - before;
488 layer.scroll.y = after;
489 if consumed != 0.0 {
490 chain.push((index, consumed));
491 }
492 leftover -= consumed;
493 if leftover.abs() < 1e-4 {
494 break;
495 }
496 match layer.anchor {
497 Some(anchor) => index = anchor.parent,
498 None => break,
499 }
500 }
501 chain
502 }
503
504 #[cfg(feature = "a11y")]
510 pub fn a11y(&self) -> noonoo_a11y::A11yTree {
511 let mut trees = Vec::with_capacity(self.layers.len());
512 for (index, layer) in self.layers.iter().enumerate() {
513 let focused = match self.focus {
514 Some((layer_index, node)) if layer_index == index => Some(node),
515 _ => None,
516 };
517 let tree = layer.a11y(focused);
518 let offset = Point::new(layer.rect.x - layer.scroll.x, layer.rect.y - layer.scroll.y);
519 trees.push((tree, offset));
520 }
521 let layers: Vec<(&noonoo_a11y::A11yTree, Point)> =
522 trees.iter().map(|(tree, offset)| (tree, *offset)).collect();
523 noonoo_a11y::compose("", &layers)
524 }
525}
526
527fn local_point(rect: Rect, scroll: Point, point: Point) -> Point {
528 Point::new(point.x - rect.x + scroll.x, point.y - rect.y + scroll.y)
529}
530
531pub const VERSION: &str = env!("CARGO_PKG_VERSION");
533
534#[cfg(test)]
535mod tests {
536 use super::*;
537 use noonoo_layout::MetricShaper;
538 use noonoo_paint::Color;
539 use std::cell::RefCell;
540 use std::rc::Rc;
541
542 fn engine(html: &str, css: &str) -> Engine {
543 Engine::from_html(&format!("<style>body {{ margin: 0 }} {css}</style>{html}"))
545 }
546
547 fn host() -> Host {
548 let mut host = Host::new(Size::new(400.0, 300.0));
549 host.add_chrome(
550 engine(
551 r#"<div id="bar">chrome</div>"#,
552 "#bar { height: 24px; background-color: #222222 }",
553 ),
554 Rect::new(0.0, 0.0, 400.0, 24.0),
555 );
556 host.add_content(
557 engine(
558 r#"<div id="page">content</div>"#,
559 "#page { height: 100px; background-color: #ffffff }",
560 ),
561 Rect::new(0.0, 24.0, 400.0, 276.0),
562 );
563 host.layout(&MetricShaper);
564 host
565 }
566
567 #[test]
570 fn layers_draw_the_images_their_engines_loaded() {
571 let dir = std::env::temp_dir().join("noonoo-shell-images");
572 std::fs::create_dir_all(&dir).unwrap();
573 let mut png = b"\x89PNG\r\n\x1a\n".to_vec();
574 png.extend(13u32.to_be_bytes());
575 png.extend(b"IHDR");
576 png.extend(40u32.to_be_bytes());
577 png.extend(30u32.to_be_bytes());
578 png.extend([8, 6, 0, 0, 0]);
579 std::fs::write(dir.join("a.png"), png).unwrap();
580 let mut host = host();
581 assert!(!host.poll_resources());
582 let mut page = engine(r#"<img src="a.png">"#, "");
583 page.set_base_url(format!("{}/index.html", dir.display()));
584 page.set_loader(noonoo_net::FileLoader);
585 page.load_resources();
586 let layer = host.add_content(page, Rect::new(0.0, 24.0, 400.0, 276.0));
587 assert!(host.poll_resources());
588 assert!(!host.poll_resources());
589 host.layout(&MetricShaper);
590 let drawn = host.layers()[layer]
591 .commands()
592 .commands()
593 .iter()
594 .filter(|c| matches!(c, noonoo_paint::Command::DrawImage { .. }))
595 .count();
596 assert_eq!(drawn, 1);
597 }
598
599 #[test]
602 fn a_layers_document_can_be_changed_in_place() {
603 let mut host = host();
604 let engine = host.layers_mut()[0].engine_mut();
605 let bar = engine.dom().get_element_by_id("bar").unwrap();
606 let text = engine.dom().tree().children(bar)[0];
607 engine.dom_mut().mutate().set_text(text, "patched").unwrap();
608 host.layout(&MetricShaper);
609 let painted = host.layers()[0].commands().commands().iter().any(|command| {
610 matches!(command, noonoo_paint::Command::DrawText { text, .. } if text == "patched")
611 });
612 assert!(painted);
613 }
614
615 #[test]
616 fn routes_by_region() {
617 let host = host();
618 assert_eq!(host.route(Point::new(10.0, 10.0)), Some(0));
619 assert_eq!(host.route(Point::new(10.0, 50.0)), Some(1));
620 assert_eq!(host.route(Point::new(10.0, 999.0)), None);
621 }
622
623 #[test]
624 fn hit_tests_to_the_right_document_and_node() {
625 let host = host();
626 let (layer, node) = host.hit(Point::new(10.0, 50.0)).unwrap();
627 assert_eq!(layer, 1);
628 assert_eq!(
629 host.layer(1)
630 .unwrap()
631 .engine()
632 .dom()
633 .element(node)
634 .unwrap()
635 .name,
636 "div"
637 );
638 }
639
640 #[test]
641 fn pointer_sets_focus_and_dispatches() {
642 let mut host = host();
643 let seen: Rc<RefCell<Vec<NodeId>>> = Rc::new(RefCell::new(Vec::new()));
644 let listener = {
645 let seen = seen.clone();
646 noonoo_events::FnListener(
647 move |node: NodeId, _e: &Event, _p: noonoo_events::EventPhase| {
648 seen.borrow_mut().push(node);
649 noonoo_events::Propagation::Continue
650 },
651 )
652 };
653 let routed = host.dispatch_pointer(
654 Point::new(10.0, 50.0),
655 &Event::Click(noonoo_events::PointerEvent {
656 x: 10.0,
657 y: 50.0,
658 button: noonoo_events::MouseButton::Primary,
659 state: noonoo_events::ElementState::Released,
660 modifiers: noonoo_events::Modifiers::default(),
661 }),
662 &listener,
663 );
664 let (layer, _node) = routed.unwrap();
665 assert_eq!(layer, 1);
666 assert_eq!(host.focus().unwrap().0, 1);
667 assert!(!seen.borrow().is_empty());
668
669 assert!(host.dispatch_key(&Event::Input { value: "a".into() }, &listener));
671 }
672
673 #[test]
674 fn composes_one_command_stream_per_layer() {
675 let host = host();
676 assert_eq!(host.layers().len(), 2);
677 assert!(!host.layer(0).unwrap().commands().is_empty());
678 assert!(!host.layer(1).unwrap().commands().is_empty());
679 }
680
681 #[test]
682 fn sub_document_is_sized_by_its_host_node() {
683 let mut host = Host::new(Size::new(400.0, 300.0));
684 let parent = host.add_chrome(
685 engine(
686 r#"<div id="slot"></div>"#,
687 "#slot { width: 200px; height: 100px }",
688 ),
689 Rect::new(0.0, 0.0, 400.0, 300.0),
690 );
691 let slot = host
692 .layer(parent)
693 .unwrap()
694 .engine()
695 .dom()
696 .get_element_by_id("slot")
697 .unwrap();
698 let sub = engine(
699 r#"<p id="emb">embedded</p>"#,
700 "p { margin: 0; height: 40px; background-color: #eeeeee }",
701 );
702 let sub_index = host.add_sub_document(parent, slot, sub);
703 host.layout(&MetricShaper);
704
705 assert_eq!(
707 host.layer(sub_index).unwrap().rect,
708 Rect::new(0.0, 0.0, 200.0, 100.0)
709 );
710 assert_eq!(host.route(Point::new(10.0, 10.0)), Some(sub_index));
712 let (layer, node) = host.hit(Point::new(10.0, 10.0)).unwrap();
713 assert_eq!(layer, sub_index);
714 assert_eq!(
716 host.layer(sub_index)
717 .unwrap()
718 .engine()
719 .dom()
720 .node(node)
721 .and_then(|data| data.as_text()),
722 Some("embedded")
723 );
724 assert!(!host.layer(sub_index).unwrap().commands().is_empty());
726 }
727
728 #[test]
729 fn pointing_at_text_hovers_and_presses_its_element() {
730 let mut host = Host::new(Size::new(400.0, 300.0));
731 host.add_content(
732 engine(
733 "<p>hello</p>",
734 "body { margin: 0 } p { margin: 0; cursor: pointer }
735 p:hover { background: red }",
736 ),
737 Rect::new(0.0, 0.0, 400.0, 300.0),
738 );
739 host.layout(&MetricShaper);
740 let point = Point::new(2.0, 2.0);
742 let (_, deepest) = host.hit(point).unwrap();
743 let dom = host.layer(0).unwrap().engine().dom();
744 assert!(dom.element(deepest).is_none(), "the hit is the text node");
745
746 assert_eq!(host.cursor_at(point), Cursor::Pointer);
747 host.hover(point);
748 host.press(point);
749 let p = host.hovered().unwrap().1;
750 let dom = host.layer(0).unwrap().engine().dom();
751 assert_eq!(dom.element(p).unwrap().name, "p");
752 assert_eq!(host.active().unwrap().1, p);
753 host.layout(&MetricShaper);
754 assert_eq!(
755 host.layer(0)
756 .unwrap()
757 .styles()
758 .get(p)
759 .unwrap()
760 .background_color,
761 Color::rgb(255, 0, 0)
762 );
763 }
764
765 #[test]
766 fn hover_and_active_restyle_on_the_next_layout() {
767 let mut host = Host::new(Size::new(400.0, 300.0));
768 host.add_content(
769 engine(
770 r#"<button id="b">hi</button>"#,
771 "button { cursor: pointer; background: white }
772 button:hover { background: red }
773 button:active { background: green }
774 button:focus { outline: 1px }",
775 ),
776 Rect::new(0.0, 0.0, 400.0, 300.0),
777 );
778 host.layout(&MetricShaper);
779 let point = Point::new(10.0, 10.0);
780
781 assert!(host.hovered().is_none());
783 assert_eq!(host.cursor_at(point), Cursor::Pointer);
784
785 assert!(host.hover(point), "the first hover is a change");
787 host.layout(&MetricShaper);
788 let b = host.hovered().unwrap().1;
789 assert_eq!(
790 host.layer(0)
791 .unwrap()
792 .styles()
793 .get(b)
794 .unwrap()
795 .background_color,
796 Color::rgb(255, 0, 0)
797 );
798 assert_eq!(host.cursor_at(point), Cursor::Pointer);
799 assert!(!host.hover(point));
801
802 host.press(point);
804 host.layout(&MetricShaper);
805 assert_eq!(
806 host.layer(0)
807 .unwrap()
808 .styles()
809 .get(b)
810 .unwrap()
811 .background_color,
812 Color::rgb(0, 128, 0)
813 );
814 host.release();
815 host.layout(&MetricShaper);
816 assert_eq!(
817 host.layer(0)
818 .unwrap()
819 .styles()
820 .get(b)
821 .unwrap()
822 .background_color,
823 Color::rgb(255, 0, 0)
824 );
825 }
826
827 #[test]
828 fn hover_does_not_leak_across_layers() {
829 let mut host = Host::new(Size::new(400.0, 300.0));
830 host.add_chrome(
831 engine("<div id=\"c\">x</div>", "div:hover { color: red }"),
832 Rect::new(0.0, 0.0, 400.0, 50.0),
833 );
834 host.add_content(
835 engine("<div id=\"d\">y</div>", "div { color: black }"),
836 Rect::new(0.0, 50.0, 400.0, 250.0),
837 );
838 host.layout(&MetricShaper);
839
840 assert!(host.hover(Point::new(10.0, 60.0)));
842 host.layout(&MetricShaper);
843 let c = host
844 .layer(0)
845 .unwrap()
846 .engine()
847 .dom()
848 .get_element_by_id("c")
849 .unwrap();
850 assert_eq!(
851 host.layer(0).unwrap().styles().get(c).unwrap().color,
852 Color::BLACK
853 );
854 }
855
856 #[test]
857 fn wheel_chains_from_a_sub_document_to_its_parent() {
858 let mut host = Host::new(Size::new(400.0, 200.0));
859 let parent = host.add_chrome(
860 engine(
861 r#"<div id="slot"></div><div id="tail"></div>"#,
862 "#slot { width: 200px; height: 100px } #tail { height: 400px }",
863 ),
864 Rect::new(0.0, 0.0, 400.0, 200.0),
865 );
866 let slot = host
867 .layer(parent)
868 .unwrap()
869 .engine()
870 .dom()
871 .get_element_by_id("slot")
872 .unwrap();
873 let sub = engine(r#"<div id="long"></div>"#, "#long { height: 300px }");
874 let sub_index = host.add_sub_document(parent, slot, sub);
875 host.layout(&MetricShaper);
876
877 assert_eq!(host.layer(sub_index).unwrap().max_scroll_y(), 200.0);
879 assert_eq!(host.layer(parent).unwrap().max_scroll_y(), 300.0);
880
881 let chain = host.wheel(Point::new(10.0, 10.0), 250.0);
883 assert_eq!(chain, vec![(sub_index, 200.0), (parent, 50.0)]);
884 assert_eq!(host.layer(sub_index).unwrap().scroll().y, 200.0);
885 assert_eq!(host.layer(parent).unwrap().scroll().y, 50.0);
886 }
887
888 #[test]
891 fn set_scroll_y_clamps_to_the_scrollable_range() {
892 let mut host = Host::new(Size::new(400.0, 200.0));
893 let page = host.add_content(
894 engine(r#"<div id="long"></div>"#, "#long { height: 500px }"),
895 Rect::new(0.0, 0.0, 400.0, 200.0),
896 );
897 host.layout(&MetricShaper);
898 let layer = &mut host.layers_mut()[page];
899 assert_eq!(layer.max_scroll_y(), 300.0);
900 layer.set_scroll_y(120.0);
901 assert_eq!(layer.scroll().y, 120.0);
902 layer.set_scroll_y(1_000.0);
903 assert_eq!(layer.scroll().y, 300.0);
904 layer.set_scroll_y(-5.0);
905 assert_eq!(layer.scroll().y, 0.0);
906 }
907
908 #[test]
911 fn hit_accounts_for_the_layers_scroll() {
912 let mut host = Host::new(Size::new(400.0, 200.0));
913 let page = host.add_content(
914 engine(
915 r#"<div id="top"></div><div id="bottom"></div>"#,
916 "#top { height: 300px } #bottom { height: 300px }",
917 ),
918 Rect::new(0.0, 0.0, 400.0, 200.0),
919 );
920 host.layout(&MetricShaper);
921 let dom = host.layer(page).unwrap().engine().dom();
922 let top = dom.get_element_by_id("top").unwrap();
923 let bottom = dom.get_element_by_id("bottom").unwrap();
924 let point = Point::new(10.0, 50.0);
925 assert_eq!(host.hit(point), Some((page, top)));
926 host.layers_mut()[page].set_scroll_y(300.0);
927 assert_eq!(host.hit(point), Some((page, bottom)));
928 }
929
930 #[test]
931 fn wheel_does_not_chain_while_the_sub_document_can_scroll() {
932 let mut host = Host::new(Size::new(400.0, 200.0));
933 let parent = host.add_chrome(
934 engine(
935 r#"<div id="slot"></div>"#,
936 "#slot { width: 200px; height: 100px }",
937 ),
938 Rect::new(0.0, 0.0, 400.0, 200.0),
939 );
940 let slot = host
941 .layer(parent)
942 .unwrap()
943 .engine()
944 .dom()
945 .get_element_by_id("slot")
946 .unwrap();
947 let sub = engine(r#"<div id="long"></div>"#, "#long { height: 300px }");
948 let sub_index = host.add_sub_document(parent, slot, sub);
949 host.layout(&MetricShaper);
950
951 let chain = host.wheel(Point::new(10.0, 10.0), 50.0);
952 assert_eq!(chain, vec![(sub_index, 50.0)]);
953 assert_eq!(host.layer(parent).unwrap().scroll().y, 0.0);
954 }
955
956 struct MarkGlyphs;
959
960 impl noonoo_paint::Glyphs for MarkGlyphs {
961 fn draw(
962 &self,
963 _text: &str,
964 (x, y): (f32, f32),
965 _font_size: f32,
966 _color: Color,
967 _request: noonoo_paint::FontRequest,
968 out: &mut noonoo_paint::CommandList,
969 ) {
970 out.0.push(noonoo_paint::Command::FillRect {
971 rect: Rect::new(x, y, 1.0, 1.0),
972 color: Color::rgb(0, 255, 0),
973 radius: (0.0, 0.0, 0.0, 0.0),
974 });
975 }
976 }
977
978 fn marks(host: &Host, index: usize) -> (usize, usize) {
979 let commands = host.layer(index).unwrap().commands().commands();
980 let marks = commands
981 .iter()
982 .filter(|c| {
983 matches!(c, noonoo_paint::Command::FillRect { color, .. } if *color == Color::rgb(0, 255, 0))
984 })
985 .count();
986 let runs = commands
987 .iter()
988 .filter(|c| matches!(c, noonoo_paint::Command::DrawText { .. }))
989 .count();
990 (marks, runs)
991 }
992
993 #[test]
997 fn text_paints_through_the_hosts_glyphs() {
998 let mut host = Host::new(Size::new(400.0, 300.0));
999 host.set_glyphs(Box::new(MarkGlyphs));
1000 let index = host.add_content(
1001 engine(
1002 r#"<div id="list"><p>one</p><div id="tall"></div></div>"#,
1003 "#list { height: 50px; overflow-y: auto } #tall { height: 200px }",
1004 ),
1005 Rect::new(0.0, 0.0, 400.0, 300.0),
1006 );
1007 host.layout(&MetricShaper);
1008 assert_eq!(marks(&host, index), (1, 0));
1009
1010 host.wheel(Point::new(10.0, 10.0), 100.0);
1011 assert_eq!(
1012 marks(&host, index),
1013 (1, 0),
1014 "the scroll repaint keeps the glyphs"
1015 );
1016 }
1017
1018 #[test]
1019 fn wheel_scrolls_an_inner_container_before_the_layer() {
1020 let mut host = Host::new(Size::new(400.0, 300.0));
1021 let index = host.add_content(
1022 engine(
1023 r#"<div id="list"><div id="tall"></div></div><div id="tail"></div>"#,
1024 "#list { width: 200px; height: 50px; overflow-y: auto } \
1025 #tall { height: 200px } #tail { height: 600px }",
1026 ),
1027 Rect::new(0.0, 0.0, 400.0, 300.0),
1028 );
1029 host.layout(&MetricShaper);
1030 let list = host
1031 .layer(index)
1032 .unwrap()
1033 .engine()
1034 .dom()
1035 .get_element_by_id("list")
1036 .unwrap();
1037 assert_eq!(host.layer(index).unwrap().layout().scroll_max(list), 150.0);
1038
1039 host.wheel(Point::new(10.0, 10.0), 100.0);
1041 assert_eq!(
1042 host.layer(index).unwrap().layout().scroll_offset(list),
1043 100.0
1044 );
1045 assert_eq!(host.layer(index).unwrap().scroll().y, 0.0);
1046 }
1047
1048 #[test]
1049 fn wheel_chains_from_a_container_to_the_layer() {
1050 let mut host = Host::new(Size::new(400.0, 300.0));
1051 let index = host.add_content(
1052 engine(
1053 r#"<div id="list"><div id="tall"></div></div><div id="tail"></div>"#,
1054 "#list { width: 200px; height: 50px; overflow-y: auto } \
1055 #tall { height: 200px } #tail { height: 600px }",
1056 ),
1057 Rect::new(0.0, 0.0, 400.0, 300.0),
1058 );
1059 host.layout(&MetricShaper);
1060 let list = host
1061 .layer(index)
1062 .unwrap()
1063 .engine()
1064 .dom()
1065 .get_element_by_id("list")
1066 .unwrap();
1067
1068 let chain = host.wheel(Point::new(10.0, 10.0), 200.0);
1070 assert_eq!(
1071 host.layer(index).unwrap().layout().scroll_offset(list),
1072 150.0
1073 );
1074 assert_eq!(host.layer(index).unwrap().scroll().y, 50.0);
1075 assert_eq!(chain, vec![(index, 50.0)]);
1076 }
1077
1078 #[cfg(feature = "a11y")]
1079 #[test]
1080 fn a11y_composes_layers_with_bounds_and_focus() {
1081 let mut host = host();
1082 let node = host
1083 .layer(1)
1084 .unwrap()
1085 .engine()
1086 .dom()
1087 .get_element_by_id("page")
1088 .unwrap();
1089 host.set_focus(1, node);
1090
1091 let tree = host.a11y();
1092 assert_eq!(tree.root.role, noonoo_a11y::Role::Window);
1093 assert_eq!(tree.root.children.len(), 2);
1094
1095 let focused = tree.focus.unwrap();
1096 let node = tree.find_by_id(focused).unwrap();
1097 assert_eq!(
1098 node.node,
1099 Some(
1100 host.layer(1)
1101 .unwrap()
1102 .engine()
1103 .dom()
1104 .get_element_by_id("page")
1105 .unwrap()
1106 )
1107 );
1108 assert_eq!(node.layer, Some(1));
1109 assert_eq!(node.role, noonoo_a11y::Role::Generic);
1110 assert!(node.bounds.unwrap().y >= 24.0);
1111 }
1112
1113 #[test]
1114 fn origin_gates_internal_schemes() {
1115 assert!(navigation_allowed(&Origin::Chrome, "shell"));
1116 assert!(!navigation_allowed(&Origin::Content, "shell"));
1117 assert!(navigation_allowed(&Origin::Content, "https"));
1118 assert!(navigation_allowed(&Origin::Custom("app".into()), "exo"));
1119 }
1120}
1121
1122#[cfg(doctest)]
1123#[doc = include_str!("../README.md")]
1124pub struct ReadmeDoctests;